test(client): couverture comportementale des 3 changements SDK (fake déterministe)
Les fix récents (anti-fork, open-repo, access-log) n'avaient AUCUN test de comportement dans le domaine de la lib. Ajout de tests DÉTERMINISTES à base de `ng` factice modélisant la condition d'échec (pas de broker réel — le harness e2e réel réhydrate trop vite et ne reproduit pas ces cas). - anti-fork.test.ts : fake avec lag de sync (0 lignes les K premières lectures du record de compte, puis les vraies). Asserte le cœur du fix : compte retrouvé au retry → réutilisé, 0 doc_create (pas de fork) ; compte réellement neuf → 1 seul jeu de docs provisionné, budget de retry prouvé consommé ; idempotence de session ; cas limite « trouvé à la dernière tentative ». - open-repo.test.ts : fake où une requête ancrée rend vide tant que doc_subscribe n'a pas ouvert le repo. Asserte subscribe-avant-read + idempotence (Set des repos ouverts) + no-op si le ng n'a pas doc_subscribe. - access-log.test.ts : off par défaut (silencieux), on via config ET via env NG_EVENTUALLY_ACCESS_LOG, préfixe = identité active (suit setCurrentUser), row-count sur READ. Restaure console.log/env fidèlement. bun test : 91 → 117 pass, 0 fail. tsc --noEmit propre. src/ non touché. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,280 @@
|
||||
/**
|
||||
* access-log.test.ts — behavioral tests for logAccess / setAccessLog / enabled
|
||||
* (src/access-log.ts), as wired through the docs primitives (src/docs.ts).
|
||||
*
|
||||
* Tests:
|
||||
* (a) OFF by default: reads + writes via sparqlQuery / sparqlUpdate / docCreate
|
||||
* emit nothing to console.log.
|
||||
* (b) ON via configure({ debugAccessLog: true }): each read/write emits a line
|
||||
* matching `[<identity>] READ/WRITE <nuri> (<label>)` plus row-count suffix
|
||||
* on READs.
|
||||
* (c) ON via env var NG_EVENTUALLY_ACCESS_LOG=1: same behavior without changing
|
||||
* calling code.
|
||||
* (d) Identity follows setCurrentUser: after setCurrentUser the prefix changes.
|
||||
*
|
||||
* Spy approach: replace console.log with a mock, restore it after each test.
|
||||
* Env var tests set/delete process.env.NG_EVENTUALLY_ACCESS_LOG and restore it.
|
||||
*/
|
||||
|
||||
import { describe, it, expect, mock, beforeEach, afterEach, afterAll } from "bun:test";
|
||||
import { setAccessLog, enabled } from "../src/access-log";
|
||||
import { docCreate, sparqlUpdate, sparqlQuery } from "../src/docs";
|
||||
import {
|
||||
configure,
|
||||
configureStoreRegistry,
|
||||
resetStoreRegistry,
|
||||
resetConfig,
|
||||
setCurrentUser,
|
||||
getCurrentUser,
|
||||
} from "../src/polyfill";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function fakeNg() {
|
||||
return {
|
||||
doc_create: mock(async (..._a: unknown[]) => "did:ng:o:log-doc"),
|
||||
sparql_update: mock(async (..._a: unknown[]) => undefined),
|
||||
sparql_query: mock(async (..._a: unknown[]) => ({
|
||||
results: { bindings: [{ x: { value: "v" } }] }, // 1 row so row-count is visible
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
function injectFake(debugAccessLog = false) {
|
||||
const ng = fakeNg();
|
||||
configure({ ng: ng as any, useShape: (() => {}) as any, debugAccessLog });
|
||||
configureStoreRegistry({
|
||||
getSession: async () => ({ sessionId: "sid-log", privateStoreId: "P" }),
|
||||
provisionRetry: { attempts: 1 },
|
||||
});
|
||||
return ng;
|
||||
}
|
||||
|
||||
// Capture console.log lines for the duration of a test.
|
||||
// Returns the captured lines array and a restore function.
|
||||
function spyConsoleLog(): { lines: string[]; restore: () => void } {
|
||||
const lines: string[] = [];
|
||||
const orig = console.log;
|
||||
console.log = (...args: unknown[]) => {
|
||||
lines.push(args.map(String).join(" "));
|
||||
};
|
||||
return { lines, restore: () => { console.log = orig; } };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Lifecycle: restore config state after each test to avoid cross-test bleed.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// Save the env var value that was present BEFORE any test ran, so tests
|
||||
// that run in an environment where NG_EVENTUALLY_ACCESS_LOG is already set
|
||||
// don't permanently destroy that value.
|
||||
const _originalEnvVar = process.env?.NG_EVENTUALLY_ACCESS_LOG;
|
||||
|
||||
afterEach(() => {
|
||||
setAccessLog(false); // always reset the config toggle
|
||||
setCurrentUser(null); // clear active identity
|
||||
// Restore the original env var value (don't just delete — it may have existed before)
|
||||
if ((globalThis as any)?.process?.env) {
|
||||
if (_originalEnvVar === undefined) {
|
||||
delete process.env.NG_EVENTUALLY_ACCESS_LOG;
|
||||
} else {
|
||||
process.env.NG_EVENTUALLY_ACCESS_LOG = _originalEnvVar;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
resetConfig();
|
||||
resetStoreRegistry();
|
||||
setAccessLog(false);
|
||||
setCurrentUser(null);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Tests
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("access-log: OFF by default", () => {
|
||||
beforeEach(() => {
|
||||
// Force the env var OFF for these tests, regardless of the shell environment.
|
||||
if ((globalThis as any)?.process?.env) {
|
||||
delete process.env.NG_EVENTUALLY_ACCESS_LOG;
|
||||
}
|
||||
setAccessLog(false);
|
||||
});
|
||||
|
||||
it("no console.log output for sparqlQuery when disabled", async () => {
|
||||
injectFake(false);
|
||||
const { lines, restore } = spyConsoleLog();
|
||||
try {
|
||||
await sparqlQuery("sid-log", "SELECT * {}");
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
expect(lines.length).toBe(0);
|
||||
});
|
||||
|
||||
it("no console.log output for sparqlUpdate when disabled", async () => {
|
||||
injectFake(false);
|
||||
const { lines, restore } = spyConsoleLog();
|
||||
try {
|
||||
await sparqlUpdate("sid-log", "INSERT DATA {}", "did:ng:o:x");
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
expect(lines.length).toBe(0);
|
||||
});
|
||||
|
||||
it("no console.log output for docCreate when disabled", async () => {
|
||||
injectFake(false);
|
||||
const { lines, restore } = spyConsoleLog();
|
||||
try {
|
||||
await docCreate("sid-log", "Graph", "data:graph", "store");
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
expect(lines.length).toBe(0);
|
||||
});
|
||||
|
||||
it("enabled() returns false when disabled", () => {
|
||||
setAccessLog(false);
|
||||
if (process.env) delete process.env.NG_EVENTUALLY_ACCESS_LOG;
|
||||
expect(enabled()).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("access-log: ON via configure({ debugAccessLog: true })", () => {
|
||||
beforeEach(() => {
|
||||
setCurrentUser("alice");
|
||||
});
|
||||
|
||||
it("sparqlQuery emits a READ line with identity, nuri, label, and row-count", async () => {
|
||||
injectFake(true);
|
||||
setCurrentUser("alice");
|
||||
const { lines, restore } = spyConsoleLog();
|
||||
try {
|
||||
await sparqlQuery("sid-log", "SELECT * {}", undefined, "did:ng:o:q", "myLabel");
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
expect(lines.length).toBe(1);
|
||||
expect(lines[0]).toMatch(/\[alice\]/);
|
||||
expect(lines[0]).toMatch(/READ/);
|
||||
expect(lines[0]).toMatch(/did:ng:o:q/);
|
||||
expect(lines[0]).toMatch(/myLabel/);
|
||||
expect(lines[0]).toMatch(/→ 1 rows/); // row-count from the 1-row fake result
|
||||
});
|
||||
|
||||
it("sparqlUpdate emits a WRITE line with identity, anchor nuri, and label", async () => {
|
||||
injectFake(true);
|
||||
setCurrentUser("alice");
|
||||
const { lines, restore } = spyConsoleLog();
|
||||
try {
|
||||
await sparqlUpdate("sid-log", "INSERT DATA {}", "did:ng:o:w", "writeLabel");
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
expect(lines.length).toBe(1);
|
||||
expect(lines[0]).toMatch(/\[alice\]/);
|
||||
expect(lines[0]).toMatch(/WRITE/);
|
||||
expect(lines[0]).toMatch(/did:ng:o:w/);
|
||||
expect(lines[0]).toMatch(/writeLabel/);
|
||||
});
|
||||
|
||||
it("docCreate emits a WRITE line with identity and the returned nuri", async () => {
|
||||
injectFake(true);
|
||||
setCurrentUser("alice");
|
||||
const { lines, restore } = spyConsoleLog();
|
||||
try {
|
||||
await docCreate("sid-log", "Graph", "data:graph", "store");
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
expect(lines.length).toBe(1);
|
||||
expect(lines[0]).toMatch(/\[alice\]/);
|
||||
expect(lines[0]).toMatch(/WRITE/);
|
||||
// The nuri is the value returned by ng.doc_create
|
||||
expect(lines[0]).toMatch(/did:ng:o:log-doc/);
|
||||
});
|
||||
|
||||
it("enabled() returns true when set via setAccessLog", () => {
|
||||
setAccessLog(true);
|
||||
expect(enabled()).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("access-log: ON via env var NG_EVENTUALLY_ACCESS_LOG=1", () => {
|
||||
it("emits READ line when env var is set, even without configure() setting", async () => {
|
||||
// Set env var but do NOT pass debugAccessLog=true to configure
|
||||
if (!(globalThis as any)?.process?.env) return; // skip in env-less runtimes
|
||||
process.env.NG_EVENTUALLY_ACCESS_LOG = "1";
|
||||
injectFake(false); // debugAccessLog = false explicitly
|
||||
setCurrentUser("bob");
|
||||
const { lines, restore } = spyConsoleLog();
|
||||
try {
|
||||
await sparqlQuery("sid-log", "SELECT * {}", undefined, "did:ng:o:env-q");
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
expect(lines.length).toBe(1);
|
||||
expect(lines[0]).toMatch(/\[bob\]/);
|
||||
expect(lines[0]).toMatch(/READ/);
|
||||
expect(lines[0]).toMatch(/did:ng:o:env-q/);
|
||||
});
|
||||
|
||||
it("env var NG_EVENTUALLY_ACCESS_LOG=true also enables the log", async () => {
|
||||
if (!(globalThis as any)?.process?.env) return;
|
||||
process.env.NG_EVENTUALLY_ACCESS_LOG = "true";
|
||||
injectFake(false);
|
||||
setCurrentUser("charlie");
|
||||
const { lines, restore } = spyConsoleLog();
|
||||
try {
|
||||
await sparqlUpdate("sid-log", "INSERT DATA {}", "did:ng:o:env-w");
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
expect(lines.length).toBe(1);
|
||||
expect(lines[0]).toMatch(/\[charlie\]/);
|
||||
expect(lines[0]).toMatch(/WRITE/);
|
||||
});
|
||||
|
||||
it("enabled() returns true when env var is set", () => {
|
||||
if (!(globalThis as any)?.process?.env) return;
|
||||
process.env.NG_EVENTUALLY_ACCESS_LOG = "1";
|
||||
setAccessLog(false); // config toggle is off
|
||||
expect(enabled()).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("access-log: identity follows setCurrentUser", () => {
|
||||
it("prefix changes after setCurrentUser", async () => {
|
||||
injectFake(true);
|
||||
setCurrentUser("first-user");
|
||||
const { lines, restore } = spyConsoleLog();
|
||||
try {
|
||||
await sparqlUpdate("sid-log", "INSERT DATA {}", "did:ng:o:id1", "step1");
|
||||
setCurrentUser("second-user");
|
||||
await sparqlUpdate("sid-log", "INSERT DATA {}", "did:ng:o:id2", "step2");
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
expect(lines.length).toBe(2);
|
||||
expect(lines[0]).toMatch(/\[first-user\]/);
|
||||
expect(lines[1]).toMatch(/\[second-user\]/);
|
||||
});
|
||||
|
||||
it("prefix is (none) when no identity is set", async () => {
|
||||
injectFake(true);
|
||||
setCurrentUser(null); // no active identity
|
||||
const { lines, restore } = spyConsoleLog();
|
||||
try {
|
||||
await sparqlUpdate("sid-log", "INSERT DATA {}", "did:ng:o:anon");
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
expect(lines.length).toBe(1);
|
||||
expect(lines[0]).toMatch(/\[\(none\)\]/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,267 @@
|
||||
/**
|
||||
* anti-fork.test.ts — behavioral tests for the ANTI-FORK guard in ensureAccount /
|
||||
* resolveAccountReliably (src/store-registry.ts).
|
||||
*
|
||||
* The guard is: before treating a 0-row read as "genuinely new account" and
|
||||
* provisioning a new set of scope docs, the registry retries a bounded number of
|
||||
* times (with ensureRepoOpen + backoff between each). If the account IS found on
|
||||
* any attempt, it is reused (no second set of docs = no fork). Only if EVERY
|
||||
* attempt still reads 0 rows does the registry treat it as a first-time account
|
||||
* and provision exactly once.
|
||||
*
|
||||
* This file uses a FAKE `ng` that simulates broker sync lag: the sparql_query for
|
||||
* the account record returns 0 rows for the first K calls, then returns real rows.
|
||||
* We control the retry budget via `provisionRetry.attempts`.
|
||||
*/
|
||||
|
||||
import { describe, it, expect, mock, beforeEach, afterAll } from "bun:test";
|
||||
import {
|
||||
ensureAccount,
|
||||
resetRegistryCache,
|
||||
} from "../src/store-registry";
|
||||
import type { RegistrySession } from "../src/store-registry";
|
||||
import {
|
||||
configure,
|
||||
configureStoreRegistry,
|
||||
resetStoreRegistry,
|
||||
resetConfig,
|
||||
} from "../src/polyfill";
|
||||
import { resetOpenedRepos } from "../src/open-repo";
|
||||
|
||||
afterAll(() => {
|
||||
resetConfig();
|
||||
resetStoreRegistry();
|
||||
resetRegistryCache();
|
||||
resetOpenedRepos();
|
||||
});
|
||||
|
||||
const SESSION: RegistrySession = { sessionId: "sid-af", privateStoreId: "PRIV-AF" };
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Fake ng with sync-lag simulation
|
||||
//
|
||||
// `lagCalls` controls how many account-record reads return 0 rows before the
|
||||
// real data is visible. Each call to sparql_query that matches the account
|
||||
// SELECT decrements the counter; once it hits 0 the real data is returned.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
interface Quad { g: string; s: string; p: string; o: string }
|
||||
|
||||
function unescapeLiteral(s: string): string {
|
||||
let out = "";
|
||||
for (let i = 0; i < s.length; i++) {
|
||||
if (s[i] === "\\" && i + 1 < s.length) {
|
||||
const next = s[++i];
|
||||
out += next === "n" ? "\n" : next === "r" ? "\r" : next === "t" ? "\t" : next;
|
||||
} else {
|
||||
out += s[i];
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function makeLaggedNg(lagCalls: number) {
|
||||
const quads: Quad[] = [];
|
||||
let docCounter = 0;
|
||||
let accountQueryCount = 0;
|
||||
|
||||
const doc_create = mock(async (..._a: unknown[]) => `did:ng:o:doc${++docCounter}`);
|
||||
|
||||
const sparql_update = mock(async (...a: unknown[]) => {
|
||||
const query = a[1] as string;
|
||||
const anchor = a[2] as string | undefined;
|
||||
const gm = query.match(/GRAPH <([^>]+)>\s*\{([\s\S]*)\}/);
|
||||
let g: string;
|
||||
let body: string;
|
||||
if (gm) {
|
||||
g = gm[1]!;
|
||||
body = gm[2]!;
|
||||
} else {
|
||||
if (!anchor) return undefined;
|
||||
g = anchor;
|
||||
body = query.replace(/^\s*INSERT DATA\s*\{/, "").replace(/\}\s*$/, "");
|
||||
}
|
||||
const sm = body.match(/<([^>]+)>/);
|
||||
if (!sm) return undefined;
|
||||
const s = sm[1]!;
|
||||
const pairRe = /(?:a|<([^>]+)>)\s+(?:"((?:[^"\\]|\\.)*)"|<([^>]+)>)/g;
|
||||
let m: RegExpExecArray | null;
|
||||
const after = body.slice(body.indexOf(sm[0]) + sm[0].length);
|
||||
while ((m = pairRe.exec(after)) !== null) {
|
||||
const p = m[1] ?? "urn:ng-eventually:shim:Account";
|
||||
const o = m[2] !== undefined ? unescapeLiteral(m[2]) : (m[3] ?? "");
|
||||
quads.push({ g, s, p, o });
|
||||
}
|
||||
return undefined;
|
||||
});
|
||||
|
||||
const sparql_query = mock(async (...a: unknown[]) => {
|
||||
const query = a[1] as string;
|
||||
const anchor = a[3] as string | undefined;
|
||||
|
||||
if (query.includes("<urn:ng-eventually:shim:id>")) {
|
||||
// This is an account SELECT (resolveAccount / loadShim)
|
||||
accountQueryCount++;
|
||||
|
||||
// Still in the lag window → pretend the store hasn't synced yet
|
||||
if (accountQueryCount <= lagCalls) {
|
||||
return { results: { bindings: [] } };
|
||||
}
|
||||
|
||||
// Lag lifted → return real data from the quads store
|
||||
const subjM = query.match(/GRAPH <[^>]+>\s*\{\s*<([^>]+)>\s+a\s+<urn:ng-eventually:shim:Account>/);
|
||||
const onlySubject = subjM ? subjM[1]! : null;
|
||||
const bySubject = new Map<string, Record<string, string>>();
|
||||
for (const q of quads) {
|
||||
if (q.g !== anchor) continue;
|
||||
if (onlySubject !== null && q.s !== onlySubject) continue;
|
||||
const rec = bySubject.get(q.s) ?? {};
|
||||
if (q.p === "urn:ng-eventually:shim:id") rec.id = q.o;
|
||||
if (q.p === "urn:ng-eventually:shim:docPublic") rec.docPublic = q.o;
|
||||
if (q.p === "urn:ng-eventually:shim:docProtected") rec.docProtected = q.o;
|
||||
if (q.p === "urn:ng-eventually:shim:docPrivate") rec.docPrivate = q.o;
|
||||
bySubject.set(q.s, rec);
|
||||
}
|
||||
const bindings = [...bySubject.values()]
|
||||
.filter((r) => r.id)
|
||||
.map((r) => ({
|
||||
id: { value: r.id! },
|
||||
docPublic: { value: r.docPublic ?? "" },
|
||||
docProtected: { value: r.docProtected ?? "" },
|
||||
docPrivate: { value: r.docPrivate ?? "" },
|
||||
}));
|
||||
return { results: { bindings } };
|
||||
}
|
||||
|
||||
// Entity-index SELECT
|
||||
const bindings = quads
|
||||
.filter((q) => q.g === anchor && q.p === "urn:ng-eventually:shim:contains")
|
||||
.map((q) => ({ e: { value: q.o } }));
|
||||
return { results: { bindings } };
|
||||
});
|
||||
|
||||
return {
|
||||
doc_create,
|
||||
sparql_update,
|
||||
sparql_query,
|
||||
_quads: quads,
|
||||
getAccountQueryCount: () => accountQueryCount,
|
||||
};
|
||||
}
|
||||
|
||||
function inject(laggedNg: ReturnType<typeof makeLaggedNg>, attempts: number) {
|
||||
configure({ ng: laggedNg as any, useShape: (() => {}) as any });
|
||||
configureStoreRegistry({
|
||||
getSession: async () => SESSION,
|
||||
normalizeId: (u) => u.trim().toLowerCase(),
|
||||
provisionRetry: { attempts, baseMs: 0, maxStepMs: 0 },
|
||||
});
|
||||
resetRegistryCache();
|
||||
resetOpenedRepos();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Tests
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("anti-fork: resolveAccountReliably / ensureAccount", () => {
|
||||
beforeEach(() => {
|
||||
resetRegistryCache();
|
||||
resetOpenedRepos();
|
||||
});
|
||||
|
||||
it("(a) sync lag: 0 rows for K-1 calls then real rows → reuses existing docs (no fork)", async () => {
|
||||
// budget = 3 attempts; lag = 1 call (the first targeted read returns 0,
|
||||
// but the second (after retry) returns the real data written in the same
|
||||
// session before the cache was dropped). We simulate a scenario where the
|
||||
// account IS already provisioned (written to quads by a previous
|
||||
// ensureAccount call in an earlier "session"), then we reset the cache and
|
||||
// re-call with lag to simulate broker sync delay.
|
||||
|
||||
const laggedNg = makeLaggedNg(0); // no lag — first provision a real account
|
||||
inject(laggedNg, 1);
|
||||
const first = await ensureAccount("LauraLag");
|
||||
expect(laggedNg.doc_create).toHaveBeenCalledTimes(3);
|
||||
|
||||
// Now simulate a fresh session with lag: cache cleared, first K reads are 0
|
||||
// We reuse the SAME quads store (same laggedNg with quads intact) but
|
||||
// rebuild with lag > 0 so the first read returns 0, then real data.
|
||||
const laggedNg2 = makeLaggedNg(1); // 1 empty read before real data
|
||||
// Copy the quads from the first ng into laggedNg2 so it "knows" the account
|
||||
for (const q of laggedNg._quads) {
|
||||
laggedNg2._quads.push(q);
|
||||
}
|
||||
inject(laggedNg2, 3); // 3 attempts, lag=1 → second attempt succeeds
|
||||
|
||||
const second = await ensureAccount("LauraLag");
|
||||
|
||||
// ANTI-FORK: must return the SAME scope docs — no new doc_create
|
||||
expect(second.docPublic).toBe(first.docPublic);
|
||||
expect(second.docProtected).toBe(first.docProtected);
|
||||
expect(second.docPrivate).toBe(first.docPrivate);
|
||||
// doc_create must NOT have been called (the lagged ng2 finds the account on retry)
|
||||
expect(laggedNg2.doc_create).toHaveBeenCalledTimes(0);
|
||||
});
|
||||
|
||||
it("(b) always-0 rows (genuinely new account): provisions exactly ONCE (1 set of docs)", async () => {
|
||||
// Lag longer than the retry budget → account is treated as new
|
||||
const laggedNg = makeLaggedNg(999); // always returns 0 for account queries
|
||||
inject(laggedNg, 2); // budget: 2 attempts, both see 0 → provision
|
||||
|
||||
const rec = await ensureAccount("NewUser");
|
||||
|
||||
// Exactly 3 doc_create calls (1 set of scope docs)
|
||||
expect(laggedNg.doc_create).toHaveBeenCalledTimes(3);
|
||||
expect(rec.docPublic).toMatch(/^did:ng:o:doc/);
|
||||
expect(rec.docProtected).not.toBe(rec.docPublic);
|
||||
expect(rec.docPrivate).not.toBe(rec.docProtected);
|
||||
// Verify budget was fully consumed: both attempts fired before provisioning
|
||||
expect(laggedNg.getAccountQueryCount()).toBe(2);
|
||||
});
|
||||
|
||||
it("idempotence within a session: calling ensureAccount twice never creates 2 sets", async () => {
|
||||
const laggedNg = makeLaggedNg(0); // no lag
|
||||
inject(laggedNg, 1);
|
||||
|
||||
const a = await ensureAccount("SameUser");
|
||||
const b = await ensureAccount("SameUser");
|
||||
|
||||
expect(b).toEqual(a);
|
||||
// Must still be exactly 3 (not 6)
|
||||
expect(laggedNg.doc_create).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
|
||||
it("retry budget of 1 (sync fake): a genuinely-absent account provisions without extra retries", async () => {
|
||||
const laggedNg = makeLaggedNg(0); // will never return lag (account not in quads)
|
||||
inject(laggedNg, 1);
|
||||
|
||||
await ensureAccount("BrandNew");
|
||||
|
||||
// 3 scope docs created exactly once
|
||||
expect(laggedNg.doc_create).toHaveBeenCalledTimes(3);
|
||||
// The targeted account query was called exactly once (no retries at attempts=1)
|
||||
const accountQueryCalls = laggedNg.getAccountQueryCount();
|
||||
expect(accountQueryCalls).toBe(1);
|
||||
});
|
||||
|
||||
it("lag of exactly (attempts-1): found on last allowed attempt → reused, not forked", async () => {
|
||||
// 3 attempts, lag=2 (first 2 calls return 0, 3rd returns real data).
|
||||
// We pre-populate the quads by provisioning with a fresh no-lag ng first.
|
||||
const seedNg = makeLaggedNg(0);
|
||||
inject(seedNg, 1);
|
||||
const original = await ensureAccount("EdgeUser");
|
||||
expect(seedNg.doc_create).toHaveBeenCalledTimes(3);
|
||||
|
||||
// Now re-inject with the same quads but with lag=2, budget=3
|
||||
const laggedNg = makeLaggedNg(2);
|
||||
for (const q of seedNg._quads) laggedNg._quads.push(q);
|
||||
inject(laggedNg, 3);
|
||||
|
||||
const retried = await ensureAccount("EdgeUser");
|
||||
|
||||
// Found on the 3rd attempt (lag=2 means first 2 return 0, 3rd returns real)
|
||||
expect(retried.docPublic).toBe(original.docPublic);
|
||||
expect(retried.docProtected).toBe(original.docProtected);
|
||||
expect(laggedNg.doc_create).toHaveBeenCalledTimes(0); // no new provisioning
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,214 @@
|
||||
/**
|
||||
* open-repo.test.ts — behavioral tests for ensureRepoOpen / ensureReposOpen
|
||||
* (src/open-repo.ts).
|
||||
*
|
||||
* Core invariant: on a fresh session over a persistent wallet, a scope-index
|
||||
* or entity repo is NOT yet in `self.repos`, so an anchored sparql_query returns
|
||||
* 0 rows. `ensureRepoOpen(nuri)` calls `doc_subscribe(nuri, …)` FIRST (which
|
||||
* pushes the repo into the session), then the anchored read returns data.
|
||||
*
|
||||
* Fake design:
|
||||
* - sparql_query returns EMPTY for a nuri UNTIL doc_subscribe has been called
|
||||
* for that nuri (tracked in a Set).
|
||||
* - doc_subscribe is a mock that records calls, fires the callback once
|
||||
* (simulating the initial State push), then returns an unsubscribe fn.
|
||||
*
|
||||
* We test ensureRepoOpen via readUnion (from read-model) because that is the
|
||||
* production caller — it gates on ensureReposOpen internally.
|
||||
*/
|
||||
|
||||
import { describe, it, expect, mock, beforeEach, afterAll } from "bun:test";
|
||||
import { ensureRepoOpen, ensureReposOpen, resetOpenedRepos } from "../src/open-repo";
|
||||
import { readUnion } from "../src/read-model";
|
||||
import { configure, configureStoreRegistry, resetStoreRegistry, resetConfig } from "../src/polyfill";
|
||||
import { resetRegistryCache } from "../src/store-registry";
|
||||
|
||||
afterAll(() => {
|
||||
resetConfig();
|
||||
resetStoreRegistry();
|
||||
resetRegistryCache();
|
||||
resetOpenedRepos();
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
resetOpenedRepos();
|
||||
resetRegistryCache();
|
||||
});
|
||||
|
||||
const SESSION = { sessionId: "sid-or", privateStoreId: "PRIV-OR" };
|
||||
const TYPE = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type";
|
||||
const FP = "http://festipod.org/";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Fake ng builder: tracks which nuris have been doc_subscribe-d.
|
||||
// sparql_query returns rows only AFTER the corresponding nuri is subscribed.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function makeFakeNgWithSubscribe(
|
||||
triplesByDoc: Record<string, Array<[string, string]>>,
|
||||
) {
|
||||
const subscribed = new Set<string>();
|
||||
const subscribeCallOrder: string[] = [];
|
||||
|
||||
// doc_subscribe: record the call, fire callback immediately (initial push), return unsub
|
||||
const doc_subscribe = mock(async (nuri: string, _sid: string, cb: (r: unknown) => void) => {
|
||||
subscribed.add(nuri);
|
||||
subscribeCallOrder.push(nuri);
|
||||
// Simulate initial State push (synchronously deferred so the subscription
|
||||
// setup promise path in ensureRepoOpen can resolve it).
|
||||
setTimeout(() => cb({ V0: { State: {} } }), 0);
|
||||
return () => {}; // unsubscribe fn
|
||||
});
|
||||
|
||||
const sparql_query = mock(async (_sid: string, _query: string, _base: unknown, anchor: unknown) => {
|
||||
const doc = anchor as string | undefined;
|
||||
if (!doc) return { results: { bindings: [] } };
|
||||
// Only return data if the repo has been subscribed (i.e. opened)
|
||||
if (!subscribed.has(doc)) return { results: { bindings: [] } };
|
||||
const triples = triplesByDoc[doc];
|
||||
if (!triples) return { results: { bindings: [] } };
|
||||
const bindings = triples.map(([p, o]) => ({
|
||||
s: { value: doc },
|
||||
p: { value: p },
|
||||
o: { value: o },
|
||||
}));
|
||||
return { results: { bindings } };
|
||||
});
|
||||
|
||||
const doc_create = mock(async () => "did:ng:o:new");
|
||||
const sparql_update = mock(async () => undefined);
|
||||
|
||||
return { doc_subscribe, sparql_query, doc_create, sparql_update, subscribed, subscribeCallOrder };
|
||||
}
|
||||
|
||||
function inject(ng: ReturnType<typeof makeFakeNgWithSubscribe>) {
|
||||
configure({ ng: ng as any, useShape: (() => {}) as any });
|
||||
configureStoreRegistry({
|
||||
getSession: async () => SESSION,
|
||||
normalizeId: (u: string) => u,
|
||||
provisionRetry: { attempts: 1 },
|
||||
});
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Tests
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("ensureRepoOpen", () => {
|
||||
it("calls doc_subscribe BEFORE the anchored read returns data", async () => {
|
||||
const ng = makeFakeNgWithSubscribe({
|
||||
"did:ng:o:a": [[TYPE, `${FP}Event`], [`${FP}title`, "Alpha"]],
|
||||
});
|
||||
inject(ng);
|
||||
|
||||
// Directly call ensureRepoOpen then verify read sees data
|
||||
await ensureRepoOpen("did:ng:o:a");
|
||||
|
||||
// doc_subscribe was called for the nuri
|
||||
expect(ng.doc_subscribe).toHaveBeenCalledTimes(1);
|
||||
expect(ng.subscribeCallOrder[0]).toBe("did:ng:o:a");
|
||||
|
||||
// sparql_query was called AFTER subscribe (ensureRepoOpen guarantees ordering)
|
||||
const result = await readUnion(["did:ng:o:a"]);
|
||||
expect(result.length).toBe(1);
|
||||
expect(result[0]!.props[`${FP}title`]).toEqual(["Alpha"]);
|
||||
});
|
||||
|
||||
it("WITHOUT doc_subscribe, sparql_query returns 0 rows (verifies fake mechanics)", async () => {
|
||||
const ng = makeFakeNgWithSubscribe({
|
||||
"did:ng:o:a": [[TYPE, `${FP}Event`], [`${FP}title`, "Alpha"]],
|
||||
});
|
||||
inject(ng);
|
||||
|
||||
// Do NOT call ensureRepoOpen — subscribed Set remains empty
|
||||
// Query directly (bypass readUnion which calls ensureReposOpen internally)
|
||||
const result = await ng.sparql_query("sid-or", "SELECT ?s ?p ?o WHERE { ?s ?p ?o }", undefined, "did:ng:o:a");
|
||||
const bindings = (result as any).results.bindings;
|
||||
expect(bindings.length).toBe(0); // not subscribed → 0 rows (confirms fake design)
|
||||
});
|
||||
|
||||
it("idempotence: a 2nd ensureRepoOpen for the same nuri does NOT re-subscribe", async () => {
|
||||
const ng = makeFakeNgWithSubscribe({
|
||||
"did:ng:o:b": [[TYPE, `${FP}Event`]],
|
||||
});
|
||||
inject(ng);
|
||||
|
||||
await ensureRepoOpen("did:ng:o:b");
|
||||
await ensureRepoOpen("did:ng:o:b"); // second call
|
||||
|
||||
// doc_subscribe must have been called exactly ONCE
|
||||
expect(ng.doc_subscribe).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("no-op when the fake ng has no doc_subscribe (unit fake path)", async () => {
|
||||
// Fake ng WITHOUT doc_subscribe
|
||||
const noSubscribeNg = {
|
||||
doc_create: mock(async () => "did:ng:o:new"),
|
||||
sparql_update: mock(async () => undefined),
|
||||
sparql_query: mock(async () => ({ results: { bindings: [] } })),
|
||||
};
|
||||
configure({ ng: noSubscribeNg as any, useShape: (() => {}) as any });
|
||||
configureStoreRegistry({
|
||||
getSession: async () => SESSION,
|
||||
normalizeId: (u: string) => u,
|
||||
provisionRetry: { attempts: 1 },
|
||||
});
|
||||
|
||||
// Must not throw; nuri is added to opened Set (guard skips subscribe)
|
||||
await expect(ensureRepoOpen("did:ng:o:c")).resolves.toBeUndefined();
|
||||
|
||||
// Calling again should also be a no-op (idempotent, already in opened)
|
||||
await expect(ensureRepoOpen("did:ng:o:c")).resolves.toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("ensureReposOpen", () => {
|
||||
it("opens all provided nuris in parallel (one subscribe per unique nuri)", async () => {
|
||||
const ng = makeFakeNgWithSubscribe({
|
||||
"did:ng:o:x": [[TYPE, `${FP}Event`]],
|
||||
"did:ng:o:y": [[TYPE, `${FP}Event`]],
|
||||
});
|
||||
inject(ng);
|
||||
|
||||
await ensureReposOpen(["did:ng:o:x", "did:ng:o:y"]);
|
||||
|
||||
expect(ng.doc_subscribe).toHaveBeenCalledTimes(2);
|
||||
expect(ng.subscribed.has("did:ng:o:x")).toBe(true);
|
||||
expect(ng.subscribed.has("did:ng:o:y")).toBe(true);
|
||||
});
|
||||
|
||||
it("deduplicates: repeated nuri in input leads to exactly one subscribe", async () => {
|
||||
const ng = makeFakeNgWithSubscribe({
|
||||
"did:ng:o:dup": [[TYPE, `${FP}Event`]],
|
||||
});
|
||||
inject(ng);
|
||||
|
||||
await ensureReposOpen(["did:ng:o:dup", "did:ng:o:dup", "did:ng:o:dup"]);
|
||||
|
||||
expect(ng.doc_subscribe).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("empty or all-falsy input is a no-op (no subscribe calls)", async () => {
|
||||
const ng = makeFakeNgWithSubscribe({});
|
||||
inject(ng);
|
||||
|
||||
await ensureReposOpen([]);
|
||||
await ensureReposOpen(["" as any]);
|
||||
|
||||
expect(ng.doc_subscribe).toHaveBeenCalledTimes(0);
|
||||
});
|
||||
|
||||
it("readUnion triggers doc_subscribe then returns data (integration path)", async () => {
|
||||
const ng = makeFakeNgWithSubscribe({
|
||||
"did:ng:o:p": [[TYPE, `${FP}Participation`], [`${FP}event`, "did:ng:o:e"]],
|
||||
});
|
||||
inject(ng);
|
||||
|
||||
const subjects = await readUnion(["did:ng:o:p"]);
|
||||
|
||||
// doc_subscribe was called as part of ensureReposOpen inside readUnion
|
||||
expect(ng.doc_subscribe).toHaveBeenCalledTimes(1);
|
||||
expect(subjects.length).toBe(1);
|
||||
expect(subjects[0]!.props[`${FP}event`]).toEqual(["did:ng:o:e"]);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user