@spooky-sync/core 1.0.0-beta.10 → 1.0.0-beta.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,6 +2,7 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest';
2
2
  import { RecordId } from 'surrealdb';
3
3
  import type { QueryPlan } from '@spooky-sync/query-builder';
4
4
  import {
5
+ PaintCache,
5
6
  RowsCacheEngine,
6
7
  ROWS_DURABLE_TABLES,
7
8
  ROWS_PREWARM_KEY,
@@ -818,6 +819,161 @@ describe('prewarming the row worker', () => {
818
819
  });
819
820
  });
820
821
 
822
+ describe('with shared tabs', () => {
823
+ const tick = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 0));
824
+ const save = (e: RowsCacheEngine): void => (e as unknown as { saveStartupReads(): void }).saveStartupReads();
825
+ const types = (): string[] => started[0].worker.posted.map((m) => m.type);
826
+ const lead = { workerLockName: 'lock-1', allowMemoryFallback: false, resumeHeld: false };
827
+ const sharedEngine = (): RowsCacheEngine =>
828
+ new RowsCacheEngine(
829
+ {
830
+ store: 'indexeddb',
831
+ workers: {
832
+ rows: () => {
833
+ const worker = new FakeRowsWorker(disks);
834
+ own.push(worker);
835
+ return worker as unknown as Worker;
836
+ },
837
+ },
838
+ } as any,
839
+ logger,
840
+ { useOpfs: true, shared: true }
841
+ );
842
+
843
+ /** A leader's session that reads two games at startup, and what it leaves for the next page load. */
844
+ const firstSession = async (): Promise<void> => {
845
+ const first = sharedEngine();
846
+ await first.adoptOwner('user_a', lead);
847
+ await first.upsert('game', 'game:a', { n: 1 }, 'replace');
848
+ await first.upsert('game', 'game:b', { n: 2 }, 'replace');
849
+ expect((await first.selectByIds('game', ['game:a', 'game:b'])).length).toBe(2);
850
+ save(first);
851
+ await first.close();
852
+ own.length = 0;
853
+ };
854
+
855
+ it('saves a leader\'s startup reads, and answers the next leader\'s first read from the page head', async () => {
856
+ await firstSession();
857
+ expect(JSON.parse(stored.get(ROWS_PREWARM_KEY)!).reads).toEqual([['by-ids', { table: 'game', ids: ['game:a', 'game:b'] }]]);
858
+ prewarmRows();
859
+ await tick();
860
+ const second = sharedEngine();
861
+ await second.adoptOwner('user_a', lead);
862
+ // Its own worker was not needed. The open is asked: it is what takes the role's lock.
863
+ expect(own).toEqual([]);
864
+ expect(types()).toEqual(['open', 'by-ids', 'warm', 'open']);
865
+ expect((await second.selectByIds('game', ['game:a', 'game:b'])).map((r) => r.n)).toEqual([1, 2]);
866
+ expect(types()).toEqual(['open', 'by-ids', 'warm', 'open']);
867
+ });
868
+
869
+ it('forgets what was read ahead once another tab can write through the worker', async () => {
870
+ await firstSession();
871
+ prewarmRows();
872
+ await tick();
873
+ const second = sharedEngine();
874
+ await second.adoptOwner('user_a', lead);
875
+ const { port1 } = new MessageChannel();
876
+ // The fake worker knows no ports; what matters is what the engine did before asking.
877
+ await second.exposeClientPort('tab-2', port1).catch(() => {});
878
+ port1.close();
879
+ expect((await second.selectByIds('game', ['game:a', 'game:b'])).map((r) => r.n)).toEqual([1, 2]);
880
+ expect(types().filter((t) => t === 'by-ids').length).toBe(2);
881
+ });
882
+
883
+ it('saves the startup reads of a session once, whatever roles follow', async () => {
884
+ await firstSession();
885
+ const tab = sharedEngine();
886
+ await tab.adoptOwner('user_a', lead);
887
+ await tab.selectByIds('game', ['game:a']);
888
+ save(tab);
889
+ expect(JSON.parse(stored.get(ROWS_PREWARM_KEY)!).reads).toEqual([['by-ids', { table: 'game', ids: ['game:a'] }]]);
890
+ // Leadership moves on and comes back, long after startup: what the tab reads then is not a startup read.
891
+ (tab as unknown as { startupUntil: number }).startupUntil = 0;
892
+ await tab.adoptOwner('user_a', { ...lead, workerLockName: 'lock-2' });
893
+ await tab.selectByIds('game', ['game:b']);
894
+ save(tab);
895
+ expect(JSON.parse(stored.get(ROWS_PREWARM_KEY)!).reads).toEqual([['by-ids', { table: 'game', ids: ['game:a'] }]]);
896
+ await tab.close();
897
+ });
898
+
899
+ it('asks for the open even when the worker answered it, in a tab that may share the store', async () => {
900
+ await firstSession();
901
+ prewarmRows();
902
+ await tick();
903
+ // Shared tabs were not to be had and the tab opens the store alone.
904
+ const solo = sharedEngine();
905
+ await solo.connect('user_a');
906
+ expect(types()).toEqual(['open', 'by-ids', 'warm', 'open']);
907
+ expect(await solo.getById('game', 'game:a')).toEqual({ id: 'game:a', n: 1 });
908
+ });
909
+
910
+ const gaveAway = { id: -1, ok: false, error: 'rows worker: gave the store to the tab that leads' };
911
+
912
+ it('takes back its open and everything read ahead when the worker gave the store away', async () => {
913
+ for (const start of [prewarmRows, () => void new Function(ROWS_PREWARM_SNIPPET)()]) {
914
+ disks = new Map();
915
+ stored = new Map();
916
+ started.length = 0;
917
+ delete g.__sp00kyRowsPrewarm;
918
+ await firstSession();
919
+ start();
920
+ await tick();
921
+ const pre = g.__sp00kyRowsPrewarm as { opened?: unknown; reads: unknown[]; replies: Record<number, unknown> };
922
+ expect(pre.opened).toBeDefined();
923
+ expect(Object.keys(pre.replies).length).toBe(1);
924
+ // Another tab leads: this page's worker closes its store and says so.
925
+ started[0].worker.postMessage({ id: -5, type: 'close', payload: undefined });
926
+ await tick();
927
+ started[0].worker.onmessage?.({ data: gaveAway });
928
+ expect(pre.opened).toBeUndefined();
929
+ expect(pre.reads).toEqual([]);
930
+ expect(pre.replies).toEqual({});
931
+ // That tab writes, and is gone before this page has a role. (It has a worker of its own.)
932
+ delete g.__sp00kyRowsPrewarm;
933
+ const other = sharedEngine();
934
+ await other.adoptOwner('user_a', { ...lead, workerLockName: 'lock-other' });
935
+ await other.upsert('game', 'game:a', { n: 100 }, 'merge');
936
+ await other.close();
937
+ own.length = 0;
938
+ g.__sp00kyRowsPrewarm = pre;
939
+
940
+ const second = sharedEngine();
941
+ await second.adoptOwner('user_a', lead);
942
+ // The read is asked of the worker, and answers what the other tab wrote.
943
+ expect((await second.selectByIds('game', ['game:a', 'game:b'])).map((r) => r.n)).toEqual([100, 2]);
944
+ // On the worker its head script started: one read asked ahead, one asked now.
945
+ expect(own).toEqual([]);
946
+ expect(types().filter((t) => t === 'by-ids').length).toBe(2);
947
+ await second.close();
948
+ }
949
+ });
950
+
951
+ it('drops what was read ahead when the store is given away after the worker was adopted', async () => {
952
+ await firstSession();
953
+ prewarmRows();
954
+ await tick();
955
+ const second = sharedEngine();
956
+ await second.adoptOwner('user_a', lead);
957
+ // The hand-over was under way when the page adopted the worker: its word arrives now.
958
+ started[0].worker.onmessage?.({ data: gaveAway });
959
+ expect((await second.selectByIds('game', ['game:a', 'game:b'])).map((r) => r.n)).toEqual([1, 2]);
960
+ expect(types().filter((t) => t === 'by-ids').length).toBe(2);
961
+ });
962
+
963
+ it('starts its own worker when the one started ahead is another release', async () => {
964
+ stored.set(ROWS_PREWARM_KEY, JSON.stringify({ url: 'https://app.test/assets/rows-worker-OLD.js', bucket: 'user_a' }));
965
+ prewarmedProto = 0;
966
+ prewarmRows();
967
+ const engine = sharedEngine();
968
+ await engine.adoptOwner('user_a', lead);
969
+ expect(started[0].worker.terminated).toBe(true);
970
+ expect(own.length).toBe(1);
971
+ await engine.upsert('game', 'game:a', { n: 2 }, 'replace');
972
+ expect(await engine.getById('game', 'game:a')).toEqual({ id: 'game:a', n: 2 });
973
+ expect(JSON.parse(stored.get(ROWS_PREWARM_KEY)!).url).toBe('https://app.test/assets/rows-worker.js');
974
+ });
975
+ });
976
+
821
977
  it('starts its own worker when the prewarmed one is another release', async () => {
822
978
  stored.set(ROWS_PREWARM_KEY, JSON.stringify({ url: 'https://app.test/assets/rows-worker-OLD.js', bucket: 'user_a' }));
823
979
  prewarmedProto = 0;
@@ -953,10 +1109,10 @@ describe('painting from the last session', () => {
953
1109
  expect(next.peekSelect(plan, {}, { paintKey: 'view-1' })).toBeNull();
954
1110
  await next.close();
955
1111
 
956
- // With shared tabs no copy is kept, so none is handed out.
1112
+ // A tab that shares the store with others is told the same way, before it has a role.
957
1113
  const shared = new RowsCacheEngine({ store: 'indexeddb' } as any, logger, { useOpfs: true, shared: true });
958
1114
  shared.expectBucket('user_a');
959
- expect(shared.peekSelect(plan, {}, { paintKey: 'view-1' })).toBeNull();
1115
+ expect(shared.peekSelect(plan, {}, { paintKey: 'view-1' })).toEqual(rows);
960
1116
  });
961
1117
 
962
1118
  it('lets go of a copy the moment its table is written, and takes the next read of the same thing', async () => {
@@ -965,7 +1121,8 @@ describe('painting from the last session', () => {
965
1121
  expect([...stored.keys()].some((k) => k.startsWith('sp00ky.paint.user_a.'))).toBe(true);
966
1122
  await engine.upsert('game', 'game:a', { n: 10 }, 'merge');
967
1123
  expect(engine.peekByIds('game', ids)).toBeNull();
968
- expect([...stored.keys()].filter((k) => k.startsWith('sp00ky.paint.user_a.'))).toEqual([]);
1124
+ // Nothing is left but the marks of the tables written to.
1125
+ expect([...stored.keys()].filter((k) => k.startsWith('sp00ky.paint.user_a.') && !k.startsWith('sp00ky.paint.user_a.t.'))).toEqual([]);
969
1126
  // A write to another table leaves it alone.
970
1127
  const again = await engine.selectByIds('game', ids);
971
1128
  await engine.upsert('user', 'user:1', { name: 'Ada L.' }, 'merge');
@@ -1012,3 +1169,416 @@ describe('painting from the last session', () => {
1012
1169
  }
1013
1170
  });
1014
1171
  });
1172
+
1173
+ describe('painting with shared tabs', () => {
1174
+ const g = globalThis as Record<string, unknown>;
1175
+ let stored: Map<string, string>;
1176
+ let disks: RowsDisks;
1177
+ let leader: RowsCacheEngine;
1178
+ let leaderHost: RowsHost;
1179
+ const ids = ['game:b', 'game:a'];
1180
+ const flush = (e: RowsCacheEngine): void => (e as unknown as { paint: { flush(): void } }).paint.flush();
1181
+ const shared = (config: Record<string, unknown> = {}): RowsCacheEngine =>
1182
+ new RowsCacheEngine({ store: 'indexeddb', ...config } as any, logger, { useOpfs: true, shared: true });
1183
+ const attached = { bucketId: 'user_a', storageHealth: { status: 'persistent', fallback: false } as const };
1184
+
1185
+ /** A follower tab: its ops go into the leader's worker through a port. */
1186
+ const follow = async (health: { status: 'persistent' | 'memory'; fallback: boolean } = attached.storageHealth): Promise<RowsCacheEngine> => {
1187
+ const tab = shared();
1188
+ const port = {
1189
+ onmessage: null as null | ((ev: { data: unknown }) => void),
1190
+ onmessageerror: null,
1191
+ start() {},
1192
+ close() {},
1193
+ postMessage(msg: { id: number; type: string; payload: unknown }, transfer?: Transferable[]) {
1194
+ const payload = structuredClone(msg.payload, { transfer: transfer ?? [] });
1195
+ void leaderHost.answer(msg.type, payload).then(
1196
+ ({ result, transfer: back }) =>
1197
+ port.onmessage?.({ data: { id: msg.id, ok: true, wt: 0, ...(structuredClone(result, { transfer: back ?? [] }) as object) } }),
1198
+ (error: unknown) => port.onmessage?.({ data: { id: msg.id, ok: false, error: String(error) } })
1199
+ );
1200
+ },
1201
+ };
1202
+ await tab.adoptAttached(port as unknown as MessagePort, { ...attached, storageHealth: health }, () => {});
1203
+ return tab;
1204
+ };
1205
+
1206
+ beforeEach(async () => {
1207
+ stored = new Map();
1208
+ disks = new Map();
1209
+ g.localStorage = {
1210
+ getItem: (k: string) => stored.get(k) ?? null,
1211
+ setItem: (k: string, v: string) => void stored.set(k, v),
1212
+ removeItem: (k: string) => void stored.delete(k),
1213
+ key: (i: number) => [...stored.keys()][i] ?? null,
1214
+ get length() {
1215
+ return stored.size;
1216
+ },
1217
+ };
1218
+ leader = shared();
1219
+ leaderHost = inProcessRows(leader, disks);
1220
+ await leader.adoptOwner('user_a', { workerLockName: 'lock-1', allowMemoryFallback: false, resumeHeld: false });
1221
+ await leader.upsert('game', 'game:a', { n: 1 }, 'replace');
1222
+ await leader.upsert('game', 'game:b', { n: 2 }, 'replace');
1223
+ await leader.upsert('user', 'user:1', { name: 'Ada' }, 'replace');
1224
+ });
1225
+
1226
+ afterEach(() => {
1227
+ delete g.localStorage;
1228
+ });
1229
+
1230
+ it('keeps what a leader and a follower read at startup, for whichever tab opens next', async () => {
1231
+ const tab = await follow();
1232
+ const games = await leader.selectByIds('game', ids);
1233
+ const users = await tab.selectByIds('user', ['user:1']);
1234
+ flush(leader);
1235
+ flush(tab);
1236
+
1237
+ // The next page load, before it has any role.
1238
+ const next = shared();
1239
+ next.expectBucket('user_a');
1240
+ expect(next.peekByIds('game', ids)).toEqual(games);
1241
+ expect(next.peekByIds('user', ['user:1'])).toEqual(users);
1242
+ // And each tab has the other's copy.
1243
+ expect(tab.peekByIds('game', ids)).toEqual(games);
1244
+ expect(leader.peekByIds('user', ['user:1'])).toEqual(users);
1245
+ });
1246
+
1247
+ it('hands out no copy of a table another tab has written to since', async () => {
1248
+ const tab = await follow();
1249
+ await tab.selectByIds('game', ids);
1250
+ await tab.selectByIds('user', ['user:1']);
1251
+ flush(tab);
1252
+ expect(tab.peekByIds('game', ids)).not.toBeNull();
1253
+
1254
+ await leader.upsert('game', 'game:a', { n: 10 }, 'merge');
1255
+ // Not in the tab that holds it in memory, not in one that would read it from storage.
1256
+ expect(tab.peekByIds('game', ids)).toBeNull();
1257
+ const next = shared();
1258
+ next.expectBucket('user_a');
1259
+ expect(next.peekByIds('game', ids)).toBeNull();
1260
+ // The other table's copy stands.
1261
+ expect(next.peekByIds('user', ['user:1'])).not.toBeNull();
1262
+
1263
+ // The follower's own write voids the leader's copy the same way.
1264
+ await leader.selectByIds('user', ['user:1']);
1265
+ await tab.upsert('user', 'user:1', { name: 'Grace' }, 'merge');
1266
+ expect(leader.peekByIds('user', ['user:1'])).toBeNull();
1267
+ // The next read of the same thing is kept again.
1268
+ const again = await tab.selectByIds('game', ids);
1269
+ expect(again[1].n).toBe(10);
1270
+ flush(tab);
1271
+ expect(next.peekByIds('game', ids)).toEqual(again);
1272
+ });
1273
+
1274
+ it('does not keep a read that another tab\'s write overtook', async () => {
1275
+ const tab = await follow();
1276
+ const kept = (e: RowsCacheEngine): number => (e as unknown as { paint: { entries: Map<string, unknown> } }).paint.entries.size;
1277
+ const reading = tab.selectByIds('game', ids);
1278
+ const writing = leader.upsert('game', 'game:a', { n: 99 }, 'merge');
1279
+ await Promise.all([reading, writing]);
1280
+ // Not kept at all: its marks alone would not say so had the read come back after the leader's second mark.
1281
+ expect(kept(tab)).toBe(0);
1282
+ flush(tab);
1283
+ expect(tab.peekByIds('game', ids)).toBeNull();
1284
+ expect([...stored.keys()].filter((k) => k.startsWith('sp00ky.paint.user_a.') && !k.includes('.t.'))).toEqual([]);
1285
+ });
1286
+
1287
+ it('does not write a copy that went stale over one another tab took since', async () => {
1288
+ const tab = await follow();
1289
+ await tab.selectByIds('game', ids);
1290
+ await leader.upsert('game', 'game:a', { n: 5 }, 'merge');
1291
+ const fresh = await leader.selectByIds('game', ids);
1292
+ flush(leader);
1293
+ // The follower's copy is the older one, and still unsaved.
1294
+ flush(tab);
1295
+ const next = shared();
1296
+ next.expectBucket('user_a');
1297
+ expect(next.peekByIds('game', ids)).toEqual(fresh);
1298
+ });
1299
+
1300
+ it('starts a session with the first role only', async () => {
1301
+ const tab = await follow();
1302
+ await tab.selectByIds('game', ids);
1303
+ const paint = (tab as unknown as { paint: { since: number } }).paint;
1304
+ const since = paint.since;
1305
+ expect(since).toBeGreaterThan(0);
1306
+ paint.since = since - 10_000;
1307
+ // Promoted later: reads from here on are not what the tab reads at startup.
1308
+ inProcessRows(tab, disks);
1309
+ await leader.close();
1310
+ await tab.adoptOwner('user_a', { workerLockName: 'lock-2', allowMemoryFallback: false, resumeHeld: false });
1311
+ expect(paint.since).toBe(since - 10_000);
1312
+ await tab.selectByIds('user', ['user:1']);
1313
+ expect(tab.peekByIds('user', ['user:1'])).toBeNull();
1314
+ // What it kept at startup it keeps renewing.
1315
+ await tab.upsert('game', 'game:a', { n: 7 }, 'merge');
1316
+ const again = await tab.selectByIds('game', ids);
1317
+ expect(tab.peekByIds('game', ids)).toEqual(again);
1318
+ });
1319
+
1320
+ it('keeps nothing while the shared store lives in memory', async () => {
1321
+ const tab = await follow({ status: 'memory', fallback: true });
1322
+ await tab.selectByIds('game', ids);
1323
+ flush(tab);
1324
+ expect(tab.peekByIds('game', ids)).toBeNull();
1325
+ expect([...stored.keys()].filter((k) => k.startsWith('sp00ky.paint.user_a.') && !k.includes('.t.'))).toEqual([]);
1326
+ // Nor does a leader that was granted a store in memory.
1327
+ const lost = shared();
1328
+ inProcessRows(lost, new Map());
1329
+ // The worker could not have the files and was allowed to open in memory.
1330
+ const seam = lost as unknown as { createTransport: () => { call: (type: string, ...rest: unknown[]) => Promise<object> } };
1331
+ const make = seam.createTransport;
1332
+ seam.createTransport = () => {
1333
+ const transport = make();
1334
+ const call = transport.call;
1335
+ transport.call = async (type, ...rest) => {
1336
+ const reply = await call(type, ...rest);
1337
+ return type === 'open' ? { ...reply, persisted: false, opfsError: 'held by another tab' } : reply;
1338
+ };
1339
+ return transport;
1340
+ };
1341
+ await lost.adoptOwner('user_m', { workerLockName: 'lock-m', allowMemoryFallback: true, resumeHeld: false });
1342
+ expect(lost.storageHealth.status).toBe('memory');
1343
+ await lost.upsert('game', 'game:m', { n: 1 }, 'replace');
1344
+ await lost.selectByIds('game', ['game:m']);
1345
+ flush(lost);
1346
+ expect(lost.peekByIds('game', ['game:m'])).toBeNull();
1347
+ expect([...stored.keys()].filter((k) => k.startsWith('sp00ky.paint.user_m'))).toEqual([]);
1348
+ });
1349
+ });
1350
+
1351
+ describe('PaintCache marks', () => {
1352
+ const g = globalThis as Record<string, unknown>;
1353
+ let stored: Map<string, string>;
1354
+ const rows = JSON.stringify([{ id: 'game:a', n: 1 }]);
1355
+ const none = (b64: string): Uint8Array => new Uint8Array(b64.length);
1356
+ const open = (max = 1_000_000): PaintCache => {
1357
+ const cache = new PaintCache(max);
1358
+ cache.start('user_a');
1359
+ return cache;
1360
+ };
1361
+
1362
+ beforeEach(() => {
1363
+ stored = new Map();
1364
+ g.localStorage = {
1365
+ getItem: (k: string) => stored.get(k) ?? null,
1366
+ setItem: (k: string, v: string) => void stored.set(k, v),
1367
+ removeItem: (k: string) => void stored.delete(k),
1368
+ key: (i: number) => [...stored.keys()][i] ?? null,
1369
+ get length() {
1370
+ return stored.size;
1371
+ },
1372
+ };
1373
+ });
1374
+
1375
+ afterEach(() => {
1376
+ delete g.localStorage;
1377
+ });
1378
+
1379
+ it('keeps a tab\'s own read that was queued behind its write', () => {
1380
+ const a = open();
1381
+ a.touch(['game']);
1382
+ const sent = a.stamp(['game']);
1383
+ // The store answers the write, then the read.
1384
+ a.touch(['game'], true);
1385
+ a.note('k', ['game'], rows, false, sent);
1386
+ expect(a.get('k', none)).toEqual(JSON.parse(rows));
1387
+ // A read sent before the write is another matter.
1388
+ const early = a.stamp(['game']);
1389
+ a.touch(['game']);
1390
+ a.touch(['game'], true);
1391
+ a.note('k2', ['game'], rows, false, early);
1392
+ expect(a.get('k2', none)).toBeNull();
1393
+ });
1394
+
1395
+ it('voids the copy a tab took between another tab\'s write being sent and being taken', () => {
1396
+ const a = open();
1397
+ const b = open();
1398
+ a.touch(['game']);
1399
+ // B reads after A's first mark, and the store answers it before A's write.
1400
+ const sent = b.stamp(['game']);
1401
+ b.note('k', ['game'], rows, false, sent);
1402
+ expect(b.get('k', none)).not.toBeNull();
1403
+ a.touch(['game'], true);
1404
+ expect(b.get('k', none)).toBeNull();
1405
+ b.flush();
1406
+ expect(stored.has('sp00ky.paint.user_a.k')).toBe(false);
1407
+ });
1408
+
1409
+ it('counts another tab\'s write against a read on its way, even under a mark of its own', () => {
1410
+ const a = open();
1411
+ const b = open();
1412
+ const sent = b.stamp(['game']);
1413
+ a.touch(['game']);
1414
+ a.touch(['game'], true);
1415
+ // B writes too before its read answers: A's mark is covered, not forgotten.
1416
+ b.touch(['user']);
1417
+ b.note('k', ['game'], rows, false, sent);
1418
+ expect(b.get('k', none)).toBeNull();
1419
+ const again = b.stamp(['game']);
1420
+ b.note('k', ['game'], rows, false, again);
1421
+ expect(b.get('k', none)).not.toBeNull();
1422
+ });
1423
+
1424
+ it('keeps one budget for all tabs and clears out what no longer stands', () => {
1425
+ const big = JSON.stringify([{ id: 'game:a', pad: 'p'.repeat(400) }]);
1426
+ const a = open(1000);
1427
+ const b = open(1000);
1428
+ a.note('a1', ['game'], big, false, a.stamp(['game']));
1429
+ a.flush();
1430
+ b.note('b1', ['user'], big, false, b.stamp(['user']));
1431
+ b.note('b2', ['user'], big, false, b.stamp(['user']));
1432
+ b.flush();
1433
+ // B's two fill the budget: A's is the one that goes.
1434
+ expect(stored.has('sp00ky.paint.user_a.a1')).toBe(false);
1435
+ expect(Object.keys(JSON.parse(stored.get('sp00ky.paint.user_a')!)).sort()).toEqual(['b1', 'b2']);
1436
+
1437
+ // A copy from another release, and one whose table was written by a tab that is gone.
1438
+ stored.set('sp00ky.paint.user_a.old', '0[{"id":"game:z"}]');
1439
+ stored.set('sp00ky.paint.user_a', JSON.stringify({ ...JSON.parse(stored.get('sp00ky.paint.user_a')!), old: ['game'] }));
1440
+ const c = open(1000);
1441
+ expect(c.get('old', none)).toBeNull();
1442
+ stored.set('sp00ky.paint.user_a.t.user', 'gone.1');
1443
+ expect(c.get('b1', none)).toBeNull();
1444
+ c.flush();
1445
+ expect([...stored.keys()].filter((k) => !k.includes('.t.')).sort()).toEqual(['sp00ky.paint.user_a']);
1446
+ expect(JSON.parse(stored.get('sp00ky.paint.user_a')!)).toEqual({});
1447
+ });
1448
+
1449
+ it('tells the other tabs even when there is no room for a mark', () => {
1450
+ const a = open();
1451
+ const b = open();
1452
+ a.touch(['game']);
1453
+ a.touch(['game'], true);
1454
+ b.note('k', ['game'], rows, false, b.stamp(['game']));
1455
+ expect(b.get('k', none)).not.toBeNull();
1456
+ const setItem = (g.localStorage as { setItem: unknown }).setItem;
1457
+ (g.localStorage as { setItem: unknown }).setItem = () => {
1458
+ throw new Error('QuotaExceededError');
1459
+ };
1460
+ a.touch(['game']);
1461
+ (g.localStorage as { setItem: unknown }).setItem = setItem;
1462
+ expect(stored.has('sp00ky.paint.user_a.t.game')).toBe(false);
1463
+ expect(b.get('k', none)).toBeNull();
1464
+ });
1465
+
1466
+ it('makes room for a mark by letting the copies go, on a table that never had one too', () => {
1467
+ const a = open();
1468
+ const b = open();
1469
+ b.note('k', ['game'], rows, false, b.stamp(['game']));
1470
+ b.note('u', ['user'], rows, false, b.stamp(['user']));
1471
+ b.flush();
1472
+ expect(stored.has('sp00ky.paint.user_a.t.game')).toBe(false);
1473
+ // Full: a new key does not fit, an existing one can still be removed.
1474
+ const setItem = (g.localStorage as { setItem: (k: string, v: string) => void }).setItem;
1475
+ (g.localStorage as { setItem: unknown }).setItem = (k: string, v: string) => {
1476
+ if ([...stored.keys()].some((name) => /^sp00ky\.paint\.user_a\.[^.]+$/.test(name))) throw new Error('QuotaExceededError');
1477
+ setItem(k, v);
1478
+ };
1479
+ a.touch(['game']);
1480
+ (g.localStorage as { setItem: unknown }).setItem = setItem;
1481
+ // The copies went, the mark is there, and no tab hands out what it held.
1482
+ expect(stored.has('sp00ky.paint.user_a.t.game')).toBe(true);
1483
+ expect([...stored.keys()].filter((name) => /^sp00ky\.paint\.user_a\.[^.]+$/.test(name))).toEqual([]);
1484
+ expect(b.get('k', none)).toBeNull();
1485
+ });
1486
+
1487
+ it('saves the copies that fit when one does not, and lets go of copies the index lost', () => {
1488
+ const a = open();
1489
+ a.note('fits', ['game'], rows, false, a.stamp(['game']));
1490
+ a.note('too-big', ['user'], rows, false, a.stamp(['user']));
1491
+ const setItem = (g.localStorage as { setItem: (k: string, v: string) => void }).setItem;
1492
+ (g.localStorage as { setItem: unknown }).setItem = (k: string, v: string) => {
1493
+ if (k.endsWith('.too-big')) throw new Error('QuotaExceededError');
1494
+ setItem(k, v);
1495
+ };
1496
+ a.flush();
1497
+ (g.localStorage as { setItem: unknown }).setItem = setItem;
1498
+ expect(Object.keys(JSON.parse(stored.get('sp00ky.paint.user_a')!))).toEqual(['fits']);
1499
+ expect(a.get('fits', none)).not.toBeNull();
1500
+
1501
+ // A copy two tabs saving at once left out of the index. Its table is written, then some tab saves.
1502
+ const stray = stored.get('sp00ky.paint.user_a.fits')!;
1503
+ stored.set('sp00ky.paint.user_a.stray', stray);
1504
+ const b = open();
1505
+ b.touch(['game']);
1506
+ b.touch(['game'], true);
1507
+ b.flush();
1508
+ expect(stored.has('sp00ky.paint.user_a.stray')).toBe(false);
1509
+ // One that still stands is taken into the index, and goes with the next write to its table.
1510
+ b.note('again', ['game'], rows, false, b.stamp(['game']));
1511
+ b.flush();
1512
+ stored.set('sp00ky.paint.user_a.stray2', stored.get('sp00ky.paint.user_a.again')!);
1513
+ const c = open();
1514
+ c.flush();
1515
+ expect(Object.keys(JSON.parse(stored.get('sp00ky.paint.user_a')!)).sort()).toEqual(['again', 'stray2']);
1516
+ c.touch(['game']);
1517
+ expect(stored.has('sp00ky.paint.user_a.stray2')).toBe(false);
1518
+ });
1519
+
1520
+ it('hands out another tab\'s newer copy when its own no longer stands', () => {
1521
+ const a = open();
1522
+ const b = open();
1523
+ b.note('k', ['game'], rows, false, b.stamp(['game']));
1524
+ a.touch(['game']);
1525
+ a.touch(['game'], true);
1526
+ const newer = JSON.stringify([{ id: 'game:a', n: 2 }]);
1527
+ a.note('k', ['game'], newer, false, a.stamp(['game']));
1528
+ a.flush();
1529
+ expect(b.get('k', none)).toEqual(JSON.parse(newer));
1530
+ });
1531
+
1532
+ it('leaves no marks, and touches storage for no write, in a tab that is alone in the store', () => {
1533
+ const solo = new PaintCache(1_000_000, false);
1534
+ solo.start('user_a');
1535
+ let calls = 0;
1536
+ const real = g.localStorage as Record<string, unknown>;
1537
+ g.localStorage = new Proxy(real, {
1538
+ get: (target, prop) => {
1539
+ const value = target[prop as string];
1540
+ if (typeof value !== 'function') return value;
1541
+ return (...args: unknown[]) => {
1542
+ calls++;
1543
+ return (value as (...a: unknown[]) => unknown)(...args);
1544
+ };
1545
+ },
1546
+ });
1547
+ for (let i = 0; i < 100; i++) {
1548
+ solo.touch(['game']);
1549
+ solo.touch(['game'], true);
1550
+ }
1551
+ // The index is read once; after that a write costs nothing while no copy of its table is kept.
1552
+ expect(calls).toBeLessThanOrEqual(1);
1553
+ expect([...stored.keys()].filter((k) => k.includes('.t.'))).toEqual([]);
1554
+ // Its own writes still drop its copies, and an overtaken read is still not kept.
1555
+ const early = solo.stamp(['game']);
1556
+ solo.note('k', ['game'], rows, false, solo.stamp(['game']));
1557
+ solo.flush();
1558
+ expect(solo.get('k', none)).not.toBeNull();
1559
+ solo.touch(['game']);
1560
+ expect(solo.get('k', none)).toBeNull();
1561
+ solo.note('k', ['game'], rows, false, early);
1562
+ expect(solo.get('k', none)).toBeNull();
1563
+ // A copy it cannot account for (not in the index) is not kept on trust.
1564
+ solo.note('k', ['game'], rows, false, solo.stamp(['game']));
1565
+ solo.flush();
1566
+ stored.set('sp00ky.paint.user_a.stray', stored.get('sp00ky.paint.user_a.k')!);
1567
+ solo.note('k', ['game'], rows, false, solo.stamp(['game']));
1568
+ solo.flush();
1569
+ expect(stored.has('sp00ky.paint.user_a.stray')).toBe(false);
1570
+ g.localStorage = real;
1571
+ });
1572
+
1573
+ it('never keeps a read under the bucket that came after it', () => {
1574
+ const a = open();
1575
+ const sent = a.stamp(['game']);
1576
+ a.start('user_b');
1577
+ a.note('k', ['game'], rows, false, sent);
1578
+ expect(a.get('k', none)).toBeNull();
1579
+ a.stop();
1580
+ expect(a.stamp(['game'])).toBe('');
1581
+ a.touch(['game']);
1582
+ expect([...stored.keys()].filter((k) => k.includes('user_b'))).toEqual([]);
1583
+ });
1584
+ });