fix: un second doc_subscribe tuait le premier, et les inbox n'étaient lues qu'à la connexion
This commit is contained in:
@@ -7,7 +7,7 @@
|
||||
* like "the share did not work" rather than "nobody processed the queue". So the
|
||||
* moment an identity is connected ({@link setCurrentUser}), this runs.
|
||||
*
|
||||
* Two steps, in order, and the order matters:
|
||||
* Three steps, in order, and the order matters:
|
||||
*
|
||||
* 1. **Restore** — replay the durable registers back into what this user holds. All of
|
||||
* them: the Store branches of its three stores (the emulated `AddRepo { read_cap }` —
|
||||
@@ -16,9 +16,13 @@
|
||||
* a handful of reads, no inbox needed.
|
||||
* 2. **Process** — drain the user's inbox (`inbox.processInbox`), which files any
|
||||
* new Link durably and puts it among what the user holds.
|
||||
* 3. **Keep applying** — start watching those same inboxes, for as long as this identity
|
||||
* stays connected (`emulated-verifier/inbox-observer.ts`). Step 2 is the backlog;
|
||||
* this is the regime.
|
||||
*
|
||||
* Restoring first means a reconnecting user can read its documents immediately, without
|
||||
* waiting on the inbox round-trip.
|
||||
* waiting on the inbox round-trip; watching last means the backlog is applied before the
|
||||
* first push arrives to apply it again.
|
||||
*
|
||||
* ── Restoring means ALL the registers, and that is a scar ─────────────────
|
||||
* Until 2026-08-16 this step read the Links and nothing else, so a fresh page put back the
|
||||
@@ -46,12 +50,21 @@
|
||||
* both are answered by the same place — `AddInboxCap` records on the User branch
|
||||
* (`engine/repo/src/types.rs:1969`) — so `storeRegistry.myInboxes()` enumerates
|
||||
* them and this drains each in turn.
|
||||
*
|
||||
* ── And then it KEEPS going ───────────────────────────────────────────────
|
||||
* Step 2 drains the backlog; it does not end the obligation. Upstream the backlog is the
|
||||
* exception (`from_queue`) and the rule is that a session applies each message as it
|
||||
* arrives, so connecting ends by starting the continuous observation of the same inboxes
|
||||
* (`emulated-verifier/inbox-observer.ts`), which lasts as long as this identity is
|
||||
* connected. Until 2026-08-17 there was no step 3, and a deposit made while its recipient
|
||||
* sat connected in front of the application converged only when that person reloaded.
|
||||
*/
|
||||
|
||||
import { getCaps, getCurrentUser } from "../shared-wallet/bootstrap";
|
||||
import { lookupAccount } from "../shared-wallet/account-registry";
|
||||
import { accessLogPrefix, shortNuri } from "../shared-wallet/access-log";
|
||||
import { myInboxes, readLinks, restoreOwnCaps } from "./branch-registers";
|
||||
import { startObservingInboxes } from "./inbox-observer";
|
||||
import { processInbox } from "../surface/inbox";
|
||||
import type { Nuri } from "../model/types";
|
||||
|
||||
@@ -126,7 +139,7 @@ const inFlight = new Map<string, Promise<void>>();
|
||||
* Not fixed with a retry, a timeout or a flag on purpose: deciding *what to do* about a
|
||||
* broker that cannot answer belongs to the caller, and it can only decide if it is told.
|
||||
*/
|
||||
// @provenance connectedUser kind=aligned level=1 ref=engine/verifier/src/verifier.rs:inbox — upstream the verifier restores and processes with nothing for a caller to await; this is the awaitable form, for a deterministic start
|
||||
// @provenance connectedUser kind=aligned level=1 ref=engine/verifier/src/verifier.rs:inbox — upstream the verifier restores, applies the queue handed over at connection and keeps applying what follows, with nothing for a caller to await; this is the awaitable form of the first two, for a deterministic start
|
||||
export async function connectedUser(): Promise<void> {
|
||||
const holder = getCurrentUser();
|
||||
if (holder === null) return;
|
||||
@@ -165,7 +178,18 @@ export async function connectedUser(): Promise<void> {
|
||||
// success. That is how sharing broke once (`.project/concepts/sign-in/`
|
||||
// `knowledge_settling-is-not-connecting`), and conflating absence with ignorance is
|
||||
// the same fault `inbox.share` was fixed for on 2026-08-10.
|
||||
if ((await lookupAccount(holder)) === null) return;
|
||||
if ((await lookupAccount(holder)) === null) {
|
||||
// Nothing to restore and no queue to drain — but this identity is CONNECTED, and it
|
||||
// will acquire both during the session: provisioning is lazy here, so a person's very
|
||||
// first visit connects with no stores at all and gets its account the moment the
|
||||
// application creates anything. Watching from now on provisions nothing (`myInboxes`
|
||||
// answers `[]` for an identity with no account) and is what makes that first session
|
||||
// behave like every other one — the alternative was a brand-new user watched from
|
||||
// their SECOND visit onwards, which is precisely the person most likely to be sent
|
||||
// something.
|
||||
if (stillConnected()) await startObservingInboxes();
|
||||
return;
|
||||
}
|
||||
if (!stillConnected()) return;
|
||||
// 1. Durable first, and ALL of it — see the header. The documents this user MADE, from
|
||||
// the Store branches of its own stores, and then the caps it was GIVEN, from the
|
||||
@@ -202,6 +226,24 @@ export async function connectedUser(): Promise<void> {
|
||||
reportUndrained(inbox, error);
|
||||
}
|
||||
}
|
||||
// 3. …and from here on, KEEP applying. The backlog above is the special case, not the
|
||||
// rule: upstream a session is handed each inbox message as it arrives and applies it
|
||||
// inline, and only the messages waiting at connection are the "queue"
|
||||
// (`from_queue`). Draining once and stopping made a deposit wait for the recipient
|
||||
// to reload the page. See `emulated-verifier/inbox-observer.ts`.
|
||||
//
|
||||
// After the drain, not before: connecting owes the backlog first, and the
|
||||
// observation subscribes to the same inboxes this loop just read.
|
||||
//
|
||||
// Unconditional on the loop's outcome, deliberately. An inbox that could not be
|
||||
// drained is reported and denies nobody their session, and it must not deny them the
|
||||
// observation of the OTHER inboxes either — nor of itself, since the next push is a
|
||||
// fresh attempt at exactly the deposit that failed.
|
||||
// Awaited, and it never rejects: what connecting starts, connecting finishes, so a
|
||||
// caller that got its promise back knows the watching is in place — not merely
|
||||
// requested. (It does not wait for the applying that watching then triggers.)
|
||||
if (!stillConnected()) return;
|
||||
await startObservingInboxes();
|
||||
})();
|
||||
|
||||
inFlight.set(holder, run);
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
/**
|
||||
* ONE drain at a time per inbox — the serializer both things that drain an inbox go through.
|
||||
*
|
||||
* Two of them exist in this package, and they are not coordinated by anything else: the
|
||||
* CONTINUOUS observation of the connected identity's own inboxes
|
||||
* (`emulated-verifier/inbox-observer.ts`) and the deferred timer that stands in for an
|
||||
* ABSENT owner (`emulated-verifier/inbox-processor.ts`). Both can be pointed at the same
|
||||
* inbox in the same page — a deposit into an inbox whose owner is also connected here arms
|
||||
* the timer AND pushes to the observation.
|
||||
*
|
||||
* Draining writes what it applies (`branch-registers.addLink`, on the owner's User branch),
|
||||
* so two passes over one queue interleave their reads and writes and apply the same records
|
||||
* twice. Sequencing them is the same reasoning `connect.connectedUser` drains its inboxes
|
||||
* one after another for, and it belongs HERE rather than in either caller: an invariant that
|
||||
* holds only while both callers remember it is not an invariant.
|
||||
*
|
||||
* It is a queue, not a lock: a run that arrives while another is going is not dropped, it
|
||||
* follows. Dropping would be wrong — the second run exists because something new landed.
|
||||
*/
|
||||
|
||||
import { accessLogPrefix, shortNuri } from "../shared-wallet/access-log";
|
||||
import type { Nuri } from "../model/types";
|
||||
|
||||
/** Drains in flight or queued, per inbox — the chain a new run appends itself to. */
|
||||
const running = new Map<Nuri, Promise<void>>();
|
||||
|
||||
/**
|
||||
* Where a drain's failure goes.
|
||||
*
|
||||
* It cannot throw: nothing awaits these — neither the timer nor a push is a caller — and an
|
||||
* unhandled rejection would take down whatever runtime it is in over work the application
|
||||
* never requested. But "nowhere" is not the alternative. A drain that swallows its failure
|
||||
* is indistinguishable from one that succeeded, which is precisely the defect family removed
|
||||
* from this package on 2026-08-13, and a CONTINUOUS drain that swallowed would repeat that
|
||||
* silence for as long as the session lasts. So it goes to the package's own log stream — the
|
||||
* same `console.error` with the same `[<identity>][polyfill]` prefix `startConnect` and
|
||||
* `inbox.watch` use — and it is NOT gated by the access-log flag: a diagnostic may be
|
||||
* opt-in, a failure may not.
|
||||
*
|
||||
* One failed item denies nothing, here as at connection: the inbox is not consumed by
|
||||
* failing, the deposit stays in it, and the next push or the next connection applies it.
|
||||
*/
|
||||
function reportFailure(inbox: Nuri, error: unknown): void {
|
||||
console.error(
|
||||
accessLogPrefix() + " could not apply what is in this inbox — its deposits stay in it " +
|
||||
"and the next attempt will try again: " + shortNuri(inbox) + ":",
|
||||
error,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Run `process` for `inbox`, behind any run of the same inbox still in flight.
|
||||
*
|
||||
* Resolves when THIS run has finished (or failed, having reported itself), so a caller
|
||||
* that wants to wait can — while a caller that does not simply drops the promise.
|
||||
*/
|
||||
// @provenance drainInboxSerially kind=aligned level=1 ref=engine/verifier/src/verifier.rs:inbox — upstream one verifier owns an inbox and applies its messages one at a time as they arrive; this is that serialization, for the two paths this package drains from
|
||||
export function drainInboxSerially(inbox: Nuri, process: () => Promise<void>): Promise<void> {
|
||||
const previous = running.get(inbox) ?? Promise.resolve();
|
||||
const next = previous
|
||||
// A previous run that FAILED must not cancel this one: its failure was reported where
|
||||
// failures go, and the deposits it did not apply are exactly what this run is for.
|
||||
.catch(() => undefined)
|
||||
.then(process)
|
||||
.catch((error: unknown) => reportFailure(inbox, error))
|
||||
.then(() => {
|
||||
if (running.get(inbox) === next) running.delete(inbox);
|
||||
});
|
||||
running.set(inbox, next);
|
||||
return next;
|
||||
}
|
||||
|
||||
/**
|
||||
* Wait until no drain is in flight. The seam a suite needs to observe convergence without
|
||||
* waiting for it — and the one `runScheduledInboxProcessingNow` awaits after firing its
|
||||
* windows. Loops, because a drain can be chained behind the one being awaited.
|
||||
*/
|
||||
// @provenance drainsSettled kind=invention level=none ref=none — a test/lifecycle seam over the queue above; upstream nothing exposes "is the verifier done applying"
|
||||
export async function drainsSettled(): Promise<void> {
|
||||
while (running.size > 0) {
|
||||
await Promise.all([...running.values()]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,346 @@
|
||||
/**
|
||||
* While an identity is connected, its inboxes are WATCHED and what arrives is APPLIED.
|
||||
*
|
||||
* ── The regime this restores, and the one it replaces ─────────────────────
|
||||
* Upstream, applying an inbox is not something that happens at connection — it is what a
|
||||
* session DOES. A sealed message reaches the recipient's own verifier as it arrives
|
||||
* (`LocalBrokerMessage::Inbox` → `session.verifier.inbox(msg, from_queue)`,
|
||||
* `sdk/rust/src/local_broker.rs`), which unseals it and applies it inline
|
||||
* (`engine/verifier/src/inbox_processor.rs`); `from_queue` distinguishes the backlog handed
|
||||
* over at connection from the messages that follow, and BOTH go through the same door. So
|
||||
* the backlog is the special case, and the continuity is the rule.
|
||||
*
|
||||
* This package had emulated only the backlog. `inbox.processInbox` was called from exactly
|
||||
* one place — `connect.connectedUser`, at connection — and nothing anywhere applied a
|
||||
* deposit after that. A share deposited into an inbox whose owner was sitting connected in
|
||||
* front of it converged only when that person reloaded the page, and the deposit's own
|
||||
* session covered the gap by usurping the owner's identity on a twenty-second timer
|
||||
* (`emulated-verifier/inbox-processor.ts`) — which does nothing at all if the depositor
|
||||
* closes their tab, and tells the connected owner nothing either way.
|
||||
*
|
||||
* So: for as long as an identity is connected, every inbox it may read is subscribed to,
|
||||
* and every push over one of them applies what is in it.
|
||||
*
|
||||
* ── Watching is not applying ──────────────────────────────────────────────
|
||||
* `inbox.watch` looks like this and is not: it NOTIFIES an application that made a call and
|
||||
* named one inbox, and it applies nothing. This applies, on the whole set, without anybody
|
||||
* asking — because processing an inbox is the library's job and not the app's, which is the
|
||||
* same ruling `connect.ts` opens with.
|
||||
*
|
||||
* ── Subscription, never a poll ────────────────────────────────────────────
|
||||
* Every half is push-driven. The inboxes themselves are subscribed to individually. WHICH
|
||||
* inboxes exist is itself a subscription, on two channels that do not overlap:
|
||||
*
|
||||
* - the REGISTER — an inbox opened mid-session appends an `AddInboxCap` record to the
|
||||
* User branch of the private store (`branch-registers.openDocumentInbox`), so a push on
|
||||
* that document re-enumerates `myInboxes()`;
|
||||
* - WHAT THIS IDENTITY HOLDS (`CapRegistry.onChange`) — the same signal `watchShape`
|
||||
* re-reads on. It answers the case the register cannot: an identity that connects
|
||||
* before it has an account at all. Provisioning is lazy here, so a person's FIRST visit
|
||||
* connects with no stores, no private store to follow and no inbox to watch; the
|
||||
* account appears later, the moment the application creates anything, and filing its
|
||||
* caps is what says so. Without this channel a brand-new user was watched from their
|
||||
* SECOND visit onwards — which is exactly the person most likely to be sent something.
|
||||
*
|
||||
* So a document whose inbox this identity opened five minutes into the session is watched
|
||||
* like the rest, and so is the very first inbox of a person who had none when they arrived.
|
||||
*
|
||||
* ── It belongs to ONE holder, and stops when that holder does ─────────────
|
||||
* Everything below resolves the CURRENT holder when it runs — `myInboxes`, `processInbox`
|
||||
* and everything under them ask `getCurrentUser()` at the moment they execute. So an
|
||||
* observation started for Alice must not still be firing when Bob is connected: it would
|
||||
* read Alice's registers under Bob, or file Alice's capabilities into Bob's ring. The
|
||||
* observation is therefore stamped with its holder, every step re-checks it, and switching
|
||||
* identity (or disconnecting) tears it down — the same rule, and the same reason,
|
||||
* `connect.connectedUser` carries `stillConnected()` for.
|
||||
*/
|
||||
|
||||
import { getCaps, getCurrentUser } from "../shared-wallet/bootstrap";
|
||||
import { accessLogPrefix, logStage, shortNuri } from "../shared-wallet/access-log";
|
||||
import { myInboxes } from "./branch-registers";
|
||||
import { drainInboxSerially, drainsSettled } from "./inbox-drain";
|
||||
import { lookupAccount } from "../shared-wallet/account-registry";
|
||||
import { processInbox } from "../surface/inbox";
|
||||
import { subscribeDoc, type Unsubscribe } from "../surface/subscribe";
|
||||
import type { Nuri, PrincipalId } from "../model/types";
|
||||
|
||||
/**
|
||||
* One identity's live observation. Held whole rather than as loose module variables so
|
||||
* that a step started under it can ask "am I still the current one" by IDENTITY of the
|
||||
* object, not by comparing a name that a re-connection may have restored in between.
|
||||
*/
|
||||
interface Observation {
|
||||
/** WHO this observation belongs to. Every step re-checks it before acting. */
|
||||
holder: PrincipalId;
|
||||
/** One subscription per inbox observed, keyed by it. */
|
||||
inboxes: Map<Nuri, Unsubscribe>;
|
||||
/** The subscription on the register that says WHICH inboxes exist. */
|
||||
register: Unsubscribe | null;
|
||||
/** Unsubscribe from the held-caps change signal — the second "which inboxes" channel. */
|
||||
holdings: Unsubscribe | null;
|
||||
/** True while a re-enumeration is running, so its own effects do not restart it. */
|
||||
enumerating: boolean;
|
||||
/** A trigger that arrived mid-cycle: the running one repeats once rather than lose it. */
|
||||
enumerateAgain: boolean;
|
||||
/** Enumerations and applications in flight — what {@link observationSettled} waits on. */
|
||||
pending: Set<Promise<void>>;
|
||||
}
|
||||
|
||||
let observation: Observation | null = null;
|
||||
|
||||
/**
|
||||
* Where a failure to WATCH goes — distinct from a failure to APPLY, which
|
||||
* `inbox-drain.ts` reports.
|
||||
*
|
||||
* Not a rejection: nothing awaits this work, exactly as at connection. And not silence, for
|
||||
* the same reason as everywhere else in this package — an observation that cannot be
|
||||
* established leaves deposits unapplied for the whole session, and the only thing a person
|
||||
* would notice is that a share never arrives.
|
||||
*/
|
||||
function reportUnobserved(what: string, error: unknown): void {
|
||||
console.error(
|
||||
accessLogPrefix() + " connected, but " + what + " — deposits made from now on may not be " +
|
||||
"applied until the next connection:",
|
||||
error,
|
||||
);
|
||||
}
|
||||
|
||||
/** Is `obs` still the live observation, for the identity it belongs to? */
|
||||
function current(obs: Observation): boolean {
|
||||
return observation === obs && getCurrentUser() === obs.holder;
|
||||
}
|
||||
|
||||
/** Track a piece of in-flight work so {@link observationSettled} can wait for it. */
|
||||
function track(obs: Observation, work: Promise<void>): void {
|
||||
obs.pending.add(work);
|
||||
void work.finally(() => obs.pending.delete(work));
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply whatever is in `inbox`, for the holder this observation belongs to.
|
||||
*
|
||||
* Through the shared per-inbox queue, so this cannot interleave with a drain the deferred
|
||||
* timer started on the same inbox (nor with another push of its own): two passes over one
|
||||
* queue apply the same records twice. A failure is reported there and stops nothing — the
|
||||
* next push over this inbox tries again, and the other inboxes were never involved.
|
||||
*/
|
||||
async function applyWhatArrived(obs: Observation, inbox: Nuri): Promise<void> {
|
||||
if (!current(obs)) return;
|
||||
await drainInboxSerially(inbox, async () => {
|
||||
// Re-checked INSIDE the queue: this run may have waited behind another one, and the
|
||||
// identity can have moved while it waited. `processInbox` resolves the holder at each
|
||||
// of its steps, so running it for the wrong one is not a near-miss — it reads someone
|
||||
// else's registers and files into someone else's ring.
|
||||
if (!current(obs)) return;
|
||||
try {
|
||||
await processInbox(inbox);
|
||||
} catch (error) {
|
||||
// An identity that moved MID-DRAIN throws here too, and it is the ordinary case rather
|
||||
// than an exotic one: `processInbox` resolves the holder at each step, so the new
|
||||
// holder is refused an inbox that is not theirs somewhere in the middle. That is
|
||||
// ABANDONING — which this package has always called "not a failure" — and reporting it
|
||||
// would put a broker-looking error in the log every time a page switches user.
|
||||
// Nothing is lost: an inbox is not consumed by being abandoned, so the deposit is
|
||||
// still there for its owner's next connection. Same rule, same words, as the drain
|
||||
// loop in `connect.connectedUser`.
|
||||
if (!current(obs)) return;
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* (Re-)enumerate the inboxes this identity may read and subscribe to the ones not yet
|
||||
* watched. Idempotent: an inbox already observed is left alone, so a re-enumeration costs
|
||||
* one read and nothing else.
|
||||
*
|
||||
* Never removes: the list only grows within a session (an `AddInboxCap` record is durable),
|
||||
* and dropping a subscription on a guess would silently stop applying an inbox.
|
||||
*/
|
||||
async function watchTheInboxes(obs: Observation): Promise<void> {
|
||||
if (!current(obs)) return;
|
||||
let inboxes: Nuri[];
|
||||
try {
|
||||
inboxes = await myInboxes();
|
||||
} catch (error) {
|
||||
// Not knowing WHICH inboxes exist is the whole observation failing, not one queue.
|
||||
reportUnobserved("the inboxes to watch could not be listed", error);
|
||||
return;
|
||||
}
|
||||
if (!current(obs)) return;
|
||||
for (const inbox of inboxes) {
|
||||
if (obs.inboxes.has(inbox)) continue;
|
||||
try {
|
||||
// The push is the signal; the drain is the work. The FIRST push is the initial
|
||||
// `State`, which drains an inbox connection has usually just drained — idempotent,
|
||||
// and the alternative (skip the first) would lose a deposit that landed in the gap
|
||||
// between the two.
|
||||
obs.inboxes.set(
|
||||
inbox,
|
||||
subscribeDoc(inbox, () => track(obs, applyWhatArrived(obs, inbox))),
|
||||
);
|
||||
logStage("OBSERVING " + shortNuri(inbox) + " for " + obs.holder);
|
||||
} catch (error) {
|
||||
reportUnobserved("this inbox could not be watched: " + shortNuri(inbox), error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Follow the register that says which inboxes exist, so one opened MID-SESSION is picked
|
||||
* up. See the module header: `openDocumentInbox` appends its record to the User branch of
|
||||
* the private store, and a same-session write pushes to its own subscribers.
|
||||
*
|
||||
* Idempotent, and RETRIED rather than given up on: an identity that connects before it has
|
||||
* an account has no private store to follow yet, and acquires one the first time the
|
||||
* application creates anything. Re-entered from the holdings signal, it catches up then.
|
||||
*/
|
||||
async function watchTheRegister(obs: Observation): Promise<void> {
|
||||
if (!current(obs) || obs.register !== null) return;
|
||||
let store: Nuri | undefined;
|
||||
try {
|
||||
// `lookupAccount`, not `resolveAccount`: the tolerant form answers `null` for a read
|
||||
// that FAILED exactly as for one that found nothing, and the two could not mean more
|
||||
// different things here — "this identity has no account yet" is a state to wait
|
||||
// quietly through, "the broker did not answer" is a failure to report. The same
|
||||
// distinction `connect.connectedUser` and `inbox.share` are built on.
|
||||
store = (await lookupAccount(obs.holder))?.docPrivate;
|
||||
} catch (error) {
|
||||
reportUnobserved("the register of your inboxes could not be reached", error);
|
||||
return;
|
||||
}
|
||||
// No account yet — nothing to follow, and asking for one would PROVISION it, which
|
||||
// connecting deliberately does not do (`connect.connectedUser`). The holdings signal
|
||||
// brings us back here the moment there is something to follow.
|
||||
if (!store || !current(obs) || obs.register !== null) return;
|
||||
try {
|
||||
obs.register = subscribeDoc(store, () => track(obs, enumerate(obs)));
|
||||
} catch (error) {
|
||||
reportUnobserved("an inbox opened later in this session will not be watched", error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The whole "which inboxes am I watching" cycle: catch up on the register, then on the
|
||||
* inboxes. Both halves are idempotent, so this is what every trigger runs.
|
||||
*
|
||||
* A trigger that arrives while a cycle is running does not start a second one — the cycle
|
||||
* FILES caps for the inboxes it lists (`myInboxes` → `fileOwnInbox`), which is one of the
|
||||
* signals that runs it, so overlapping runs would pile up on their own effects. It is
|
||||
* REMEMBERED instead of dropped: the running cycle repeats once more at the end, because a
|
||||
* signal that arrived mid-cycle may be about something that cycle had already read past.
|
||||
*
|
||||
* That terminates rather than ping-ponging: filing a cap this identity already holds fires
|
||||
* nothing (`caps.file` notifies only on a genuinely new one), so the repeat that finds
|
||||
* nothing new sets no flag and the loop ends.
|
||||
*/
|
||||
async function enumerate(obs: Observation): Promise<void> {
|
||||
if (!current(obs)) return;
|
||||
if (obs.enumerating) {
|
||||
obs.enumerateAgain = true;
|
||||
return;
|
||||
}
|
||||
obs.enumerating = true;
|
||||
try {
|
||||
do {
|
||||
obs.enumerateAgain = false;
|
||||
await watchTheRegister(obs);
|
||||
await watchTheInboxes(obs);
|
||||
} while (obs.enumerateAgain && current(obs));
|
||||
} finally {
|
||||
obs.enumerating = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Start observing the connected identity's inboxes. Called at the end of the connection
|
||||
* work (`connect.connectedUser`), and idempotent: calling it again for the identity already
|
||||
* being observed changes nothing.
|
||||
*
|
||||
* ── It resolves when the WATCHING is in place, not when the applying is done ──
|
||||
* Connecting publishes one guarantee — *the work it starts, it finishes* — and "your
|
||||
* inboxes are now being watched" is part of that work, so this is awaited rather than
|
||||
* fired. What it does NOT wait for is the applying: subscribing pushes an initial `State`,
|
||||
* which drains each inbox again, and making a person's sign-in wait on a second pass over
|
||||
* a backlog `connectedUser` has just applied would buy nothing.
|
||||
*
|
||||
* It never rejects. Failing to WATCH is reported where failures go and denies nobody their
|
||||
* session — the same rule the drain loop above it follows, and for the same reason: what
|
||||
* has not been applied stays in its queue for the next attempt.
|
||||
*/
|
||||
// @provenance startObservingInboxes kind=aligned level=1 ref=engine/verifier/src/verifier.rs:inbox — upstream a connected verifier is handed each inbox message as it arrives and applies it; here the arrival signal is a document push, and the set of inboxes is the User branch's `AddInboxCap` records
|
||||
export async function startObservingInboxes(): Promise<void> {
|
||||
const holder = getCurrentUser();
|
||||
if (holder === null) return;
|
||||
if (observation !== null && observation.holder === holder) return;
|
||||
stopObservingInboxes();
|
||||
const obs: Observation = {
|
||||
holder,
|
||||
inboxes: new Map(),
|
||||
register: null,
|
||||
holdings: null,
|
||||
enumerating: false,
|
||||
enumerateAgain: false,
|
||||
pending: new Set(),
|
||||
};
|
||||
observation = obs;
|
||||
// The second "which inboxes exist" channel — see the module header. It is what makes a
|
||||
// person's FIRST session watched at all: they connect holding nothing, and their account
|
||||
// (with its inboxes) appears the moment the application creates something.
|
||||
obs.holdings = getCaps().onChange(() => track(obs, enumerate(obs)));
|
||||
const setup = enumerate(obs);
|
||||
track(obs, setup);
|
||||
await setup;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop observing — on an identity change, on disconnection, and when the library is
|
||||
* un-configured.
|
||||
*
|
||||
* Work already inside the drain queue is not cancelled (nothing can un-issue a write
|
||||
* already sent); it is neutralised instead, because every step re-checks that its
|
||||
* observation is still the current one and returns rather than filing for the wrong holder.
|
||||
*/
|
||||
// @provenance stopObservingInboxes kind=aligned level=1 ref=engine/verifier/src/verifier.rs:Verifier — a verifier's inbox processing lives and dies with its session; switching identity is another session, so nothing of the previous one keeps applying
|
||||
export function stopObservingInboxes(): void {
|
||||
const obs = observation;
|
||||
if (obs === null) return;
|
||||
observation = null;
|
||||
for (const unsub of obs.inboxes.values()) {
|
||||
try {
|
||||
unsub();
|
||||
} catch (error) {
|
||||
console.error(accessLogPrefix() + " stopping an inbox observation failed:", error);
|
||||
}
|
||||
}
|
||||
obs.inboxes.clear();
|
||||
for (const unsub of [obs.register, obs.holdings]) {
|
||||
if (!unsub) continue;
|
||||
try {
|
||||
unsub();
|
||||
} catch (error) {
|
||||
console.error(accessLogPrefix() + " stopping an inbox observation failed:", error);
|
||||
}
|
||||
}
|
||||
obs.register = null;
|
||||
obs.holdings = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Wait until the observation has nothing in flight — the enumerations it is running and the
|
||||
* drains they started.
|
||||
*
|
||||
* A seam for a suite that has to observe convergence without waiting for it, in the same
|
||||
* spirit as `runScheduledInboxProcessingNow`: it names no inbox and starts no work, so it
|
||||
* can only wait for what a push has already caused. Never exported from the package.
|
||||
*/
|
||||
// @provenance observationSettled kind=invention level=none ref=none — a test seam over the observation; upstream nothing exposes "has the verifier finished applying"
|
||||
export async function observationSettled(): Promise<void> {
|
||||
for (;;) {
|
||||
const obs = observation;
|
||||
const inFlight = obs ? [...obs.pending] : [];
|
||||
if (inFlight.length === 0) break;
|
||||
await Promise.all(inFlight);
|
||||
}
|
||||
await drainsSettled();
|
||||
}
|
||||
@@ -1,18 +1,26 @@
|
||||
/**
|
||||
* The inbox-processing SERVICE this deployment has not got — emulated by a timer.
|
||||
* A stand-in for an inbox whose owner is NOT HERE — emulated by a timer.
|
||||
*
|
||||
* ── What is missing, and what stands in for it ────────────────────────────
|
||||
* Upstream a deposit does not wait for anybody: the broker routes the sealed message
|
||||
* (`inboxes: PubKey → RepoId`, `engine/verifier/src/verifier.rs:105,1677`) and the
|
||||
* recipient's verifier applies it when it processes the inbox
|
||||
* (`engine/verifier/src/inbox_processor.rs`). A real NextGraph deployment will have
|
||||
* something running continuously that does this; today, in this library, the ONLY thing
|
||||
* that drains an inbox is its owner connecting (`connect.connectedUser` →
|
||||
* `inbox.processInbox`), which can be hours away.
|
||||
* RECIPIENT's own verifier applies it as it arrives, for as long as that recipient has a
|
||||
* session (`LocalBrokerMessage::Inbox` → `session.verifier.inbox(…)`,
|
||||
* `sdk/rust/src/local_broker.rs`). Two different things follow from that, and this module
|
||||
* is only one of them:
|
||||
*
|
||||
* - a connected identity's own inboxes are observed and applied continuously, which is
|
||||
* `emulated-verifier/inbox-observer.ts` and needs no timer at all;
|
||||
* - an identity that is NOT connected has nobody to apply anything for it. Upstream the
|
||||
* broker queues the message until it comes back; here, on ONE shared wallet, the
|
||||
* depositor's own page can stand in for it.
|
||||
*
|
||||
* So: a successful deposit arms a ONE-SHOT timer that processes the TARGET's inbox, twenty
|
||||
* seconds later. Alice deposits into Bob's inbox; twenty seconds later this package drains
|
||||
* Bob's inbox, while the connected session is still Alice's.
|
||||
* Bob's inbox, while the connected session is still Alice's. When Bob IS connected in this
|
||||
* page, the observation has already applied it long before the window closes and the timer
|
||||
* finds nothing left to do — harmless (draining is idempotent) and not worth a special
|
||||
* case: the two answer different questions, and only this one answers the absent owner.
|
||||
*
|
||||
* ── That is identity usurpation, and it is deliberate ─────────────────────
|
||||
* It is only possible because one shared wallet holds every virtual identity, and it is
|
||||
@@ -32,7 +40,8 @@
|
||||
* the real path, not a repair.
|
||||
*/
|
||||
|
||||
import { accessLogPrefix, logStage, shortNuri } from "../shared-wallet/access-log";
|
||||
import { logStage, shortNuri } from "../shared-wallet/access-log";
|
||||
import { drainInboxSerially, drainsSettled } from "./inbox-drain";
|
||||
import type { Nuri } from "../model/types";
|
||||
|
||||
/**
|
||||
@@ -62,13 +71,6 @@ interface Scheduled {
|
||||
*/
|
||||
const scheduled = new Map<Nuri, Scheduled>();
|
||||
|
||||
/**
|
||||
* Drains in flight, per inbox — so a run that starts while another is still going CHAINS
|
||||
* behind it instead of interleaving with it. Same reason `connect.connectedUser` drains its
|
||||
* inboxes sequentially: two concurrent passes over one queue apply the same records twice.
|
||||
*/
|
||||
const running = new Map<Nuri, Promise<void>>();
|
||||
|
||||
/**
|
||||
* Keep a pending drain from holding a runtime open.
|
||||
*
|
||||
@@ -83,38 +85,14 @@ function releaseFromTheEventLoop(handle: ReturnType<typeof setTimeout>): void {
|
||||
}
|
||||
|
||||
/**
|
||||
* Where a deferred drain's failure goes.
|
||||
*
|
||||
* It cannot throw: nothing awaits it — the application never asked for this work, and an
|
||||
* unhandled rejection would take down whatever runtime it is in over a drain it did not
|
||||
* request. But "nowhere" is not the alternative. A drain that swallows its failure is
|
||||
* indistinguishable from one that succeeded, which is precisely the defect family removed
|
||||
* from this package on 2026-08-13. So it goes to the package's own log stream — the same
|
||||
* `console.error` with the same `[<identity>][polyfill]` prefix that `startConnect` and
|
||||
* `inbox.watch` use for their un-awaitable failures, and it is NOT gated by the access-log
|
||||
* flag: a diagnostic may be opt-in, a failure may not.
|
||||
* Run the drain of `inbox`, behind any run of the same inbox still in flight — including a
|
||||
* run the CONTINUOUS observation started, which is why the queue lives in
|
||||
* `emulated-verifier/inbox-drain.ts` rather than here. That module also owns where a
|
||||
* drain's failure goes; it cannot travel back to a caller, because a timer has none.
|
||||
*/
|
||||
function reportFailure(inbox: Nuri, error: unknown): void {
|
||||
console.error(
|
||||
accessLogPrefix() + " deferred inbox processing failed for " + shortNuri(inbox) + ":",
|
||||
error,
|
||||
);
|
||||
}
|
||||
|
||||
/** Run the drain of `inbox`, behind any run of the same inbox still in flight. */
|
||||
function fire(inbox: Nuri, process: () => Promise<void>): void {
|
||||
scheduled.delete(inbox);
|
||||
const previous = running.get(inbox) ?? Promise.resolve();
|
||||
const next = previous
|
||||
// A previous run that FAILED must not cancel this one: its failure was reported where
|
||||
// failures go, and the deposits it did not apply are exactly what this run is for.
|
||||
.catch(() => undefined)
|
||||
.then(process)
|
||||
.catch((error: unknown) => reportFailure(inbox, error))
|
||||
.then(() => {
|
||||
if (running.get(inbox) === next) running.delete(inbox);
|
||||
});
|
||||
running.set(inbox, next);
|
||||
void drainInboxSerially(inbox, process);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -126,7 +104,7 @@ function fire(inbox: Nuri, process: () => Promise<void>): void {
|
||||
*
|
||||
* Idempotent inside the window: a second deposit into the same inbox joins the pending run.
|
||||
*/
|
||||
// @provenance scheduleInboxProcessing kind=divergent level=1 ref=engine/verifier/src/verifier.rs:inbox — upstream the RECIPIENT's own verifier applies its inbox; here another identity's session drains it on a timer. Deliberate, unpublished, and only possible on one shared wallet
|
||||
// @provenance scheduleInboxProcessing kind=divergent level=1 ref=engine/verifier/src/verifier.rs:inbox — upstream the RECIPIENT's own verifier applies its inbox and the broker queues for it while it is away; here another identity's session drains it on a timer, for a recipient that is not connected in this page (one that IS has its own observation). Deliberate, unpublished, and only possible on one shared wallet
|
||||
export function scheduleInboxProcessing(inbox: Nuri, process: () => Promise<void>): void {
|
||||
if (scheduled.has(inbox)) return;
|
||||
const handle = setTimeout(() => fire(inbox, process), PROCESSING_DELAY_MS);
|
||||
@@ -152,7 +130,7 @@ export async function runScheduledInboxProcessingNow(): Promise<void> {
|
||||
clearTimeout(entry.handle);
|
||||
fire(inbox, entry.process);
|
||||
}
|
||||
await Promise.all([...running.values()]);
|
||||
await drainsSettled();
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -74,7 +74,7 @@
|
||||
import { mustNotAttempt } from "./reach";
|
||||
import { fetchReadCap } from "./public-store";
|
||||
import { getConfig, getStoreRegistryDeps } from "../shared-wallet/bootstrap";
|
||||
import { subscribeDocUnguarded, type Unsubscribe } from "../surface/subscribe";
|
||||
import { resubscribeDocs, subscribeDocUnguarded, type Unsubscribe } from "../surface/subscribe";
|
||||
import { logStage, shortNuri } from "../shared-wallet/access-log";
|
||||
import type { Nuri } from "../model/types";
|
||||
|
||||
@@ -137,6 +137,15 @@ export function resetOpenedRepos(): void {
|
||||
syncState.clear();
|
||||
boundSessionId = null;
|
||||
OPEN_TIMEOUT_MS = 8000;
|
||||
// Whatever ELSE was still subscribed to a document — a `watchShape` following a scope,
|
||||
// an inbox observation — belongs to the session that just went away too. One real
|
||||
// subscription now serves all of them (`surface/subscribe.ts`), so dropping the bootstrap
|
||||
// ones above no longer closes those channels; they are re-opened against the new session,
|
||||
// with their barrier forgotten. Without this a bootstrap open would join a surviving
|
||||
// fan-out, be handed the PREVIOUS session's `State`, and call a repo the new session has
|
||||
// never synced "synced". After the held teardown, so a document nobody else follows is
|
||||
// simply released.
|
||||
resubscribeDocs();
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in New Issue
Block a user