fix: un second doc_subscribe tuait le premier, et les inbox n'étaient lues qu'à la connexion
This commit is contained in:
@@ -0,0 +1,340 @@
|
||||
/**
|
||||
* While I am connected, what lands in my inboxes is applied — no reload, nobody asked.
|
||||
*
|
||||
* ── The regime, and the one this replaces ─────────────────────────────────
|
||||
* Upstream, applying an inbox is what a SESSION does: a sealed message reaches the
|
||||
* recipient's own verifier as it arrives and is applied inline, and only the backlog handed
|
||||
* over at connection is marked apart (`from_queue`). This package had emulated the backlog
|
||||
* and nothing else — `inbox.processInbox` was called from exactly one place, at connection —
|
||||
* so a share deposited while its recipient sat connected in front of the application
|
||||
* converged when that person next RELOADED the page. Its stand-in was a twenty-second timer
|
||||
* in the DEPOSITOR's session, which does nothing if that tab closes and tells the connected
|
||||
* owner nothing either way.
|
||||
*
|
||||
* ── How a deposit gets here without a reconnection ────────────────────────
|
||||
* Bob makes his deposit through the published surface, under his own identity, naming a
|
||||
* PERSON (`inbox.share(doc, "alice")`) — he is handed no address, and the test hands him
|
||||
* none. What the test then does is what a broker does: it HOLDS what he wrote and delivers
|
||||
* it to this page later, once Alice is the one connected (`wallet-fake._deliver`). The
|
||||
* quads delivered are the ones the library itself produced under Bob; nothing is composed
|
||||
* by hand. That is the cross-session case verified against the real broker
|
||||
* (`e2e/reactivity-doc-subscribe.ts`): a second session's write reaches the first session's
|
||||
* subscription as a `Patch`.
|
||||
*
|
||||
* ── A deposit by the owner is a REAL case, not a shortcut ─────────────────
|
||||
* Two tests below have Alice deposit into her own document's inbox while she is connected.
|
||||
* That is not a stand-in for a stranger: it is the case a consuming application reported,
|
||||
* and a same-session write is pushed to that session's own subscription — verified against
|
||||
* the real broker the same day (`Patch@69ms` on the writer's own `sparqlUpdate`).
|
||||
*/
|
||||
|
||||
import { test, expect, describe, afterAll, beforeEach } from "bun:test";
|
||||
import { inbox as inboxSurface, storeRegistry } from "../src/index";
|
||||
import { getCaps, setCurrentUser } from "../src/shared-wallet/bootstrap";
|
||||
import { resolveAccount, userInbox } from "../src/shared-wallet/account-registry";
|
||||
import { observationSettled } from "../src/emulated-verifier/inbox-observer";
|
||||
import { cancelScheduledInboxProcessing } from "../src/emulated-verifier/inbox-processor";
|
||||
import { bootPage, forgetEverything, signIn, type FakeWallet, type Quad } from "./wallet-fake";
|
||||
import type { Nuri } from "../src/model/types";
|
||||
|
||||
const SHIM = "urn:ng-eventually:shim";
|
||||
const INBOX = "urn:ng-eventually:inbox";
|
||||
|
||||
/** The reactive fake: a repo answers nothing until subscribed, and a commit pushes. */
|
||||
const COLD = { unsyncedUntilSubscribed: true } as const;
|
||||
|
||||
let quads: Quad[];
|
||||
let fake: FakeWallet;
|
||||
|
||||
function boot(): void {
|
||||
quads = [];
|
||||
fake = bootPage(quads, COLD);
|
||||
}
|
||||
|
||||
/**
|
||||
* Let the page's pushes land, and everything they set off finish.
|
||||
*
|
||||
* Not a sleep with a number on it: each round YIELDS so the fake can deliver the push it
|
||||
* queued (on a macrotask, as the real RPC does), then WAITS on the work that push actually
|
||||
* started (`observationSettled` — the enumerations in flight and the drains behind them).
|
||||
* Several rounds because applying one push can queue the next: a Link filed on the private
|
||||
* store pushes to the register subscription, which re-enumerates.
|
||||
*/
|
||||
async function converge(): Promise<void> {
|
||||
for (let round = 0; round < 5; round += 1) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
await observationSettled();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Take what has been written into `graph` OUT of this page's wallet and hand it back — the
|
||||
* broker holding a commit it has not delivered yet. Delivering it later
|
||||
* (`fake._deliver`) is the only way a deposit made in another session can arrive here
|
||||
* while Alice, and not its author, is the connected identity.
|
||||
*/
|
||||
function heldByTheBroker(graph: Nuri): Quad[] {
|
||||
const held: Quad[] = [];
|
||||
for (let i = quads.length - 1; i >= 0; i -= 1) {
|
||||
if (quads[i]!.g === graph) held.unshift(...quads.splice(i, 1));
|
||||
}
|
||||
return held;
|
||||
}
|
||||
|
||||
/**
|
||||
* The documents a user has durably been GIVEN — the emulated `AddLink` records on their
|
||||
* User branch, named by the document each one opens. The record holds a `ReadCap` (the
|
||||
* reference plus its secret); the tests are about WHICH document arrived, so the secret is
|
||||
* dropped here rather than pinned to the stand-in value the emulation currently mints.
|
||||
*/
|
||||
async function documentsGivenTo(id: string): Promise<string[]> {
|
||||
const store = (await resolveAccount(id))?.docPrivate;
|
||||
if (!store) return [];
|
||||
return quads
|
||||
.filter((q) => q.g === store && q.p === `${SHIM}:link`)
|
||||
.map((q) => q.o.split(":r:")[0]!);
|
||||
}
|
||||
|
||||
/** How many times this inbox's deposits have been read — i.e. how often it was processed. */
|
||||
function depositReadsOf(inbox: Nuri): number {
|
||||
return fake.sparql_query.mock.calls.filter(
|
||||
(c) => c[3] === inbox && String(c[1]).includes(`${INBOX}:payload`),
|
||||
).length;
|
||||
}
|
||||
|
||||
/** The inbox recorded for a note, read off the WALLET — no application can ask the package. */
|
||||
function inboxOnTheNote(note: Nuri): Nuri {
|
||||
const record = quads.find((q) => q.p === `${SHIM}:inboxCap` && q.o.startsWith(note + " "));
|
||||
if (!record) throw new Error("no AddInboxCap record was written for the note");
|
||||
return record.o.split(" ")[1] as Nuri;
|
||||
}
|
||||
|
||||
/** Capture what `console.error` is told while `body` runs. */
|
||||
async function whileWatchingTheLog(body: () => Promise<void>): Promise<string[]> {
|
||||
const lines: string[] = [];
|
||||
const real = console.error;
|
||||
console.error = ((...args: unknown[]) => {
|
||||
lines.push(args.map((a) => String(a)).join(" "));
|
||||
}) as typeof console.error;
|
||||
try {
|
||||
await body();
|
||||
} finally {
|
||||
console.error = real;
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
/**
|
||||
* Bob makes a document and shares it with Alice by NAME, then the broker holds his deposit
|
||||
* back. Returns the document he shared and the quads still in transit.
|
||||
*
|
||||
* Alice has to have been here before, and to have DONE something: `inbox.share` refuses a
|
||||
* recipient nobody has ever been, and connecting does not provision — an identity acquires
|
||||
* its account the first time it creates anything. That is the model and not a fixture
|
||||
* detail: upstream a deposit is sealed to an inbox key somebody had to hand you, so you
|
||||
* cannot address a name you invented. Her first visit here is not the one under test; every
|
||||
* test below connects her again afterwards, and the deposit arrives strictly after that.
|
||||
*/
|
||||
async function bobSharesWithAlice(): Promise<{ doc: Nuri; inTransit: Quad[] }> {
|
||||
await signIn("alice");
|
||||
await storeRegistry.createEntityDoc("protected"); // her first visit — now she exists
|
||||
await signIn("bob");
|
||||
const doc = await storeRegistry.createEntityDoc("protected");
|
||||
await inboxSurface.share(doc, "alice");
|
||||
// Test-side inspection only — the address is read off the wallet to say WHICH document
|
||||
// is in transit, and is never handed to an actor.
|
||||
const aliceInbox = await userInbox("alice", "protected");
|
||||
return { doc, inTransit: heldByTheBroker(aliceInbox) };
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
forgetEverything();
|
||||
boot();
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
cancelScheduledInboxProcessing();
|
||||
forgetEverything();
|
||||
});
|
||||
|
||||
describe("a deposit that arrives while its recipient is connected", () => {
|
||||
test("is applied, without anyone reconnecting", async () => {
|
||||
const { doc, inTransit } = await bobSharesWithAlice();
|
||||
|
||||
await signIn("alice");
|
||||
// The honest baseline: as far as this page is concerned Alice's inbox is empty, so
|
||||
// connecting applied nothing. Whatever the next lines prove, they do not prove it twice.
|
||||
expect(getCaps().capForHolder("alice", doc)).toBeUndefined();
|
||||
|
||||
fake._deliver(inTransit);
|
||||
await converge();
|
||||
|
||||
expect(getCaps().capForHolder("alice", doc)).toBeDefined();
|
||||
expect(await documentsGivenTo("alice")).toContain(doc);
|
||||
});
|
||||
|
||||
test("is applied DURABLY — the same as if she had reconnected to find it", async () => {
|
||||
const { doc, inTransit } = await bobSharesWithAlice();
|
||||
await signIn("alice");
|
||||
fake._deliver(inTransit);
|
||||
await converge();
|
||||
|
||||
// A cap held only in memory is a cap lost at the next reload, and the whole point of
|
||||
// applying rather than merely reading is that it survives.
|
||||
expect(await documentsGivenTo("alice")).toEqual([doc]);
|
||||
});
|
||||
|
||||
test("does not need the depositor's tab to stay open — no timer is involved", async () => {
|
||||
const { doc, inTransit } = await bobSharesWithAlice();
|
||||
await signIn("alice");
|
||||
// Whatever the deposit armed in Bob's session is dropped here, exactly as a closed tab
|
||||
// drops it. What follows is the connected owner's own doing, or it does not happen.
|
||||
cancelScheduledInboxProcessing();
|
||||
|
||||
fake._deliver(inTransit);
|
||||
await converge();
|
||||
|
||||
expect(getCaps().capForHolder("alice", doc)).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("an inbox opened in the middle of a session", () => {
|
||||
test("is watched too — what lands in it is processed without reconnecting", async () => {
|
||||
await signIn("alice");
|
||||
// The note and its inbox come into existence AFTER connecting, so nothing the
|
||||
// connection enumerated could have included them.
|
||||
const note = await storeRegistry.createEntityDoc("public");
|
||||
await storeRegistry.openDocumentInbox(note);
|
||||
await converge();
|
||||
|
||||
const inbox = inboxOnTheNote(note);
|
||||
const readsBefore = depositReadsOf(inbox);
|
||||
|
||||
// A message is left on the NOTE — the depositor names the document, never an address.
|
||||
await inboxSurface.postToDocument(note, { payload: { text: "j'apporte le café" }, from: null, ts: 1 });
|
||||
await converge();
|
||||
|
||||
// Processing an inbox IS reading its queue and applying what is this library's to
|
||||
// apply; for a document inbox nothing is (a Link only ever reaches a person's inbox),
|
||||
// so the read is the whole of the consequence — and it can come from nowhere else:
|
||||
// depositing reads the shim, not the queue, and the deferred window has not closed.
|
||||
expect(depositReadsOf(inbox)).toBeGreaterThan(readsBefore);
|
||||
});
|
||||
|
||||
test("the messages left on it are readable, on the document its owner named", async () => {
|
||||
await signIn("alice");
|
||||
const note = await storeRegistry.createEntityDoc("public");
|
||||
await storeRegistry.openDocumentInbox(note);
|
||||
await converge();
|
||||
|
||||
await inboxSurface.postToDocument(note, { payload: { text: "à demain" }, from: null, ts: 2 });
|
||||
await converge();
|
||||
|
||||
const left = await inboxSurface.readForDocument(note);
|
||||
expect(left.map((d) => (d.payload as { text: string }).text)).toEqual(["à demain"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("switching identity", () => {
|
||||
test("stops the observation — the previous identity's inbox is no longer applied", async () => {
|
||||
const { doc, inTransit } = await bobSharesWithAlice();
|
||||
await signIn("alice");
|
||||
|
||||
// Alice steps away and Bob takes the page. A session belongs to one person.
|
||||
await signIn("bob");
|
||||
|
||||
fake._deliver(inTransit);
|
||||
await converge();
|
||||
|
||||
// Nothing was applied for Alice — she is not connected, and her queue keeps its
|
||||
// deposit for the next time she is.
|
||||
expect(getCaps().capForHolder("alice", doc)).toBeUndefined();
|
||||
expect(await documentsGivenTo("alice")).toEqual([]);
|
||||
// …and emphatically nothing was filed for Bob either: work started for one holder must
|
||||
// never file for another. (Bob's own cap on the document is not evidence of that — he
|
||||
// made it. What would be evidence is a Link, and there is none.)
|
||||
expect(await documentsGivenTo("bob")).toEqual([]);
|
||||
});
|
||||
|
||||
test("and disconnecting stops it too", async () => {
|
||||
const { doc, inTransit } = await bobSharesWithAlice();
|
||||
await signIn("alice");
|
||||
|
||||
setCurrentUser(null); // no identity is acting — anonymous holds nothing and owns no inbox
|
||||
|
||||
fake._deliver(inTransit);
|
||||
await converge();
|
||||
|
||||
expect(await documentsGivenTo("alice")).toEqual([]);
|
||||
});
|
||||
|
||||
test("and Alice coming back finds the deposit still there to apply", async () => {
|
||||
const { doc, inTransit } = await bobSharesWithAlice();
|
||||
await signIn("alice");
|
||||
await signIn("bob");
|
||||
fake._deliver(inTransit);
|
||||
await converge();
|
||||
|
||||
// An inbox is not consumed by being ignored: connecting again drains what was left.
|
||||
await signIn("alice");
|
||||
await converge();
|
||||
|
||||
expect(getCaps().capForHolder("alice", doc)).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("a deposit that cannot be applied", () => {
|
||||
test("is reported, and stops neither the observation nor the next deposit", async () => {
|
||||
const first = await bobSharesWithAlice();
|
||||
const second = await bobSharesWithAlice();
|
||||
const aliceInbox = await userInbox("alice", "protected");
|
||||
|
||||
await signIn("alice");
|
||||
|
||||
// The broker cannot answer for Alice's inbox — the deposit lands, applying it does not.
|
||||
fake._failReadsOn.add(aliceInbox);
|
||||
const reported = await whileWatchingTheLog(async () => {
|
||||
fake._deliver(first.inTransit);
|
||||
await converge();
|
||||
});
|
||||
|
||||
expect(reported.filter((l) => /could not apply what is in this inbox/.test(l)).length)
|
||||
.toBeGreaterThan(0);
|
||||
// Prefixed by the connected identity, like every other polyfill-layer line.
|
||||
expect(reported.find((l) => /could not apply what is in this inbox/.test(l)))
|
||||
.toContain("[alice][polyfill]");
|
||||
expect(getCaps().capForHolder("alice", first.doc)).toBeUndefined();
|
||||
|
||||
// The broker recovers. The observation is still running — one unapplicable item denies
|
||||
// nothing — and the deposit that failed was never consumed, so both land now.
|
||||
fake._failReadsOn.delete(aliceInbox);
|
||||
fake._deliver(second.inTransit);
|
||||
await converge();
|
||||
|
||||
expect(getCaps().capForHolder("alice", second.doc)).toBeDefined();
|
||||
expect(getCaps().capForHolder("alice", first.doc)).toBeDefined();
|
||||
});
|
||||
|
||||
test("never rejects into the application — nobody asked for this work", async () => {
|
||||
const { inTransit } = await bobSharesWithAlice();
|
||||
const aliceInbox = await userInbox("alice", "protected");
|
||||
await signIn("alice");
|
||||
fake._failReadsOn.add(aliceInbox);
|
||||
|
||||
const unhandled: unknown[] = [];
|
||||
const onUnhandled = (e: unknown): void => {
|
||||
unhandled.push(e);
|
||||
};
|
||||
process.on("unhandledRejection", onUnhandled);
|
||||
try {
|
||||
await whileWatchingTheLog(async () => {
|
||||
fake._deliver(inTransit);
|
||||
await converge();
|
||||
});
|
||||
} finally {
|
||||
process.off("unhandledRejection", onUnhandled);
|
||||
fake._failReadsOn.delete(aliceInbox);
|
||||
}
|
||||
expect(unhandled).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -434,7 +434,10 @@ test("a drain that fails says so in the package's log, and rejects into nobody",
|
||||
console.error = realError;
|
||||
}
|
||||
|
||||
const reported = errors.filter((line) => /deferred inbox processing failed/.test(line));
|
||||
// The wording is the SHARED reporter's since 2026-08-17 (`emulated-verifier/inbox-drain.ts`):
|
||||
// the timer is no longer the only thing that drains an inbox — the continuous observation
|
||||
// does too, through the same queue — so the line names the act and not the schedule.
|
||||
const reported = errors.filter((line) => /could not apply what is in this inbox/.test(line));
|
||||
expect(reported.length).toBe(1);
|
||||
// Prefixed by the CONNECTED identity, like every other polyfill-layer line — which is
|
||||
// what makes a drain running under someone else's session legible in a live trace.
|
||||
|
||||
@@ -145,21 +145,30 @@ test("a public store serves every asker, not only the first", async () => {
|
||||
|
||||
test("asked once per document: the outcome is memoised, in both directions", async () => {
|
||||
const { sparql_query } = inject();
|
||||
// Counted PER DOCUMENT (the read is anchored on the one being asked about), not over
|
||||
// every read the process makes. `setCurrentUser` fires the connection work, which reads
|
||||
// on its own account in the background — none of it about this document — so a total
|
||||
// makes the memo's arithmetic depend on whatever else happens to be in flight. This is
|
||||
// the same assertion, about the read it is actually about.
|
||||
const asks = (nuri: string): number =>
|
||||
sparql_query.mock.calls.filter((c) => c[3] === nuri).length;
|
||||
|
||||
setCurrentUser("alice");
|
||||
await aliceExposesHerNote();
|
||||
armEmulation();
|
||||
setCurrentUser("bob");
|
||||
|
||||
await fetchReadCap(PUB);
|
||||
const afterHit = sparql_query.mock.calls.length;
|
||||
const afterHit = asks(PUB);
|
||||
await fetchReadCap(PUB); // held now → not even the memo is consulted
|
||||
expect(sparql_query.mock.calls.length).toBe(afterHit);
|
||||
expect(asks(PUB)).toBe(afterHit);
|
||||
|
||||
const absent = "did:ng:o:nothing-here" as Nuri;
|
||||
await fetchReadCap(absent);
|
||||
const afterMiss = sparql_query.mock.calls.length;
|
||||
const afterMiss = asks(absent);
|
||||
expect(afterMiss).toBe(1); // it WAS asked once — a memo over nothing proves nothing
|
||||
await fetchReadCap(absent); // a miss is remembered too
|
||||
expect(sparql_query.mock.calls.length).toBe(afterMiss);
|
||||
expect(asks(absent)).toBe(afterMiss);
|
||||
});
|
||||
|
||||
test("resetting the caps forgets the memo — a stale yes would hand back what is no longer held", async () => {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { test, expect, mock, afterAll } from "bun:test";
|
||||
import { subscribeDoc, subscribeDocs } from "../src/surface/subscribe";
|
||||
import { docChangeType, subscribeDoc, subscribeDocs } from "../src/surface/subscribe";
|
||||
import { configure } from "../src/index";
|
||||
import { configureStoreRegistry } from "../src/shared-wallet/bootstrap";
|
||||
import { resetConfig, resetStoreRegistry } from "../src/shared-wallet/bootstrap";
|
||||
@@ -17,29 +17,41 @@ afterAll(() => {
|
||||
const SESSION: RegistrySession = { sessionId: "sid-1", privateStoreId: "PRIV" };
|
||||
|
||||
/**
|
||||
* A fake reactive `ng`: `doc_subscribe(nuri, sid, cb)` registers `cb` for `nuri`,
|
||||
* fires it once (initial State push), and returns an unsubscribe. `push(nuri)`
|
||||
* drives a later change to that doc's subscribers. A per-doc `failFor` set makes
|
||||
* `doc_subscribe` reject for chosen NURIs (a not-yet-synced doc).
|
||||
* A fake reactive `ng`: `doc_subscribe(nuri, sid, cb)` takes over `nuri`, fires `cb` once
|
||||
* (initial State push), and returns an unsubscribe. `push(nuri)` drives a later change to
|
||||
* that doc's subscriber. A per-doc `failFor` set makes `doc_subscribe` reject for chosen
|
||||
* NURIs (a not-yet-synced doc).
|
||||
*
|
||||
* ── ONE subscriber per document, and a second one EVICTS it ───────────────
|
||||
* Not a simplification — it is what the broker does. A branch holds a single sender
|
||||
* (`branch_subscriptions: HashMap<BranchId, Sender<AppResponse>>`) and
|
||||
* `create_branch_subscription` closes whatever it displaces, silently: the evicted
|
||||
* unsubscribe still returns cleanly and nothing anywhere errors. Confirmed against the real
|
||||
* broker on 2026-08-17 — with two subscriptions on one document, a write fired the second
|
||||
* callback and the first, which had been firing moments earlier, went quiet for good.
|
||||
*
|
||||
* A Set of callbacks here would model a world where every subscriber coexists. It is
|
||||
* exactly the assumption that cost this package a view that never re-read and an inbox that
|
||||
* never notified, and a fake that holds it cannot fail on either.
|
||||
*/
|
||||
function makeFakeNg(failFor: Set<string> = new Set()) {
|
||||
const subs = new Map<string, Set<(r: unknown) => void>>();
|
||||
const subs = new Map<string, (r: unknown) => void>();
|
||||
const doc_subscribe = mock(async (nuri: string, _sid: unknown, cb: (r: unknown) => void) => {
|
||||
if (failFor.has(nuri)) throw new Error(`RepoNotFound: ${nuri}`);
|
||||
let set = subs.get(nuri);
|
||||
if (!set) {
|
||||
set = new Set();
|
||||
subs.set(nuri, set);
|
||||
}
|
||||
set.add(cb);
|
||||
// Initial State push, delivered async (as the real RPC does).
|
||||
queueMicrotask(() => cb({ V0: { State: { doc: nuri } } }));
|
||||
return () => set!.delete(cb);
|
||||
subs.set(nuri, cb); // whoever held this branch is dropped, without a word
|
||||
// Initial State push, delivered async (as the real RPC does) — and only while this
|
||||
// callback still holds the branch.
|
||||
queueMicrotask(() => {
|
||||
if (subs.get(nuri) === cb) cb({ V0: { State: { doc: nuri } } });
|
||||
});
|
||||
return () => {
|
||||
if (subs.get(nuri) === cb) subs.delete(nuri);
|
||||
};
|
||||
});
|
||||
const push = (nuri: string): void => {
|
||||
for (const cb of subs.get(nuri) ?? []) cb({ V0: { Patch: { doc: nuri } } });
|
||||
subs.get(nuri)?.({ V0: { Patch: { doc: nuri } } });
|
||||
};
|
||||
const isSubscribed = (nuri: string): boolean => (subs.get(nuri)?.size ?? 0) > 0;
|
||||
const isSubscribed = (nuri: string): boolean => subs.has(nuri);
|
||||
return { doc_subscribe, push, isSubscribed, _subs: subs };
|
||||
}
|
||||
|
||||
@@ -143,3 +155,73 @@ test("subscribeDocs deduplicates repeated NURIs", async () => {
|
||||
await tick();
|
||||
expect(ng.doc_subscribe).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
// --- two subscribers on ONE document ---------------------------------------
|
||||
//
|
||||
// A branch has room for exactly one subscriber and a second `doc_subscribe` evicts the
|
||||
// first (see `makeFakeNg`). Everything inside this package subscribes — `ensureRepoOpen`
|
||||
// holds a bootstrap subscription per document for the session, `watchShape` follows the
|
||||
// documents of a scope, `inbox.watch` follows an inbox, and the inbox observation follows
|
||||
// every inbox — so any two of them on the same document used to silence one another.
|
||||
// Nothing rejected and nothing logged; the view simply stopped re-reading.
|
||||
//
|
||||
// So the package opens ONE real subscription per document and fans it out. These are the
|
||||
// tests that say so.
|
||||
|
||||
test("two subscribers on one document BOTH keep firing", async () => {
|
||||
const ng = inject();
|
||||
const first: unknown[] = [];
|
||||
const second: unknown[] = [];
|
||||
subscribeDoc(A, (r) => first.push(r));
|
||||
await tick();
|
||||
expect(first).toHaveLength(1); // its initial State
|
||||
|
||||
subscribeDoc(A, (r) => second.push(r));
|
||||
await tick();
|
||||
|
||||
ng.push(A);
|
||||
// The one that was there first is not silenced by the one that came second.
|
||||
expect(first).toHaveLength(2);
|
||||
expect(second.length).toBeGreaterThanOrEqual(1);
|
||||
});
|
||||
|
||||
test("one real doc_subscribe serves every subscriber of a document", async () => {
|
||||
const ng = inject();
|
||||
subscribeDoc(A, () => {});
|
||||
subscribeDoc(A, () => {});
|
||||
subscribeDoc(A, () => {});
|
||||
await tick();
|
||||
// Three callers, one branch taken. A second call would have evicted the first caller.
|
||||
expect(ng.doc_subscribe).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test("a subscriber that joins LATE still gets its initial State", async () => {
|
||||
inject();
|
||||
subscribeDoc(A, () => {});
|
||||
await tick(); // the initial State has come and gone
|
||||
|
||||
const late: unknown[] = [];
|
||||
subscribeDoc(A, (r) => late.push(r));
|
||||
await tick();
|
||||
|
||||
// Its own `doc_subscribe` would have pushed it a State; joining an open one owes it the
|
||||
// same, or "fires once immediately" quietly stops being true for whoever arrives second.
|
||||
expect(late).toHaveLength(1);
|
||||
expect(docChangeType(late[0])).toBe("State");
|
||||
});
|
||||
|
||||
test("the real subscription is released only when the LAST subscriber leaves", async () => {
|
||||
const ng = inject();
|
||||
const seen: unknown[] = [];
|
||||
const stopFirst = subscribeDoc(A, () => {});
|
||||
const stopSecond = subscribeDoc(A, (r) => seen.push(r));
|
||||
await tick();
|
||||
|
||||
stopFirst();
|
||||
expect(ng.isSubscribed(A)).toBe(true); // somebody is still listening
|
||||
ng.push(A);
|
||||
expect(seen.length).toBeGreaterThanOrEqual(2); // and still hearing
|
||||
|
||||
stopSecond();
|
||||
expect(ng.isSubscribed(A)).toBe(false); // now nobody is
|
||||
});
|
||||
|
||||
@@ -125,6 +125,23 @@ export interface FakeWallet {
|
||||
/** Present only under {@link WalletOptions.unsyncedUntilSubscribed}. */
|
||||
doc_subscribe?: ReturnType<typeof mock>;
|
||||
_quads: Quad[];
|
||||
/**
|
||||
* A commit made in ANOTHER session, reaching this page now — the broker delivering what
|
||||
* it was holding. The quads land in the wallet and each document they touch pushes to
|
||||
* its subscriber, which is what a remote write does here: verified against the real
|
||||
* broker, a second session's write reached the first session's subscription as a `Patch`
|
||||
* 12ms after it landed (`e2e/reactivity-doc-subscribe.ts`, CROSS).
|
||||
*
|
||||
* It delivers; it does not INVENT. A caller hands it quads the library itself produced
|
||||
* under the other actor's identity — never a shape a test wrote by hand.
|
||||
*/
|
||||
_deliver: (arriving: Quad[]) => void;
|
||||
/**
|
||||
* Anchors whose anchored READ throws, as an unreachable repo does. Mutable after boot,
|
||||
* so a suite builds a healthy world first and breaks only the one call it is about —
|
||||
* the fault is the broker's, never a reach into the library to make it reject.
|
||||
*/
|
||||
_failReadsOn: Set<string>;
|
||||
}
|
||||
|
||||
export interface WalletOptions {
|
||||
@@ -168,6 +185,38 @@ export function makeWallet(quads: Quad[], options: WalletOptions = {}): FakeWall
|
||||
const synced = new Set<string>();
|
||||
const cold = options.unsyncedUntilSubscribed === true;
|
||||
|
||||
/**
|
||||
* The ONE subscriber a document can have.
|
||||
*
|
||||
* Not a convenience — it is what the broker does. A branch holds exactly one sender
|
||||
* (`branch_subscriptions: HashMap<BranchId, Sender<AppResponse>>`) and
|
||||
* `create_branch_subscription` closes whatever it displaces, so a second
|
||||
* `doc_subscribe` on a document does not join the first, it EVICTS it — silently, with
|
||||
* the evicted unsubscribe still callable and no error anywhere. Confirmed against the
|
||||
* real broker on 2026-08-17: with two subscriptions on one document, a write fired the
|
||||
* second callback and the first, which had been firing moments before, went quiet.
|
||||
*
|
||||
* A Set here would fabricate a world where every subscriber coexists — precisely the
|
||||
* assumption whose falseness cost this package a view that never re-read and an inbox
|
||||
* that never notified.
|
||||
*/
|
||||
const subscriber = new Map<string, (r: unknown) => void>();
|
||||
|
||||
/** See {@link FakeWallet._failReadsOn}. */
|
||||
const failReadsOn = new Set<string>();
|
||||
|
||||
/** A commit on `g` pushes a `Patch` to that document's subscriber — the SESSION THAT
|
||||
* WROTE IT INCLUDED. Verified against the real broker the same day: a session's own
|
||||
* `sparqlUpdate` to a document it subscribes to pushed `Patch@69ms`. The engine keys
|
||||
* its senders by branch and knows nothing about who issued the write. */
|
||||
const commit = (g: string): void => {
|
||||
const cb = subscriber.get(g);
|
||||
if (!cb) return;
|
||||
setTimeout(() => {
|
||||
if (subscriber.get(g) === cb) cb({ V0: { Patch: {} } });
|
||||
}, 0);
|
||||
};
|
||||
|
||||
const doc_create = mock(async () => {
|
||||
const nuri = `did:ng:o:doc${++minted}`;
|
||||
// Created here: nothing remote to wait for. This is why the session that wrote the
|
||||
@@ -180,11 +229,19 @@ export function makeWallet(quads: Quad[], options: WalletOptions = {}): FakeWall
|
||||
const nuri = a[0] as string;
|
||||
const onChange = a[2] as (r: unknown) => void;
|
||||
synced.add(nuri);
|
||||
subscriber.set(nuri, onChange);
|
||||
// `TabInfo` first, then the initial `State` — the platform's own order, so a waiter
|
||||
// that resolved on "the first push of any kind" would return BEFORE the barrier.
|
||||
setTimeout(() => onChange({ V0: { TabInfo: {} } }), 0);
|
||||
setTimeout(() => onChange({ V0: { State: {} } }), 0);
|
||||
return () => {};
|
||||
// Only while this callback still holds the branch: an evicted subscriber hears nothing.
|
||||
setTimeout(() => {
|
||||
if (subscriber.get(nuri) === onChange) onChange({ V0: { TabInfo: {} } });
|
||||
}, 0);
|
||||
setTimeout(() => {
|
||||
if (subscriber.get(nuri) === onChange) onChange({ V0: { State: {} } });
|
||||
}, 0);
|
||||
return () => {
|
||||
if (subscriber.get(nuri) === onChange) subscriber.delete(nuri);
|
||||
};
|
||||
});
|
||||
|
||||
const sparql_update = mock(async (...a: unknown[]) => {
|
||||
@@ -199,6 +256,7 @@ export function makeWallet(quads: Quad[], options: WalletOptions = {}): FakeWall
|
||||
const q = quads[i]!;
|
||||
if (q.g === anchor && q.s === pattern[1] && q.p === pattern[2]) quads.splice(i, 1);
|
||||
}
|
||||
commit(anchor);
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
@@ -210,6 +268,7 @@ export function makeWallet(quads: Quad[], options: WalletOptions = {}): FakeWall
|
||||
? wrapped[2]!
|
||||
: query.replace(/^[\s\S]*?INSERT\s+DATA\s*\{/i, "").replace(/\}\s*$/, "");
|
||||
for (const t of parseTriples(body)) quads.push({ g, ...t });
|
||||
commit(g);
|
||||
return undefined;
|
||||
});
|
||||
|
||||
@@ -221,6 +280,12 @@ export function makeWallet(quads: Quad[], options: WalletOptions = {}): FakeWall
|
||||
// The repo the verifier resolves the read against — the anchor when there is one,
|
||||
// otherwise the graph named in the query.
|
||||
const target = anchor ?? g;
|
||||
// The repo this broker cannot answer for. Rejects, as `resolve_target_for_sparql`
|
||||
// does on a repo the verifier does not have — never 0 rows, which would be the
|
||||
// altogether different (and silent) cold-start state modelled below.
|
||||
if (target !== undefined && failReadsOn.has(target)) {
|
||||
throw new Error(`RepoNotFound: ${target}`);
|
||||
}
|
||||
// COLD: present but unsynced. No error, no rows — which is exactly why it is dangerous.
|
||||
if (cold && target !== undefined && !synced.has(target)) return { results: { bindings: [] } };
|
||||
const inGraph = quads.filter((q) => q.g === g);
|
||||
@@ -299,9 +364,17 @@ export function makeWallet(quads: Quad[], options: WalletOptions = {}): FakeWall
|
||||
return { results: { bindings: [] } };
|
||||
});
|
||||
|
||||
return cold
|
||||
? { doc_create, doc_subscribe, sparql_update, sparql_query, _quads: quads }
|
||||
: { doc_create, sparql_update, sparql_query, _quads: quads };
|
||||
const _deliver = (arriving: Quad[]): void => {
|
||||
const touched = new Set<string>();
|
||||
for (const q of arriving) {
|
||||
quads.push(q);
|
||||
touched.add(q.g);
|
||||
}
|
||||
for (const g of touched) commit(g);
|
||||
};
|
||||
|
||||
const common = { doc_create, sparql_update, sparql_query, _quads: quads, _deliver, _failReadsOn: failReadsOn };
|
||||
return cold ? { ...common, doc_subscribe } : common;
|
||||
}
|
||||
|
||||
/** Wire the library onto `quads` — what a page load does. */
|
||||
|
||||
Reference in New Issue
Block a user