fix(client): durcir le cold-start du shim — ensureRepoOpen(anchor) avant lecture/écriture
Défensif : loadShim/resolveAccount/ensureAccount ouvrent l'anchor (private-store-root) avant de lire/écrire le compte shim, comme le fait déjà readScopeIndex. Robustesse same-session si l'anchor est là-mais-pas-encore-souscrit. NB (vérifié nextgraph-rs) : sur le login broker normal, le bootstrap charge le private-store dans self.repos AVANT de rendre la session à JS → un wallet FRAIS retourne 0 rows (pas RepoNotFound) et provisionne. Il n'existe AUCUN primitif JS pour ouvrir un repo *inconnu* : ce heal n'est pas un remède à un store non bootstrappé (limite NextGraph), juste une robustesse d'ouverture same-session. Tests : cold-start-anchor.test.ts (rouge-avant/vert-après unit) ; harness e2e repro-fresh-wallet (mint un wallet neuf par run — comble le trou "aucun test de démarrage à froid sur wallet vierge"). Fakes anti-fork/watch-shape honorent désormais la barrière first-State dont dépend le heal. e2e réel 42/42. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -140,6 +140,72 @@ export async function launchWalletContext(): Promise<BrowserContext> {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a BRAND-NEW wallet in a BRAND-NEW profile dir and RETURN the launched
|
||||
* context, without a `.wallet-ready` marker and WITHOUT tearing the context down.
|
||||
* Unlike {@link ensureWallet} (which reuses one persistent dedicated wallet across
|
||||
* runs — so it is always "hot"), this mints a genuinely FRESH wallet each call so
|
||||
* the cold-start (private-store repo not yet in `self.repos`) can be exercised.
|
||||
*
|
||||
* Same headless nextgraph.eu creation + first-login-bootstrap flow as ensureWallet,
|
||||
* but the context stays OPEN and is returned (with its dir) so the caller can then
|
||||
* open the SDK page in the SAME profile — i.e. the very first app session over a
|
||||
* wallet that has never run the app. Caller cleans up ctx + dir.
|
||||
*/
|
||||
export async function createFreshWalletContext(): Promise<{
|
||||
ctx: BrowserContext;
|
||||
dir: string;
|
||||
name: string;
|
||||
}> {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ng-eventually-fresh-"));
|
||||
const name = "ng-fresh-" + Date.now().toString(36) + Math.random().toString(36).slice(2, 6);
|
||||
const ctx = await chromium.launchPersistentContext(dir, {
|
||||
headless: true,
|
||||
executablePath: resolveChromePath(),
|
||||
args: LAUNCH_ARGS,
|
||||
});
|
||||
const page = ctx.pages()[0] || (await ctx.newPage());
|
||||
page.on("pageerror", () => {});
|
||||
await page.goto("https://nextgraph.eu/", { waitUntil: "domcontentloaded", timeout: 30000 });
|
||||
const createButton = page.getByText("Create Wallet", { exact: true });
|
||||
await createButton.waitFor({ state: "visible", timeout: 15000 });
|
||||
await createButton.click();
|
||||
|
||||
await page.waitForURL("**/account*", { timeout: 15000 }).catch(() => {});
|
||||
const acceptButton = page.getByText("I accept", { exact: true });
|
||||
await acceptButton.waitFor({ state: "visible", timeout: 15000 });
|
||||
await acceptButton.click();
|
||||
|
||||
const usernameInput = page.locator("#username-input");
|
||||
await usernameInput.waitFor({ state: "visible", timeout: 30000 });
|
||||
await usernameInput.fill(name);
|
||||
const passwordInput = page.locator("#password-input");
|
||||
await passwordInput.waitFor({ state: "visible", timeout: 5000 });
|
||||
await passwordInput.fill(WALLET_PASSWORD);
|
||||
|
||||
const submitButton = page.getByText("create my wallet", { exact: false });
|
||||
await submitButton.waitFor({ state: "visible", timeout: 5000 });
|
||||
await submitButton.click();
|
||||
|
||||
await page.waitForURL("**/#/wallet/login", { timeout: 30000 });
|
||||
await page.waitForTimeout(2000);
|
||||
|
||||
// First login → bootstrap the verifier repos from the broker (this is what a
|
||||
// brand-new wallet does on its very first unlock).
|
||||
const walletLink = page.getByText("Click here to login with your wallet");
|
||||
if (await walletLink.isVisible({ timeout: 5000 }).catch(() => false)) {
|
||||
await walletLink.click();
|
||||
await page.waitForTimeout(1000);
|
||||
}
|
||||
const loginPassword = page.locator('input[type="password"]');
|
||||
await loginPassword.waitFor({ state: "visible", timeout: 10000 });
|
||||
await loginPassword.fill(WALLET_PASSWORD);
|
||||
await loginPassword.press("Enter");
|
||||
await page.waitForTimeout(10000);
|
||||
await page.close().catch(() => {});
|
||||
return { ctx, dir, name };
|
||||
}
|
||||
|
||||
/**
|
||||
* Launch a persistent context on a FRESH, EMPTY profile dir (its own userDataDir).
|
||||
* Empty local storage ⇒ empty verifier repo cache ⇒ the reconnection cold-start:
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
/**
|
||||
* COLD-START repro — a genuinely FRESH wallet (never ran the app) driving the
|
||||
* shim's first account resolution/provision.
|
||||
*
|
||||
* Unlike `run.ts`, which reuses ONE dedicated wallet (always "hot" — its
|
||||
* private-store repo is already in the verifier's `self.repos`), this mints a
|
||||
* BRAND-NEW wallet + fresh profile per run and opens the SDK page over it as the
|
||||
* very first session. It then, in order:
|
||||
* 1) probes the RAW anchored shim SELECT on `did:ng:${private_store_id}` — the
|
||||
* cold-start bug surfaces here as `RepoNotFound` (the private-store repo not
|
||||
* yet open) rather than a silent 0 rows;
|
||||
* 2) runs `ensureAccount` (resetRegistryCache first) — the app's first-login
|
||||
* bootstrap — and asserts it provisions 3 scope docs WITHOUT throwing;
|
||||
* 3) re-resolves the SAME id from a fresh anchored read and asserts it returns
|
||||
* the SAME docs (real persistence in the shim).
|
||||
*
|
||||
* Expected BEFORE the fix: step 1 throws RepoNotFound; step 2/3 fail to persist.
|
||||
* Expected AFTER the fix: step 1 may still throw (raw, no open), but step 2/3
|
||||
* succeed because ensureAccount opens the anchor repo before read/write.
|
||||
*
|
||||
* Run: `bun run e2e/repro-fresh-wallet.ts`.
|
||||
*/
|
||||
|
||||
import * as fs from "node:fs";
|
||||
import type { Frame, Page, BrowserContext } from "playwright";
|
||||
import { buildBundle, serveHarness, createFreshWalletContext, setupBrokerPage } from "./broker";
|
||||
|
||||
type Check = { name: string; ok: boolean; detail?: string };
|
||||
const results: Check[] = [];
|
||||
function check(name: string, ok: boolean, detail?: string): void {
|
||||
results.push({ name, ok, detail });
|
||||
console.log(` [${ok ? "PASS" : "FAIL"}] ${name}${detail ? " — " + detail : ""}`);
|
||||
}
|
||||
|
||||
function sdk<T>(frame: Frame, method: string, ...args: unknown[]): Promise<T> {
|
||||
return frame.evaluate(
|
||||
([m, a]) => (window as any).__sdk[m as string](...(a as unknown[])),
|
||||
[method, args] as const,
|
||||
) as Promise<T>;
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
console.log("[repro] building SDK page bundle...");
|
||||
buildBundle();
|
||||
const { url, close: closeServer } = await serveHarness();
|
||||
console.log(`[repro] harness served at ${url}`);
|
||||
|
||||
console.log("[repro] creating a BRAND-NEW wallet (fresh profile)...");
|
||||
let ctx: BrowserContext | null = null;
|
||||
let dir: string | null = null;
|
||||
let page: Page | null = null;
|
||||
try {
|
||||
const fresh = await createFreshWalletContext();
|
||||
ctx = fresh.ctx;
|
||||
dir = fresh.dir;
|
||||
console.log(`[repro] fresh wallet: ${fresh.name}`);
|
||||
|
||||
page = await ctx.newPage();
|
||||
page.on("pageerror", (e) => console.error("[iframe error]", e.message));
|
||||
page.on("console", (m) => {
|
||||
if (m.type() === "error") console.error("[iframe console]", m.text());
|
||||
});
|
||||
|
||||
console.log("[repro] opening SDK page over the FRESH wallet (first-ever app session)...");
|
||||
const frame = await setupBrokerPage(page, url);
|
||||
await frame.waitForFunction(() => (window as any).__sdk !== undefined, { timeout: 30000 });
|
||||
await frame.waitForFunction(() => (window as any).__sdk.status() === "connected", {
|
||||
timeout: 60000,
|
||||
});
|
||||
console.log("[repro] connected. Driving the cold-start shim resolution...");
|
||||
|
||||
// 1) RAW anchored shim probe — the diagnostic. Reports RepoNotFound if the
|
||||
// private-store repo is not yet open in this fresh session.
|
||||
const probe = await sdk<any>(frame, "shimAnchorProbe");
|
||||
console.log(
|
||||
` [DIAG] raw anchored shim read: threw=${probe.threw} error=${probe.error} rows=${probe.rows}`,
|
||||
);
|
||||
|
||||
// 2) ensureAccount — the real bootstrap. This MUST provision cleanly on a fresh
|
||||
// wallet (all 3 docs truthy, no throw). This is the load-bearing assertion.
|
||||
const ensured = await sdk<any>(frame, "coldEnsureAccount", "@cold-user-1");
|
||||
check(
|
||||
"fresh wallet: ensureAccount provisions the account without throwing",
|
||||
!ensured.threw && !!ensured.docPublic && !!ensured.docProtected && !!ensured.docPrivate,
|
||||
ensured.threw
|
||||
? `THREW: ${ensured.error}`
|
||||
: `pub=${String(ensured.docPublic).slice(0, 22)}… prot=${String(ensured.docProtected).slice(0, 22)}…`,
|
||||
);
|
||||
|
||||
// 3) Re-resolve from a FRESH anchored read — proves the shim actually persisted.
|
||||
const verified = await sdk<any>(frame, "verifyShimPersisted", "@cold-user-1");
|
||||
check(
|
||||
"fresh wallet: the provisioned account persists (re-resolves the SAME docs, no RepoNotFound)",
|
||||
!verified.threw &&
|
||||
verified.docPublic === ensured.docPublic &&
|
||||
verified.docProtected === ensured.docProtected &&
|
||||
verified.docPrivate === ensured.docPrivate,
|
||||
verified.threw
|
||||
? `THREW: ${verified.error}`
|
||||
: `same=${verified.docPublic === ensured.docPublic && verified.docProtected === ensured.docProtected}`,
|
||||
);
|
||||
} finally {
|
||||
try { if (page) await page.close(); } catch { /* ignore */ }
|
||||
try { if (ctx) await ctx.close(); } catch { /* ignore */ }
|
||||
try { if (dir) fs.rmSync(dir, { recursive: true, force: true }); } catch { /* ignore */ }
|
||||
closeServer();
|
||||
}
|
||||
|
||||
const passed = results.filter((r) => r.ok).length;
|
||||
const failed = results.length - passed;
|
||||
console.log(`\n══ cold-start repro: ${passed} passed, ${failed} failed ══`);
|
||||
if (failed > 0) {
|
||||
for (const r of results.filter((x) => !x.ok)) console.log(` - ${r.name}: ${r.detail ?? ""}`);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
main().catch((e) => {
|
||||
console.error("[repro] fatal:", e);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -571,6 +571,67 @@ const identity = new IdentityStore(
|
||||
return { priv, prot, pub };
|
||||
},
|
||||
|
||||
/**
|
||||
* COLD-START anchor probe. Runs the EXACT shim SELECT the registry issues,
|
||||
* anchored to `did:ng:${private_store_id}` (the shim anchor), as the very first
|
||||
* thing in a fresh session — BEFORE anything opens that repo. Reports whether the
|
||||
* raw anchored query threw `RepoNotFound` (the cold-start bug: the private-store
|
||||
* repo not yet in `self.repos`) or returned rows. Uses the low-level docs
|
||||
* primitive directly so nothing (open-repo, ensureAccount) opens the repo first.
|
||||
*/
|
||||
async shimAnchorProbe() {
|
||||
const s = session ?? (await sessionReady);
|
||||
const anchor = `did:ng:${s.private_store_id}`;
|
||||
const query =
|
||||
"SELECT ?acc WHERE { GRAPH <" +
|
||||
anchor +
|
||||
"> { ?acc a <urn:ng-eventually:shim:Account> } }";
|
||||
try {
|
||||
const res: any = await docs.sparqlQuery(s.session_id, query, undefined, anchor);
|
||||
const rows = Array.isArray(res) ? res.length : (res?.results?.bindings?.length ?? 0);
|
||||
return { threw: false, error: null, rows, anchor };
|
||||
} catch (e: any) {
|
||||
return { threw: true, error: String(e?.message ?? e), rows: -1, anchor };
|
||||
}
|
||||
},
|
||||
/**
|
||||
* COLD-START account provision. resetRegistryCache then ensureAccount(id) — the
|
||||
* real bootstrap the app runs on first login. On a fresh wallet, if the anchor
|
||||
* repo isn't open, resolveAccount's read AND ensureAccount's provision write both
|
||||
* hit RepoNotFound; the account never persists. Returns the 3 scope docs (all
|
||||
* truthy iff provisioning succeeded) so the runner can gate on real persistence.
|
||||
*/
|
||||
async coldEnsureAccount(id: string) {
|
||||
storeRegistry.resetRegistryCache();
|
||||
try {
|
||||
const rec = await storeRegistry.ensureAccount(id);
|
||||
return {
|
||||
threw: false,
|
||||
error: null,
|
||||
docPublic: rec.docPublic,
|
||||
docProtected: rec.docProtected,
|
||||
docPrivate: rec.docPrivate,
|
||||
};
|
||||
} catch (e: any) {
|
||||
return { threw: true, error: String(e?.message ?? e), docPublic: "", docProtected: "", docPrivate: "" };
|
||||
}
|
||||
},
|
||||
/**
|
||||
* VERIFY the provisioned account actually PERSISTED to the shim: resetRegistryCache
|
||||
* then re-resolve the SAME id via a fresh anchored read. Returns whether the read
|
||||
* threw + the resolved docs. After the fix, on a fresh wallet this returns the SAME
|
||||
* docs coldEnsureAccount minted (real persistence, no RepoNotFound).
|
||||
*/
|
||||
async verifyShimPersisted(id: string) {
|
||||
storeRegistry.resetRegistryCache();
|
||||
try {
|
||||
const rec = await storeRegistry.ensureAccount(id);
|
||||
return { threw: false, error: null, docPublic: rec.docPublic, docProtected: rec.docProtected, docPrivate: rec.docPrivate };
|
||||
} catch (e: any) {
|
||||
return { threw: true, error: String(e?.message ?? e), docPublic: "", docProtected: "", docPrivate: "" };
|
||||
}
|
||||
},
|
||||
|
||||
// ── watchShape (reactive useQuery-shaped read) ───────────────────────────
|
||||
// A minimal SHEX-ish ShapeType pinning rdf:type to an e2e class IRI. watchShape
|
||||
// reads only `.shape`/`.schema[...].predicates[rdf:type].dataTypes[].literals`
|
||||
|
||||
@@ -235,6 +235,10 @@ export async function loadShim(): Promise<Map<string, AccountRecord>> {
|
||||
}
|
||||
}`;
|
||||
const map = new Map<string, AccountRecord>();
|
||||
// COLD-START heal: open the anchor (private-store-root) repo before the shim scan,
|
||||
// so an anchored read on a fresh wallet whose anchor repo isn't yet in `self.repos`
|
||||
// resolves instead of throwing `RepoNotFound`. Idempotent; see resolveAccount.
|
||||
await ensureRepoOpen(anchor);
|
||||
try {
|
||||
const result = await sparqlQuery(s.sessionId, query, undefined, anchor, "loadShim");
|
||||
// Group ALL bindings by account key first, then pick the CANONICAL doc per
|
||||
@@ -281,6 +285,21 @@ export async function resolveAccount(id: string): Promise<AccountRecord | null>
|
||||
|
||||
const s = await session();
|
||||
const anchor = await anchorNuri();
|
||||
// COLD-START heal (polyfill-era): the shim lives in the private-store-root graph
|
||||
// (the anchor). An anchored `sparql_query` on a repo absent from the verifier's
|
||||
// `self.repos` throws `RepoNotFound` — a HARD error here, unlike per-entity docs
|
||||
// which silently read 0 (the private/store target resolves through
|
||||
// `resolve_target_for_sparql`, which requires the repo loaded). Open the anchor
|
||||
// ONCE before reading, idempotently — the SAME open-before-read guard
|
||||
// `readScopeIndex` applies to its index doc. NB (see docs/nextgraph-current-state):
|
||||
// `ensureRepoOpen` (→ `doc_subscribe`) can only OPEN/subscribe a repo the session
|
||||
// ALREADY holds; it cannot pull a genuinely-absent repo (no JS primitive does). On
|
||||
// the real broker the private-store repo is bootstrapped into `self.repos` at
|
||||
// connect, so this is a defensive same-session open — it makes the anchor read/write
|
||||
// robust to a not-yet-subscribed anchor without ever being able to hide a truly
|
||||
// unbootstrapped store. No-op with the unit fake ng and when the repo is already
|
||||
// open. See open-repo.ts.
|
||||
await ensureRepoOpen(anchor);
|
||||
// `subj` is already IRI-safe (accountSubject → escapeIri); `anchor` is a
|
||||
// trusted-shaped NURI → assertNuri. The query is bounded to this one subject.
|
||||
const subj = accountSubject(id);
|
||||
@@ -443,6 +462,13 @@ export async function ensureAccount(id: string): Promise<AccountRecord> {
|
||||
|
||||
const s = await session();
|
||||
const anchor = await anchorNuri();
|
||||
// COLD-START heal: open the anchor (private-store-root) repo before PROVISIONING
|
||||
// into it. The provision `sparqlUpdate` targets the private-store graph, which
|
||||
// resolves through the same repo-loaded requirement — an unopened anchor repo on
|
||||
// a fresh wallet would throw `RepoNotFound` and the account would never persist.
|
||||
// Idempotent; a no-op once the repo is open (resolveAccountReliably already
|
||||
// opened it on the read above in the common path). See open-repo.ts.
|
||||
await ensureRepoOpen(anchor);
|
||||
const subj = accountSubject(id);
|
||||
// `subj` is already IRI-safe (accountSubject → escapeIri). `anchor` is a
|
||||
// trusted-shaped NURI → assertNuri. `id` is UNTRUSTED text in a LITERAL
|
||||
|
||||
@@ -178,12 +178,14 @@ function makeLaggyFakeNg(opts: { lag?: number } = {}) {
|
||||
.map((q) => ({ e: { value: q.o } }));
|
||||
return { results: { bindings } };
|
||||
});
|
||||
// doc_subscribe: immediately push a State (the barrier) so ensureRepoOpen resolves.
|
||||
const doc_subscribe = mock(async (..._a: unknown[]) => {
|
||||
// Return an async-iterator-like the subscribe wrapper can consume; but the
|
||||
// registry only needs `typeof doc_subscribe === "function"` for the reactive
|
||||
// path. open-repo's subscribeDoc handles the actual shape; here it is unused
|
||||
// (ensureAccount does not call ensureRepoOpen). Kept as a real fn.
|
||||
// doc_subscribe: immediately push a State (the sync barrier) so `ensureRepoOpen`
|
||||
// resolves at once. `resolveAccount`/`ensureAccount` now open the anchor repo
|
||||
// (open-repo.ts) before reading/writing the shim (the cold-start heal); the real
|
||||
// broker pushes `TabInfo` then a first `State` on subscribe, and open-repo awaits
|
||||
// that `State`. Model it: invoke the callback with a `State` AppResponse so the
|
||||
// barrier is reached synchronously (no 8s fallback → the retry tests stay fast).
|
||||
const doc_subscribe = mock(async (_repo: unknown, _sid: unknown, cb: Function) => {
|
||||
if (typeof cb === "function") cb({ V0: { State: {} } });
|
||||
return () => {};
|
||||
});
|
||||
return {
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
/**
|
||||
* cold-start-anchor.test.ts — the shim ANCHOR (private-store-root) must be OPENED
|
||||
* before the registry reads/writes it, or a cold anchor throws `RepoNotFound`.
|
||||
*
|
||||
* ── The gap this pins ──────────────────────────────────────────────────────
|
||||
* The shim lives in the private-store-root graph (`did:ng:${privateStoreId}`, the
|
||||
* "anchor"). Unlike a per-entity doc — whose anchored read on an unopened repo
|
||||
* SILENTLY returns 0 rows — the private/store target resolves through the verifier's
|
||||
* `resolve_target_for_sparql`, which HARD-errors `RepoNotFound` when the repo is not
|
||||
* in `self.repos` (verified in nextgraph-rs `request_processor.rs`). On a wallet whose
|
||||
* anchor repo is not yet loaded, both the shim READ (`resolveAccount`/`loadShim`) and
|
||||
* the provision WRITE (`ensureAccount`) throw — so the account never provisions.
|
||||
*
|
||||
* The heal: `resolveAccount`/`loadShim`/`ensureAccount` call `ensureRepoOpen(anchor)`
|
||||
* (open-repo.ts, via `doc_subscribe` + first-`State` barrier) before touching the
|
||||
* shim — the same open-before-read guard `readScopeIndex` already applies to its
|
||||
* index doc. This suite models a fake `ng` where the anchor throws `RepoNotFound`
|
||||
* UNTIL it has been `doc_subscribe`-d, and asserts the registry provisions cleanly.
|
||||
*
|
||||
* RED without the heal (ensureAccount would throw on the cold anchor); GREEN with it.
|
||||
*/
|
||||
|
||||
import { describe, it, expect, mock, afterAll, beforeEach } from "bun:test";
|
||||
import { ensureAccount, resolveWriteGraph, resetRegistryCache } from "../src/store-registry";
|
||||
import { resetOpenedRepos } from "../src/open-repo";
|
||||
import {
|
||||
configure,
|
||||
configureStoreRegistry,
|
||||
resetStoreRegistry,
|
||||
resetConfig,
|
||||
} from "../src/polyfill";
|
||||
|
||||
const SESSION = { sessionId: "sid-cold", privateStoreId: "PRIV-COLD" };
|
||||
const ANCHOR = `did:ng:${SESSION.privateStoreId}`;
|
||||
|
||||
afterAll(() => {
|
||||
resetConfig();
|
||||
resetStoreRegistry();
|
||||
resetRegistryCache();
|
||||
resetOpenedRepos();
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
resetRegistryCache();
|
||||
resetOpenedRepos();
|
||||
});
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
* A fake `ng` whose ANCHOR repo behaves like the real private-store target:
|
||||
* `sparql_query`/`sparql_update` anchored to it THROW `RepoNotFound` until the
|
||||
* anchor has been `doc_subscribe`-d (i.e. opened into `self.repos`). Any OTHER
|
||||
* anchor (per-entity docs) behaves normally. `doc_subscribe` fires the first
|
||||
* `State` so `ensureRepoOpen` crosses the barrier.
|
||||
*/
|
||||
function makeColdAnchorNg() {
|
||||
const quads: Quad[] = [];
|
||||
let docCounter = 0;
|
||||
const opened = new Set<string>();
|
||||
let anchorSubscribes = 0;
|
||||
|
||||
const doc_create = mock(async () => `did:ng:o:doc${++docCounter}`);
|
||||
|
||||
const doc_subscribe = mock(async (nuri: string, _sid: string, cb: (r: unknown) => void) => {
|
||||
if (nuri === ANCHOR) anchorSubscribes += 1;
|
||||
opened.add(nuri);
|
||||
setTimeout(() => cb({ V0: { State: {} } }), 0);
|
||||
return () => {};
|
||||
});
|
||||
|
||||
const sparql_update = mock(async (_sid: string, query: string, anchor?: string) => {
|
||||
if (anchor === ANCHOR && !opened.has(ANCHOR)) throw new Error("RepoNotFound");
|
||||
// Parse the shim INSERT (GRAPH <anchor> { <subj> a <Account> ; <p> "o" … }).
|
||||
const gm = query.match(/GRAPH <([^>]+)>\s*\{([\s\S]*)\}/);
|
||||
if (!gm) return undefined;
|
||||
const g = gm[1]!;
|
||||
const body = gm[2]!;
|
||||
const sm = body.match(/<([^>]+)>/);
|
||||
if (!sm) return undefined;
|
||||
const s = sm[1]!;
|
||||
const after = body.slice(body.indexOf(sm[0]) + sm[0].length);
|
||||
const pairRe = /(?:a|<([^>]+)>)\s+(?:"((?:[^"\\]|\\.)*)"|<([^>]+)>)/g;
|
||||
let m: RegExpExecArray | null;
|
||||
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 (_sid: string, query: string, _base: unknown, anchor?: string) => {
|
||||
if (anchor === ANCHOR && !opened.has(ANCHOR)) throw new Error("RepoNotFound");
|
||||
const subjM = query.match(
|
||||
/<([^>]+)>\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 } };
|
||||
});
|
||||
|
||||
return {
|
||||
doc_create, doc_subscribe, sparql_update, sparql_query,
|
||||
_quads: quads,
|
||||
anchorSubscribeCount: () => anchorSubscribes,
|
||||
};
|
||||
}
|
||||
|
||||
function inject(ng: ReturnType<typeof makeColdAnchorNg>) {
|
||||
configure({ ng: ng as any, useShape: (() => {}) as any });
|
||||
configureStoreRegistry({
|
||||
getSession: async () => SESSION,
|
||||
normalizeId: (u: string) => u.trim().replace(/^@+/, "").toLowerCase(),
|
||||
});
|
||||
resetRegistryCache();
|
||||
resetOpenedRepos();
|
||||
}
|
||||
|
||||
describe("cold-start anchor heal", () => {
|
||||
it("ensureAccount provisions over a COLD anchor (RepoNotFound-until-opened) without throwing", async () => {
|
||||
const ng = makeColdAnchorNg();
|
||||
inject(ng);
|
||||
|
||||
// Without the open-before-shim heal, the read AND the provision write would both
|
||||
// throw RepoNotFound on the cold anchor and the account would never persist.
|
||||
const rec = await ensureAccount("@cold-alice");
|
||||
expect(rec.docPublic).toBeTruthy();
|
||||
expect(rec.docProtected).toBeTruthy();
|
||||
expect(rec.docPrivate).toBeTruthy();
|
||||
|
||||
// The anchor repo was actually opened (doc_subscribe-d) before the shim op.
|
||||
expect(ng.anchorSubscribeCount()).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it("the provisioned account re-resolves from the shim (real persistence, no RepoNotFound)", async () => {
|
||||
const ng = makeColdAnchorNg();
|
||||
inject(ng);
|
||||
|
||||
const first = await ensureAccount("@cold-bob");
|
||||
// Fresh cache → a real anchored re-read of the shim (anchor already opened → OK).
|
||||
resetRegistryCache();
|
||||
const again = await ensureAccount("@cold-bob");
|
||||
expect(again.docPublic).toBe(first.docPublic);
|
||||
expect(again.docProtected).toBe(first.docProtected);
|
||||
expect(again.docPrivate).toBe(first.docPrivate);
|
||||
});
|
||||
|
||||
it("resolveWriteGraph (scope resolver) works over a cold anchor", async () => {
|
||||
const ng = makeColdAnchorNg();
|
||||
inject(ng);
|
||||
const g = await resolveWriteGraph("@cold-carol", "protected");
|
||||
expect(g).toBeTruthy();
|
||||
});
|
||||
});
|
||||
@@ -68,6 +68,13 @@ function makeFake(opts?: { holdState?: boolean }) {
|
||||
const hold = opts?.holdState ?? false;
|
||||
// Nuris whose barrier `State` has been released (auto-fire on future subscribe).
|
||||
const released = new Set<string>();
|
||||
// The shim ANCHOR (private-store-root) is ALWAYS loaded/synced on the real broker
|
||||
// (the store repo is bootstrapped at connect), so its barrier `State` is always
|
||||
// available. `resolveAccount`/`ensureAccount` now open it (the cold-start heal)
|
||||
// before touching the shim — pre-release it here so `holdState` (which gates the
|
||||
// per-ENTITY docs the tests control) never blocks the anchor open. This mirrors the
|
||||
// real invariant the production heal relies on.
|
||||
released.add(`did:ng:${SESSION.privateStoreId}`);
|
||||
let releaseEverything = false;
|
||||
|
||||
const doc_create = mock(async () => `did:ng:o:doc${++docCounter}`);
|
||||
|
||||
Reference in New Issue
Block a user