openmaic-custom/tests/runtime/learner-key.test.ts
wyuc 667f3b0c51
feat(runtime): device-anonymous learner identity + RuntimeStore app bootstrap (#869 Part C, step 1) (#885)
* feat(runtime): device-anonymous learnerKey + app RuntimeStore singleton (#869)

* feat(runtime): cascade stage deletion into the runtime store (#869)

deleteStageWithRelatedData now cascades into the runtime layer after its
Dexie transaction completes. The runtime data lives in a separate
IndexedDB database (maic-runtime), so it cannot join the transaction, and
the cascade goes through deleteStageRuntimeSafely — a helper that never
throws (warns with context instead): a broken or hung runtime DB must not
brick stage deletion in the main app DB. deleteStageRuntime is idempotent,
so a failed cascade can simply be retried.

Covered at the helper seam with a stub RuntimeStore (success + throwing);
the repo has no Dexie-in-node harness for database.ts and this change
does not invent one.

* fix(runtime): wire the live deletion path, serialize learner-key minting (#869)

Cross-review fixes on the C1 bootstrap:

- The runtime cascade was wired into deleteStageWithRelatedData, which has
  zero callers; the UI classroom-deletion flow goes through deleteStageData
  in stage-storage. Wire deleteStageRuntimeSafely into that live path too
  (after its Dexie work, same isolation rationale), and cover the wiring by
  running the real deleteStageData with its module deps mocked — the
  repo's established pattern for database-touching code.
- getLearnerKey minted twice under concurrency. Same-bundle callers now
  share one in-flight promise on the default path (failures are not
  cached), and every path re-reads after writing and returns the PERSISTED
  key, so a cross-tab race converges on the stored winner instead of
  keeping an orphaned local mint.
- Guard crypto.randomUUID with the house fallback pattern.
- Honest docs: the cascade comment no longer claims a retry path exists
  (orphaned rows are inert today; a startup sweep is deferred to Part C2),
  and both lib/runtime modules note they are client-only.

* fix(runtime): cross-tab mint lock and bounded deletion cascade (#869)

- Read-after-write alone still let a tab keep an orphaned learner key
  when its re-read landed before the other tab's write. Minting now runs
  under the Web Locks API ('maic:learner-key') where available: grants
  are mutually exclusive across tabs, the loser re-reads the winner's key
  inside its grant, and an existing key is never overwritten (so the
  per-tab memo stays safe). Without navigator.locks (older browsers,
  non-window contexts) the memo + read-after-write behavior remains, with
  the residual race named in a comment and accepted — it merely splits
  one anonymous learner's local history.
- deleteStageRuntimeSafely awaited without a bound, so a hung runtime
  IndexedDB could block the live deletion path — the exact failure the
  helper exists to isolate. The cascade now races a 5s timeout: on
  timeout it warns and resolves (orphaned rows stay inert), and the still
  -pending cascade carries a swallow handler so a late rejection cannot
  become an unhandled rejection.

* fix(runtime): probe for the runtime DB before cascading a stage deletion (#869)

deleteStageRuntimeSafely reached openDb() unconditionally, and opening
CREATES the maic-runtime database — so deleting a classroom on a device
that never wrote runtime data paid an open-or-create of a second
IndexedDB DB, and in degraded environments burned the full 5s bound for
zero cleanup value.

Probe first without creating: where indexedDB.databases() is available,
a missing maic-runtime entry returns immediately; where the probe API is
unavailable (older Firefox), fall through to the bounded cascade —
skipping there would strand real cleanup once Part C2 adds writers. The
probe shares the existing try/catch + timeout envelope, so a hanging
databases() cannot brick deletion either. The DB name is a module const
passed explicitly to BrowserRuntimeStore so probe and store can never
drift.
2026-07-09 14:54:21 +08:00

112 lines
4.5 KiB
TypeScript

import { afterEach, describe, expect, it, vi } from 'vitest';
import { BrowserKVStore } from '@openmaic/storage';
import { getLearnerKey, LEARNER_KEY_KV_KEY } from '@/lib/runtime/learner-key';
function memoryStorage(): Storage {
const m = new Map<string, string>();
return {
get length() {
return m.size;
},
clear: () => m.clear(),
getItem: (k: string) => m.get(k) ?? null,
key: (i: number) => [...m.keys()][i] ?? null,
removeItem: (k: string) => void m.delete(k),
setItem: (k: string, v: string) => void m.set(k, String(v)),
} as Storage;
}
describe('getLearnerKey', () => {
it('mints an anon key once and returns the same key afterwards', async () => {
const kv = new BrowserKVStore({ storage: memoryStorage() });
const first = await getLearnerKey(kv);
expect(first).toMatch(/^anon:[0-9a-f-]{36}$/);
await expect(getLearnerKey(kv)).resolves.toBe(first);
});
it('persists under the device scope, never the account scope', async () => {
const storage = memoryStorage();
const kv = new BrowserKVStore({ storage });
const key = await getLearnerKey(kv);
// BrowserKVStore encodes the scope in the storage key: `maic:<scope>:<key>`
const entries = [...Array(storage.length).keys()].map((i) => storage.key(i));
const deviceEntry = entries.find((k) => k?.includes(':device:'));
expect(deviceEntry).toContain(LEARNER_KEY_KV_KEY);
expect(storage.getItem(deviceEntry!)).toContain(key);
expect(entries.find((k) => k?.includes(':account:'))).toBeUndefined();
});
it('two different devices (stores) mint different keys', async () => {
const a = await getLearnerKey(new BrowserKVStore({ storage: memoryStorage() }));
const b = await getLearnerKey(new BrowserKVStore({ storage: memoryStorage() }));
expect(a).not.toBe(b);
});
it('concurrent calls on one device converge on a single key', async () => {
const kv = new BrowserKVStore({ storage: memoryStorage() });
const keys = await Promise.all([getLearnerKey(kv), getLearnerKey(kv), getLearnerKey(kv)]);
expect(new Set(keys).size).toBe(1);
// and later calls agree with what actually persisted
await expect(getLearnerKey(kv)).resolves.toBe(keys[0]);
});
it('returns the persisted winner when another tab wins the write race', async () => {
const winner = 'anon:11111111-1111-4111-8111-111111111111';
const m = new Map<string, string>();
// Simulate a cross-tab race: whatever this caller persists, the storage
// ends up holding another tab's later write (last write wins). The caller
// must converge on the stored value, never keep an orphaned local mint.
const storage = {
get length() {
return m.size;
},
clear: () => m.clear(),
getItem: (k: string) => m.get(k) ?? null,
key: (i: number) => [...m.keys()][i] ?? null,
removeItem: (k: string) => void m.delete(k),
setItem: (k: string) => void m.set(k, JSON.stringify(winner)),
} as Storage;
await expect(getLearnerKey(new BrowserKVStore({ storage }))).resolves.toBe(winner);
});
});
describe('getLearnerKey cross-tab locking', () => {
afterEach(() => {
vi.unstubAllGlobals();
});
it('mints inside a Web Lock when navigator.locks is available', async () => {
// A serializing fake: grants run strictly one at a time, like the real
// Web Locks API does for a single lock name.
const requestedNames: string[] = [];
let chain: Promise<unknown> = Promise.resolve();
const locks = {
request: (name: string, cb: () => Promise<unknown>) => {
requestedNames.push(name);
const granted = chain.then(() => cb());
chain = granted.catch(() => undefined);
return granted;
},
};
vi.stubGlobal('navigator', { locks });
const kv = new BrowserKVStore({ storage: memoryStorage() });
const keys = await Promise.all([getLearnerKey(kv), getLearnerKey(kv), getLearnerKey(kv)]);
expect(new Set(keys).size).toBe(1);
// every miss went through the lock, under one shared name
expect(requestedNames.length).toBe(3);
expect(new Set(requestedNames).size).toBe(1);
});
it('falls back to read-after-write when navigator.locks is unavailable', async () => {
vi.stubGlobal('navigator', {}); // e.g. an old browser: no Web Locks
const kv = new BrowserKVStore({ storage: memoryStorage() });
const key = await getLearnerKey(kv);
expect(key).toMatch(/^anon:[0-9a-f-]{36}$/);
await expect(getLearnerKey(kv)).resolves.toBe(key);
});
});