@941design/marmot 0.2.0-alpha.0 → 0.2.0-alpha.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +30 -0
- package/dist/account/teardown.d.ts +66 -3
- package/dist/account/teardown.js +24 -2
- package/dist/client/admission-cleanup.d.ts +197 -0
- package/dist/client/admission-cleanup.js +635 -0
- package/dist/client/adoption-proof.d.ts +39 -0
- package/dist/client/adoption-proof.js +102 -0
- package/dist/client/before-publish-hooks.js +3 -1
- package/dist/client/commit-redrive.d.ts +28 -4
- package/dist/client/commit-redrive.js +54 -1
- package/dist/client/confirm-hooks.d.ts +6 -1
- package/dist/client/confirm-hooks.js +15 -0
- package/dist/client/create-client.d.ts +107 -3
- package/dist/client/create-client.js +114 -7
- package/dist/client/group-availability.d.ts +182 -0
- package/dist/client/group-availability.js +301 -0
- package/dist/client/group-history.d.ts +26 -0
- package/dist/client/group-history.js +77 -7
- package/dist/client/group-records.d.ts +39 -2
- package/dist/client/group-records.js +88 -5
- package/dist/client/group-runtime.d.ts +30 -3
- package/dist/client/group-runtime.js +131 -21
- package/dist/client/group-snapshot.d.ts +7 -1
- package/dist/client/group-snapshot.js +23 -2
- package/dist/client/index.d.ts +4 -1
- package/dist/client/ingest.js +47 -13
- package/dist/client/invitation-outcomes.d.ts +50 -0
- package/dist/client/invitation-outcomes.js +135 -0
- package/dist/client/opaque-candidates.d.ts +2 -1
- package/dist/client/opaque-candidates.js +2 -1
- package/dist/client/own-change-outbox.js +2 -0
- package/dist/client/pipeline.d.ts +30 -1
- package/dist/client/pipeline.js +142 -21
- package/dist/client/reentrancy-guard.d.ts +6 -0
- package/dist/client/reentrancy-guard.js +6 -0
- package/dist/history/admission-lineage.d.ts +186 -0
- package/dist/history/admission-lineage.js +589 -0
- package/dist/history/fencing.d.ts +41 -0
- package/dist/history/fencing.js +67 -7
- package/dist/history/index.d.ts +2 -1
- package/dist/history/index.js +2 -1
- package/dist/history/own-change.d.ts +13 -1
- package/dist/invitations/decline.d.ts +8 -2
- package/dist/invitations/decline.js +9 -3
- package/dist/invitations/delivery-evidence.d.ts +288 -0
- package/dist/invitations/delivery-evidence.js +766 -0
- package/dist/invitations/index.d.ts +4 -2
- package/dist/invitations/index.js +4 -2
- package/dist/invitations/invitation-outcome.d.ts +110 -0
- package/dist/invitations/invitation-outcome.js +210 -0
- package/dist/invitations/invite.d.ts +61 -6
- package/dist/invitations/invite.js +187 -51
- package/dist/invitations/welcome-processor.d.ts +20 -1
- package/dist/invitations/welcome-processor.js +81 -20
- package/dist/shared/errors.d.ts +7 -0
- package/dist/shared/errors.js +11 -0
- package/dist/shared/index.d.ts +1 -1
- package/dist/shared/index.js +1 -1
- package/dist/storage/index.d.ts +10 -0
- package/dist/storage/index.js +33 -1
- package/dist/storage/lease.d.ts +13 -0
- package/dist/storage/lease.js +51 -0
- package/package.json +2 -2
|
@@ -0,0 +1,301 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Group availability (epic marmot-invitation-outcomes S1, SC-10 A-1..A-8): one race-free observation per group of
|
|
3
|
+
* three independent facts — the fence, the sync state and the membership — plus whether the group is writable now.
|
|
4
|
+
*
|
|
5
|
+
* Availability subscriptions are their own set on the runtime ({@link GroupRuntime.availabilityListeners}). They are
|
|
6
|
+
* never terminal watchers: a fence is an ordinary observation that leaves the subscription open, and `endRuntime`
|
|
7
|
+
* never closes them. Exactly one `ended` closes a subscription, and only for the lifecycle exits
|
|
8
|
+
* ({@link AvailabilityEndReason}): a teardown purge, a failed restore taken back, client dispose, or the account
|
|
9
|
+
* lease ending (released, closed, or lost to a successor).
|
|
10
|
+
*
|
|
11
|
+
* Every change of a fact goes through one choke point on the runtime (the accessors of `fence`, `exposedState`,
|
|
12
|
+
* `caughtUp`, `sendGateOpen` and `disbanded`, group-runtime.ts `makeRuntime`), which calls
|
|
13
|
+
* {@link publishAvailability}; an observation is delivered only when the snapshot actually changed, so listeners see
|
|
14
|
+
* changes in the order they happened, each with a strictly increasing `seq` per runtime.
|
|
15
|
+
*
|
|
16
|
+
* Fence observation is monotonic within a client session: the fence setter records every fence in the client's
|
|
17
|
+
* {@link SessionFences}, and a runtime the client builds again for the group (group-runtime.ts `readLoadedRuntime`)
|
|
18
|
+
* starts fenced from it even when the durable marker could not be written. Nothing here awaits, schedules work or
|
|
19
|
+
* touches a store: {@link closeAvailability} and {@link closeAllAvailability} are synchronous, which is what lets the
|
|
20
|
+
* lease-end close run inside the store's release barrier.
|
|
21
|
+
*/
|
|
22
|
+
import { fenceCauseOf } from '../history/fencing.js';
|
|
23
|
+
import { MarmotError } from '../shared/index.js';
|
|
24
|
+
/**
|
|
25
|
+
* Fences raised in this client session, by group: a runtime built again for the group starts fenced from here, so a
|
|
26
|
+
* fence whose marker write failed never reads clear again in the same session (A-7). Cleared by a teardown purge and
|
|
27
|
+
* by a new adoption of the group (a join or a restore), which start the group over.
|
|
28
|
+
*/
|
|
29
|
+
export class SessionFences {
|
|
30
|
+
#fences = new Map();
|
|
31
|
+
/** Records `groupId`'s first fence of the session (a later one never replaces it). */
|
|
32
|
+
record(groupId, fence) {
|
|
33
|
+
if (!this.#fences.has(groupId))
|
|
34
|
+
this.#fences.set(groupId, fence);
|
|
35
|
+
}
|
|
36
|
+
get(groupId) {
|
|
37
|
+
return this.#fences.get(groupId);
|
|
38
|
+
}
|
|
39
|
+
causeOf(groupId) {
|
|
40
|
+
const fence = this.#fences.get(groupId);
|
|
41
|
+
return fence === undefined ? undefined : fenceCauseOf(fence);
|
|
42
|
+
}
|
|
43
|
+
clear(groupId) {
|
|
44
|
+
this.#fences.delete(groupId);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
export function createClientAvailability(runtimes = () => []) {
|
|
48
|
+
return { sessionFences: new SessionFences(), leaseEnded: false, ended: undefined, runtimes };
|
|
49
|
+
}
|
|
50
|
+
const CLEAR = Object.freeze({ state: 'clear' });
|
|
51
|
+
/** Pure: the availability the facts describe. */
|
|
52
|
+
export function availabilityFrom(facts) {
|
|
53
|
+
const fence = facts.fence === undefined ? CLEAR : Object.freeze({ state: 'fenced', cause: fenceCauseOf(facts.fence) });
|
|
54
|
+
// The send gate opens right after the first catch-up of a loaded group: one change, observed once.
|
|
55
|
+
const sync = facts.caughtUp && facts.sendGateOpen ? 'synced' : 'syncing';
|
|
56
|
+
const membership = facts.disbanded ? 'disbanded' : facts.removedFromGroup ? 'membership-lost' : 'member';
|
|
57
|
+
const writable = fence.state === 'clear' && sync === 'synced' && membership === 'member' && facts.leaseLive;
|
|
58
|
+
return Object.freeze({ fence, sync, membership, writable });
|
|
59
|
+
}
|
|
60
|
+
/** The runtime's current facts. */
|
|
61
|
+
export function factsOf(rt) {
|
|
62
|
+
return {
|
|
63
|
+
fence: rt.fence,
|
|
64
|
+
caughtUp: rt.caughtUp,
|
|
65
|
+
sendGateOpen: rt.sendGateOpen,
|
|
66
|
+
removedFromGroup: rt.exposedState.groupActiveState.kind === 'removedFromGroup',
|
|
67
|
+
disbanded: rt.disbanded !== undefined,
|
|
68
|
+
leaseLive: rt.leaseLost === undefined && !rt.availabilityClient.leaseEnded,
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
/** The runtime's current availability (pure over {@link factsOf}). */
|
|
72
|
+
export function availabilityOf(rt) {
|
|
73
|
+
return availabilityFrom(factsOf(rt));
|
|
74
|
+
}
|
|
75
|
+
function sameAvailability(a, b) {
|
|
76
|
+
if (a.sync !== b.sync || a.membership !== b.membership || a.writable !== b.writable || a.fence.state !== b.fence.state)
|
|
77
|
+
return false;
|
|
78
|
+
return a.fence.state === 'clear' || b.fence.state === 'clear' || a.fence.cause === b.fence.cause;
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Hands `observation` to `listener`. Never throws. Two contexts:
|
|
82
|
+
* - `'detached'` (a change the group's own work published): outside every re-entrancy frame of the operation that
|
|
83
|
+
* produced it — nothing waits on the listener, so an operation it starts simply queues.
|
|
84
|
+
* - `'caller'` (a delivery made synchronously inside `observeAvailability`, on the subscribing caller's stack): in
|
|
85
|
+
* the caller's own frame, so a subscription made from inside a consumer surface (an `onConfirm` hook, a store, …)
|
|
86
|
+
* gets the same `reentrant` rejection for a same-group operation its listener starts as the surface itself would —
|
|
87
|
+
* instead of an operation queued behind the one awaiting that surface.
|
|
88
|
+
*/
|
|
89
|
+
function deliver(rt, listener, observation, context) {
|
|
90
|
+
const run = () => {
|
|
91
|
+
try {
|
|
92
|
+
// The listener type returns `void`, so an `async` listener type-checks: its rejection is swallowed here without
|
|
93
|
+
// awaiting it (delivery stays synchronous), so it never surfaces as an unhandled rejection.
|
|
94
|
+
const returned = listener(observation);
|
|
95
|
+
if (typeof returned?.then === 'function') {
|
|
96
|
+
returned.then(undefined, () => undefined);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
catch {
|
|
100
|
+
// A throwing listener never breaks the operation that changed the group, nor the other listeners.
|
|
101
|
+
}
|
|
102
|
+
};
|
|
103
|
+
if (context === 'caller')
|
|
104
|
+
run();
|
|
105
|
+
else
|
|
106
|
+
rt.guard.detached(run);
|
|
107
|
+
}
|
|
108
|
+
function enqueue(sub, observation) {
|
|
109
|
+
if (sub.endQueued || sub.unsubscribed)
|
|
110
|
+
return;
|
|
111
|
+
sub.queue.push(observation);
|
|
112
|
+
if (observation.type === 'ended')
|
|
113
|
+
sub.endQueued = true;
|
|
114
|
+
}
|
|
115
|
+
function drain(rt, sub, context = 'detached') {
|
|
116
|
+
if (sub.draining)
|
|
117
|
+
return;
|
|
118
|
+
sub.draining = true;
|
|
119
|
+
try {
|
|
120
|
+
while (!sub.unsubscribed) {
|
|
121
|
+
const next = sub.queue.shift();
|
|
122
|
+
if (next === undefined)
|
|
123
|
+
break;
|
|
124
|
+
deliver(rt, sub.listener, next, context);
|
|
125
|
+
}
|
|
126
|
+
if (sub.unsubscribed)
|
|
127
|
+
sub.queue.length = 0;
|
|
128
|
+
}
|
|
129
|
+
finally {
|
|
130
|
+
sub.draining = false;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
/** Enqueues `observation` for every subscription live now, then drains each (a drain already running continues it). */
|
|
134
|
+
function broadcast(rt, subs, observation) {
|
|
135
|
+
for (const sub of subs)
|
|
136
|
+
enqueue(sub, observation);
|
|
137
|
+
for (const sub of subs)
|
|
138
|
+
drain(rt, sub);
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* Re-reads the runtime's facts and, when the snapshot changed, delivers it to every live listener with the next
|
|
142
|
+
* `seq`. A no-op once the subscriptions ended. Synchronous; never throws.
|
|
143
|
+
*/
|
|
144
|
+
export function publishAvailability(rt) {
|
|
145
|
+
if (rt.availabilityEnded !== undefined)
|
|
146
|
+
return;
|
|
147
|
+
const next = availabilityOf(rt);
|
|
148
|
+
const last = rt.availabilityLast;
|
|
149
|
+
if (last !== undefined && sameAvailability(last, next))
|
|
150
|
+
return;
|
|
151
|
+
rt.availabilityLast = next;
|
|
152
|
+
rt.availabilitySeq += 1;
|
|
153
|
+
if (last === undefined)
|
|
154
|
+
return;
|
|
155
|
+
const observation = Object.freeze({ type: 'availability', seq: rt.availabilitySeq, availability: next });
|
|
156
|
+
broadcast(rt, [...rt.availabilityListeners], observation);
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* Subscribes `listener` to the group's availability (`MarmotGroup.observeAvailability`): the current snapshot is
|
|
160
|
+
* delivered synchronously, before this returns, then every change. After the subscriptions ended — or once the
|
|
161
|
+
* client's account lease ended — the listener gets the one `ended` and nothing more. The returned function
|
|
162
|
+
* unsubscribes (idempotent); no callback reaches the listener after it. What is delivered before this returns runs in
|
|
163
|
+
* the caller's re-entrancy frame (see {@link deliver}); every later change runs detached.
|
|
164
|
+
*/
|
|
165
|
+
export function observeAvailability(rt, listener) {
|
|
166
|
+
if (typeof listener !== 'function')
|
|
167
|
+
throw new MarmotError('invalid-options', 'MarmotGroup.observeAvailability: listener must be a function');
|
|
168
|
+
const client = rt.availabilityClient;
|
|
169
|
+
const clientEnd = client.ended ?? (client.leaseEnded ? 'no-lease' : undefined);
|
|
170
|
+
if (rt.availabilityEnded === undefined && clientEnd !== undefined)
|
|
171
|
+
closeAvailability(rt, clientEnd);
|
|
172
|
+
const ended = rt.availabilityEnded;
|
|
173
|
+
if (ended !== undefined) {
|
|
174
|
+
deliver(rt, listener, ended, 'caller');
|
|
175
|
+
return () => undefined;
|
|
176
|
+
}
|
|
177
|
+
// Bring the snapshot up to date first (an existing listener sees a pending change before this one's initial).
|
|
178
|
+
publishAvailability(rt);
|
|
179
|
+
const sub = { listener, queue: [], draining: false, endQueued: false, unsubscribed: false };
|
|
180
|
+
// The initial observation is the subscription's first entry, and the subscription joins the set in the same step:
|
|
181
|
+
// every later change or `ended` queues behind it (AC-FENCE-2 — a change its own callback raises is never delivered
|
|
182
|
+
// nested inside it; it follows it), with no gap and no duplicate.
|
|
183
|
+
enqueue(sub, Object.freeze({ type: 'availability', seq: rt.availabilitySeq, availability: rt.availabilityLast ?? availabilityOf(rt) }));
|
|
184
|
+
rt.availabilityListeners.add(sub);
|
|
185
|
+
// Drained on the caller's stack and in the caller's frame: the initial snapshot, then any change its own callback
|
|
186
|
+
// raised (still synchronously inside this call). Later changes drain detached, from whatever published them.
|
|
187
|
+
drain(rt, sub, 'caller');
|
|
188
|
+
return () => {
|
|
189
|
+
sub.unsubscribed = true;
|
|
190
|
+
sub.queue.length = 0;
|
|
191
|
+
rt.availabilityListeners.delete(sub);
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* Phase one of a close: records the runtime's `ended` (every later subscriber gets exactly it), clears its listener set
|
|
196
|
+
* and enqueues the `ended` to every subscription it held — delivering nothing. `undefined` when it had already ended.
|
|
197
|
+
*/
|
|
198
|
+
function markEnded(rt, reason) {
|
|
199
|
+
if (rt.availabilityEnded !== undefined)
|
|
200
|
+
return undefined;
|
|
201
|
+
const final = Object.freeze({ ...availabilityOf(rt), writable: false });
|
|
202
|
+
rt.availabilitySeq += 1;
|
|
203
|
+
const ended = Object.freeze({ type: 'ended', seq: rt.availabilitySeq, reason, final });
|
|
204
|
+
rt.availabilityEnded = ended;
|
|
205
|
+
const subs = [...rt.availabilityListeners];
|
|
206
|
+
rt.availabilityListeners.clear();
|
|
207
|
+
for (const sub of subs)
|
|
208
|
+
enqueue(sub, ended);
|
|
209
|
+
return { rt, subs };
|
|
210
|
+
}
|
|
211
|
+
/** Phase two: delivers what {@link markEnded} enqueued (a drain already running continues it). Never throws. */
|
|
212
|
+
function drainEnded(pending) {
|
|
213
|
+
for (const { rt, subs } of pending) {
|
|
214
|
+
for (const sub of subs) {
|
|
215
|
+
try {
|
|
216
|
+
drain(rt, sub);
|
|
217
|
+
}
|
|
218
|
+
catch {
|
|
219
|
+
// One runtime never keeps the others' listeners from their `ended`.
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
/**
|
|
225
|
+
* Ends the runtime's availability subscriptions (A-3): exactly one `ended` with `reason` to every listener, whose
|
|
226
|
+
* `final` is the current snapshot made not writable (a fenced group stays fenced in it). Idempotent: a later call is a
|
|
227
|
+
* no-op. Synchronous: awaits, schedules and stores nothing.
|
|
228
|
+
*/
|
|
229
|
+
export function closeAvailability(rt, reason) {
|
|
230
|
+
const pending = markEnded(rt, reason);
|
|
231
|
+
if (pending !== undefined)
|
|
232
|
+
drainEnded([pending]);
|
|
233
|
+
}
|
|
234
|
+
/**
|
|
235
|
+
* Ends every runtime's subscriptions in two phases: every runtime's `ended` is recorded (each isolated) before the
|
|
236
|
+
* returned function delivers any of them. So no listener of one runtime's `ended` can observe another runtime of the
|
|
237
|
+
* same close still open — a subscribe to it gets the stored `ended`, and a second close (a dispose raised from a
|
|
238
|
+
* `no-lease` listener) finds it already ended with the first reason.
|
|
239
|
+
*/
|
|
240
|
+
export function markAllAvailabilityEnded(runtimes, reason) {
|
|
241
|
+
const pending = [];
|
|
242
|
+
for (const rt of runtimes) {
|
|
243
|
+
try {
|
|
244
|
+
const marked = markEnded(rt, reason);
|
|
245
|
+
if (marked !== undefined)
|
|
246
|
+
pending.push(marked);
|
|
247
|
+
}
|
|
248
|
+
catch {
|
|
249
|
+
// One runtime never keeps the others open.
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
let drained = false;
|
|
253
|
+
return () => {
|
|
254
|
+
if (drained)
|
|
255
|
+
return;
|
|
256
|
+
drained = true;
|
|
257
|
+
drainEnded(pending);
|
|
258
|
+
};
|
|
259
|
+
}
|
|
260
|
+
/** {@link closeAvailability} for every runtime: all recorded first, then all delivered (see {@link markAllAvailabilityEnded}). */
|
|
261
|
+
export function closeAllAvailability(runtimes, reason) {
|
|
262
|
+
markAllAvailabilityEnded(runtimes, reason)();
|
|
263
|
+
}
|
|
264
|
+
/**
|
|
265
|
+
* The client is being disposed: records the client-wide `disposed` end (unless the lease ended first) and every
|
|
266
|
+
* runtime's `ended/'disposed'` without delivering any; the returned function delivers them. Run the delivery once the
|
|
267
|
+
* runtimes are torn down, so a listener never sees a disposed client's group as still open.
|
|
268
|
+
*/
|
|
269
|
+
export function beginDisposeAvailability(client, runtimes) {
|
|
270
|
+
client.ended ??= 'disposed';
|
|
271
|
+
return markAllAvailabilityEnded(runtimes, 'disposed');
|
|
272
|
+
}
|
|
273
|
+
/**
|
|
274
|
+
* Phase one of the client's account lease end (A-5): records the client-wide lease end (every later subscription of
|
|
275
|
+
* this client gets one immediate `ended/'no-lease'`) and every runtime's `ended/'no-lease'`, delivering nothing; the
|
|
276
|
+
* returned function delivers them. The caller settles its own lease-end consequences (the pending `synced()` waits)
|
|
277
|
+
* between the two, so a listener reacting to its `ended` (a `dispose()`) never pre-empts them. Synchronous; schedules
|
|
278
|
+
* no group work, timer, store access or transport call.
|
|
279
|
+
*/
|
|
280
|
+
export function beginLeaseEndAvailability(client, runtimes) {
|
|
281
|
+
client.leaseEnded = true;
|
|
282
|
+
client.ended ??= 'no-lease';
|
|
283
|
+
return markAllAvailabilityEnded(runtimes, 'no-lease');
|
|
284
|
+
}
|
|
285
|
+
/**
|
|
286
|
+
* The client's account lease ended (A-5): every runtime's subscriptions end `no-lease`, and every later subscription
|
|
287
|
+
* of this client gets one immediate `ended/'no-lease'`. Every runtime is marked ended before any listener runs.
|
|
288
|
+
* Synchronous; schedules no group work, timer, store access or transport call.
|
|
289
|
+
*/
|
|
290
|
+
export function endAvailabilityForLease(client, runtimes) {
|
|
291
|
+
beginLeaseEndAvailability(client, runtimes)();
|
|
292
|
+
}
|
|
293
|
+
/**
|
|
294
|
+
* A lost lease observed lazily on `rt` (a background retry meeting `no-lease`): the account lease is the client's, so
|
|
295
|
+
* this is phase one of the client-wide lease end of {@link beginLeaseEndAvailability} — the fallback for a store
|
|
296
|
+
* without `onLeaseEnded`. `rt` is closed too even when the registry does not hold it (yet). The returned function
|
|
297
|
+
* delivers the `ended` observations.
|
|
298
|
+
*/
|
|
299
|
+
export function beginLostLeaseAvailability(rt) {
|
|
300
|
+
return beginLeaseEndAvailability(rt.availabilityClient, [rt, ...rt.availabilityClient.runtimes()]);
|
|
301
|
+
}
|
|
@@ -15,6 +15,7 @@ import type { Rumor } from '@941design/nostr-events/event';
|
|
|
15
15
|
import type { LeafEquivocation } from '@941design/marmot-engine/core';
|
|
16
16
|
import { type EquivocationRecord, type GroupNotification, type MessageNotification, type OrderingKey, type MessageWithdrawnNotification, type RetainedWindow } from '../history/index.js';
|
|
17
17
|
import { type EncryptedMedia, type EncryptMediaOptions } from '../media/index.js';
|
|
18
|
+
import { MarmotError } from '../shared/index.js';
|
|
18
19
|
import { type ClientState } from '@941design/marmot-engine/mls';
|
|
19
20
|
import type { GroupStoreTx, KeyValueView } from '../storage/index.js';
|
|
20
21
|
import { type MarkerChange, type OwnCommitMarker, type PendingIntentRecord } from './group-records.js';
|
|
@@ -173,6 +174,16 @@ export interface TransitionPlan {
|
|
|
173
174
|
* (their tips included), moved or not; {@link cancelRestoredReenqueues} treats an empty set as "nothing to restore".
|
|
174
175
|
*/
|
|
175
176
|
readonly canonicalTags: ReadonlySet<string>;
|
|
177
|
+
/**
|
|
178
|
+
* Epic marmot-invitation-outcomes S4 (SC-4 I11): what {@link recordTransition} advances admission lineage over — the
|
|
179
|
+
* window the transition started from, the one it diffed against, and `window`'s tip state. Absent on a plan that
|
|
180
|
+
* does not move the window (a lost message): no checkpoint moves then.
|
|
181
|
+
*/
|
|
182
|
+
readonly lineage?: {
|
|
183
|
+
readonly before: RetainedWindow;
|
|
184
|
+
readonly diff: RetainedWindow;
|
|
185
|
+
readonly tip: ClientState;
|
|
186
|
+
};
|
|
176
187
|
}
|
|
177
188
|
/**
|
|
178
189
|
* The announcements of moving the group from `before` (tip `beforeTip`) to
|
|
@@ -421,6 +432,21 @@ export declare function assertNotInHistoryBackend(rt: GroupRuntime): void;
|
|
|
421
432
|
export declare function historyOf(rt: GroupRuntime): AsyncIterable<Rumor>;
|
|
422
433
|
/** Refuses an operation on a fenced group: `fenced`, carrying the fencing error as `cause`. */
|
|
423
434
|
export declare function assertNotFenced(rt: GroupRuntime, operation: string): void;
|
|
435
|
+
/**
|
|
436
|
+
* The session fence was just recorded on `rt`: every `synced()` wait for the group's first catch-up fails `fenced` now —
|
|
437
|
+
* a fenced group never opens its send gate. In-memory only and independent of the durable intent cleanup
|
|
438
|
+
* (`failAwaitingIntents`), so a fence whose store work failed or never runs still settles every waiter.
|
|
439
|
+
*/
|
|
440
|
+
export declare function rejectSyncWaitersFenced(rt: GroupRuntime): void;
|
|
441
|
+
/**
|
|
442
|
+
* Every pending `synced()` wait for the group's first catch-up fails now, each with its own error from `errorOf`: the
|
|
443
|
+
* condition that ends it (a fence, a lost lease) means the send gate never opens in this session.
|
|
444
|
+
*/
|
|
445
|
+
export declare function rejectSyncWaiters(rt: GroupRuntime, errorOf: () => Error): void;
|
|
446
|
+
/** The cause of a client-wide lease end signalled by the account store (`AccountStore.onLeaseEnded`). */
|
|
447
|
+
export declare function accountLeaseEndedError(): MarmotError;
|
|
448
|
+
/** The `no-lease` refusal of a `synced()` wait: the stores lost their lease before the group's first catch-up. */
|
|
449
|
+
export declare function syncedLeaseLostError(rt: GroupRuntime, cause: unknown): MarmotError;
|
|
424
450
|
/**
|
|
425
451
|
* Fences the group for good: the marker is persisted first (a reload stays
|
|
426
452
|
* fenced), then every further operation is refused. Idempotent.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { breakdownWithdrawnCommit, fencedError, canonicalPath, tagOf, equivocationKey, equivocationNotification, equivocationRecordOf, isRecordableEquivocation, leafTransition, readWindow, windowTransition, writeEquivocation, writeFence, EQUIVOCATION_EXTENSION, FENCE_EXTENSION, } from '../history/index.js';
|
|
1
|
+
import { ADMISSION_LINEAGE_EXTENSION, advanceLineageRecords, breakdownWithdrawnCommit, forkPointNode, fencedError, canonicalPath, tagOf, equivocationKey, equivocationNotification, equivocationRecordOf, isRecordableEquivocation, leafTransition, readWindow, windowTransition, writeEquivocation, fenceCauseOf, writeFence, EQUIVOCATION_EXTENSION, FENCE_EXTENSION, } from '../history/index.js';
|
|
2
2
|
import { attachmentOf, decryptMedia, encryptMedia, sha256Hex } from '../media/index.js';
|
|
3
3
|
import { MarmotError } from '../shared/index.js';
|
|
4
4
|
import { nodeTypes } from '@941design/marmot-engine/mls';
|
|
@@ -7,6 +7,7 @@ import { deletePendingIntentRecord, isCommitRedrive, listPendingIntentRecords, n
|
|
|
7
7
|
import { dropDelivered, enqueueTerminals, isTerminalNotification, OWN_CHANGE_OUTBOX_EXTENSION, readOutboxLenient, terminalKey } from './own-change-outbox.js';
|
|
8
8
|
import { clearOpaque, isEmptyOpaque, OPAQUE_EXTENSION } from './opaque-candidates.js';
|
|
9
9
|
import { ownAccountOf } from './rekey.js';
|
|
10
|
+
import { emitCleanupDispositions, noteCleanupCandidate } from './admission-cleanup.js';
|
|
10
11
|
// ---------------------------------------------------------------------------
|
|
11
12
|
// Notifications
|
|
12
13
|
// ---------------------------------------------------------------------------
|
|
@@ -285,8 +286,22 @@ diffAgainst = after) {
|
|
|
285
286
|
...(own.entries.length === 0 ? {} : { withdrawnOwnCommitEntries: own.entries }),
|
|
286
287
|
...(own.unreadable.length === 0 ? {} : { unreadableOwnCommits: own.unreadable }),
|
|
287
288
|
...(own.restored.length === 0 ? {} : { restoredOwnCommits: own.restored }),
|
|
289
|
+
lineage: { before, diff: diffAgainst, tip: afterTip },
|
|
288
290
|
};
|
|
289
291
|
}
|
|
292
|
+
/**
|
|
293
|
+
* Epic marmot-invitation-outcomes S5 (SC-6 I16): the `admission-removed` changes of a marker — those its change list already holds (a
|
|
294
|
+
* re-drive's marker, a later withdrawal), else one per target its intent declared (`declared.admissions`).
|
|
295
|
+
*/
|
|
296
|
+
function admissionChangesOf(marker) {
|
|
297
|
+
if (marker.changes !== undefined)
|
|
298
|
+
return marker.changes.filter((c) => c.change.type === 'admission-removed');
|
|
299
|
+
return (marker.declared?.admissions ?? []).map((target) => ({
|
|
300
|
+
change: { type: 'admission-removed', account: target.account, leafKey: target.anchor.leafKey, candidateId: target.candidateId },
|
|
301
|
+
fork: {},
|
|
302
|
+
target,
|
|
303
|
+
}));
|
|
304
|
+
}
|
|
290
305
|
/** `MarkerChange`s of `forked`: an Add gets the KeyPackage the marker kept for that leaf key (`undefined`: the marker names none — unreadable). */
|
|
291
306
|
function markerChangesOf(forked, marker) {
|
|
292
307
|
const out = [];
|
|
@@ -369,14 +384,24 @@ async function ownCommitTransition(rt, input) {
|
|
|
369
384
|
unreadable.push({ eventId: c.eventId, rootIntentId: marker.root, node: c.entry.node, reason: broken.reason });
|
|
370
385
|
continue;
|
|
371
386
|
}
|
|
372
|
-
|
|
387
|
+
// Epic marmot-invitation-outcomes S5 (SC-6 I16): a scoped cleanup's change is DECLARED (the marker's `declared.admissions`, or the
|
|
388
|
+
// `admission-removed` entries a marker's change list already holds), never derived from the diff — whose `member-removed` a
|
|
389
|
+
// cleanup never declares, so it is filtered out above. It carries its target; it has no fork-point values.
|
|
390
|
+
const admissions = admissionChangesOf(marker);
|
|
391
|
+
if (broken.changes.length === 0 && admissions.length === 0)
|
|
373
392
|
continue; // nothing the intent declared shows in the diff: nothing to re-drive or name
|
|
374
|
-
const
|
|
375
|
-
if (
|
|
393
|
+
const diffChanges = markerChangesOf(broken.changes, marker);
|
|
394
|
+
if (diffChanges === undefined) {
|
|
376
395
|
unreadable.push({ eventId: c.eventId, rootIntentId: marker.root, node: c.entry.node, reason: 'invitee-missing' });
|
|
377
396
|
continue;
|
|
378
397
|
}
|
|
379
|
-
const
|
|
398
|
+
const changes = [...diffChanges, ...admissions];
|
|
399
|
+
// Set exactly when the diff's `changes` are non-empty; a cleanup-only commit takes the fork point of the same windows.
|
|
400
|
+
const forkEpoch = broken.forkEpoch ?? forkPointNode(before, afters)?.epoch;
|
|
401
|
+
if (forkEpoch === undefined) {
|
|
402
|
+
unreadable.push({ eventId: c.eventId, rootIntentId: marker.root, node: c.entry.node, reason: 'state-missing' });
|
|
403
|
+
continue;
|
|
404
|
+
}
|
|
380
405
|
found.push({
|
|
381
406
|
epoch: c.epoch,
|
|
382
407
|
at: c.at,
|
|
@@ -806,6 +831,10 @@ export async function recordTransition(rt, tx, plan, epoch) {
|
|
|
806
831
|
if (retired.length > 0)
|
|
807
832
|
retiredWelcomes.set(plan, retired);
|
|
808
833
|
await updateSettlementRecheck(tx.extension(SETTLEMENT_RECHECK_EXTENSION), plan);
|
|
834
|
+
// S4 (SC-4 I11, canonical-path rule): admission lineage advances here and only here — each checkpoint the persisted
|
|
835
|
+
// window would leave unprovable moves to the new window root, in the transaction that persists that window.
|
|
836
|
+
if (plan.lineage !== undefined)
|
|
837
|
+
await advanceLineageRecords(tx.extension(ADMISSION_LINEAGE_EXTENSION), { before: plan.lineage.before, diff: plan.lineage.diff, after: plan.window }, plan.lineage.tip);
|
|
809
838
|
if (rt.ctx.history === undefined)
|
|
810
839
|
return cancelled;
|
|
811
840
|
const ops = [
|
|
@@ -1005,6 +1034,14 @@ export async function deliverTransition(rt, plan, defer = new Set()) {
|
|
|
1005
1034
|
// The device port's `onRotation`: only an applied `leaf-key-rotated`, never the withdrawn variant (a recorded link is a fact about the device).
|
|
1006
1035
|
if (plan.notifications.some((n) => n.type === 'leaf-key-rotated'))
|
|
1007
1036
|
rt.announceRotation();
|
|
1037
|
+
// Epic marmot-invitation-outcomes S5 (SC-12): a transition may change a cleanup's disposition (confirmed, withdrawn, restored,
|
|
1038
|
+
// settled): every candidate a withdrawn cleanup names joins the session's reported ones, then each changed report is emitted
|
|
1039
|
+
// (detached, best effort, reads only).
|
|
1040
|
+
for (const w of plan.withdrawnOwnCommits ?? [])
|
|
1041
|
+
for (const c of w.changes)
|
|
1042
|
+
if (c.change.type === 'admission-removed')
|
|
1043
|
+
noteCleanupCandidate(rt, c.change.candidateId);
|
|
1044
|
+
emitCleanupDispositions(rt);
|
|
1008
1045
|
void scheduleHistoryDrain(rt);
|
|
1009
1046
|
}
|
|
1010
1047
|
/** Removes the outbox entries of the terminals `plan` just dispatched. Never throws. */
|
|
@@ -1215,6 +1252,35 @@ export function assertNotFenced(rt, operation) {
|
|
|
1215
1252
|
if (rt.fence !== undefined)
|
|
1216
1253
|
throw fencedError(rt.groupId, operation, rt.fence);
|
|
1217
1254
|
}
|
|
1255
|
+
/**
|
|
1256
|
+
* The session fence was just recorded on `rt`: every `synced()` wait for the group's first catch-up fails `fenced` now —
|
|
1257
|
+
* a fenced group never opens its send gate. In-memory only and independent of the durable intent cleanup
|
|
1258
|
+
* (`failAwaitingIntents`), so a fence whose store work failed or never runs still settles every waiter.
|
|
1259
|
+
*/
|
|
1260
|
+
export function rejectSyncWaitersFenced(rt) {
|
|
1261
|
+
const fence = rt.fence;
|
|
1262
|
+
if (fence === undefined)
|
|
1263
|
+
return;
|
|
1264
|
+
rejectSyncWaiters(rt, () => fencedError(rt.groupId, 'synced', fence));
|
|
1265
|
+
}
|
|
1266
|
+
/**
|
|
1267
|
+
* Every pending `synced()` wait for the group's first catch-up fails now, each with its own error from `errorOf`: the
|
|
1268
|
+
* condition that ends it (a fence, a lost lease) means the send gate never opens in this session.
|
|
1269
|
+
*/
|
|
1270
|
+
export function rejectSyncWaiters(rt, errorOf) {
|
|
1271
|
+
const waiters = [...rt.syncWaiters];
|
|
1272
|
+
rt.syncWaiters.clear();
|
|
1273
|
+
for (const waiter of waiters)
|
|
1274
|
+
waiter.reject(errorOf());
|
|
1275
|
+
}
|
|
1276
|
+
/** The cause of a client-wide lease end signalled by the account store (`AccountStore.onLeaseEnded`). */
|
|
1277
|
+
export function accountLeaseEndedError() {
|
|
1278
|
+
return new MarmotError('no-lease', 'the account store reported that its lease ended');
|
|
1279
|
+
}
|
|
1280
|
+
/** The `no-lease` refusal of a `synced()` wait: the stores lost their lease before the group's first catch-up. */
|
|
1281
|
+
export function syncedLeaseLostError(rt, cause) {
|
|
1282
|
+
return new MarmotError('no-lease', `synced: the stores lost their lease before group ${rt.groupId} completed its first sync`, { cause, details: { groupId: rt.groupId } });
|
|
1283
|
+
}
|
|
1218
1284
|
/**
|
|
1219
1285
|
* Fences the group for good: the marker is persisted first (a reload stays
|
|
1220
1286
|
* fenced), then every further operation is refused. Idempotent.
|
|
@@ -1222,7 +1288,8 @@ export function assertNotFenced(rt, operation) {
|
|
|
1222
1288
|
export async function fenceGroup(rt, cause) {
|
|
1223
1289
|
if (rt.fence !== undefined)
|
|
1224
1290
|
return;
|
|
1225
|
-
|
|
1291
|
+
// Epic marmot-invitation-outcomes S1: the marker records the fence's coarse cause (additive on v:1).
|
|
1292
|
+
const record = { at: rt.ctx.clock.now(), epoch: String(rt.exposedState.groupContext.epoch), message: cause.message, cause: fenceCauseOf(cause) };
|
|
1226
1293
|
// The held opaque record goes with the marker, in the same transaction: a fenced group keeps none (a reload must not
|
|
1227
1294
|
// resurrect them), and the marker never outlives a record that still names candidates that decide nothing any more.
|
|
1228
1295
|
const clearOpaqueRecord = !isEmptyOpaque(rt.opaque);
|
|
@@ -1237,14 +1304,17 @@ export async function fenceGroup(rt, cause) {
|
|
|
1237
1304
|
// The verdict outlives the failed write. The engine may already have released the held candidate it came from
|
|
1238
1305
|
// (it does once the verdict is yielded), so this session is fenced in memory and the next operation reloads the
|
|
1239
1306
|
// durable state first: no write of a candidate-free record can follow a lost fence write, and the durable record
|
|
1240
|
-
// still holds the candidate, which a reload re-decides.
|
|
1307
|
+
// still holds the candidate, which a reload re-decides. Assigning the fence still publishes it to the group's
|
|
1308
|
+
// availability observers and records it as this session's (the reload never reads clear: SC-10 A-7).
|
|
1241
1309
|
rt.fence = cause;
|
|
1242
1310
|
rt.needsReload = true;
|
|
1311
|
+
rejectSyncWaitersFenced(rt);
|
|
1243
1312
|
throw error;
|
|
1244
1313
|
}
|
|
1245
1314
|
if (clearOpaqueRecord)
|
|
1246
1315
|
rt.opaque = undefined;
|
|
1247
1316
|
rt.fence = cause;
|
|
1317
|
+
rejectSyncWaitersFenced(rt);
|
|
1248
1318
|
}
|
|
1249
1319
|
// ---------------------------------------------------------------------------
|
|
1250
1320
|
// Media (AC-MEDIA-1/2)
|
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
* accepts a `KeyValueView`, so it works identically against a store's own
|
|
8
8
|
* scope-level view or a transaction's `tx` view.
|
|
9
9
|
*/
|
|
10
|
-
import { type DeclaredChanges, type OrderingKey, type OwnChange, type OwnChangeLostReason } from '../history/index.js';
|
|
10
|
+
import { type DeclaredChanges, type LineageAnchor, type OrderingKey, type OwnChange, type OwnChangeLostReason } from '../history/index.js';
|
|
11
11
|
import type { ClientState } from '@941design/marmot-engine/mls';
|
|
12
12
|
import { type StoredWelcome } from '../invitations/index.js';
|
|
13
13
|
import { MarmotError } from '../shared/index.js';
|
|
@@ -166,6 +166,12 @@ export type StorableIntent = {
|
|
|
166
166
|
readonly id: number;
|
|
167
167
|
readonly data: Uint8Array | null;
|
|
168
168
|
}[];
|
|
169
|
+
/**
|
|
170
|
+
* Epic marmot-invitation-outcomes S5 (SC-5): `removeAdmission` (`MarmotGroup.removeAdmission`) — the commit Removes the ONE leaf
|
|
171
|
+
* position the target's admission occupies, inline, after the build re-checked on the actual parent that the proven original
|
|
172
|
+
* admission still occupies it (I15). Exclusive with every other member. Absent on every record written before this field existed.
|
|
173
|
+
*/
|
|
174
|
+
readonly removeAdmission?: AdmissionTarget;
|
|
169
175
|
}
|
|
170
176
|
/**
|
|
171
177
|
* `after` (S13): the intentId of the own commit of staged Adds this self-update must follow (a self-update over
|
|
@@ -189,6 +195,21 @@ export type StorableIntent = {
|
|
|
189
195
|
export interface RekeyTarget {
|
|
190
196
|
readonly target: string;
|
|
191
197
|
}
|
|
198
|
+
/**
|
|
199
|
+
* Epic marmot-invitation-outcomes S5 (SC-5): what one scoped cleanup removes — the admission of decline candidate
|
|
200
|
+
* `candidateId` (the Add `anchor` names: its commit, position and leaf key), accepted while the group's tip was
|
|
201
|
+
* `acceptedAtTag`; `account` is the credential account of the leaf at acceptance (the `admission-removed` change names it).
|
|
202
|
+
*/
|
|
203
|
+
export interface AdmissionTarget {
|
|
204
|
+
readonly candidateId: string;
|
|
205
|
+
readonly anchor: LineageAnchor;
|
|
206
|
+
readonly acceptedAtTag: string;
|
|
207
|
+
readonly account: string;
|
|
208
|
+
}
|
|
209
|
+
/** Strict decoder of an {@link AdmissionTarget}: exactly its members, each well-formed; `fail` builds the error. */
|
|
210
|
+
export declare function decodeAdmissionTarget(raw: unknown, at: string, fail: Fail): AdmissionTarget;
|
|
211
|
+
/** The `Storable` form of an {@link AdmissionTarget} (re-checked: a mis-shaped write is refused like a mis-shaped read). */
|
|
212
|
+
export declare function encodeAdmissionTarget(target: AdmissionTarget, fail: Fail): Storable;
|
|
192
213
|
/**
|
|
193
214
|
* The invitees of an invite commit (S5): each one's KeyPackage event (the Add
|
|
194
215
|
* is rebuilt from it if the record resumes before staging) and KeyPackageRef.
|
|
@@ -398,6 +419,17 @@ type OwnChangeVariant = {
|
|
|
398
419
|
readonly event: Storable;
|
|
399
420
|
readonly inviteeRef: string;
|
|
400
421
|
};
|
|
422
|
+
} | {
|
|
423
|
+
/**
|
|
424
|
+
* Epic marmot-invitation-outcomes S5 (SC-6 I16): a scoped cleanup's removal, declared from the intent (never from the diff). It
|
|
425
|
+
* carries the cleanup's whole target, so the re-drive record is self-sufficient (the original marker may be pruned); a re-drive
|
|
426
|
+
* re-checks the admission's lineage on the actual parent (`commit-redrive.ts`). No fork-point values: `fork` is empty.
|
|
427
|
+
*/
|
|
428
|
+
readonly change: Extract<OwnChange, {
|
|
429
|
+
readonly type: 'admission-removed';
|
|
430
|
+
}>;
|
|
431
|
+
readonly fork: Record<string, never>;
|
|
432
|
+
readonly target: AdmissionTarget;
|
|
401
433
|
};
|
|
402
434
|
export type Fail = (detail: string) => MarmotError;
|
|
403
435
|
export declare function decodeOwnChange(raw: unknown, at: string, fail: Fail): OwnChange;
|
|
@@ -442,9 +474,14 @@ export interface OwnCommitMarker {
|
|
|
442
474
|
readonly changes?: readonly MarkerChange[];
|
|
443
475
|
readonly forkEpoch?: number;
|
|
444
476
|
}
|
|
445
|
-
/**
|
|
477
|
+
/**
|
|
478
|
+
* The declared changes a marker stores: `removed` accounts, `admins` set, component ids (the Adds come from `invitees`); and (epic
|
|
479
|
+
* marmot-invitation-outcomes S5, SC-6 I16) `admissions`, the targets of a scoped cleanup — an `admission-removed` change each,
|
|
480
|
+
* declared from the intent and never matched against the diff (whose `member-removed` a cleanup never declares).
|
|
481
|
+
*/
|
|
446
482
|
export type OwnCommitDeclared = Pick<DeclaredChanges, 'removed' | 'components'> & {
|
|
447
483
|
readonly admins?: true;
|
|
484
|
+
readonly admissions?: readonly AdmissionTarget[];
|
|
448
485
|
};
|
|
449
486
|
export declare function decodeOwnCommitMarker(eventId: string, raw: unknown): OwnCommitMarker;
|
|
450
487
|
export declare function encodeOwnCommitMarker(marker: OwnCommitMarker, eventId?: string): Storable;
|