@941design/marmot 0.0.0-stage → 0.2.0-alpha.0
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 +709 -0
- package/LICENSE +21 -0
- package/README.md +33 -2
- package/dist/account/admin.d.ts +72 -0
- package/dist/account/admin.js +209 -0
- package/dist/account/device-deps.d.ts +379 -0
- package/dist/account/device-deps.js +36 -0
- package/dist/account/device-lineage.d.ts +199 -0
- package/dist/account/device-lineage.js +390 -0
- package/dist/account/device-registry.d.ts +93 -0
- package/dist/account/device-registry.js +1290 -0
- package/dist/account/device-rotation.d.ts +61 -0
- package/dist/account/device-rotation.js +827 -0
- package/dist/account/enrolment.d.ts +339 -0
- package/dist/account/enrolment.js +1247 -0
- package/dist/account/identity-proof.d.ts +79 -0
- package/dist/account/identity-proof.js +264 -0
- package/dist/account/index.d.ts +17 -0
- package/dist/account/index.js +16 -0
- package/dist/account/restore-rotation.d.ts +21 -0
- package/dist/account/restore-rotation.js +22 -0
- package/dist/account/same-account-authorization.d.ts +86 -0
- package/dist/account/same-account-authorization.js +180 -0
- package/dist/account/teardown.d.ts +127 -0
- package/dist/account/teardown.js +856 -0
- package/dist/client/before-create-group.d.ts +18 -0
- package/dist/client/before-create-group.js +65 -0
- package/dist/client/before-publish-hooks.d.ts +121 -0
- package/dist/client/before-publish-hooks.js +180 -0
- package/dist/client/client-config.d.ts +42 -0
- package/dist/client/client-config.js +13 -0
- package/dist/client/commit-redrive.d.ts +68 -0
- package/dist/client/commit-redrive.js +221 -0
- package/dist/client/component-update.d.ts +43 -0
- package/dist/client/component-update.js +53 -0
- package/dist/client/confirm-hooks.d.ts +50 -0
- package/dist/client/confirm-hooks.js +59 -0
- package/dist/client/create-client.d.ts +1022 -0
- package/dist/client/create-client.js +1125 -0
- package/dist/client/group-disband.d.ts +28 -0
- package/dist/client/group-disband.js +64 -0
- package/dist/client/group-history.d.ts +435 -0
- package/dist/client/group-history.js +1295 -0
- package/dist/client/group-profile.d.ts +31 -0
- package/dist/client/group-profile.js +62 -0
- package/dist/client/group-records.d.ts +485 -0
- package/dist/client/group-records.js +1034 -0
- package/dist/client/group-removal.d.ts +36 -0
- package/dist/client/group-removal.js +127 -0
- package/dist/client/group-remove-member.d.ts +49 -0
- package/dist/client/group-remove-member.js +163 -0
- package/dist/client/group-runtime.d.ts +388 -0
- package/dist/client/group-runtime.js +2701 -0
- package/dist/client/group-snapshot.d.ts +98 -0
- package/dist/client/group-snapshot.js +453 -0
- package/dist/client/history-pages.d.ts +107 -0
- package/dist/client/history-pages.js +194 -0
- package/dist/client/inbox-send.d.ts +19 -0
- package/dist/client/inbox-send.js +71 -0
- package/dist/client/index.d.ts +21 -0
- package/dist/client/index.js +13 -0
- package/dist/client/ingest.d.ts +82 -0
- package/dist/client/ingest.js +1550 -0
- package/dist/client/lifecycle-events.d.ts +63 -0
- package/dist/client/lifecycle-events.js +35 -0
- package/dist/client/opaque-candidates.d.ts +81 -0
- package/dist/client/opaque-candidates.js +169 -0
- package/dist/client/own-change-outbox.d.ts +66 -0
- package/dist/client/own-change-outbox.js +156 -0
- package/dist/client/pending-leaf.d.ts +116 -0
- package/dist/client/pending-leaf.js +378 -0
- package/dist/client/permissions.d.ts +9 -0
- package/dist/client/permissions.js +12 -0
- package/dist/client/pipeline.d.ts +554 -0
- package/dist/client/pipeline.js +3545 -0
- package/dist/client/reentrancy-guard.d.ts +96 -0
- package/dist/client/reentrancy-guard.js +153 -0
- package/dist/client/rekey.d.ts +58 -0
- package/dist/client/rekey.js +149 -0
- package/dist/client/transport-policy.d.ts +181 -0
- package/dist/client/transport-policy.js +214 -0
- package/dist/history/equivocation.d.ts +55 -0
- package/dist/history/equivocation.js +113 -0
- package/dist/history/fencing.d.ts +25 -0
- package/dist/history/fencing.js +61 -0
- package/dist/history/hex.d.ts +3 -0
- package/dist/history/hex.js +10 -0
- package/dist/history/index.d.ts +73 -0
- package/dist/history/index.js +31 -0
- package/dist/history/notifications.d.ts +270 -0
- package/dist/history/notifications.js +264 -0
- package/dist/history/ordering-key.d.ts +24 -0
- package/dist/history/ordering-key.js +101 -0
- package/dist/history/own-change-fork.d.ts +112 -0
- package/dist/history/own-change-fork.js +196 -0
- package/dist/history/own-change.d.ts +106 -0
- package/dist/history/own-change.js +146 -0
- package/dist/history/policy.d.ts +48 -0
- package/dist/history/policy.js +52 -0
- package/dist/history/retained-window.d.ts +215 -0
- package/dist/history/retained-window.js +565 -0
- package/dist/inbox/demux.d.ts +90 -0
- package/dist/inbox/demux.js +78 -0
- package/dist/inbox/handler-registry.d.ts +42 -0
- package/dist/inbox/handler-registry.js +37 -0
- package/dist/inbox/index.d.ts +11 -0
- package/dist/inbox/index.js +10 -0
- package/dist/inbox/seen-set.d.ts +82 -0
- package/dist/inbox/seen-set.js +202 -0
- package/dist/inbox/subscription.d.ts +236 -0
- package/dist/inbox/subscription.js +644 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.js +9 -0
- package/dist/invitations/competing-welcome.d.ts +223 -0
- package/dist/invitations/competing-welcome.js +128 -0
- package/dist/invitations/decline.d.ts +61 -0
- package/dist/invitations/decline.js +143 -0
- package/dist/invitations/expect-welcome.d.ts +66 -0
- package/dist/invitations/expect-welcome.js +138 -0
- package/dist/invitations/index.d.ts +16 -0
- package/dist/invitations/index.js +16 -0
- package/dist/invitations/invite.d.ts +303 -0
- package/dist/invitations/invite.js +966 -0
- package/dist/invitations/offers.d.ts +79 -0
- package/dist/invitations/offers.js +115 -0
- package/dist/invitations/on-proposal.d.ts +47 -0
- package/dist/invitations/on-proposal.js +40 -0
- package/dist/invitations/pending-proposal-policy.d.ts +52 -0
- package/dist/invitations/pending-proposal-policy.js +139 -0
- package/dist/invitations/proposal-deadline.d.ts +133 -0
- package/dist/invitations/proposal-deadline.js +164 -0
- package/dist/invitations/relay-planes.d.ts +43 -0
- package/dist/invitations/relay-planes.js +70 -0
- package/dist/invitations/welcome-processor.d.ts +253 -0
- package/dist/invitations/welcome-processor.js +1180 -0
- package/dist/key-packages/device-key.d.ts +131 -0
- package/dist/key-packages/device-key.js +272 -0
- package/dist/key-packages/device-rotation-records.d.ts +83 -0
- package/dist/key-packages/device-rotation-records.js +173 -0
- package/dist/key-packages/group-refs.d.ts +40 -0
- package/dist/key-packages/group-refs.js +79 -0
- package/dist/key-packages/index.d.ts +18 -0
- package/dist/key-packages/index.js +18 -0
- package/dist/key-packages/key-package-ref.d.ts +16 -0
- package/dist/key-packages/key-package-ref.js +21 -0
- package/dist/key-packages/observation-stream.d.ts +4 -0
- package/dist/key-packages/observation-stream.js +120 -0
- package/dist/key-packages/offer-rumor.d.ts +26 -0
- package/dist/key-packages/offer-rumor.js +69 -0
- package/dist/key-packages/publisher.d.ts +174 -0
- package/dist/key-packages/publisher.js +1247 -0
- package/dist/key-packages/select-key-package.d.ts +24 -0
- package/dist/key-packages/select-key-package.js +90 -0
- package/dist/key-packages/slot-manager.d.ts +167 -0
- package/dist/key-packages/slot-manager.js +327 -0
- package/dist/key-packages/validate-key-package-event.d.ts +3 -0
- package/dist/key-packages/validate-key-package-event.js +49 -0
- package/dist/media/cache.d.ts +14 -0
- package/dist/media/cache.js +10 -0
- package/dist/media/index.d.ts +52 -0
- package/dist/media/index.js +71 -0
- package/dist/mls.d.ts +15 -0
- package/dist/mls.js +15 -0
- package/dist/shared/account-pubkey.d.ts +4 -0
- package/dist/shared/account-pubkey.js +10 -0
- package/dist/shared/errors.d.ts +21 -0
- package/dist/shared/errors.js +85 -0
- package/dist/shared/hex.d.ts +4 -0
- package/dist/shared/hex.js +13 -0
- package/dist/shared/index.d.ts +14 -0
- package/dist/shared/index.js +14 -0
- package/dist/shared/kinds.d.ts +8 -0
- package/dist/shared/kinds.js +28 -0
- package/dist/shared/publish-classification.d.ts +26 -0
- package/dist/shared/publish-classification.js +31 -0
- package/dist/storage/envelope.d.ts +39 -0
- package/dist/storage/envelope.js +201 -0
- package/dist/storage/index.d.ts +227 -0
- package/dist/storage/index.js +459 -0
- package/dist/storage/indexeddb/idb-types.d.ts +68 -0
- package/dist/storage/indexeddb/idb-types.js +1 -0
- package/dist/storage/indexeddb/index.d.ts +17 -0
- package/dist/storage/indexeddb/index.js +141 -0
- package/dist/storage/lease.d.ts +41 -0
- package/dist/storage/lease.js +117 -0
- package/dist/storage/memory/deterministic-signer.d.ts +27 -0
- package/dist/storage/memory/deterministic-signer.js +65 -0
- package/dist/storage/memory/index.d.ts +32 -0
- package/dist/storage/memory/index.js +87 -0
- package/dist/storage/memory/lock-manager.d.ts +8 -0
- package/dist/storage/memory/lock-manager.js +71 -0
- package/package.json +66 -3
|
@@ -0,0 +1,644 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The per-account inbox (S6): the ONE kind-1059 subscription of a client
|
|
3
|
+
* (AC-INBOX-1), the persisted bounded seen-set (AC-INBOX-3/4, `seen-set.ts`)
|
|
4
|
+
* and the verifier gate in front of every decryption (AC-PIPE-12).
|
|
5
|
+
*
|
|
6
|
+
* An inbox PASS is: the maintenance hook (`beforePass`), a paginated
|
|
7
|
+
* backfill of the account's wraps since the stored floor (discarded whole
|
|
8
|
+
* when it timed out, AC-PIPE-7), then every wrap still `deferred`. `start()`
|
|
9
|
+
* runs one pass and then opens the live subscription; a subscription the
|
|
10
|
+
* transport ends is replaced after a backoff pass, never duplicated.
|
|
11
|
+
*
|
|
12
|
+
* Every wrap, from the backfill or the live subscription:
|
|
13
|
+
*
|
|
14
|
+
* 1. in-flight dedup by wrap id (the same wrap from two sources at once);
|
|
15
|
+
* 2. seen-set check — a seen wrap is never unwrapped again;
|
|
16
|
+
* 3. the consumer `verifier`, before any signer call: false (or a throw)
|
|
17
|
+
* → `rejected('verifier')`, id marked seen;
|
|
18
|
+
* 4. NIP-59 unwrap with the account signer, outside any transaction (a
|
|
19
|
+
* remote signer may wait on its user). A transient failure
|
|
20
|
+
* ({@link classifyUnwrapFailure}) → `deferred`: not marked seen, kept
|
|
21
|
+
* for the next pass; any other failure → `rejected(code)`, marked seen;
|
|
22
|
+
* 5. the rumor DISPATCH POINT, on the inbox's serial queue (seen-set
|
|
23
|
+
* re-checked first): `deps.dispatch` returns the disposition and may
|
|
24
|
+
* mark the wrap seen inside its own final transaction
|
|
25
|
+
* (`ctx.markSeen(tx)`), atomically with its own records; otherwise the
|
|
26
|
+
* wrap is marked seen here — unless the disposition is `deferred`.
|
|
27
|
+
*
|
|
28
|
+
* S6's dispatch handled Welcome rumors only; S7's demux (`demux.ts`: native
|
|
29
|
+
* kinds, registered handlers, application rumors) is the dispatch function
|
|
30
|
+
* now — the subscription and seen-set are still created once, here. A
|
|
31
|
+
* dispatcher's `deferred` may be `counted` (a consumer handler that threw):
|
|
32
|
+
* such deferrals count toward the processing-failure cap like a throwing
|
|
33
|
+
* dispatch.
|
|
34
|
+
*/
|
|
35
|
+
import { verifyEvent } from '@941design/nostr-events/event';
|
|
36
|
+
import { isMarmotError, MarmotError } from '../shared/index.js';
|
|
37
|
+
import { isSeen, listDeferred, markSeen, readDeferred, readBackfillContinuation, readInboxFloor, recordDeferred, writeBackfillContinuation, writeInboxFloor, } from './seen-set.js';
|
|
38
|
+
export const GIFT_WRAP_KIND = 1059;
|
|
39
|
+
/**
|
|
40
|
+
* How far below a pass's start the next backfill (and the live
|
|
41
|
+
* subscription) reaches: NIP-59 randomises a wrap's `created_at` up to two
|
|
42
|
+
* days into the past, so a wrap published after a pass began can carry an
|
|
43
|
+
* older stamp.
|
|
44
|
+
*/
|
|
45
|
+
export const INBOX_BACKFILL_OVERLAP_S = 3 * 24 * 60 * 60;
|
|
46
|
+
/**
|
|
47
|
+
* How long the "live covers it" shortcut may stand in for a newer-window walk (seconds). Within one live
|
|
48
|
+
* session a resumed continuation skips re-walking `[startedAt - overlap, now]`: the live subscription saw
|
|
49
|
+
* everything published meanwhile — unless the transport dropped and silently re-established its socket
|
|
50
|
+
* (an `autoReconnect` adapter re-issues the `limit: 0` filter without telling the observer), in which case
|
|
51
|
+
* wraps published during the outage reached neither path. The shortcut is therefore trusted for at most
|
|
52
|
+
* this long since the newer window was last walked; past it the newer window is walked again, so an
|
|
53
|
+
* outage hidden by a silent reconnect delays a wrap by at most this much (plus the retry backoff), never
|
|
54
|
+
* until the next restart. Must stay well below one day: the newer window's `startedAt - overlap` reach
|
|
55
|
+
* covers every wrap published after `now - (overlap - NIP-59's two days)`.
|
|
56
|
+
*/
|
|
57
|
+
export const INBOX_LIVE_COVERS_MAX_AGE_S = 10 * 60;
|
|
58
|
+
/** The backfill floor stays this far below the oldest deferred wrap's `created_at`. */
|
|
59
|
+
export const INBOX_DEFERRED_MARGIN_S = 60;
|
|
60
|
+
/**
|
|
61
|
+
* Default cap on a wrap's non-transient deferrals (a dispatch that keeps
|
|
62
|
+
* throwing, a malformed record): past it the wrap is `rejected('processing-
|
|
63
|
+
* failed')` and marked seen, so a poison wrap costs a bounded number of
|
|
64
|
+
* signer unwraps. Transient failures (AC-WEL-3) never count toward it.
|
|
65
|
+
*/
|
|
66
|
+
export const DEFAULT_MAX_PROCESSING_FAILURES = 10;
|
|
67
|
+
/**
|
|
68
|
+
* The `deferred` reason of a consumer handler that threw (demux.ts). Its counted deferral keeps the unwrapped rumor
|
|
69
|
+
* with the wrap (seen-set.ts `DeferredWrap.rumor`), so the retry does not unwrap again (handler-retry-reunwraps-wrap).
|
|
70
|
+
*/
|
|
71
|
+
export const HANDLER_FAILED_REASON = 'handler-failed';
|
|
72
|
+
// ---------------------------------------------------------------------------
|
|
73
|
+
// Failure classification (AC-WEL-3)
|
|
74
|
+
// ---------------------------------------------------------------------------
|
|
75
|
+
// key-unavailable: a locked bunker or extension — it comes back.
|
|
76
|
+
const TRANSIENT_SIGNER_CODES = new Set(['timeout', 'cancelled', 'transport', 'auth-required', 'disposed', 'key-unavailable']);
|
|
77
|
+
const TRANSIENT_MARMOT_CODES = new Set(['lease-held', 'no-lease', 'store-failed', 'transaction-closed', 'reentrant', 'disposed']);
|
|
78
|
+
/**
|
|
79
|
+
* A `store-failed` raised by a record codec (a stored value that does not
|
|
80
|
+
* decode or validate) is a fact about the data, not about the store's
|
|
81
|
+
* availability: retrying cannot fix it. Codecs say so structurally with
|
|
82
|
+
* `details.malformed: true` (test/inbox/malformed-flag.test.ts pins every
|
|
83
|
+
* codec); the message wording is never consulted.
|
|
84
|
+
*/
|
|
85
|
+
function isMalformedRecord(error) {
|
|
86
|
+
return error.code === 'store-failed' && error.details?.malformed === true;
|
|
87
|
+
}
|
|
88
|
+
function libError(value, subsystem) {
|
|
89
|
+
if (typeof value !== 'object' || value === null)
|
|
90
|
+
return undefined;
|
|
91
|
+
const { subsystem: s, code } = value;
|
|
92
|
+
return s === subsystem && typeof code === 'string' ? { subsystem: s, code } : undefined;
|
|
93
|
+
}
|
|
94
|
+
function causes(error) {
|
|
95
|
+
const chain = [];
|
|
96
|
+
for (let e = error, depth = 0; e !== undefined && e !== null && depth < 8; depth++) {
|
|
97
|
+
chain.push(e);
|
|
98
|
+
e = e.cause;
|
|
99
|
+
}
|
|
100
|
+
return chain;
|
|
101
|
+
}
|
|
102
|
+
/** Store failures a retry can fix (not `store-failed`: a backend that keeps failing is counted). */
|
|
103
|
+
const TRANSIENT_STORE_CODES = new Set(['lease-held', 'no-lease', 'transaction-closed', 'reentrant', 'disposed']);
|
|
104
|
+
/**
|
|
105
|
+
* Why a maintenance attempt (a rotation, a decline delivery, completing an
|
|
106
|
+
* interrupted join) failed, when the failure COUNTS toward the retry cap —
|
|
107
|
+
* or `undefined` for an explicitly transient one: a `SignerError` timeout /
|
|
108
|
+
* cancelled / transport / auth-required / disposed / key-unavailable (a
|
|
109
|
+
* locked bunker comes back) anywhere in the cause chain; a store lease-held /
|
|
110
|
+
* no-lease / transaction-closed / reentrant / disposed; S4's publish-failed
|
|
111
|
+
* or a busy slot (`pending-intent`); a Welcome join deferred by a restore in
|
|
112
|
+
* flight (`commit-pending`, `restore-in-flight`). Everything else counts — a refusal, a
|
|
113
|
+
* malformed record, and any error nobody classified — so a failure retrying
|
|
114
|
+
* cannot fix never prompts a signer forever.
|
|
115
|
+
*/
|
|
116
|
+
export function maintenanceFailureReason(error) {
|
|
117
|
+
const chain = causes(error);
|
|
118
|
+
for (const e of chain) {
|
|
119
|
+
const signer = libError(e, 'signer');
|
|
120
|
+
if (signer !== undefined && TRANSIENT_SIGNER_CODES.has(signer.code))
|
|
121
|
+
return undefined;
|
|
122
|
+
if (isMarmotError(e) && (TRANSIENT_STORE_CODES.has(e.code) || e.code === 'publish-failed'))
|
|
123
|
+
return undefined;
|
|
124
|
+
if (isMarmotError(e, 'invalid-options') && e.details?.reason === 'pending-intent')
|
|
125
|
+
return undefined;
|
|
126
|
+
// AC-MX-2: a Welcome join deferred while its group is being restored — completed once the restore settled.
|
|
127
|
+
if (isMarmotError(e, 'commit-pending') && e.details?.reason === 'restore-in-flight')
|
|
128
|
+
return undefined;
|
|
129
|
+
}
|
|
130
|
+
for (const e of chain) {
|
|
131
|
+
const signer = libError(e, 'signer');
|
|
132
|
+
if (signer !== undefined)
|
|
133
|
+
return `signer-${signer.code}`;
|
|
134
|
+
if (isMarmotError(e))
|
|
135
|
+
return isMalformedRecord(e) ? 'malformed-record' : e.code;
|
|
136
|
+
}
|
|
137
|
+
return 'unknown-error';
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* AC-WEL-3: `deferred` for a transient failure — a `SignerError` timeout
|
|
141
|
+
* (the budget's timeout/lease), cancelled (aborted), transport,
|
|
142
|
+
* auth-required or disposed anywhere in the cause chain (the gift-wrap layer
|
|
143
|
+
* wraps the signer's error), or a store `lease-held` / `no-lease` /
|
|
144
|
+
* `store-failed` / `transaction-closed` / `reentrant`; `rejected(code)` for
|
|
145
|
+
* everything else — a bad MAC (`GiftWrapError('decrypt')` over the signer's
|
|
146
|
+
* `crypto` error), a malformed wrap or seal, an invalid seal signature, a
|
|
147
|
+
* pubkey or id mismatch.
|
|
148
|
+
*/
|
|
149
|
+
export function classifyUnwrapFailure(error) {
|
|
150
|
+
const chain = causes(error);
|
|
151
|
+
for (const e of chain) {
|
|
152
|
+
const signer = libError(e, 'signer');
|
|
153
|
+
if (signer !== undefined && TRANSIENT_SIGNER_CODES.has(signer.code))
|
|
154
|
+
return { kind: 'deferred', reason: `signer-${signer.code}` };
|
|
155
|
+
if (isMarmotError(e) && isMalformedRecord(e))
|
|
156
|
+
return { kind: 'rejected', reason: 'malformed-record' };
|
|
157
|
+
if (isMarmotError(e) && TRANSIENT_MARMOT_CODES.has(e.code))
|
|
158
|
+
return { kind: 'deferred', reason: e.code };
|
|
159
|
+
}
|
|
160
|
+
const giftWrap = chain.map((e) => libError(e, 'gift-wrap')).find((e) => e !== undefined);
|
|
161
|
+
if (giftWrap !== undefined)
|
|
162
|
+
return { kind: 'rejected', reason: giftWrap.code };
|
|
163
|
+
const signer = chain.map((e) => libError(e, 'signer')).find((e) => e !== undefined);
|
|
164
|
+
return { kind: 'rejected', reason: signer === undefined ? 'unwrap-failed' : `signer-${signer.code}` };
|
|
165
|
+
}
|
|
166
|
+
// ---------------------------------------------------------------------------
|
|
167
|
+
// The subscription
|
|
168
|
+
// ---------------------------------------------------------------------------
|
|
169
|
+
class SerialQueue {
|
|
170
|
+
#tail = Promise.resolve();
|
|
171
|
+
run(task) {
|
|
172
|
+
const result = this.#tail.then(task, task);
|
|
173
|
+
this.#tail = result.catch(() => undefined);
|
|
174
|
+
return result;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
function sameRelays(a, b) {
|
|
178
|
+
return a.length === b.length && a.every((r) => b.includes(r));
|
|
179
|
+
}
|
|
180
|
+
function backoffMs(attempt) {
|
|
181
|
+
return Math.min(1000 * 2 ** Math.max(0, attempt - 1), 60_000);
|
|
182
|
+
}
|
|
183
|
+
export function createInboxSubscription(deps) {
|
|
184
|
+
const queue = new SerialQueue();
|
|
185
|
+
const inFlight = new Set();
|
|
186
|
+
const maxFailures = deps.maxProcessingFailures ?? DEFAULT_MAX_PROCESSING_FAILURES;
|
|
187
|
+
/** Incremented by every live subscription this client opens: one gapless live session each. */
|
|
188
|
+
let liveEpoch = 0;
|
|
189
|
+
/**
|
|
190
|
+
* The live session that was open when the stored continuation was saved (in memory only: after a reload
|
|
191
|
+
* nothing is known to be covered). While that same session is still open, everything published since the
|
|
192
|
+
* continuation's walk began reached this client live, so no newer-window walk is needed.
|
|
193
|
+
*/
|
|
194
|
+
let continuationLiveEpoch;
|
|
195
|
+
/**
|
|
196
|
+
* The start (seconds) of the pass whose walk last covered the newer window — the oldest moment the live
|
|
197
|
+
* shortcut vouches for. Kept across passes that take the shortcut; capped by {@link INBOX_LIVE_COVERS_MAX_AGE_S}.
|
|
198
|
+
*/
|
|
199
|
+
let liveCoversSinceS;
|
|
200
|
+
/** Wraps deferred whose deferral could not be stored: retried from memory, and holding every cursor below them. */
|
|
201
|
+
const unpersisted = new Map();
|
|
202
|
+
let disposed = false;
|
|
203
|
+
let running = false;
|
|
204
|
+
let starting;
|
|
205
|
+
let live;
|
|
206
|
+
let retryTimer;
|
|
207
|
+
let retryAttempts = 0;
|
|
208
|
+
/** Account and relays of the last pass (the live subscription uses the same). */
|
|
209
|
+
let routing;
|
|
210
|
+
const stopped = () => disposed || !running || deps.isDisposed();
|
|
211
|
+
function emit(disposition) {
|
|
212
|
+
try {
|
|
213
|
+
deps.onDisposition(disposition);
|
|
214
|
+
}
|
|
215
|
+
catch {
|
|
216
|
+
// A throwing listener never breaks the inbox.
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
async function markSeenNow(wrapId) {
|
|
220
|
+
await deps.transaction((tx) => markSeen(tx.artifact('inboxSeenSet'), wrapId, deps.seenSetCap));
|
|
221
|
+
}
|
|
222
|
+
/**
|
|
223
|
+
* Persists the deferral (the wrap itself, so every later pass — also after a
|
|
224
|
+
* reload — retries it, and the backfill floor stays below it). `counted`:
|
|
225
|
+
* a non-transient failure; the one that reaches the cap turns the wrap
|
|
226
|
+
* `rejected('processing-failed')` and marks it seen instead.
|
|
227
|
+
*/
|
|
228
|
+
async function defer(wrap, reason, counted = false, rumor) {
|
|
229
|
+
const entry = await deps.transaction((tx) => recordDeferred(tx.artifact('inboxSeenSet'), wrap, counted, rumor));
|
|
230
|
+
if (counted && entry.failures >= maxFailures) {
|
|
231
|
+
await markSeenNow(wrap.id);
|
|
232
|
+
return { kind: 'rejected', reason: 'processing-failed', wrapId: wrap.id };
|
|
233
|
+
}
|
|
234
|
+
scheduleRetry();
|
|
235
|
+
return { kind: 'deferred', reason, wrapId: wrap.id };
|
|
236
|
+
}
|
|
237
|
+
/**
|
|
238
|
+
* One wrap, end to end. Never throws; returns what it emitted (`undefined` when skipped). `arrivedFrom`: the
|
|
239
|
+
* relays that delivered it, when the delivery says (see {@link DispatchContext.relays}).
|
|
240
|
+
*/
|
|
241
|
+
async function handle(wrap, arrivedFrom) {
|
|
242
|
+
if (disposed || deps.isDisposed())
|
|
243
|
+
return undefined;
|
|
244
|
+
if (typeof wrap !== 'object' || wrap === null || wrap.kind !== GIFT_WRAP_KIND || typeof wrap.id !== 'string')
|
|
245
|
+
return undefined;
|
|
246
|
+
if (inFlight.has(wrap.id))
|
|
247
|
+
return undefined;
|
|
248
|
+
inFlight.add(wrap.id);
|
|
249
|
+
try {
|
|
250
|
+
// Re-added by process() if this attempt, too, ends deferred without a durable record.
|
|
251
|
+
unpersisted.delete(wrap.id);
|
|
252
|
+
const disposition = await process(wrap, arrivedFrom !== undefined && arrivedFrom.length > 0 ? arrivedFrom : undefined);
|
|
253
|
+
if (disposition !== undefined)
|
|
254
|
+
emit(disposition);
|
|
255
|
+
return disposition;
|
|
256
|
+
}
|
|
257
|
+
finally {
|
|
258
|
+
inFlight.delete(wrap.id);
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
async function process(wrap, arrivedFrom) {
|
|
262
|
+
const wrapId = wrap.id;
|
|
263
|
+
// The outer wrap's id and signature first: a forged event reusing a genuine wrap's id must never reach
|
|
264
|
+
// the seen-set (it would poison it for the genuine one). Dropped, not marked seen — nothing durable.
|
|
265
|
+
let genuine;
|
|
266
|
+
try {
|
|
267
|
+
genuine = verifyEvent(wrap);
|
|
268
|
+
}
|
|
269
|
+
catch {
|
|
270
|
+
genuine = false;
|
|
271
|
+
}
|
|
272
|
+
if (!genuine)
|
|
273
|
+
return { kind: 'rejected', reason: 'invalid-signature', wrapId };
|
|
274
|
+
try {
|
|
275
|
+
const [seen, deferred] = await deps.transaction(async (tx) => {
|
|
276
|
+
const view = tx.artifact('inboxSeenSet');
|
|
277
|
+
if (await isSeen(view, wrapId))
|
|
278
|
+
return [true, undefined];
|
|
279
|
+
// A deferral record that does not decode only loses its stored rumor here: the wrap unwraps as before.
|
|
280
|
+
return [false, await readDeferred(view, wrapId).catch(() => undefined)];
|
|
281
|
+
});
|
|
282
|
+
if (seen)
|
|
283
|
+
return undefined;
|
|
284
|
+
// AC-PIPE-12: before any decryption.
|
|
285
|
+
if (deps.verifier !== undefined) {
|
|
286
|
+
let trusted;
|
|
287
|
+
try {
|
|
288
|
+
trusted = (await deps.verifier(wrap)) === true;
|
|
289
|
+
}
|
|
290
|
+
catch {
|
|
291
|
+
trusted = false;
|
|
292
|
+
}
|
|
293
|
+
if (!trusted) {
|
|
294
|
+
await markSeenNow(wrapId);
|
|
295
|
+
return { kind: 'rejected', reason: 'verifier', wrapId };
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
// A counted handler-failed deferral kept the rumor (keyed by this wrap's id): redispatched without a second
|
|
299
|
+
// signer unwrap. Anything else — none stored, or one that did not decode — unwraps.
|
|
300
|
+
let rumor;
|
|
301
|
+
try {
|
|
302
|
+
rumor = deferred?.rumor !== undefined && deferred.wrap.id === wrapId ? deferred.rumor : await deps.unwrap(wrap);
|
|
303
|
+
}
|
|
304
|
+
catch (error) {
|
|
305
|
+
const failure = classifyUnwrapFailure(error);
|
|
306
|
+
if (failure.kind === 'deferred')
|
|
307
|
+
return await defer(wrap, failure.reason);
|
|
308
|
+
await markSeenNow(wrapId);
|
|
309
|
+
return { kind: 'rejected', reason: failure.reason, wrapId };
|
|
310
|
+
}
|
|
311
|
+
return await queue.run(async () => {
|
|
312
|
+
if (disposed || deps.isDisposed())
|
|
313
|
+
throw new MarmotError('disposed', 'inbox: client has been disposed');
|
|
314
|
+
// Another delivery of this wrap may have finished while this one was unwrapping.
|
|
315
|
+
if (await deps.transaction((tx) => isSeen(tx.artifact('inboxSeenSet'), wrapId)))
|
|
316
|
+
return undefined;
|
|
317
|
+
let marked = false;
|
|
318
|
+
const ctx = {
|
|
319
|
+
relays: Object.freeze([...(arrivedFrom ?? routing?.relays ?? [])]),
|
|
320
|
+
async markSeen(tx) {
|
|
321
|
+
await markSeen(tx.artifact('inboxSeenSet'), wrapId, deps.seenSetCap);
|
|
322
|
+
marked = true;
|
|
323
|
+
},
|
|
324
|
+
};
|
|
325
|
+
const outcome = await deps.dispatch(rumor, wrap, ctx);
|
|
326
|
+
if (outcome.kind === 'deferred') {
|
|
327
|
+
const counted = outcome.counted === true;
|
|
328
|
+
return defer(wrap, outcome.reason, counted, counted && outcome.reason === HANDLER_FAILED_REASON ? rumor : undefined);
|
|
329
|
+
}
|
|
330
|
+
if (!marked)
|
|
331
|
+
await markSeenNow(wrapId);
|
|
332
|
+
return { ...outcome, wrapId };
|
|
333
|
+
}).catch(async (error) => {
|
|
334
|
+
if (disposed || deps.isDisposed() || isMarmotError(error, 'disposed'))
|
|
335
|
+
throw error;
|
|
336
|
+
// A dispatch that threw: transient → deferred; anything else (a bug, a malformed record) counts toward the cap.
|
|
337
|
+
const failure = classifyUnwrapFailure(error);
|
|
338
|
+
return failure.kind === 'deferred' ? defer(wrap, failure.reason) : defer(wrap, 'processing-failed', true);
|
|
339
|
+
});
|
|
340
|
+
}
|
|
341
|
+
catch (error) {
|
|
342
|
+
if (disposed || deps.isDisposed() || isMarmotError(error, 'disposed'))
|
|
343
|
+
return undefined;
|
|
344
|
+
// A store failure outside the dispatch (seen check, deferral record): nothing is marked seen, a later pass retries.
|
|
345
|
+
const failure = classifyUnwrapFailure(error);
|
|
346
|
+
try {
|
|
347
|
+
return await defer(wrap, failure.kind === 'deferred' ? failure.reason : 'processing-failed', failure.kind !== 'deferred');
|
|
348
|
+
}
|
|
349
|
+
catch {
|
|
350
|
+
// Not even the deferral could be stored: nothing durable remembers this wrap.
|
|
351
|
+
unpersisted.set(wrapId, wrap);
|
|
352
|
+
scheduleRetry();
|
|
353
|
+
return { kind: 'deferred', reason: failure.reason, wrapId };
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
function scheduleRetry() {
|
|
358
|
+
if (stopped() || retryTimer !== undefined)
|
|
359
|
+
return;
|
|
360
|
+
retryAttempts += 1;
|
|
361
|
+
retryTimer = deps.timers.set(() => {
|
|
362
|
+
retryTimer = undefined;
|
|
363
|
+
if (stopped())
|
|
364
|
+
return;
|
|
365
|
+
void runPass()
|
|
366
|
+
.then(() => {
|
|
367
|
+
if (!stopped() && live === undefined)
|
|
368
|
+
openLive();
|
|
369
|
+
})
|
|
370
|
+
.catch(() => scheduleRetry());
|
|
371
|
+
}, backoffMs(retryAttempts));
|
|
372
|
+
}
|
|
373
|
+
/**
|
|
374
|
+
* One paginated backfill walk, every wrap handled oldest first. `failed`:
|
|
375
|
+
* timed out (the batch is discarded, AC-PIPE-7), or some wrap it handled was
|
|
376
|
+
* deferred with no durable record — then nothing may be persisted past it.
|
|
377
|
+
*/
|
|
378
|
+
async function walk(relays, filter, account) {
|
|
379
|
+
const result = await deps.backfill(relays, filter);
|
|
380
|
+
if (result.timedOut)
|
|
381
|
+
return { kind: 'failed' };
|
|
382
|
+
// A relay may send anything on a subscription id, so the filter is re-applied.
|
|
383
|
+
const wraps = [...result.events]
|
|
384
|
+
.filter((e) => e.kind === GIFT_WRAP_KIND && e.tags.some((t) => t[0] === 'p' && t[1] === account))
|
|
385
|
+
.sort((a, b) => a.created_at - b.created_at || (a.id < b.id ? -1 : 1));
|
|
386
|
+
let lost = false;
|
|
387
|
+
for (const wrap of wraps) {
|
|
388
|
+
if (disposed || deps.isDisposed())
|
|
389
|
+
return { kind: 'failed' };
|
|
390
|
+
const liveInFlight = inFlight.has(wrap.id);
|
|
391
|
+
const handled = await handle(wrap, result.eventRelays?.get(wrap.id));
|
|
392
|
+
// Deferred with no durable record, or in flight on the live path (neither seen nor durably deferred
|
|
393
|
+
// yet): nothing may be persisted past it.
|
|
394
|
+
if (unpersisted.has(wrap.id) || (handled === undefined && liveInFlight))
|
|
395
|
+
lost = true;
|
|
396
|
+
}
|
|
397
|
+
if (lost)
|
|
398
|
+
return { kind: 'failed' };
|
|
399
|
+
return result.complete ? { kind: 'complete' } : { kind: 'incomplete', resumeUntil: result.resumeUntil };
|
|
400
|
+
}
|
|
401
|
+
/**
|
|
402
|
+
* Passes are single-flight: a pass requested while one runs (the retry timer, start()) is not started
|
|
403
|
+
* alongside it — two concurrent walks would count a wrap the other is still unwrapping (in flight) as
|
|
404
|
+
* handled and raise the floor past it — but recorded, and run once the current one finished.
|
|
405
|
+
*/
|
|
406
|
+
let passRunning;
|
|
407
|
+
let passRequested = false;
|
|
408
|
+
function runPass() {
|
|
409
|
+
if (passRunning !== undefined) {
|
|
410
|
+
passRequested = true;
|
|
411
|
+
return passRunning;
|
|
412
|
+
}
|
|
413
|
+
const run = (async () => {
|
|
414
|
+
try {
|
|
415
|
+
do {
|
|
416
|
+
passRequested = false;
|
|
417
|
+
await pass();
|
|
418
|
+
} while (passRequested && !stopped());
|
|
419
|
+
}
|
|
420
|
+
finally {
|
|
421
|
+
passRunning = undefined;
|
|
422
|
+
}
|
|
423
|
+
})();
|
|
424
|
+
passRunning = run;
|
|
425
|
+
return run;
|
|
426
|
+
}
|
|
427
|
+
async function pass() {
|
|
428
|
+
let outstanding = false;
|
|
429
|
+
try {
|
|
430
|
+
outstanding = await deps.beforePass();
|
|
431
|
+
}
|
|
432
|
+
catch {
|
|
433
|
+
outstanding = true; // maintenance is retried by the next pass; it never blocks the inbox
|
|
434
|
+
}
|
|
435
|
+
if (disposed || deps.isDisposed())
|
|
436
|
+
return;
|
|
437
|
+
// Only wraps deferred BEFORE this pass are retried by it (one deferred by its own backfill waits for the next).
|
|
438
|
+
const retries = [...(await deps.transaction((tx) => listDeferred(tx.artifact('inboxSeenSet')))).map((d) => d.wrap), ...unpersisted.values()];
|
|
439
|
+
const account = await deps.account();
|
|
440
|
+
const { relays, transient } = await deps.relays();
|
|
441
|
+
const passStartS = Math.floor(deps.clock.now() / 1000);
|
|
442
|
+
// The live subscription is (re)opened BEFORE the backfill — at start, after it ended, or on new inbox
|
|
443
|
+
// relays — so nothing published while the backfill reads history falls between the two (`limit: 0`
|
|
444
|
+
// replays nothing); the seen and in-flight sets absorb the overlap. Closed first: never two at a time.
|
|
445
|
+
const moved = live !== undefined && routing !== undefined && !sameRelays(routing.relays, relays);
|
|
446
|
+
if (moved)
|
|
447
|
+
closeLive();
|
|
448
|
+
routing = { account, relays, since: passStartS - INBOX_BACKFILL_OVERLAP_S };
|
|
449
|
+
if (live === undefined)
|
|
450
|
+
openLive();
|
|
451
|
+
const [floor, stored] = await deps.transaction(async (tx) => [await readInboxFloor(tx.artifact('inboxSeenSet')), await readBackfillContinuation(tx.artifact('inboxSeenSet'))]);
|
|
452
|
+
// A walk the page bound cut off continues below where it stopped — on the SAME relays only: other relays
|
|
453
|
+
// were never walked above `until`, so their walk starts over.
|
|
454
|
+
const sortedRelays = [...relays].sort();
|
|
455
|
+
const resume = stored !== undefined && sameRelays(stored.relays, sortedRelays) ? stored : undefined;
|
|
456
|
+
if (stored !== undefined && resume === undefined)
|
|
457
|
+
await deps.transaction((tx) => writeBackfillContinuation(tx.artifact('inboxSeenSet'), undefined));
|
|
458
|
+
const base = { kinds: [GIFT_WRAP_KIND], '#p': [account] };
|
|
459
|
+
let liveCovers = false;
|
|
460
|
+
const saveContinuation = async (until) => {
|
|
461
|
+
// Never from a transient pass: its relays are a stand-in, the real ones are walked from the top.
|
|
462
|
+
if (until === undefined || transient)
|
|
463
|
+
return;
|
|
464
|
+
await deps.transaction((tx) => writeBackfillContinuation(tx.artifact('inboxSeenSet'), { until, startedAt: passStartS, relays: sortedRelays }));
|
|
465
|
+
continuationLiveEpoch = live === undefined ? undefined : liveEpoch;
|
|
466
|
+
// A pass that took the shortcut walked no newer window: what it vouches for still starts where the last one did.
|
|
467
|
+
if (!liveCovers)
|
|
468
|
+
liveCoversSinceS = passStartS;
|
|
469
|
+
};
|
|
470
|
+
let complete = !transient;
|
|
471
|
+
if (relays.length > 0) {
|
|
472
|
+
// Resuming a walk whose start the live subscription does not cover without a gap (after a restart, a
|
|
473
|
+
// reopen, a relay change): what was published meanwhile — back-dated by NIP-59, so anywhere in
|
|
474
|
+
// `[startedAt - overlap, now]`, and not replayable by `limit: 0` live — is walked FIRST, from now down;
|
|
475
|
+
// only once that newer window is complete does the walk continue below `until`. A newer window the page
|
|
476
|
+
// bound cuts off becomes the continuation itself (its `until` lies above the old one: the part in
|
|
477
|
+
// between is re-walked, never skipped). Within one live session no newer window is needed.
|
|
478
|
+
// Capped by age (INBOX_LIVE_COVERS_MAX_AGE_S): a transport may reconnect silently inside one live session.
|
|
479
|
+
liveCovers =
|
|
480
|
+
resume !== undefined &&
|
|
481
|
+
live !== undefined &&
|
|
482
|
+
continuationLiveEpoch === liveEpoch &&
|
|
483
|
+
liveCoversSinceS !== undefined &&
|
|
484
|
+
passStartS - liveCoversSinceS <= INBOX_LIVE_COVERS_MAX_AGE_S;
|
|
485
|
+
const top = resume === undefined || liveCovers ? undefined : await walk(relays, { ...base, since: floor === undefined ? resume.startedAt - INBOX_BACKFILL_OVERLAP_S : Math.max(floor, resume.startedAt - INBOX_BACKFILL_OVERLAP_S) }, account);
|
|
486
|
+
if (disposed || deps.isDisposed())
|
|
487
|
+
return;
|
|
488
|
+
if (top !== undefined && top.kind !== 'complete') {
|
|
489
|
+
complete = false;
|
|
490
|
+
if (top.kind === 'incomplete')
|
|
491
|
+
await saveContinuation(top.resumeUntil);
|
|
492
|
+
}
|
|
493
|
+
else {
|
|
494
|
+
const result = await walk(relays, { ...base, ...(floor === undefined ? {} : { since: floor }), ...(resume === undefined ? {} : { until: resume.until }) }, account);
|
|
495
|
+
if (disposed || deps.isDisposed())
|
|
496
|
+
return;
|
|
497
|
+
if (result.kind === 'complete') {
|
|
498
|
+
if (resume !== undefined)
|
|
499
|
+
await deps.transaction((tx) => writeBackfillContinuation(tx.artifact('inboxSeenSet'), undefined));
|
|
500
|
+
}
|
|
501
|
+
else {
|
|
502
|
+
complete = false;
|
|
503
|
+
if (result.kind === 'incomplete')
|
|
504
|
+
await saveContinuation(result.resumeUntil);
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
for (const wrap of retries) {
|
|
509
|
+
if (disposed || deps.isDisposed())
|
|
510
|
+
return;
|
|
511
|
+
await handle(wrap);
|
|
512
|
+
}
|
|
513
|
+
try {
|
|
514
|
+
if (await deps.afterBackfill())
|
|
515
|
+
outstanding = true;
|
|
516
|
+
}
|
|
517
|
+
catch {
|
|
518
|
+
outstanding = true;
|
|
519
|
+
}
|
|
520
|
+
if (disposed || deps.isDisposed())
|
|
521
|
+
return;
|
|
522
|
+
const stillDeferred = await deps.transaction((tx) => listDeferred(tx.artifact('inboxSeenSet')));
|
|
523
|
+
// A wrap deferred without a durable record (its deferral could not be stored either) holds everything:
|
|
524
|
+
// neither the floor nor a continuation may pass it until a pass handles it durably.
|
|
525
|
+
if (unpersisted.size > 0)
|
|
526
|
+
complete = false;
|
|
527
|
+
if (complete) {
|
|
528
|
+
// The walk reached the floor (and, when resumed, covered everything above its start): the floor rises to
|
|
529
|
+
// this pass's start minus NIP-59's back-dating — never above a deferred wrap: after a reload its backfill
|
|
530
|
+
// must still reach it (AC-WEL-3).
|
|
531
|
+
const oldestDeferred = Math.min(...stillDeferred.map((d) => d.wrap.created_at - INBOX_DEFERRED_MARGIN_S));
|
|
532
|
+
await deps.transaction((tx) => writeInboxFloor(tx.artifact('inboxSeenSet'), Math.min(passStartS - INBOX_BACKFILL_OVERLAP_S, oldestDeferred)));
|
|
533
|
+
}
|
|
534
|
+
if (!complete || stillDeferred.length > 0 || outstanding)
|
|
535
|
+
scheduleRetry();
|
|
536
|
+
else
|
|
537
|
+
retryAttempts = 0;
|
|
538
|
+
}
|
|
539
|
+
function openLive() {
|
|
540
|
+
if (stopped() || live !== undefined || routing === undefined || routing.relays.length === 0)
|
|
541
|
+
return;
|
|
542
|
+
const { account, relays, since } = routing;
|
|
543
|
+
let ended = false;
|
|
544
|
+
let subscription;
|
|
545
|
+
const end = () => {
|
|
546
|
+
if (ended)
|
|
547
|
+
return;
|
|
548
|
+
ended = true;
|
|
549
|
+
if (subscription !== undefined && live === subscription)
|
|
550
|
+
live = undefined;
|
|
551
|
+
subscription?.unsubscribe();
|
|
552
|
+
// Replaced after a backoff pass — never a second subscription alongside it.
|
|
553
|
+
scheduleRetry();
|
|
554
|
+
};
|
|
555
|
+
try {
|
|
556
|
+
// `limit: 0`: live events only — the backfill owns history (a relay that replays anyway is harmless:
|
|
557
|
+
// the seen-set and the in-flight set absorb it). `since` still reaches back: NIP-59 back-dates wraps.
|
|
558
|
+
subscription = deps.subscription(relays, { kinds: [GIFT_WRAP_KIND], '#p': [account], since, limit: 0 }).subscribe({
|
|
559
|
+
// Deferred past the transport frame: a transport may deliver synchronously from inside subscribe().
|
|
560
|
+
// The relay it arrived on, when the transport says (DeliveryMeta, BACKLOG marmot-use-relay-provenance).
|
|
561
|
+
next: (event, meta) => {
|
|
562
|
+
const relay = typeof meta?.relay === 'string' ? meta.relay : undefined;
|
|
563
|
+
void Promise.resolve().then(() => handle(event, relay === undefined ? undefined : [relay]));
|
|
564
|
+
},
|
|
565
|
+
error: end,
|
|
566
|
+
complete: end,
|
|
567
|
+
});
|
|
568
|
+
}
|
|
569
|
+
catch {
|
|
570
|
+
scheduleRetry();
|
|
571
|
+
return;
|
|
572
|
+
}
|
|
573
|
+
if (ended || stopped()) {
|
|
574
|
+
subscription.unsubscribe();
|
|
575
|
+
return;
|
|
576
|
+
}
|
|
577
|
+
live = subscription;
|
|
578
|
+
liveEpoch += 1;
|
|
579
|
+
}
|
|
580
|
+
function closeLive() {
|
|
581
|
+
const current = live;
|
|
582
|
+
live = undefined;
|
|
583
|
+
current?.unsubscribe();
|
|
584
|
+
}
|
|
585
|
+
function teardown() {
|
|
586
|
+
running = false;
|
|
587
|
+
starting = undefined;
|
|
588
|
+
if (retryTimer !== undefined)
|
|
589
|
+
deps.timers.clear(retryTimer);
|
|
590
|
+
retryTimer = undefined;
|
|
591
|
+
retryAttempts = 0;
|
|
592
|
+
closeLive();
|
|
593
|
+
}
|
|
594
|
+
return {
|
|
595
|
+
start() {
|
|
596
|
+
if (disposed || deps.isDisposed())
|
|
597
|
+
return Promise.reject(new MarmotError('disposed', 'inbox.start: client has been disposed'));
|
|
598
|
+
if (running && starting !== undefined)
|
|
599
|
+
return starting;
|
|
600
|
+
running = true;
|
|
601
|
+
const run = (async () => {
|
|
602
|
+
await runPass();
|
|
603
|
+
openLive();
|
|
604
|
+
})();
|
|
605
|
+
starting = run;
|
|
606
|
+
run.catch(() => {
|
|
607
|
+
// A failed first pass leaves the inbox stopped; start() may be called again.
|
|
608
|
+
if (starting === run)
|
|
609
|
+
teardown();
|
|
610
|
+
});
|
|
611
|
+
return run;
|
|
612
|
+
},
|
|
613
|
+
async stop() {
|
|
614
|
+
teardown();
|
|
615
|
+
},
|
|
616
|
+
requestPass() {
|
|
617
|
+
scheduleRetry();
|
|
618
|
+
},
|
|
619
|
+
passNow() {
|
|
620
|
+
if (stopped())
|
|
621
|
+
return;
|
|
622
|
+
if (retryTimer !== undefined)
|
|
623
|
+
deps.timers.clear(retryTimer);
|
|
624
|
+
retryTimer = undefined;
|
|
625
|
+
void runPass()
|
|
626
|
+
.then(() => {
|
|
627
|
+
if (!stopped() && live === undefined)
|
|
628
|
+
openLive();
|
|
629
|
+
})
|
|
630
|
+
.catch(() => scheduleRetry());
|
|
631
|
+
},
|
|
632
|
+
serialize(task) {
|
|
633
|
+
return queue.run(async () => {
|
|
634
|
+
if (disposed || deps.isDisposed())
|
|
635
|
+
throw new MarmotError('disposed', 'inbox: client has been disposed');
|
|
636
|
+
return task();
|
|
637
|
+
});
|
|
638
|
+
},
|
|
639
|
+
dispose() {
|
|
640
|
+
disposed = true;
|
|
641
|
+
teardown();
|
|
642
|
+
},
|
|
643
|
+
};
|
|
644
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export * from './client/index.js';
|
|
2
|
+
import type { NostrEvent } from '@941design/nostr-events/event';
|
|
3
|
+
import type { ClientState } from '@941design/marmot-engine/mls';
|
|
4
|
+
/** Placeholder seam type kept for `packages/account-sync`; superseded by `MarmotClient`. */
|
|
5
|
+
export type MarmotShellSeam = {
|
|
6
|
+
event?: NostrEvent;
|
|
7
|
+
engine?: ClientState;
|
|
8
|
+
};
|
|
9
|
+
export { rotatedLeaves, successionsInWindow } from './history/index.js';
|
|
10
|
+
export type { JoinEvidence, LeafKeyRotatedNotification, LeafKeyRotationWithdrawnNotification, RetiredKeyReaddedNotification, RetainedWindow, RotatedLeaf, WindowNode, WindowSuccession, } from './history/index.js';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// Package root of `@941design/marmot`: the client surface
|
|
2
|
+
// (docs/client-api.md) lives in ./client and is re-exported here.
|
|
3
|
+
// `marmot` never re-exports `nostr-events` (Design Decision 6 of
|
|
4
|
+
// epic-monorepo-restructure's spec.md; enforced by AC-API-9 in
|
|
5
|
+
// test/public-types.test.ts).
|
|
6
|
+
export * from './client/index.js';
|
|
7
|
+
// Rotation notifications and the canonical-path succession feed. `GroupNotification` (exported with the client
|
|
8
|
+
// surface) already carries the union members.
|
|
9
|
+
export { rotatedLeaves, successionsInWindow } from './history/index.js';
|