1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
#![allow(clippy::let_and_return)]

use crate::prelude::*;

use slotmap::dense as sm;

// ---------- newtypes and type aliases ----------

visible_slotmap_key!{ ClientId(b'C') }

const MAX_CLIENT_INACTIVITY: Duration = Duration::from_secs(200);

const GAME_SAVE_LAG: Duration = Duration::from_millis(500);

const MAX_LOG_AGE: Duration = Duration::from_secs(10 * 86400);

#[derive(Hash,Ord,PartialOrd,Eq,PartialEq,Serialize)]
#[repr(transparent)]
pub struct RawTokenVal(str);

// ---------- public data structure ----------

#[derive(Clone,Debug,Hash,Eq,PartialEq,Ord,PartialOrd)]
#[derive(Serialize,Deserialize)]
pub struct InstanceName {
  pub account: AccountName,
  pub game: String,
}

#[derive(Debug,Clone)]
pub struct InstanceRef(Arc<InstanceOuter>);

#[derive(Debug,Clone)]
pub struct InstanceWeakRef(std::sync::Weak<InstanceOuter>);

#[derive(Debug)]
pub struct InstanceOuter {
  c: Mutex<InstanceContainer>,
  b: Mutex<InstanceBundles>,
}

#[derive(Debug,Clone,Serialize,Deserialize,Default)]
#[derive(Deref,DerefMut)]
#[serde(transparent)]
pub struct LinksTable(pub EnumMap<LinkKind, Option<String>>);

pub struct Instance {
  pub name: Arc<InstanceName>,
  pub gs: GameState,
  pub ipieces: IPieces,
  pub pcaliases: PieceAliases,
  pub ioccults: IOccults,
  pub clients: DenseSlotMap<ClientId, Client>,
  pub iplayers: SecondarySlotMap<PlayerId, PlayerRecord>,
  pub tokens_players: TokenRegistry<PlayerId>,
  pub tokens_clients: TokenRegistry<ClientId>,
  pub acl: LoadedAcl<TablePermission>,
  pub links: Arc<LinksTable>,
  pub bundle_list: MgmtBundleList, // copy for easy access
  pub bundle_specs: bundles::SpecsInBundles,
  pub bundle_hashes: bundles::HashCache,
  pub asset_url_key: AssetUrlKey,
  pub local_libs: shapelib::Registry,
  pub ifastsplits: IFastSplits,
}

pub struct PlayerRecord {
  pub u: PlayerUpdates,
  pub ipl: IPlayer,
  pub account: Arc<AccountName>,
}

#[derive(Debug,Clone,Serialize,Deserialize)]
pub struct IPlayer { // usual variable: ipl
  pub acctid: AccountId,
  pub tokens_revealed: HashMap<TokenRevelationKey, TokenRevelationValue>,
  pub tz: Timezone,
}

/// Strange ownership and serialisation rules, like `OccultIlkOwningId`
#[derive(Debug,Serialize,Deserialize)]
#[derive(Deref)]
pub struct IPiece {
  #[deref] pub p: IPieceTraitObj,
  pub occilk: Option<IOccultIlk>,
  #[serde(default)] pub special: PieceSpecialProperties,
}

#[derive(Debug,Serialize,Deserialize)]
#[serde(transparent)]
pub struct IPieces(ActualIPieces);
pub type ActualIPieces = SecondarySlotMap<PieceId, IPiece>;

/// Proof token that it is OK to modify the array
///
/// This exists to prevent bugs where we forget to save aux
#[derive(Copy,Clone,Debug)]
pub struct ModifyingPieces(());

#[derive(Debug,Serialize,Deserialize,Default)]
pub struct IOccults {
  pub ilks: OccultIlks,
}

#[derive(Debug,Serialize,Deserialize,Default)]
#[derive(Deref)] // No DerefMut to make sure we send updates, save, etc.
#[serde(transparent)]
pub struct GPieces(pub(in crate::global) ActualGPieces);
type ActualGPieces = DenseSlotMap<PieceId, GPiece>;

#[derive(Debug)]
pub struct Client {
  pub player: PlayerId,
  pub lastseen: Instant,
}

pub type BundlesGuard<'b> = MutexGuard<'b, InstanceBundles>;

// KINDS OF PERSISTENT STATE
//
//               TokenTable   TokenTable    GameState    Instance GameState
//                <ClientId>   <PlayerId>    .players    .pieces  .pieces
//
//   Saved        No           a-*           g-*         a-*      g-*
//   Spec TOML    Absent       table, ish    table       game     game
//
//
// UPDATE RELIABILITY/PERSISTENCE RULES
//
// From the caller's point of view
//
// We offer atomic creation/modification/destruction of:
//
//    * Games (roughtly, a map from InstanceName to GameState;
//             includes any player)
//
//    * Player access tokens, for an existing (game, player)
//
//    * Clients (for an existing (game, player)
//
// We also offer atomic destruction of:
//
//    * Games
//
//    * Players
//
// All of the above, except clients, are persistent, in the sense
// that a server restart will preserve them.  See above.
//
// The general code gets mutable access to the GameState.  We offer
// post-hoc saving of a modified game.  This should not be used for
// player changes.  For other changes, if the save fails, a server
// restart may be a rewind.  This relaxation of the rules is
// necessary avoid complicated three-phase commit on GameState update
// for routine game events.
//
// IMPLEMENTATION
//
// Games are created in this order:
//
//  save/a-<nameforfs>    MessagePack of InstanceSaveAuxiliary
//     if, on reload, this does not exist, the game is considered
//     not to exist, so at this stage the game conclusively does
//     not exist
//
//  save/g-<nameforfs>    MessagePack of GameState
//
//  games
//     can always be done right after g-<nameforfs>
//     since games update is infallible (barring unexpected panic)
//
// For the access elements such as player tokens and client
// tokents, we
//   1. check constraints against existing state
//   2. save to disk
//   3. modify in memory (infallibly)
//
// A consequence is that game creation or deletion means running
// much of this code (including game save/load) with a write lock
// onto `games`.
//
// The Instance object is inside Arc<Mutex>.  Because of Arc the Mutex
// may persist beyond the lifetime of the actual game.  So within the
// Mutex we have a field `live' that tells us if the thing is dead.
// This allows a lockholder to infallibly declare the thing dead,
// atomically from the pov of anyone else who has got a reference
// to it.  We prevent the caller from ever seeing an Instance whosae
// `live` is `false`.
#[derive(Debug)]
pub struct InstanceGuard<'g> {
  pub c: MutexGuard<'g, InstanceContainer>,
  pub gref: InstanceRef,
}

#[derive(Debug,Default)]
pub struct TokenRegistry<Id: AccessId> {
  tr: HashSet<RawToken>,
  id: PhantomData<Id>,
}

#[derive(Clone,Debug)]
pub struct InstanceAccessDetails<Id> {
  pub gref: InstanceRef,
  pub ident: Id,
  pub acctid: AccountId,
}

// ========== internal data structures ==========

lazy_static! {
  pub static ref GLOBAL: Global = default();
}

#[derive(Default)]
pub struct Global {
  // lock hierarchy: all of these are in order of acquisition
  // (in order of lock acquisition (L first), so also in order of criticality
  // (perf impact); outermost first, innermost last)

  // <- accounts::accounts ->
  games_table: RwLock<GamesTable>,

  // per-game lock:
  // <- InstanceContainer ->
  // inner locks which the game needs:
  dirty: Mutex<VecDeque<InstanceRef>>,

  // fast global lookups
  players: RwLock<TokenTable<PlayerId>>,
  clients: RwLock<TokenTable<ClientId>>,
}

pub type GamesGuard = RwLockWriteGuard<'static, GamesTable>;
pub type GamesTable = HashMap<Arc<InstanceName>, InstanceRef>;

#[derive(Debug)]
pub struct InstanceContainer {
  live: bool,
  game_dirty: bool,
  aux_dirty: bool,
  g: Instance,
}

#[derive(Debug,Default,Serialize,Deserialize)]
struct InstanceSaveAuxiliary<RawTokenStr, PiecesLoadedRef, OccultIlksRef,
                             PieceAliasesRef, IFastSplitsRef> {
  ipieces: PiecesLoadedRef,
  ioccults: OccultIlksRef,
  pcaliases: PieceAliasesRef,
  tokens_players: Vec<(RawTokenStr, PlayerId)>,
  aplayers: SecondarySlotMap<PlayerId, IPlayer>,
  acl: Acl<TablePermission>,
  pub links: Arc<LinksTable>,
  asset_url_key: AssetUrlKey,
  #[serde(default)] pub bundle_hashes: bundles::HashCache,
  #[serde(default)] ifastsplits: IFastSplitsRef,
}

pub struct PrivateCaller(());
// outsiders cannot construct this
// workaround for inability to have private trait methods
const PRIVATE_Y: PrivateCaller = PrivateCaller(());

// ========== implementations ==========

impl<'s> From<&'s str> for &'s RawTokenVal {
  // str is [u8] with a funny hat on, so &str is pointer + byte count.
  // nomicon says &SomeStruct([T]) is pointer plus number of elements.
  // So &str and &SomeStruct(str) have the same layout
  fn from(s: &str) -> &RawTokenVal { unsafe { mem::transmute(s) } }
}

impl Borrow<RawTokenVal> for RawToken {
  fn borrow(&self) -> &RawTokenVal { (&*self.0).into() }
}

impl Debug for RawTokenVal {
  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    crate::spec::imp::raw_token_debug_as_str(&self.0, f)
  }
}

impl Debug for Instance {
  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    write!(f, "Instance {{ name: {:?}, .. }}", &self.name)
  }
}

impl ModifyingPieces {
  pub fn allow_without_necessarily_saving() -> ModifyingPieces {
    ModifyingPieces(())
  }
}

// ---------- Main API for instance lifecycle ----------

impl InstanceRef {
  #[throws(GameBeingDestroyed)]
  pub fn lock(&self) -> InstanceGuard<'_> {
    let c = self.0.c.lock();
    if !c.live { throw!(GameBeingDestroyed) }
    InstanceGuard { c, gref: self.clone() }
  }

  pub fn lock_even_destroying(&self) -> MutexGuard<InstanceContainer> {
    self.0.c.lock()
  }

  pub fn downgrade_to_weak(&self) -> InstanceWeakRef {
    InstanceWeakRef(Arc::downgrade(&self.0))
  }

  pub fn lock_bundles(&self) -> MutexGuard<'_, InstanceBundles> {
    self.0.b.lock()
  }
}

impl InstanceWeakRef {
  pub fn upgrade(&self) -> Option<InstanceRef> {
    Some(InstanceRef(self.0.upgrade()?))
  }
}

#[ext(pub)]
impl<A> Unauthorised<InstanceRef, A> {
  #[throws(GameBeingDestroyed)]
  fn lock<'r>(&'r self) -> Unauthorised<InstanceGuard<'r>, A> {
    let must_not_escape = self.by_ref(Authorisation::promise_any());
    Unauthorised::of(must_not_escape.lock()?)
  }

  fn lock_even_destroying<'r>(&'r self) -> Unauthorised<InstanceGuard<'r>, A> {
    let must_not_escape = self.by_ref(Authorisation::promise_any());
    Unauthorised::of(InstanceGuard {
      c: must_not_escape.lock_even_destroying(),
      gref: must_not_escape.clone(),
    })
  }

  fn lock_bundles<'r>(&'r self) -> Unauthorised<BundlesGuard<'_>, A> {
    let must_not_escape = self.by_ref(Authorisation::promise_any());
    Unauthorised::of(must_not_escape.lock_bundles())
  }
}

impl Instance {
  /// Returns `None` if a game with this name already exists
  #[allow(clippy::new_ret_no_self)]
  #[throws(MgmtError)]
  pub fn new(name: InstanceName, gs: GameState,
             games: &mut GamesGuard,
             acl: LoadedAcl<TablePermission>, _: Authorisation<InstanceName>)
             -> InstanceRef {
    let name = Arc::new(name);

    let g = Instance {
      name: name.clone(),
      gs, acl,
      ipieces: IPieces(default()),
      pcaliases: default(),
      ioccults: default(),
      clients: default(),
      iplayers: default(),
      tokens_players: default(),
      tokens_clients: default(),
      links: default(),
      bundle_list: default(),
      bundle_specs: default(),
      bundle_hashes: default(),
      asset_url_key: AssetUrlKey::new_random()?,
      local_libs: default(),
      ifastsplits: default(),
    };

    let c = InstanceContainer {
      live: true,
      game_dirty: false,
      aux_dirty: false,
      g,
    };

    let c = Mutex::new(c);
    let b = Mutex::new(InstanceBundles::new());
    let gref = InstanceRef(Arc::new(InstanceOuter { c, b }));
    let mut ig = gref.lock()?;

    let entry = games.entry(name);

    use hash_map::Entry::*;
    let entry = match entry {
      Vacant(ve) => ve,
      Occupied(_) => throw!(ME::AlreadyExists),
    };

    ig.save_aux_now()?;
    ig.save_game_now()?;

    (||{
      entry.insert(gref.clone());
    })(); // <- No ?, ensures that IEFE is infallible (barring panics)

    ig.gref
  }

  #[throws(MgmtError)]
  pub fn lookup_by_name_locked_unauth
    (games_table: &GamesTable, name: &InstanceName)
     -> Unauthorised<InstanceRef, InstanceName>
  {
    Unauthorised::of(
      games_table
        .get(name)
        .ok_or(ME::GameNotFound)?
        .clone()
    )
  }

  #[throws(MgmtError)]
  pub fn lookup_by_name_locked(games: &GamesTable,
                               name: &InstanceName,
                               auth: Authorisation<InstanceName>)
                               -> InstanceRef {
    Self::lookup_by_name_locked_unauth(games, name)?.by(auth)
  }

  #[throws(MgmtError)]
  pub fn lookup_by_name_unauth(name: &InstanceName)
      -> Unauthorised<InstanceRef, InstanceName>
  {
    let games = GLOBAL.games_table.read();
    Self::lookup_by_name_locked_unauth(&games, name)?
  }

  #[throws(MgmtError)]
  pub fn lookup_by_name(name: &InstanceName, auth: Authorisation<InstanceName>)
                        -> InstanceRef {
    Self::lookup_by_name_unauth(name)?.by(auth)
  }

  #[throws(InternalError)]
  pub fn destroy_game(games: &mut GamesGuard,
                      mut g: MutexGuard<InstanceContainer>,
                      _: Authorisation<InstanceName>) {
    let a_savefile = savefilename(&g.g.name, "a-", "");
    let b_dir = bundles::b_dir(&g.g.name);

    let g_file = savefilename(&g.g.name, "g-", "");
    fs::remove_file(&g_file).context("remove").context(g_file)?;

    (||{ // Infallible:
      g.live = false;
      games.remove(&g.g.name);
      InstanceGuard::forget_all_tokens(&mut g.g.tokens_clients);
      InstanceGuard::forget_all_tokens(&mut g.g.tokens_players);

      InstanceBundles::truncate_all_besteffort(&g.g.name);

      fn best_effort<F>(rm: F, path: &str, desc: &str)
      where F: FnOnce(&str) -> Result<(), io::Error>
      {
        rm(path)
          .unwrap_or_else(
            |e| warn!("failed to delete stale {} {:?}: {:?}",
                      desc, path, e)
            // apart from that, ignore the error
            // load_games will clean it up later.
          );
      }
      best_effort(|f| fs::remove_file(f), &a_savefile, "auth file");
      best_effort(|f| fs::remove_dir_all(f), &b_dir, "bundles dir");

    })(); // <- No ?, ensures that IEFE is infallible (barring panics)
  }

  pub fn list_names(account: Option<&AccountName>,
                    _: Authorisation<AccountName>)
                    -> Vec<Arc<InstanceName>> {
    let games = GLOBAL.games_table.read();
    let out: Vec<Arc<InstanceName>> =
      games.keys()
      .filter(|k| account == None || account == Some(&k.account))
      .cloned()
      .collect();
    out
  }

  #[throws(InternalError)]
  pub fn player_info_pane(&self) -> Html {
    #[derive(Serialize,Debug)]
    struct RenderContext<'r> {
      players: Vec<RenderPlayer<'r>>,
    }
    #[derive(Serialize,Debug)]
    struct RenderPlayer<'r> {
      player_num: u32,
      nick: &'r str,
      account: &'r AccountName,
    }
    let players = self.gs.players.iter().filter_map(|(player, gpl)| {
      let ipl = self.iplayers.get(player)?;
      let (idx, _) = player.data().get_idx_version();
      Some(RenderPlayer {
        player_num: idx,
        nick: &gpl.nick,
        account: &ipl.account,
      })
    }).collect::<Vec<_>>();
    let render = RenderContext { players };
    let html = Html::from_html_string(
      nwtemplates::render("player-info-pane.tera", &render)
        .context("render player info template")?
    );
    html
  }

  pub fn dummy() -> Instance {
    Instance {
      name: Arc::new("server::".parse().unwrap()),
      gs: GameState::dummy(),
      ipieces: IPieces(default()),
      pcaliases: default(),
      ioccults: default(),
      clients: default(),
      tokens_players: default(),
      tokens_clients: default(),
      acl: default(),
      links: default(),
      bundle_list: default(),
      bundle_specs: default(),
      bundle_hashes: default(),
      asset_url_key: AssetUrlKey::Dummy,
      local_libs: default(),
      iplayers: default(),
      ifastsplits: default(),
    }
  }

}

pub fn games_lock() -> RwLockWriteGuard<'static, GamesTable> {
  GLOBAL.games_table.write()
}

// ---------- Simple trait implementations ----------

deref_to_field_mut!{InstanceGuard<'_>, Instance, c.g}

impl FromStr for AccountScope {
  type Err = InvalidScopedName;
  #[throws(InvalidScopedName)]
  fn from_str(s: &str) -> Self {
    let scope = AccountScope::parse_name(s, &mut [])?;
    scope
  }
}

impl FromStr for InstanceName {
  type Err = InvalidScopedName;
  #[throws(InvalidScopedName)]
  fn from_str(s: &str) -> Self {
    let mut names: [_;2] = default();
    let scope = AccountScope::parse_name(s, &mut names)?;
    let [subaccount, game] = names;
    InstanceName {
      account: AccountName { scope, subaccount },
      game,
    }
  }
}

impl Display for InstanceName {
  #[throws(fmt::Error)]
  fn fmt(&self, f: &mut fmt::Formatter) {
    self.account.scope.display_name(
      &[ self.account.subaccount.as_str(), self.game.as_str() ],
      |s| f.write_str(s),
    )?
  }
}
hformat_as_display!{InstanceName}

impl DebugIdentify for InstanceContainer {
  #[throws(fmt::Error)]
  fn debug_identify(&self, f: &mut fmt::Formatter) {
    write!(f, "InstanceContainer({})", &self.g.name)?;
  }
  #[throws(fmt::Error)]
  fn debug_identify_type(f: &mut fmt::Formatter) {
    write!(f, "InstanceContainer")?;
  }
}

impl DebugIdentify for InstanceRef {
  #[throws(fmt::Error)]
  fn debug_identify_type(f: &mut fmt::Formatter) {
    write!(f, "InstanceRef")?;
  }
}

fn link_a_href(k: &HtmlStr, v: &str) -> Html {
  hformat!("<a href={}>{}</a>", v, k)
}
#[ext(pub)]
impl (LinkKind, &str) {
  fn to_html(self) -> Html {
    let (k, v) = self;
    link_a_href(&k.to_html(), v)
  }
}

impl From<&LinksTable> for Html {
  fn from(links: &LinksTable) -> Html {
    let mut s = links.iter()
      .filter_map(|(k,v)| {
        let v = v.as_ref()?;
        Some((k, v.as_str()).to_html())
      })
      .chain(iter::once(
        link_a_href(Html::lit("Shapelib").into(), "/_/shapelib.html")
      ))
      .collect::<Vec<Html>>()
      .iter()
      .hjoin(&Html::lit(" "));
    if s.len() != 0 { s = hformat!("links: {}", s) }
    s
  }
}

// ---------- Player and token functionality ----------

impl<Id> InstanceAccessDetails<Id>
  where Id: AccessId, Fatal: From<Id::Error>
{
  #[throws(Fatal)]
  pub fn from_token(token: &RawTokenVal) -> InstanceAccessDetails<Id> {
    let g = Id::global_tokens(PRIVATE_Y).read();
    let i = g.get(token).ok_or(Id::ERROR)?;
    i.clone()
  }
}

impl<'ig> InstanceGuard<'ig> {
  /// Core of piece deletion
  ///
  /// Caller is completely responsible for the necessary log entries.
  ///
  /// Idempotent (so does not detect if the piece didn't exist,
  /// other than by passing `None`s to the callback.
  #[throws(IE)]
  pub fn delete_piece<H,T>(&mut self, modperm: ModifyingPieces,
                             to_permute: &mut ToRecalculate,
                             piece: PieceId, hook: H)
                             -> (T, PieceUpdateOp<(),()>, UnpreparedUpdates)
  where H: FnOnce(&IOccults, &GOccults,
                  Option<&IPiece>, Option<&GPiece>) -> T
  {
    let ig = &mut **self;
    let gs = &mut ig.gs;
    let gpc = gs.pieces.as_mut(modperm).get_mut(piece);
    let mut xupdates = vec![];
    if let Some(gpc) = gpc {
      gpc.occult.passive_delete_hook(&mut gs.occults, piece);
      if gpc.occult.is_active() {
        xupdates.append(
          &mut
            remove_occultation(
              &mut gs.gen.unique_gen(),
              &mut gs.players,
              &mut gs.pieces,
              &mut gs.occults,
              &ig.ipieces,
              &ig.ioccults,
              to_permute,
              piece)?
        );
      }
    }
    let ioccults = &ig.ioccults;
    let gpc = gs.pieces.as_mut(modperm).remove(piece);
    let ipc = ig.ipieces.as_mut(modperm).remove(piece);

    let hook_r = hook(ioccults, &gs.occults,
                      ipc.as_ref(), gpc.as_ref());

    if let Some(ipc) = ipc {
      if let Some(gpc) = gpc {
        ipc.p.into_inner().delete_hook(&gpc, gs);
      }
      if let Some(occilk) = ipc.occilk {
        ig.ioccults.ilks.dispose_iilk(occilk);
      }
    }

    (hook_r, PieceUpdateOp::Delete(), xupdates.into_unprepared(None))
  }

  /// caller is responsible for logging; threading it through
  /// proves the caller has a log entry.
  #[throws(MgmtError)]
  pub fn player_new(&mut self, gnew: GPlayer, inew: IPlayer,
                    account: Arc<AccountName>, logentry: LogEntry)
                    -> (PlayerId, PreparedUpdateEntry, LogEntry) {
    // saving is fallible, but we can't attempt to save unless
    // we have a thing to serialise with the player in it
    self.check_new_nick(&gnew.nick)?;
    if self.c.g.iplayers.values().any(|r| r.ipl.acctid == inew.acctid) {
      Err(ME::AlreadyExists)?;
    }
    let player = self.c.g.gs.players.insert(gnew);
    let u = PlayerUpdates::start(&self.c.g.gs).for_player();
    let record = PlayerRecord { u, account, ipl: inew, };

    self.c.g.iplayers.insert(player, record);

    let update = (||{
      let update = self.prepare_set_player_update(player)?;
      self.save_game_now()?;
      self.save_aux_now()?;
      Ok::<_,InternalError>(update)
    })().map_err(|e|{
      self.c.g.iplayers.remove(player);
      self.c.g.gs.players.remove(player);
      // Perhaps we leave the g-* file with this player recorded,
      // but this will be ignored when we load.
      e
    })?;
    (||{
      
    })(); // <- No ?, ensures that IEFE is infallible (barring panics)
    (player, update, logentry)
  }

  #[throws(MgmtError)]
  pub fn check_new_nick(&mut self, new_nick: &str) {
    if self.c.g.gs.players.values().any(|old| old.nick == new_nick) {
      Err(ME::NickCollision)?;
    }
  }

  #[throws(IE)]
  pub fn prepare_set_player_update(&self, player: PlayerId)
                                   -> PreparedUpdateEntry {
    let new_info_pane = Arc::new(self.player_info_pane()?);
    PreparedUpdateEntry::SetPlayer {
      player, new_info_pane,
      data: DataLoadPlayer::from_player(self, player),
    }
  }

  pub fn remove_clients(&mut self,
                        players: &HashSet<PlayerId>,
                        signal: ErrorSignaledViaUpdate<PUE_P, String>) {
    let mut clients_to_remove = HashSet::new();
    self.clients.retain(|k,v| {
      let remove = players.contains(&v.player);
      if remove { clients_to_remove.insert(k); }
      !remove
    });

    let gen = self.c.g.gs.gen;
    for &player in players {
      if let Some(iplayer) = self.iplayers.get_mut(player) {
        iplayer.u.push(PreparedUpdate {
          gen,
          when: Instant::now(),
          us: vec![ PreparedUpdateEntry::Error(
            signal.clone(),
          )],
        });
      };
    }
    self.tokens_deregister_for_id(|id| clients_to_remove.contains(&id));
  }

  //  #[throws(InternalError)]
  //  https://github.com/withoutboats/fehler/issues/62
  pub fn players_remove(&mut self, old_players_set: &HashSet<PlayerId>)
                        ->
    Result<Vec<
        (Option<GPlayer>, Option<IPlayer>, PreparedUpdateEntry)
        >, InternalError>
  {
    // We have to filter this player out of everything
    // Then save
    // Then send updates
    // We make a copy so if the save fails, we can put everything back

    let mut players = self.c.g.gs.players.clone();
    let old_players: Vec<_> = old_players_set.iter().cloned().collect();
    let old_gpls: Vec<_> = old_players.iter().cloned().map(|oldplayer| {
      players.remove(oldplayer)
    }).collect();

    // New state
    let mut gs = GameState {
      // These parts are straightforward and correct
      table_colour: self.c.g.gs.table_colour.clone(),
      table_size: self.c.g.gs.table_size,
      gen: self.c.g.gs.gen,
      max_z: self.gs.max_z.clone(),
      players,
      // These have special handling
      log: default(),
      pieces: default(),
      occults: default(),
    };

    let held_by_old = |p: &GPiece| if_chain! {
      if let Some(held) = p.held;
      if old_players_set.contains(&held);
      then { true }
      else { false }
    };

    let mut updated_pieces = vec![];

    // drop order is reverse of creation order, so create undo
    // after all the things it will reference
    let mut undo: Vec<Box<dyn FnOnce(&mut InstanceGuard)>> = vec![];

    // Arrange gs.pieces
    for (piece,p) in &mut self.c.g.gs.pieces {
      if held_by_old(p) {
        p.held = None;
        updated_pieces.push(piece);
      }
    }
    undo.push(Box::new(|ig| for &piece in &updated_pieces {
      (||Some({
        held_by_old(ig.c.g.gs.pieces.get_mut(piece)?);
      }))();
    }));

    // Handle gs.log:
    // Installs gs as the new game state, stealing the log and pieces
    let mut swap_things = |ig: &mut InstanceGuard| {
      mem::swap(&mut ig.c.g.gs.log,    &mut gs.log   );
      mem::swap(&mut ig.c.g.gs.pieces, &mut gs.pieces);
      mem::swap(&mut ig.c.g.gs.occults,&mut gs.occults);
      mem::swap(&mut ig.c.g.gs,        &mut gs,   );
    };
    swap_things(self);
    undo.push(Box::new(swap_things));

    let new_info_pane = Arc::new(self.player_info_pane()?);

    self.save_game_now().map_err(|e|{
      // oof
      #[allow(clippy::iter_with_drain)] // don't eat undo, so we can drop it
      for u in undo.drain(..).rev() {
        u(self);
      }
      e
    })?;

    // point of no return
    mem::drop(undo);

    let old_ipls = (||{
      for &piece in &updated_pieces {
        (||Some({
          self.c.g.gs.pieces.get_mut(piece)?.gen = self.c.g.gs.gen;
        }))();
      }

      let estimate = updated_pieces.len() + 1;
      let mut buf = PrepareUpdatesBuffer::new(self, Some(estimate));
      for &piece in &updated_pieces {
        buf.piece_update(piece, &None, PieceUpdateOp::Modify(()).into());
      }
      buf.finish();

      self.remove_clients(old_players_set, ESVU::PlayerRemoved);
      self.tokens_deregister_for_id(
        |id:PlayerId| old_players_set.contains(&id)
      );
      let old_ipls: Vec<_> = old_players.iter().cloned().map(
        |oldplayer| self.iplayers.remove(oldplayer)
          .map(|ipr| ipr.ipl)
      ).collect();
      self.save_aux_now().unwrap_or_else(
        |e| warn!(
          "trouble garbage collecting accesses for deleted player: {:?}",
          &e)
      );
      old_ipls
    })(); // <- No ?, ensures that IEFE is infallible (barring panics)

    let updates = old_players.iter().cloned().map(
      |player| PreparedUpdateEntry::RemovePlayer {
        player,
        new_info_pane: new_info_pane.clone(),
      }
    );

    let old = izip!(
      old_gpls,
      old_ipls,
      updates
    ).collect();

    Ok(old)
  }

  #[throws(InternalError)]
  pub fn invalidate_tokens(&mut self, player: PlayerId) {
    let old_tokens = TokenRegistry {
      tr: self.tokens_players.tr.clone(),
      id: self.tokens_players.id,
    };
    self.tokens_deregister_for_id(|id:PlayerId| id==player);
    self.save_aux_now().map_err(|e|{
      // oof, the tokens are already out of the global map, but
      // not saved, so they might come back.  We need to leave
      // them here so they can be deleted later.
      self.tokens_players = old_tokens;
      e
    })?;
    // ppoint of no return
    (||{
      self.remove_clients(&[player].iter().cloned().collect(),
                          ESVU::TokenRevoked);
    })(); // <- No ?, ensures that IEFE is infallible (barring panics)
  }

  #[throws(MgmtError)]
  fn player_access_reset_redeliver(&mut self,
                                   accounts: &mut AccountsGuard,
                                   player: PlayerId,
                                   _auth: Authorisation<AccountName>,
                                   reset: bool)
                                   -> AccessTokenReport {
    let acctid = self.iplayers.byid(player)?.ipl.acctid;

    let access = {
      let (acct, _) = accounts.lookup(acctid)?;
      let access = acct.access.clone();
      let desc = access.describe_html();
      let now = Timestamp::now();
      let revk = TokenRevelationKey {
        account: (*acct.account).clone(),
        desc,
      };
      self.iplayers.byid_mut(player)?.ipl.tokens_revealed.entry(revk)
        .or_insert(TokenRevelationValue {
          latest: now,
          earliest: now,
        })
        .latest = now;
      access
    };

    let current_tokens: ArrayVec<&RawToken,2> = {
      let players = GLOBAL.players.read();
      self.tokens_players.tr.iter().
        filter(|&token| (||{
          let iad = players.get(token)?;
          if iad.ident != player { return None }
          if ! Arc::ptr_eq(&iad.gref.0, &self.gref.0) { return None }
          Some(())
        })() == Some(()))
        .take(2)
        .collect()
    };

    let reset = reset || current_tokens.is_empty();

    let token: RawToken = if reset {
      drop(current_tokens);

      self.invalidate_tokens(player)?;
      self.save_aux_now()?;

      let token = access
        .override_token()
        .cloned()
        .unwrap_or_else(||{
          RawToken::new_random()
        });
        
      let iad = InstanceAccessDetails {
        gref: self.gref.clone(),
        ident: player,
        acctid
      };
      self.token_register(token.clone(), iad);
      self.save_aux_now()?;

      token

    } else {

      let token = match current_tokens.as_slice() {
        [] => panic!(), // this possibility was excluded earlier
        [token] => token,
        _ => {
          warn!("duplicate token for {}", player);
          throw!(ME::ServerFailure("duplicate token".to_string()));
        }
      };

      (*token).clone()
    };

    let ipl = &self.c.g.iplayers.byid(player)?.ipl;
    let gpl = self.c.g.gs.players.byid(player)?;

    let url = format!("{}/?{}",
                      &config().public_url.trim_end_matches('/'),
                      token.0);
    let info = AccessTokenInfo { url };
    let report = access.deliver(accounts, &self.c.g, gpl, ipl, info)?;
    report
  }

  #[throws(MgmtError)]
  pub fn player_access_reset(&mut self,
                             accounts: &mut AccountsGuard,
                             player: PlayerId,
                             auth: Authorisation<AccountName>)
                             -> AccessTokenReport {
    self.player_access_reset_redeliver(accounts, player, auth, true)?
  }

  #[throws(MgmtError)]
  pub fn player_access_redeliver(&mut self,
                                 accounts: &mut AccountsGuard,
                                 player: PlayerId,
                                 auth: Authorisation<AccountName>)
                                 -> AccessTokenReport {
    self.player_access_reset_redeliver(accounts, player, auth, false)?
  }

  pub fn modify_pieces(&mut self) -> ModifyingPieces {
    self.save_game_and_aux_later();
    // want this to be borrowed from self, so that we tie it properly
    // to the same game.  But in practice we don't expect to write
    // bugs where we get different games mixed up.  Borrowing self
    // from the caller's pov is troublesome beczuse ultimately the
    // caller will need to manipulate various fields of Instance (so
    // we mustn't have a borrow of it).
    ModifyingPieces(())
  }

  pub fn modify_pieces_not_necessarily_saving_aux(&mut self)
                                                  -> ModifyingPieces {
    self.save_game_later();
    ModifyingPieces(())
  }

  fn token_register<Id:AccessId>(
    &mut self,
    token: RawToken,
    iad: InstanceAccessDetails<Id>
  ) {
    Id::tokens_registry(&mut self.c.g, PRIVATE_Y).tr.insert(token.clone());
    Id::global_tokens(PRIVATE_Y).write().insert(token, iad);
  }

  fn forget_all_tokens<Id:AccessId>(tokens: &mut TokenRegistry<Id>) {
    let global: &RwLock<TokenTable<Id>> = AccessId::global_tokens(PRIVATE_Y);
    let mut global = global.write();
    for t in tokens.tr.drain() { global.remove(&t); }
  }

  fn tokens_deregister_for_id<Id:AccessId, F: Fn(Id) -> bool
                              > (&mut self, oldid: F) {
    let mut tokens = AccessId::global_tokens(PRIVATE_Y).write();
    tokens.retain(|k,v| if_chain! {
      if oldid(v.ident);
      if Id::tokens_registry(self, PRIVATE_Y).tr.remove(k);
      then { false }
      else { true }
    });
  }

}

// ---------- save/load ----------

#[derive(Copy,Clone,Debug)]
enum SaveFileOrDir { File, Dir }

impl SaveFileOrDir {
  #[throws(io::Error)]
  fn remove<P:AsRef<std::path::Path>>(self, path: P) {
    match self {
      SaveFileOrDir::File => fs::remove_file(path)?,
      SaveFileOrDir::Dir  => fs::remove_dir_all(path)?,
    }
  }
}

#[derive(Debug)]
enum SavefilenameParseResult {
  NotGameFile,
  Auxiliary(SaveFileOrDir),
  TempToDelete,
  GameFile {
    aux_leaves: Vec<Vec<u8>>,
    name: InstanceName,
  },
}

pub fn savefilename(name: &InstanceName, prefix: &str, suffix: &str)
                    -> String {
  [ config().save_dir().as_str(), "/", prefix ]
    .iter().map(Deref::deref)
    .chain(iter::once( name.to_string().as_str() ))
    .chain([ suffix ].iter().map(Deref::deref))
    .collect()
}

#[throws(anyhow::Error)]
fn savefilename_parse(leaf: &[u8]) -> SavefilenameParseResult {
  use SavefilenameParseResult::*;

  if leaf.starts_with(b"a-") { return Auxiliary(SaveFileOrDir::File) }
  if leaf.starts_with(b"b-") { return Auxiliary(SaveFileOrDir::Dir ) }
  let rhs = match leaf.strip_prefix(b"g-") {
    Some(rhs) => rhs,
    None => return NotGameFile,
  };
  let after_ftype_prefix = rhs;
  let rhs = str::from_utf8(rhs)?;
  let rcomp = rhs.rsplitn(2, ':').next().unwrap();
  if rcomp.find('.').is_some() { return TempToDelete }

  let name = InstanceName::from_str(rhs)?;

  let aux_leaves = [ b"a-", b"b-" ].iter().map(|prefix| {
    let mut s: Vec<_> = (prefix[..]).into(); s.extend(after_ftype_prefix); s
  }).collect();
  GameFile { name, aux_leaves }
}

impl InstanceGuard<'_> {
  #[throws(InternalError)]
  fn save_something(
    &self, prefix: &str,
    w: fn(s: &Self, w: &mut BufWriter<fs::File>)
          -> Result<(),rmp_serde::encode::Error>
  ) {
    let tmp = savefilename(&self.name, prefix,".tmp");
    let f = fs::File::create(&tmp)
      .with_context(||format!("save: create {:?}",&tmp))?;
    let mut f = BufWriter::new(f);
    w(self, &mut f)?;
    f.flush()
      .with_context(||format!("save: flush {:?}",&tmp))?;
    drop(
      f.into_inner().map_err(|e| { let e: io::Error = e.into(); e })
        .with_context(||format!("save: close {:?}",&tmp))?
    );
    let out = savefilename(&self.name, prefix,"");
    fs::rename(&tmp, &out).context("install")
      .with_context(||format!("save: install {:?} as {:?}", &tmp, &out))?;
    debug!("saved to {}", &out);
  }

  #[throws(InternalError)]
  pub fn save_game_now(&mut self) {
    if self.c.aux_dirty {
      self.save_aux_now()?;
    }
    self.save_something("g-", |s,w| {
      rmp_serde::encode::write_named(w, &s.c.g.gs)
    })?;
    self.c.game_dirty = false;
    debug!("saved (now) {}", &self.name);
  }

  #[throws(InternalError)]
  pub fn save_aux_now(&mut self) {
    self.save_something("a-", |s, w| {
      let ipieces = &s.c.g.ipieces;
      let ioccults = &s.c.g.ioccults;
      let pcaliases = &s.c.g.pcaliases;
      let ifastsplits = &s.c.g.ifastsplits;
      let tokens_players: Vec<(&str, PlayerId)> = {
        let global_players = GLOBAL.players.read();
        s.c.g.tokens_players.tr
          .iter()
          .filter_map(|token|
               global_players.get(token)
               .map(|player| (token.0.as_str(), player.ident)))
          .collect()
      };
      let aplayers = s.c.g.iplayers.iter().map(
        |(player, PlayerRecord { ipl, .. })|
        (player, ipl.clone())
      ).collect();
      let acl = s.c.g.acl.clone().into();
      let links = s.c.g.links.clone();
      let asset_url_key = s.c.g.asset_url_key.clone();
      let bundle_hashes = s.c.g.bundle_hashes.clone();
      let isa = InstanceSaveAuxiliary {
        ipieces, ioccults, tokens_players, aplayers, acl, links,
        pcaliases, asset_url_key, bundle_hashes, ifastsplits,
      };
      rmp_serde::encode::write_named(w, &isa)
    })?;
    self.c.aux_dirty = false;
    info!("saved aux for {}", &self.name);
  }

  #[throws(InternalError)]
  fn load_something<T:DeserializeOwned>(name: &InstanceName, prefix: &str)
                                        -> T {
    let inp = savefilename(name, prefix, "");
    let f = fs::File::open(&inp).with_context(|| inp.clone())?;
    let mut f = BufReader::new(f);
    let thing = rmp_serde::decode::from_read(&mut f)?;
    debug!("loaded from {:?}", &inp);
    thing
  }

  #[throws(StartupError)]
  fn load_game(accounts: &AccountsGuard,
               games: &mut GamesGuard,
               name: InstanceName) -> Option<InstanceRef> {
    let InstanceSaveAuxiliary::
    <String,ActualIPieces,IOccults,PieceAliases,IFastSplits> {
      tokens_players, mut ipieces, mut ioccults, mut aplayers, acl, links,
      pcaliases, asset_url_key, bundle_hashes, mut ifastsplits,
    } = match Self::load_something(&name, "a-") {
      Ok(data) => data,
      Err(e) => if (||{
        let ae = match &e { InternalError::Anyhow(ae) => Some(ae), _=>None }?;
        let ioe = ae.downcast_ref::<io::Error>()?;
        let is_enoent = ioe.kind() == io::ErrorKind::NotFound;
        is_enoent.as_option()
      })().is_some() {
        return None;
      } else {
        throw!(e);
      },
    };

    let mut gs: GameState = Self::load_something(&name, "g-")?;

    fn discard_mismatches<K:slotmap::Key, V1, V2>(
      primary:   &mut DenseSlotMap<K, V1>,
      secondary: &mut SecondarySlotMap<K, V2>,
    ) {
      primary.retain(|k,_v| secondary.contains_key(k));
      secondary.retain(|k,_v| primary.contains_key(k));
    }

    for (piece, gpc) in &mut gs.pieces.0 {
      if_let!{ Some(fsid) = gpc.fastsplit; else continue; }

      // We must recover the ipc via the fastsplit table, or delete
      if_chain!{
        let ilks = &mut ioccults.ilks;
        if let Some(recovered_ipc) = ifastsplits.recover_ipc(ilks, fsid);
        then {
          if_chain!{
            if let Some(old_ipc) = ipieces.get_mut(piece);
            // We're about to overwrite this ipc, maybe owns some occilk.
            // If in fact we're the same kind, we've already acquired
            // another refcount from recover_ipc, above.
            if let Some(old_iilk) = old_ipc.occilk.take();
            then { ilks.dispose_iilk(old_iilk); }
          }
          ipieces.insert(piece, recovered_ipc);
        } else {
          // Not available in ipieces, fastsplit family must just have
          // been added.  This will get rid of it from gpieces, too, below.
          ipieces.remove(piece);
        }
      }
    }
    ifastsplits.cleanup(&mut ioccults.ilks);

    discard_mismatches(&mut gs.players,  &mut aplayers);
    discard_mismatches(&mut gs.pieces.0, &mut ipieces);
  
    let pu_bc = PlayerUpdates::start(&gs);

    let iplayers: SecondarySlotMap<PlayerId, PlayerRecord> = {
      let a = aplayers;
      a.into_iter()
    }.filter_map(|(player, ipl)| {
      let u = pu_bc.for_player();
      let account = accounts.lookup(ipl.acctid).ok()?.0.account.clone();
      Some((player, PlayerRecord { u, ipl, account }))
    }).collect();

    for mut p in gs.pieces.values_mut() {
      p.lastclient = default();
      if let Some(held) = p.held {
        if !gs.players.contains_key(held) { p.held = None }
      }
    }

    let name = Arc::new(name);
    let (tokens_players, acctids_players) = {
      let mut tokens = Vec::with_capacity(tokens_players.len());
      let mut acctids = Vec::with_capacity(tokens_players.len());
      for (token, player) in tokens_players { if_chain! {
        if let Some(record) = iplayers.get(player);
        then {
          tokens.push((token, player));
          acctids.push(record.ipl.acctid);
        }
      }}
      (tokens, accounts.bulk_check(&acctids))
    };

    let mut g = Instance {
      gs, iplayers, links,
      acl: acl.into(),
      ipieces: IPieces(ipieces),
      pcaliases,
      ioccults,
      name: name.clone(),
      clients: default(),
      tokens_clients: default(),
      tokens_players: default(),
      bundle_list: default(), // set by load_game_bundles
      local_libs: default(), // set by load_game_bundles
      bundle_specs: default(), // set by load_game_bundles
      asset_url_key,
      bundle_hashes,
      ifastsplits,
    };

    let b = InstanceBundles::reload_game_bundles(&mut g)?;
    let b = Mutex::new(b);

    let c = InstanceContainer {
      live: true,
      game_dirty: false,
      aux_dirty: false,
      g,
    };
    let c = Mutex::new(c);
    let gref = InstanceRef(Arc::new(InstanceOuter { c, b }));
    let mut g = gref.lock().unwrap();

    let ig = &mut *g;
    for (piece, ipc) in ig.ipieces.0.iter() {
      ipc.direct_trait_access()
        .save_reloaded_hook(piece, &mut ig.gs, &gref)?;
    }

    for (token, _) in &tokens_players {
      g.tokens_players.tr.insert(RawToken(token.clone()));
    }
    let mut global = GLOBAL.players.write();
    for ((token, player), acctid) in
      tokens_players.into_iter()
      .zip(acctids_players)
    { if_chain!{
      if let Some(acctid) = acctid;
      let iad = InstanceAccessDetails {
        acctid,
        gref: gref.clone(),
        ident: player,
      };
      then { global.insert(RawToken(token), iad); }
    } }
    drop(global);
    drop(g);
    games.insert(name.clone(), gref.clone());
    info!("loadewd {:?}", &name);
    Some(gref)
  }
}

#[throws(anyhow::Error)]
pub fn load_games(accounts: &mut AccountsGuard,
                  games: &mut GamesGuard) {
  enum AFState { Found(PathBuf, SaveFileOrDir), Used }
  use AFState::*;
  use SavefilenameParseResult::*;
  let mut a_leaves = HashMap::new();
  let save_dir = config().save_dir().clone();
  for de in fs::read_dir(&save_dir).context(save_dir)? {
    let de = de?;
    let leaf = de.file_name();
    (||{
      let leaf = leaf.as_bytes();
      match savefilename_parse(leaf)? {
        NotGameFile => {
        }
        TempToDelete => {
          fs::remove_file(de.path())
            .context("stale temporary file")?;
        }
        Auxiliary(fd) => {
          a_leaves.entry(leaf.to_owned()).or_insert_with(
            || Found(de.path(), fd)
          );
        }
        GameFile { aux_leaves, name } => {
          InstanceGuard::load_game(accounts, games, name)?;
          for aux_leaf in aux_leaves {
            a_leaves.insert(aux_leaf, Used);
          }
        }
      }
      <Result<_,anyhow::Error>>::Ok(())
    })().with_context(|| format!("leaf={:?}", leaf))?;
  }
  (||{
    for (leaf, state) in &a_leaves {
      if let Found(path, fd) = state {
        fd.remove(&path)
          .with_context(|| format!("leaf={:?}", leaf))?;
      }
    }
    <Result<_,anyhow::Error>>::Ok(())
  })().context("cleaning up stale files")?;
  info!("loaded games");
}

// ---------- Tokens / TokenTable / AccessId ----------

pub type TokenTable<Id> = HashMap<RawToken, InstanceAccessDetails<Id>>;

pub trait AccessId: Copy + Clone + 'static {
  type Error: Into<Fatal>;
  const ERROR: Self::Error;
  fn global_tokens(_:PrivateCaller) -> &'static RwLock<TokenTable<Self>>;
  fn tokens_registry(ig: &mut Instance, _:PrivateCaller)
                     -> &mut TokenRegistry<Self>;
}

#[derive(Debug,Copy,Clone,Eq,PartialEq,Ord,PartialOrd)]
#[derive(Serialize,Deserialize)]
#[derive(Error)]
#[error("Player not found")]
pub struct PlayerNotFound;

impl AccessId for PlayerId {
  type Error = PlayerNotFound;
  const ERROR: PlayerNotFound = PlayerNotFound;
  fn global_tokens(_: PrivateCaller) -> &'static RwLock<TokenTable<Self>> {
    &GLOBAL.players
  }
  fn tokens_registry(ig: &mut Instance, _:PrivateCaller)
                     -> &mut TokenRegistry<Self> {
    &mut ig.tokens_players
  }
}
impl AccessId for ClientId {
  type Error = Fatal;
  const ERROR: Fatal = NoClient;
  fn global_tokens(_: PrivateCaller) -> &'static RwLock<TokenTable<Self>> {
    &GLOBAL.clients
  }
  fn tokens_registry(ig: &mut Instance, _:PrivateCaller)
                     -> &mut TokenRegistry<Self> {
    &mut ig.tokens_clients
  }
}

impl RawToken {
  fn new_random() -> Self {
    let mut rng = thread_rng();
    let token = RawToken (
      repeat_with(|| rng.sample(Alphanumeric))
        .map(char::from)
        .take(64).collect()
    );
    token
  }
}

pub fn lookup_token<Id:AccessId>(s: &RawTokenVal)
      -> Result<InstanceAccessDetails<Id>, Id::Error> {
  Id::global_tokens(PRIVATE_Y).read().get(s).cloned()
    .ok_or(Id::ERROR)
}

#[throws(Fatal)]
pub fn record_token<Id:AccessId> (
  ig: &mut InstanceGuard,
  iad: InstanceAccessDetails<Id>
) -> RawToken {
  let token = RawToken::new_random();
  ig.token_register(token.clone(), iad);
  token
}

#[throws(E)]
pub fn process_all_players_for_account<
    E: Error,
    F: FnMut(&mut InstanceGuard<'_>, PlayerId) -> Result<(),E>
    >
  (games: &mut GamesGuard, acctid: AccountId, mut f: F)
{
  for gref in games.values() {
    let c = gref.lock_even_destroying();
    let remove: Vec<_> = c.g.iplayers.iter().filter_map(|(player,pr)| {
      if pr.ipl.acctid == acctid { Some(player) } else { None }
    }).collect();
    let mut ig = InstanceGuard { gref: gref.clone(), c };
    for player in remove.into_iter() {
      f(&mut ig, player)?;
    }
  }
}

// ========== instance pieces data access ==========

impl IPieces {
  pub fn get(&self, piece: PieceId) -> Option<&IPiece> {
    self.0.get(piece)
  }

  pub fn as_mut(&mut self, _: ModifyingPieces) -> &mut ActualIPieces {
    &mut self.0
  }

  pub fn is_empty(&self) -> bool {
    let IPieces(actual) = self;
    actual.is_empty()
  }
}

// ---------- gamestate pieces table ----------

impl GPieces {
  pub fn get_mut(&mut self, piece: PieceId) -> Option<&mut GPiece> {
    self.0.get_mut(piece)
  }
  pub fn values_mut(&mut self) -> sm::ValuesMut<PieceId, GPiece> {
    self.0.values_mut()
  }
  pub fn as_mut(&mut self, _: ModifyingPieces) -> &mut ActualGPieces {
    &mut self.0
  }
  #[cfg(test)]
  pub fn as_mut_t(&mut self) -> &mut ActualGPieces { &mut self.0 }
}

impl ById for GPieces {
  type Id = PieceId;
  type Entry = GPiece;
  type Error = Inapplicable;
  #[throws(Ia)]
  fn byid(&self, piece: PieceId) -> &GPiece {
    self.get(piece).ok_or(Ia::PieceGone)?
  }
  #[throws(Ia)]
  fn byid_mut(&mut self, piece: PieceId) -> &mut GPiece {
    self.get_mut(piece).ok_or(Ia::PieceGone)?
  }
}

/*impl<'p> IntoIterator for &'p Pieces {
  type Item = (PieceId, &'p PieceState);
  type IntoIter = sm::Iter<'p, PieceId, PieceState>;
  fn into_iter(self) -> Self::IntoIter { (&self.0).into_iter() }
}*/
impl<'p> IntoIterator for &'p mut GPieces {
  type Item = (PieceId, &'p mut GPiece);
  type IntoIter = sm::IterMut<'p, PieceId, GPiece>;
  fn into_iter(self) -> Self::IntoIter { (&mut self.0).into_iter() }
}

// ========== background maintenance ==========

// ---------- delayed game save ----------

impl InstanceGuard<'_> {
  pub fn save_game_later(&mut self) {
    if self.c.game_dirty { return }
    GLOBAL.dirty.lock().push_back(self.gref.clone());
    self.c.game_dirty = true;
  }

  pub fn save_game_and_aux_later(&mut self) {
    if self.c.aux_dirty { return }
    self.save_game_later();
    self.c.aux_dirty = true;
  }
}

pub fn game_flush_task() {
  let mut inner_queue = VecDeque::new();
  loop {
    {
      mem::swap(&mut inner_queue, &mut *GLOBAL.dirty.lock());
    }
    thread::sleep(GAME_SAVE_LAG);
    for _ in 0..inner_queue.len() {
      let ent = inner_queue.pop_front().unwrap();
      let mut ig = match ent.lock() { Ok(ig) => ig, _ => continue/*ah well*/ };
      if !ig.c.game_dirty { continue }
      match ig.save_game_now() {
        Ok(_) => {
          assert!(!ig.c.game_dirty);
        }
        Err(e) => {
          // todo: notify the players
          error!("save error! name={:?}: {}", &ig.name, &e);
          mem::drop(ig);
          inner_queue.push_back(ent); // oof
        }
      }
    }
  }
}

// ---------- client expiry ----------

fn client_expire_old_clients() {
  let mut expire = vec![];
  let max_age = Instant::now() - MAX_CLIENT_INACTIVITY;

  trait ClientIterator {
    type Ret;
    fn iter<'g>(&mut self, gref: &'g InstanceRef, max_age: Instant)
            -> (MutexGuard<'g, InstanceContainer>, Option<Self::Ret>) {
      let c = gref.lock_even_destroying();
      let ret = 'ret: loop {
        for (client, cl) in &c.g.clients {
          if cl.lastseen > max_age { continue }
          let ret = self.old(client);
          if ret.is_some() { break 'ret ret }
        }
        break 'ret None;
      };
      (c,ret)
    }
    fn old(&mut self, client: ClientId) -> Option<Self::Ret>;
  }

  for gref in GLOBAL.games_table.read().values() {
    struct Any;
    impl ClientIterator for Any {
      type Ret = ();
      fn old(&mut self, _client: ClientId) -> Option<()> {
        Some(())
      }
    }
    if let (_, Some(())) = Any.iter(gref, max_age) {
      expire.push(gref.clone());
    }
  }
  for gref in expire.into_iter() {
    #[derive(Debug)]
    struct Now(HashSet<ClientId>);
    impl ClientIterator for Now {
      type Ret = Void;
      fn old(&mut self, client: ClientId) -> Option<Void> {
        self.0.insert(client);
        None
      }
    }

    let mut now = Now(default());
    let (mut c, _) = now.iter(&gref, max_age);
    c.g.clients.retain(|c,_| !now.0.contains(&c));
    let mut gref = InstanceGuard { c, gref: gref.clone() };
    debug!("expiring client {:?}", &now);
    gref.tokens_deregister_for_id::<ClientId,_>(|c| now.0.contains(&c));
  }
}

pub fn client_periodic_expiry() {
  loop {
    sleep(MAX_CLIENT_INACTIVITY);
    client_expire_old_clients();
  }
}

// ---------- log expiry ----------

fn global_expire_old_logs() {
  let cutoff = Timestamp(Timestamp::now().0 - MAX_LOG_AGE.as_secs());

  let mut want_expire = vec![];

  let read = GLOBAL.games_table.read();
  for gref in read.values() {
    if gref.lock_even_destroying().g.gs.want_expire_some_logs(cutoff) {
      want_expire.push(gref.clone())
    }
  }
  drop(read);

  for gref in want_expire.into_iter() {
    let mut g = gref.lock_even_destroying();
    info!("expiring old log entries in {:?}", &g.g.name);
    g.g.gs.do_expire_old_logs(cutoff);
  }
}

pub fn logs_periodic_expiry() {
  loop {
    sleep(MAX_LOG_AGE / 10);
    global_expire_old_logs();
  }
}