fix: à la reconnexion, on retrouve ce qu'on possède — pas seulement ce qu'on a reçu

Une application signalait deux symptômes. Ils sont indépendants, et ils ont une
racine commune : se connecter ne rejouait qu'UN des registres durables du
portefeuille.

connectedUser lisait les AddLink de la branche User — ce qu'on vous a partagé —
et rien d'autre. Les capacités des documents que vous avez FAITS vivent sur la
branche Store, et un seul chemin les relisait : listMyEntityDocs. Une
application qui recharge et va droit à sa note ne tenait donc rien pour elle.
Constaté : capFor(note) vaut undefined juste après une connexion résolue, et
devient défini dès que listMyEntityDocs passe.

Le public survivait en lecture parce que fetchReadCap va rechercher la clé dans
le store ; il échouait quand même à l'écriture, qui ne fait pas cette démarche.

Deuxième défaut : myInboxes énumérait les inbox sans en remettre la clé au
détenteur. Se connecter demandait donc un document qu'on n'avait pas de quoi
lire — sur une inbox, que l'application n'a jamais nommée puisque rien ne le
lui permet.

Troisième défaut, et c'est lui qui rendait tout ça fatal : un drainage refusé
faisait échouer toute la connexion. Une inbox n'étant pas consommée par un
échec, elle refusait à chaque tentative suivante. D'où le « trois fois sur
trois », et d'où un verrouillage plutôt qu'un partage manquant.

C'est ma spécification qui l'a créé. En rendant les échecs visibles j'avais
écrasé une distinction : ne pas ATTEINDRE la file est une panne, et refuser la
session est juste ; ne pas pouvoir APPLIQUER un élément est une donnée, et ça ne
doit priver personne de sa session. Le drainage par inbox est désormais isolé —
signalé haut et fort, les autres files drainées, la session accordée — tandis
qu'énumérer les files et restaurer rejettent toujours.

Le parcours e2e ratait les deux : personne ne se reconnecte après avoir ouvert
son document aux messages. Il s'arrêtait une reconnexion trop tôt.
This commit is contained in:
Sylvain Duchesne
2026-08-16 17:23:27 +02:00
parent b50591f5bd
commit f6d1734679
8 changed files with 1113 additions and 49 deletions
+280
View File
@@ -0,0 +1,280 @@
/**
* wallet-fake — a durable fake broker, and the page RELOAD that runs over it.
*
* Not a `*.test.ts`, so `bun test` does not pick it up: it is the montage two suites share
* ({@link reloadOwnDocument} / the inbox drain), and both of them are about what survives a
* reload — which is exactly the thing a per-file fake cannot express, because the wallet
* has to outlive the library while the library keeps nothing.
*
* ── What makes it a wallet and not a stub ─────────────────────────────────
* The quads live in the fake, never in the library. {@link reloadPage} drops every piece of
* the library's module state and hands back a session that has to find its way home through
* the store-root pointer, the doc-shim and the account record — the way a fresh page does.
* Nothing is planted: a second session sees exactly what the first one WROTE.
*
* The SPARQL it answers is a tokenizer plus five shapes, rather than one regex per query
* the author happened to think of: the reload path issues reads and writes from six
* modules, and a fake that answers only the shapes someone enumerated is how a suite goes
* green over a state the library never reaches.
*/
import { mock } from "bun:test";
import { configure } from "../src/index";
import {
configureStoreRegistry,
setCurrentUser,
resetCaps,
resetConfig,
resetStoreRegistry,
} from "../src/shared-wallet/bootstrap";
import { resetRegistryCache } from "../src/shared-wallet/account-registry";
import type { RegistrySession } from "../src/shared-wallet/account-registry";
import { resetOpenedRepos } from "../src/emulated-verifier/open-repo";
import { resetPublicStoreFetches } from "../src/emulated-verifier/public-store";
import { connectedUser } from "../src/emulated-verifier/connect";
import type { NgLike, UseShapeLike } from "../src/model/types";
export const SESSION: RegistrySession = { sessionId: "sid-wallet", privateStoreId: "PRIV-WALLET" };
const SHIM = "urn:ng-eventually:shim";
const INBOX = "urn:ng-eventually:inbox";
const RDF_TYPE = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type";
export interface Quad {
g: string;
s: string;
p: string;
o: string;
}
/** Reverse of the lib's `escapeLiteral`: one left-to-right pass over `\x`. */
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;
}
interface Token {
kind: "term" | "sep";
value: string;
}
/** Tokenize a triple body into IRIs, literals, `a`, `;` and `.`. */
function tokenize(body: string): Token[] {
const re = /<([^>]*)>|"((?:[^"\\]|\\.)*)"|(;)|(\.)|\ba\b/g;
const out: Token[] = [];
let m: RegExpExecArray | null;
while ((m = re.exec(body)) !== null) {
if (m[1] !== undefined) out.push({ kind: "term", value: m[1] });
else if (m[2] !== undefined) out.push({ kind: "term", value: unescapeLiteral(m[2]) });
else if (m[3] !== undefined) out.push({ kind: "sep", value: ";" });
else if (m[4] !== undefined) out.push({ kind: "sep", value: "." });
else out.push({ kind: "term", value: RDF_TYPE });
}
return out;
}
/** `<s> p o ; p o . <s2> p o` → the triples it carries. */
function parseTriples(body: string): Array<{ s: string; p: string; o: string }> {
const toks = tokenize(body);
const out: Array<{ s: string; p: string; o: string }> = [];
let subject: string | null = null;
let i = 0;
while (i < toks.length) {
const t = toks[i]!;
if (t.kind === "sep") {
if (t.value === ".") subject = null;
i += 1;
continue;
}
if (subject === null) {
subject = t.value;
i += 1;
continue;
}
const p = toks[i];
const o = toks[i + 1];
if (!p || !o || p.kind === "sep" || o.kind === "sep") break;
out.push({ s: subject, p: p.value, o: o.value });
i += 2;
}
return out;
}
export interface FakeWallet {
doc_create: ReturnType<typeof mock>;
sparql_update: ReturnType<typeof mock>;
sparql_query: ReturnType<typeof mock>;
_quads: Quad[];
}
/**
* A quad-store fake `ng` over `quads` — the durable half. The library holds nothing across
* a {@link reloadPage}; this does.
*
* No `doc_subscribe`: `ensureRepoOpen` is then the documented no-op of the unit-fake path
* (`emulated-verifier/open-repo.ts`), so an anchored read resolves directly. A limit of the
* fake broker, not a library state.
*/
export function makeWallet(quads: Quad[]): FakeWallet {
let docCounter = 0;
const doc_create = mock(async () => `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 del = query.match(/DELETE\s+WHERE\s*\{([\s\S]*)\}/i);
if (del) {
const pattern = del[1]!.match(/<([^>]+)>\s+<([^>]+)>\s+\?/);
if (pattern && anchor !== undefined) {
for (let i = quads.length - 1; i >= 0; i--) {
const q = quads[i]!;
if (q.g === anchor && q.s === pattern[1] && q.p === pattern[2]) quads.splice(i, 1);
}
}
return undefined;
}
const wrapped = query.match(/GRAPH\s+<([^>]+)>\s*\{([\s\S]*)\}/);
const g = wrapped ? wrapped[1]! : anchor;
if (g === undefined) return undefined;
const body = wrapped
? wrapped[2]!
: query.replace(/^[\s\S]*?INSERT\s+DATA\s*\{/i, "").replace(/\}\s*$/, "");
for (const t of parseTriples(body)) quads.push({ g, ...t });
return undefined;
});
const sparql_query = mock(async (...a: unknown[]) => {
const query = a[1] as string;
const anchor = a[3] as string | undefined;
const wrapped = query.match(/GRAPH\s+<([^>]+)>/);
const g = wrapped ? wrapped[1]! : anchor;
const inGraph = quads.filter((q) => q.g === g);
// The whole-document read (`read-model.readDoc`).
if (/SELECT\s+\?s\s+\?p\s+\?o/.test(query)) {
return {
results: {
bindings: inGraph.map((q) => ({
s: { value: q.s },
p: { value: q.p },
o: { value: q.o },
})),
},
};
}
// The account record — several predicates on one subject.
if (query.includes(`<${SHIM}:docPublic>`)) {
const subjM = query.match(/<([^>]+)>\s+a\s+<[^>]*:Account>/);
const only = subjM ? subjM[1]! : null;
const bySubject = new Map<string, Record<string, string>>();
for (const q of inGraph) {
if (only !== null && q.s !== only) continue;
const rec = bySubject.get(q.s) ?? {};
if (q.p === `${SHIM}:id`) rec.id = q.o;
if (q.p === `${SHIM}:docPublic`) rec.docPublic = q.o;
if (q.p === `${SHIM}:docProtected`) rec.docProtected = q.o;
if (q.p === `${SHIM}:docPrivate`) rec.docPrivate = q.o;
bySubject.set(q.s, rec);
}
const bindings = [...bySubject.values()]
.filter((r) => r.id !== undefined)
.map((r) => ({
id: { value: r.id! },
docPublic: { value: r.docPublic ?? "" },
docProtected: { value: r.docProtected ?? "" },
docPrivate: { value: r.docPrivate ?? "" },
}));
return { results: { bindings } };
}
// An inbox's deposits — several predicates on one subject, `from` optional.
if (query.includes(`<${INBOX}:payload>`)) {
const bySubject = new Map<string, Record<string, string>>();
for (const q of inGraph) {
const rec = bySubject.get(q.s) ?? {};
if (q.p === `${INBOX}:payload`) rec.payload = q.o;
if (q.p === `${INBOX}:ts`) rec.ts = q.o;
if (q.p === `${INBOX}:from`) rec.from = q.o;
bySubject.set(q.s, rec);
}
const bindings = [...bySubject.values()]
.filter((r) => r.payload !== undefined && r.ts !== undefined)
.map((r) => {
const row: Record<string, { value: string }> = {
payload: { value: r.payload! },
ts: { value: r.ts! },
};
if (r.from !== undefined) row.from = { value: r.from };
return row;
});
return { results: { bindings } };
}
// Everything else the library reads is one bound subject, one bound predicate, one
// variable: the pointer, the store index, the Store/User/Header branches, the inbox
// index and its owner.
const one = query.match(/<([^>]+)>\s+<([^>]+)>\s+\?(\w+)/);
if (one) {
const bindings = inGraph
.filter((q) => q.s === one[1] && q.p === one[2])
.map((q) => ({ [one[3]!]: { value: q.o } }));
return { results: { bindings } };
}
return { results: { bindings: [] } };
});
return { doc_create, sparql_update, sparql_query, _quads: quads };
}
/** Wire the library onto `quads` — what a page load does. */
export function bootPage(quads: Quad[]): FakeWallet {
const ng = makeWallet(quads);
configure({ ng: ng as unknown as NgLike, useShape: (() => {}) as unknown as UseShapeLike });
configureStoreRegistry({ getSession: async () => SESSION, normalizeId: (id) => id.trim() });
return ng;
}
/**
* Drop everything the library holds in module scope — what a page reload does.
*
* Each call drops one module's state, and together they are all of it: the config and the
* captured session, the registry caches (accounts, the resolved doc-shim, the inbox index),
* the opened repos, the outer-overlay memo, the caps, and who is connected.
*/
export function forgetEverything(): void {
setCurrentUser(null);
resetConfig();
resetStoreRegistry();
resetRegistryCache();
resetOpenedRepos();
resetPublicStoreFetches();
resetCaps();
}
/** A page RELOAD: the library forgets, the wallet does not. */
export function reloadPage(quads: Quad[]): FakeWallet {
forgetEverything();
return bootPage(quads);
}
/**
* Sign in and let the connection work finish — what `ensureIdentity()` awaits, reached by
* the harness's internal path rather than through the `barrier` (there is no DOM here).
*
* It REJECTS exactly where `ensureIdentity()` would, which is the point: a suite about a
* sign-in that fails cannot use a sign-in that cannot fail.
*/
export async function signIn(id: string): Promise<void> {
setCurrentUser(id);
await connectedUser();
}