@optimystic/db-p2p 0.21.0 → 0.24.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/dist/src/cluster/client.d.ts +10 -0
- package/dist/src/cluster/client.d.ts.map +1 -1
- package/dist/src/cluster/client.js +30 -1
- package/dist/src/cluster/client.js.map +1 -1
- package/dist/src/cluster/cluster-policy.d.ts +13 -2
- package/dist/src/cluster/cluster-policy.d.ts.map +1 -1
- package/dist/src/cluster/cluster-policy.js +51 -4
- package/dist/src/cluster/cluster-policy.js.map +1 -1
- package/dist/src/cluster/cluster-repo.d.ts +42 -17
- package/dist/src/cluster/cluster-repo.d.ts.map +1 -1
- package/dist/src/cluster/cluster-repo.js +229 -122
- package/dist/src/cluster/cluster-repo.js.map +1 -1
- package/dist/src/cluster/cluster-size-coupling.d.ts +28 -0
- package/dist/src/cluster/cluster-size-coupling.d.ts.map +1 -0
- package/dist/src/cluster/cluster-size-coupling.js +35 -0
- package/dist/src/cluster/cluster-size-coupling.js.map +1 -0
- package/dist/src/cluster/quorum-restore.d.ts +6 -0
- package/dist/src/cluster/quorum-restore.d.ts.map +1 -1
- package/dist/src/cluster/quorum-restore.js +1 -1
- package/dist/src/cluster/quorum-restore.js.map +1 -1
- package/dist/src/cluster/reconcile-block.d.ts.map +1 -1
- package/dist/src/cluster/reconcile-block.js +15 -3
- package/dist/src/cluster/reconcile-block.js.map +1 -1
- package/dist/src/cluster/service.d.ts +32 -1
- package/dist/src/cluster/service.d.ts.map +1 -1
- package/dist/src/cluster/service.js +43 -2
- package/dist/src/cluster/service.js.map +1 -1
- package/dist/src/cohort-topic/stream-util.d.ts +22 -6
- package/dist/src/cohort-topic/stream-util.d.ts.map +1 -1
- package/dist/src/cohort-topic/stream-util.js +56 -10
- package/dist/src/cohort-topic/stream-util.js.map +1 -1
- package/dist/src/dispute/dispute-service.d.ts.map +1 -1
- package/dist/src/dispute/dispute-service.js +9 -3
- package/dist/src/dispute/dispute-service.js.map +1 -1
- package/dist/src/index.d.ts +5 -0
- package/dist/src/index.d.ts.map +1 -1
- package/dist/src/index.js +5 -0
- package/dist/src/index.js.map +1 -1
- package/dist/src/libp2p-key-network.d.ts +134 -7
- package/dist/src/libp2p-key-network.d.ts.map +1 -1
- package/dist/src/libp2p-key-network.js +174 -37
- package/dist/src/libp2p-key-network.js.map +1 -1
- package/dist/src/libp2p-node-base.d.ts +3 -2
- package/dist/src/libp2p-node-base.d.ts.map +1 -1
- package/dist/src/libp2p-node-base.js +859 -778
- package/dist/src/libp2p-node-base.js.map +1 -1
- package/dist/src/libp2p-node-rn.d.ts +2 -2
- package/dist/src/libp2p-node-rn.d.ts.map +1 -1
- package/dist/src/libp2p-node-rn.js.map +1 -1
- package/dist/src/libp2p-node.d.ts +2 -2
- package/dist/src/libp2p-node.d.ts.map +1 -1
- package/dist/src/libp2p-node.js.map +1 -1
- package/dist/src/logger.d.ts +17 -1
- package/dist/src/logger.d.ts.map +1 -1
- package/dist/src/logger.js +19 -2
- package/dist/src/logger.js.map +1 -1
- package/dist/src/network/network-manager-service.d.ts +2 -0
- package/dist/src/network/network-manager-service.d.ts.map +1 -1
- package/dist/src/network/network-manager-service.js +4 -0
- package/dist/src/network/network-manager-service.js.map +1 -1
- package/dist/src/optimystic-node.d.ts +35 -0
- package/dist/src/optimystic-node.d.ts.map +1 -0
- package/dist/src/optimystic-node.js +2 -0
- package/dist/src/optimystic-node.js.map +1 -0
- package/dist/src/owned-block-seed.d.ts +6 -3
- package/dist/src/owned-block-seed.d.ts.map +1 -1
- package/dist/src/owned-block-seed.js +16 -3
- package/dist/src/owned-block-seed.js.map +1 -1
- package/dist/src/peer-address-book.d.ts +72 -0
- package/dist/src/peer-address-book.d.ts.map +1 -0
- package/dist/src/peer-address-book.js +123 -0
- package/dist/src/peer-address-book.js.map +1 -0
- package/dist/src/repo/client.d.ts.map +1 -1
- package/dist/src/repo/client.js +11 -2
- package/dist/src/repo/client.js.map +1 -1
- package/dist/src/repo/cluster-coordinator.d.ts +30 -0
- package/dist/src/repo/cluster-coordinator.d.ts.map +1 -1
- package/dist/src/repo/cluster-coordinator.js +95 -3
- package/dist/src/repo/cluster-coordinator.js.map +1 -1
- package/dist/src/repo/coordinator-repo.d.ts +78 -14
- package/dist/src/repo/coordinator-repo.d.ts.map +1 -1
- package/dist/src/repo/coordinator-repo.js +266 -81
- package/dist/src/repo/coordinator-repo.js.map +1 -1
- package/dist/src/rn.d.ts +5 -0
- package/dist/src/rn.d.ts.map +1 -1
- package/dist/src/rn.js +5 -0
- package/dist/src/rn.js.map +1 -1
- package/dist/src/storage/block-storage.d.ts.map +1 -1
- package/dist/src/storage/block-storage.js +57 -5
- package/dist/src/storage/block-storage.js.map +1 -1
- package/dist/src/storage/cached-raw-storage.d.ts +83 -0
- package/dist/src/storage/cached-raw-storage.d.ts.map +1 -0
- package/dist/src/storage/cached-raw-storage.js +152 -0
- package/dist/src/storage/cached-raw-storage.js.map +1 -0
- package/dist/src/storage/cached-store-driver.d.ts +186 -0
- package/dist/src/storage/cached-store-driver.d.ts.map +1 -0
- package/dist/src/storage/cached-store-driver.js +775 -0
- package/dist/src/storage/cached-store-driver.js.map +1 -0
- package/dist/src/storage/i-block-storage.d.ts +20 -1
- package/dist/src/storage/i-block-storage.d.ts.map +1 -1
- package/dist/src/storage/i-raw-storage.d.ts +12 -5
- package/dist/src/storage/i-raw-storage.d.ts.map +1 -1
- package/dist/src/storage/shared-cache-pool.d.ts +234 -0
- package/dist/src/storage/shared-cache-pool.d.ts.map +1 -0
- package/dist/src/storage/shared-cache-pool.js +354 -0
- package/dist/src/storage/shared-cache-pool.js.map +1 -0
- package/dist/src/storage/storage-repo.d.ts +56 -3
- package/dist/src/storage/storage-repo.d.ts.map +1 -1
- package/dist/src/storage/storage-repo.js +124 -18
- package/dist/src/storage/storage-repo.js.map +1 -1
- package/dist/src/testing/raw-storage-conformance.d.ts +2 -1
- package/dist/src/testing/raw-storage-conformance.d.ts.map +1 -1
- package/dist/src/testing/raw-storage-conformance.js +52 -2
- package/dist/src/testing/raw-storage-conformance.js.map +1 -1
- package/package.json +3 -3
- package/readme.md +668 -653
- package/src/cluster/block-transfer.ts +424 -424
- package/src/cluster/client.ts +119 -88
- package/src/cluster/cluster-error.ts +64 -64
- package/src/cluster/cluster-policy.ts +203 -152
- package/src/cluster/cluster-repo.ts +245 -125
- package/src/cluster/cluster-size-coupling.ts +45 -0
- package/src/cluster/commit-cert.ts +139 -139
- package/src/cluster/i-transaction-state-store.ts +43 -43
- package/src/cluster/memory-transaction-state-store.ts +56 -56
- package/src/cluster/peer-key-binding.ts +37 -37
- package/src/cluster/persistent-transaction-state-store.ts +92 -92
- package/src/cluster/quorum-restore.ts +223 -223
- package/src/cluster/reconcile-block.ts +203 -191
- package/src/cluster/service.ts +293 -241
- package/src/cluster/supermajority-coupling.ts +37 -37
- package/src/cohort-topic/bootstrap-evidence-builder.ts +122 -122
- package/src/cohort-topic/bootstrap-evidence-verifiers.ts +132 -132
- package/src/cohort-topic/bootstrap-parent-reference.ts +159 -159
- package/src/cohort-topic/change-bridge.ts +109 -109
- package/src/cohort-topic/cohort-gossip-driver.ts +231 -231
- package/src/cohort-topic/cohort-gossip-transport.ts +84 -84
- package/src/cohort-topic/fret-trust-anchor.ts +153 -153
- package/src/cohort-topic/host.ts +2901 -2901
- package/src/cohort-topic/index.ts +13 -13
- package/src/cohort-topic/membership-publish-sink.ts +20 -20
- package/src/cohort-topic/membership-source.ts +68 -68
- package/src/cohort-topic/peer-codec.ts +31 -31
- package/src/cohort-topic/peer-sig.ts +86 -86
- package/src/cohort-topic/protocols.ts +71 -71
- package/src/cohort-topic/reactivity-membership-gate.ts +77 -77
- package/src/cohort-topic/size-estimator.ts +16 -16
- package/src/cohort-topic/stream-util.ts +135 -87
- package/src/cohort-topic/threshold-crypto.ts +239 -239
- package/src/cohort-topic/topic-router.ts +77 -77
- package/src/dispute/arbitrator-selection.ts +138 -138
- package/src/dispute/cascade.ts +524 -524
- package/src/dispute/dispute-service.ts +11 -5
- package/src/dispute/invalidation.ts +625 -625
- package/src/inbound-authorization.ts +190 -190
- package/src/index.ts +52 -47
- package/src/libp2p-key-network.ts +1120 -958
- package/src/libp2p-node-base.ts +1675 -1591
- package/src/libp2p-node-rn.ts +30 -30
- package/src/libp2p-node.ts +36 -36
- package/src/logger.ts +19 -2
- package/src/matchmaking/aggregate-counts.ts +104 -104
- package/src/matchmaking/index.ts +20 -20
- package/src/matchmaking/module.ts +363 -363
- package/src/matchmaking/protocols.ts +51 -51
- package/src/matchmaking/provider-manager.ts +95 -95
- package/src/matchmaking/query-handler.ts +88 -88
- package/src/matchmaking/query-transport.ts +492 -492
- package/src/matchmaking/seeker-manager.ts +64 -64
- package/src/matchmaking/seeker-walk-client.ts +293 -293
- package/src/matchmaking/traffic-validation.ts +195 -195
- package/src/network/network-manager-service.ts +5 -0
- package/src/optimystic-node.ts +36 -0
- package/src/owned-block-seed.ts +53 -40
- package/src/peer-address-book.ts +149 -0
- package/src/protocol-limits.ts +33 -33
- package/src/reactivity/forwarder-host.ts +438 -438
- package/src/reactivity/index.ts +19 -19
- package/src/reactivity/notify-transport.ts +144 -144
- package/src/reactivity/origination-manager.ts +192 -192
- package/src/reactivity/protocols.ts +61 -61
- package/src/reactivity/push-state-gossip.ts +291 -291
- package/src/reactivity/recover-transport.ts +408 -408
- package/src/reactivity/rotation-rereg-scheduler.ts +256 -256
- package/src/reactivity/subscriber-registry.ts +96 -96
- package/src/reactivity/subscription-manager.ts +450 -450
- package/src/reactivity/topic-bytes.ts +37 -37
- package/src/repo/client.ts +12 -2
- package/src/repo/cluster-coordinator.ts +99 -3
- package/src/repo/coordinator-repo.ts +305 -82
- package/src/repo/types.ts +7 -7
- package/src/rn.ts +39 -34
- package/src/rpc-deadline.ts +45 -45
- package/src/storage/arachnode-partition.ts +74 -74
- package/src/storage/block-storage.ts +59 -6
- package/src/storage/cached-raw-storage.ts +180 -0
- package/src/storage/cached-store-driver.ts +859 -0
- package/src/storage/i-block-storage.ts +20 -1
- package/src/storage/i-kv-store.ts +8 -8
- package/src/storage/i-raw-storage.ts +12 -5
- package/src/storage/kv-raw-storage.ts +135 -135
- package/src/storage/memory-kv-store.ts +28 -28
- package/src/storage/memory-storage.ts +25 -25
- package/src/storage/memory-store-driver.ts +157 -157
- package/src/storage/raw-store-codec.ts +42 -42
- package/src/storage/raw-store-driver.ts +80 -80
- package/src/storage/ring-selector.ts +317 -317
- package/src/storage/ring-shift-coordinator.ts +271 -271
- package/src/storage/shared-cache-pool.ts +452 -0
- package/src/storage/storage-repo.ts +1014 -903
- package/src/testing/cohort-topic-mesh-harness.ts +663 -663
- package/src/testing/index.ts +8 -8
- package/src/testing/matchmaking-mesh-harness.ts +475 -475
- package/src/testing/raw-storage-conformance.ts +453 -397
- package/src/testing/reactivity-mesh-harness.ts +922 -922
- package/dist/src/storage/restoration-coordinator-v2.d.ts +0 -67
- package/dist/src/storage/restoration-coordinator-v2.d.ts.map +0 -1
- package/dist/src/storage/restoration-coordinator-v2.js +0 -172
- package/dist/src/storage/restoration-coordinator-v2.js.map +0 -1
|
@@ -1,438 +1,438 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Reactivity — forwarder **host** orchestrator (`docs/reactivity.md` §Propagation, §Slow-subscriber
|
|
3
|
-
* backpressure, §Per-cohort policy).
|
|
4
|
-
*
|
|
5
|
-
* This is the piece that turns the in-process forward *decision* (db-core's {@link ReactivityForwarder})
|
|
6
|
-
* into live fan-out over the {@link ReactivityNotifyTransport}. For one {@link NotificationV1} — whether
|
|
7
|
-
* locally originated (the change-bridge's `emit` seam binds to {@link ReactivityForwarderHost.ingest}) or
|
|
8
|
-
* inbound off a dial ({@link ReactivityForwarderHost.onInbound}) — it:
|
|
9
|
-
*
|
|
10
|
-
* 1. lazily instantiates the per-collection {@link PushState} + forwarder behind the Edge policy gate
|
|
11
|
-
* ({@link instantiateForwarderPushState}: `undefined` on an Edge node ⇒ this node never forwards);
|
|
12
|
-
* 2. runs the db-core receive path (verify → dedupe → buffer) and stops on `"duplicate"` / `"untrusted"`;
|
|
13
|
-
* 3. on `"forward"`, fans the **unmodified** frame out to every direct subscriber (through the
|
|
14
|
-
* per-subscriber bounded queue, so a slow/dead subscriber's drops never stall the rest) and every
|
|
15
|
-
* child cohort.
|
|
16
|
-
*
|
|
17
|
-
* It owns the per-subscriber dequeue→dial delivery loop, the bounded-queue backpressure interaction,
|
|
18
|
-
* subscriber-queue eviction (the memory bound — a departed subscriber's queue is reclaimed lazily each
|
|
19
|
-
* fan-out round), and per-topic serialization so the replay ring + dedupe set never interleave across two
|
|
20
|
-
* concurrent notifications for the same collection.
|
|
21
|
-
*
|
|
22
|
-
* **Subscriber-id space.** `selfPeerId`, the {@link ReactivityForwarderHostDeps.directSubscribers} output,
|
|
23
|
-
* the {@link CohortRef.primary} child targets, and every {@link ReactivityNotifyTransport.send} target are
|
|
24
|
-
* the **same** string space (it is also the `perSubscriberQueue` key). This host is agnostic to the concrete
|
|
25
|
-
* encoding so long as it is consistent across all four seams; the **transport** pins which space —
|
|
26
|
-
* {@link import("./notify-transport.js").Libp2pReactivityNotifyTransport.send} calls `peerIdFromString`, so
|
|
27
|
-
* the space is the **canonical peer-id string** (NOT base64url-of-member-bytes — that would silently fail
|
|
28
|
-
* `peerIdFromString` and never dial). The {@link reactivityDirectSubscribers} adapter and the node-wiring
|
|
29
|
-
* layer ([reactivity-notification-transport]) therefore both emit peer-id strings.
|
|
30
|
-
*
|
|
31
|
-
* This module deliberately touches neither the libp2p node assembly ([reactivity-notification-transport])
|
|
32
|
-
* nor gossip ([reactivity-pushstate-gossip]); it depends only on the transport interface + db-core logic,
|
|
33
|
-
* so it is unit-testable with a fake transport.
|
|
34
|
-
*/
|
|
35
|
-
|
|
36
|
-
import {
|
|
37
|
-
reactivityTopicId,
|
|
38
|
-
b64urlToBytes,
|
|
39
|
-
bytesToB64url,
|
|
40
|
-
createReactivityForwarder,
|
|
41
|
-
instantiateForwarderPushState,
|
|
42
|
-
decodeSubscribeAppPayload,
|
|
43
|
-
TailDrainGate,
|
|
44
|
-
type NotificationV1,
|
|
45
|
-
type PeerRef,
|
|
46
|
-
type NodeProfile,
|
|
47
|
-
type PushState,
|
|
48
|
-
type PushStateInit,
|
|
49
|
-
type CohortRef,
|
|
50
|
-
type NotificationVerifier,
|
|
51
|
-
type ReactivityForwarder,
|
|
52
|
-
type RegistrationRecord,
|
|
53
|
-
type RotationRedirectV1,
|
|
54
|
-
} from "@optimystic/db-core";
|
|
55
|
-
import type { ReactivityNotifyTransport } from "./notify-transport.js";
|
|
56
|
-
import { bytesToPeerIdString } from "../cohort-topic/peer-codec.js";
|
|
57
|
-
import { createLogger } from "../logger.js";
|
|
58
|
-
|
|
59
|
-
const log = createLogger("reactivity-forwarder-host");
|
|
60
|
-
|
|
61
|
-
/**
|
|
62
|
-
* The reactivity topic id a notification belongs to: `H(tailId ‖ "reactivity")` over the notification's
|
|
63
|
-
* tail anchor. Kept in one place so it matches origination's `reactivityTailBytes` encoding and the
|
|
64
|
-
* subscriber/forwarder verifier's coord derivation byte-for-byte (both decode `tailId` as base64url first).
|
|
65
|
-
*/
|
|
66
|
-
export function reactivityNotificationTopicId(n: NotificationV1): Uint8Array {
|
|
67
|
-
return reactivityTopicId(b64urlToBytes(n.tailId));
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
/** The minimal cohort read the {@link reactivityDirectSubscribers} adapter needs (a {@link CoordEngine} satisfies it). */
|
|
71
|
-
export interface ReactivityRecordSource {
|
|
72
|
-
/** This cohort's locally-known direct registration records for `topicId`. */
|
|
73
|
-
records(topicId: Uint8Array): readonly RegistrationRecord[];
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
/**
|
|
77
|
-
* The direct-subscriber **peer-id strings** for a reactivity topic, read from a cohort's
|
|
78
|
-
* {@link RegistrationRecord} set: a record carries a subscriber iff its opaque `appState` decodes to a
|
|
79
|
-
* reactivity {@link import("@optimystic/db-core").SubscribeAppPayloadV1}. `record.participantId` is the
|
|
80
|
-
* subscriber's dialable member id (db-core's `service` pins `participantId = self`), carried as
|
|
81
|
-
* `peerIdToBytes(peerId) = utf8(peerIdString)`; this decodes it back to the canonical peer-id string via
|
|
82
|
-
* {@link bytesToPeerIdString} so the value is both the `transport.send` dial target (which calls
|
|
83
|
-
* `peerIdFromString`) and the `perSubscriberQueue` key. **The whole host runs in this peer-id-string space**
|
|
84
|
-
* — `selfPeerId`, `resolveChildPrimary`, and every `send` target must agree, or a base64url-vs-peer-id
|
|
85
|
-
* mismatch is a silent no-dial. A record whose `appState` is absent or decodes to a non-reactivity payload
|
|
86
|
-
* (e.g. a matchmaking registration sharing the cohort store) is skipped.
|
|
87
|
-
*/
|
|
88
|
-
export function reactivityDirectSubscribers(source: ReactivityRecordSource, topicId: Uint8Array): string[] {
|
|
89
|
-
const out: string[] = [];
|
|
90
|
-
for (const record of source.records(topicId)) {
|
|
91
|
-
if (record.appState === undefined) {
|
|
92
|
-
continue;
|
|
93
|
-
}
|
|
94
|
-
try {
|
|
95
|
-
decodeSubscribeAppPayload(record.appState); // throws on a non-reactivity / malformed payload
|
|
96
|
-
} catch {
|
|
97
|
-
continue; // not a reactivity subscriber — leave the record to its own application
|
|
98
|
-
}
|
|
99
|
-
out.push(bytesToPeerIdString(record.participantId));
|
|
100
|
-
}
|
|
101
|
-
return out;
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
/** Construction inputs for a {@link ReactivityForwarderHost}. */
|
|
105
|
-
export interface ReactivityForwarderHostDeps {
|
|
106
|
-
/** One-way notification transport (unicast send + inbound subscribe); fan-out dials each target through it. */
|
|
107
|
-
readonly transport: ReactivityNotifyTransport;
|
|
108
|
-
/** This node's member id, base64url — never dialed; a co-located subscriber is delivered in-process. */
|
|
109
|
-
readonly selfPeerId: string;
|
|
110
|
-
/** Node profile; gates {@link PushState} instantiation (Edge ⇒ subscriber-only, never forwards). */
|
|
111
|
-
readonly profile: NodeProfile;
|
|
112
|
-
/** Build the per-collection {@link PushStateInit} on first ingest for a topic this node serves. */
|
|
113
|
-
readonly pushStateInit: (topicId: Uint8Array, n: NotificationV1) => PushStateInit;
|
|
114
|
-
/** The notification verifier for a topic (a db-core `createNotificationVerifier` over the host's service verifier, T3). */
|
|
115
|
-
readonly verifierFor: (topicId: Uint8Array) => NotificationVerifier;
|
|
116
|
-
/** Direct-subscriber member ids (base64url) for a topic — e.g. {@link reactivityDirectSubscribers} over the cohort. */
|
|
117
|
-
readonly directSubscribers: (topicId: Uint8Array) => string[];
|
|
118
|
-
/** Resolve a child cohort's dialable primary when {@link CohortRef.primary} is absent (e.g. a FRET resolver). */
|
|
119
|
-
readonly resolveChildPrimary?: (ref: CohortRef) => string | undefined;
|
|
120
|
-
/**
|
|
121
|
-
* Route an inbound notification to a co-located subscription manager, when this node also subscribes the
|
|
122
|
-
* topic. **Must be idempotent on `(collectionId, revision)`**: on the {@link ReactivityForwarderHost.onInbound}
|
|
123
|
-
* path a node that is both a cohort member *and* a subscriber invokes this **twice** for the same
|
|
124
|
-
* notification — once in the subscriber role (directly) and once in the forwarder role (when `self` is in
|
|
125
|
-
* {@link directSubscribers}, via `fanOut`'s self-delivery). The db-core subscriber's `(collectionId,
|
|
126
|
-
* revision)` dedupe (`createReactivitySubscriber`) collapses the second call to a no-op, so a correctly
|
|
127
|
-
* wired manager delivers exactly once; a sink without that dedupe would double-deliver.
|
|
128
|
-
*/
|
|
129
|
-
readonly deliverLocal?: (topicId: Uint8Array, n: NotificationV1) => void;
|
|
130
|
-
/** Wall clock (unix ms) stamped on `receive`. Default `Date.now`. */
|
|
131
|
-
readonly clock?: () => number;
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
/** A topic this node forwards: its live {@link PushState} and the forwarder driving the receive path over it. */
|
|
135
|
-
interface ServedTopic {
|
|
136
|
-
readonly pushState: PushState;
|
|
137
|
-
readonly forwarder: ReactivityForwarder;
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
/**
|
|
141
|
-
* The reactivity fan-out orchestrator. Build one per node; it serves every reactivity topic the node is a
|
|
142
|
-
* cohort member for, lazily instantiating per-collection state on first ingest. Bind
|
|
143
|
-
* {@link ReactivityForwarderHost.ingest} to the origination `emit` seam and
|
|
144
|
-
* {@link ReactivityForwarderHost.onInbound} to the transport's inbound subscribe.
|
|
145
|
-
*/
|
|
146
|
-
export class ReactivityForwarderHost {
|
|
147
|
-
private readonly transport: ReactivityNotifyTransport;
|
|
148
|
-
private readonly selfPeerId: string;
|
|
149
|
-
private readonly profile: NodeProfile;
|
|
150
|
-
private readonly pushStateInit: (topicId: Uint8Array, n: NotificationV1) => PushStateInit;
|
|
151
|
-
private readonly verifierFor: (topicId: Uint8Array) => NotificationVerifier;
|
|
152
|
-
private readonly directSubscribers: (topicId: Uint8Array) => string[];
|
|
153
|
-
private readonly resolveChildPrimary?: (ref: CohortRef) => string | undefined;
|
|
154
|
-
private readonly deliverLocal?: (topicId: Uint8Array, n: NotificationV1) => void;
|
|
155
|
-
private readonly clock: () => number;
|
|
156
|
-
|
|
157
|
-
/** Per-topic served state. `ServedTopic` ⇒ forwards; `null` ⇒ resolved subscriber-only (Edge); absent ⇒ unresolved. */
|
|
158
|
-
private readonly served = new Map<string, ServedTopic | null>();
|
|
159
|
-
/** Per-topic serialization tail: an ingest chains onto its topic's prior ingest so the ring/dedupe never interleave. */
|
|
160
|
-
private readonly ingestTails = new Map<string, Promise<void>>();
|
|
161
|
-
/**
|
|
162
|
-
* Per **old-topic** drain gate: set by {@link markRotated} when this node observes the collection's tail
|
|
163
|
-
* rotate, keyed by the outgoing tail's topicId (base64url). For `T_drain` after the rotation
|
|
164
|
-
* {@link rotationRedirectFor} answers a recover request reaching the outgoing tail with the gate's
|
|
165
|
-
* {@link RotationRedirectV1} ("this moved — go to the new tree"); once the window closes the entry is
|
|
166
|
-
* evicted along with the topic's served `PushState`.
|
|
167
|
-
*/
|
|
168
|
-
private readonly rotationGates = new Map<string, TailDrainGate>();
|
|
169
|
-
|
|
170
|
-
constructor(deps: ReactivityForwarderHostDeps) {
|
|
171
|
-
this.transport = deps.transport;
|
|
172
|
-
this.selfPeerId = deps.selfPeerId;
|
|
173
|
-
this.profile = deps.profile;
|
|
174
|
-
this.pushStateInit = deps.pushStateInit;
|
|
175
|
-
this.verifierFor = deps.verifierFor;
|
|
176
|
-
this.directSubscribers = deps.directSubscribers;
|
|
177
|
-
this.resolveChildPrimary = deps.resolveChildPrimary;
|
|
178
|
-
this.deliverLocal = deps.deliverLocal;
|
|
179
|
-
this.clock = deps.clock ?? ((): number => Date.now());
|
|
180
|
-
}
|
|
181
|
-
|
|
182
|
-
/**
|
|
183
|
-
* Local origination emit **and** the inbound forwarder path: receive → forward → fan-out for one
|
|
184
|
-
* notification on `topicId`. Ingests for one topic run strictly in sequence (verify is async and the
|
|
185
|
-
* replay ring + dedupe set must not interleave); ingests for different topics proceed concurrently.
|
|
186
|
-
* Never rejects — a fan-out fault can never surface as a commit failure on the origination seam.
|
|
187
|
-
*/
|
|
188
|
-
ingest(topicId: Uint8Array, n: NotificationV1): Promise<void> {
|
|
189
|
-
const key = this.topicKey(topicId);
|
|
190
|
-
const prev = this.ingestTails.get(key) ?? Promise.resolve();
|
|
191
|
-
// Run regardless of the prior ingest's outcome; `ingestSerialized` isolates its own throws, so the
|
|
192
|
-
// chain never accumulates a rejection that would leak out of a later `ingest`.
|
|
193
|
-
const next = prev.then(
|
|
194
|
-
() => this.ingestSerialized(topicId, n, key),
|
|
195
|
-
() => this.ingestSerialized(topicId, n, key),
|
|
196
|
-
);
|
|
197
|
-
this.ingestTails.set(key, next);
|
|
198
|
-
return next;
|
|
199
|
-
}
|
|
200
|
-
|
|
201
|
-
/** One serialized ingest: resolve served state, run receive, fan out on `"forward"`. Isolates all throws. */
|
|
202
|
-
private async ingestSerialized(topicId: Uint8Array, n: NotificationV1, key: string): Promise<void> {
|
|
203
|
-
try {
|
|
204
|
-
const served = this.resolveServed(topicId, n, key);
|
|
205
|
-
if (served === null) {
|
|
206
|
-
return; // Edge / subscriber-only: this node never forwards (delivery rides onInbound → deliverLocal).
|
|
207
|
-
}
|
|
208
|
-
const decision = await served.forwarder.receive(n, this.clock());
|
|
209
|
-
if (decision !== "forward") {
|
|
210
|
-
return; // "duplicate" (already buffered) or "untrusted" (dropped before any state mutation).
|
|
211
|
-
}
|
|
212
|
-
this.fanOut(topicId, served.pushState, n);
|
|
213
|
-
} catch (err) {
|
|
214
|
-
log("ingest failed for topic=%s rev=%d (isolated): %o", key, n.revision, err);
|
|
215
|
-
}
|
|
216
|
-
}
|
|
217
|
-
|
|
218
|
-
/**
|
|
219
|
-
* Inbound notify dial: run the **subscriber** role (in-process delivery to a co-located manager) and the
|
|
220
|
-
* **forwarder** role (receive + fan-out) as applicable. A node that is both a cohort member and a
|
|
221
|
-
* subscriber does both — the forwarder dedupe + the subscriber's `(collectionId, revision)` dedupe keep
|
|
222
|
-
* it idempotent. Never rejects.
|
|
223
|
-
*/
|
|
224
|
-
async onInbound(_from: PeerRef, n: NotificationV1): Promise<void> {
|
|
225
|
-
let topicId: Uint8Array;
|
|
226
|
-
try {
|
|
227
|
-
topicId = reactivityNotificationTopicId(n);
|
|
228
|
-
} catch (err) {
|
|
229
|
-
log("onInbound: undecodable tailId on rev=%d (dropped): %o", n.revision, err);
|
|
230
|
-
return;
|
|
231
|
-
}
|
|
232
|
-
// Subscriber role first: deliver in-process to a co-located subscription manager, if any.
|
|
233
|
-
this.deliverInProcess(topicId, n);
|
|
234
|
-
// Forwarder role: ingest self-gates (Edge ⇒ no PushState; a non-member ⇒ empty fan-out).
|
|
235
|
-
await this.ingest(topicId, n);
|
|
236
|
-
}
|
|
237
|
-
|
|
238
|
-
/** The live {@link PushState} for a served topic, or `undefined` (Edge, or not yet ingested). Test/diagnostic. */
|
|
239
|
-
pushStateFor(topicId: Uint8Array): PushState | undefined {
|
|
240
|
-
const served = this.served.get(this.topicKey(topicId));
|
|
241
|
-
return served === undefined || served === null ? undefined : served.pushState;
|
|
242
|
-
}
|
|
243
|
-
|
|
244
|
-
/**
|
|
245
|
-
* Every live forwarder {@link PushState} this node currently serves: the topics it has ingested at least
|
|
246
|
-
* one notification for and instantiated state behind the Edge gate (subscriber-only `null`s and
|
|
247
|
-
* not-yet-ingested topics are skipped). The push-state-gossip driver iterates these each round to
|
|
248
|
-
* broadcast convergence state to each collection's cohort, so a member that missed an origin dial still
|
|
249
|
-
* ends up holding the replay entry.
|
|
250
|
-
*/
|
|
251
|
-
livePushStates(): PushState[] {
|
|
252
|
-
const out: PushState[] = [];
|
|
253
|
-
for (const served of this.served.values()) {
|
|
254
|
-
if (served !== null) {
|
|
255
|
-
out.push(served.pushState);
|
|
256
|
-
}
|
|
257
|
-
}
|
|
258
|
-
return out;
|
|
259
|
-
}
|
|
260
|
-
|
|
261
|
-
/**
|
|
262
|
-
* The live {@link PushState} this node serves for `collectionId` (base64url), or `undefined` if none.
|
|
263
|
-
* The served map is keyed by **topicId**, but a backfill request carries only a collectionId and a
|
|
264
|
-
* resume that lost its tail must still resolve the collection's current tail — so this scans for the
|
|
265
|
-
* served topic whose `PushState.collectionId` matches. Across a tail-rotation **drain window** a
|
|
266
|
-
* collection can briefly have two served topics (the outgoing and incoming tail); the one with the
|
|
267
|
-
* highest `lastRevision` is the current tail, so that is the one returned. (The precise drain-window
|
|
268
|
-
* redirect choreography is `reactivity-tail-rotation-transport`'s; this picks the current tail.)
|
|
269
|
-
*/
|
|
270
|
-
pushStateForCollection(collectionId: string): PushState | undefined {
|
|
271
|
-
let best: PushState | undefined;
|
|
272
|
-
for (const served of this.served.values()) {
|
|
273
|
-
if (served === null || served.pushState.collectionId !== collectionId) {
|
|
274
|
-
continue;
|
|
275
|
-
}
|
|
276
|
-
if (best === undefined || served.pushState.lastRevision > best.lastRevision) {
|
|
277
|
-
best = served.pushState;
|
|
278
|
-
}
|
|
279
|
-
}
|
|
280
|
-
return best;
|
|
281
|
-
}
|
|
282
|
-
|
|
283
|
-
/**
|
|
284
|
-
* Record that the topic anchored on `oldTopicId` has **rotated** to a successor tail, starting a
|
|
285
|
-
* {@link TailDrainGate} so the outgoing tail bounces recover requests to the new tree for `T_drain`
|
|
286
|
-
* (`docs/reactivity.md` §Tail rotation step 2). db-core derives the redirect's `newTopicId` internally via
|
|
287
|
-
* `reactivityTopicId(newTailId)`. The trigger is origination observing the collection's `event.tailId`
|
|
288
|
-
* change ({@link reactivity-rotation-host-wiring-e2e}); this seam is called directly in unit tests.
|
|
289
|
-
*
|
|
290
|
-
* **Idempotent / chained.** A second `markRotated` for the **same** successor is a no-op; a `markRotated`
|
|
291
|
-
* to a **later** successor (higher `effectiveAtRevision`) replaces the gate — so a chained OLD→A→B rotation
|
|
292
|
-
* advances the redirect to the most recent successor and restarts its drain window from `now`. An earlier
|
|
293
|
-
* (or equal) successor leaves the existing gate untouched.
|
|
294
|
-
*/
|
|
295
|
-
markRotated(oldTopicId: Uint8Array, redirect: { newTailId: string; effectiveAtRevision: number }, now: number): void {
|
|
296
|
-
const key = this.topicKey(oldTopicId);
|
|
297
|
-
const existing = this.rotationGates.get(key);
|
|
298
|
-
if (existing !== undefined && redirect.effectiveAtRevision <= existing.rotationRedirect.effectiveAtRevision) {
|
|
299
|
-
return; // same or earlier successor — the gate already points at this-or-a-later tail.
|
|
300
|
-
}
|
|
301
|
-
this.rotationGates.set(key, new TailDrainGate({
|
|
302
|
-
rotatedAt: now,
|
|
303
|
-
newTailId: redirect.newTailId,
|
|
304
|
-
effectiveAtRevision: redirect.effectiveAtRevision,
|
|
305
|
-
}));
|
|
306
|
-
}
|
|
307
|
-
|
|
308
|
-
/**
|
|
309
|
-
* The drain-window redirect for a recover request that reached the outgoing tail anchored on `oldTopicId`,
|
|
310
|
-
* or `undefined` if this topic never rotated / its drain window has elapsed. While the gate is draining
|
|
311
|
-
* (`isDraining(now)`) returns its {@link RotationRedirectV1}; once `T_drain` closes, evicts the gate **and**
|
|
312
|
-
* the topic's served `PushState` (the old tail originates nothing further — this also reclaims the
|
|
313
|
-
* `served` / `ingestTails` maps the 12.31 review flagged as un-evicted on rotation) and returns `undefined`,
|
|
314
|
-
* so the next request gets no reply and the subscriber re-walks / chain-reads.
|
|
315
|
-
*/
|
|
316
|
-
rotationRedirectFor(oldTopicId: Uint8Array, now: number): RotationRedirectV1 | undefined {
|
|
317
|
-
const key = this.topicKey(oldTopicId);
|
|
318
|
-
const gate = this.rotationGates.get(key);
|
|
319
|
-
if (gate === undefined) {
|
|
320
|
-
return undefined;
|
|
321
|
-
}
|
|
322
|
-
if (gate.isDraining(now)) {
|
|
323
|
-
return gate.rotationRedirect;
|
|
324
|
-
}
|
|
325
|
-
// Drain window closed: the outgoing tail is done. Drop the gate and reclaim its served state so the
|
|
326
|
-
// per-topic maps don't leak across rotations.
|
|
327
|
-
this.rotationGates.delete(key);
|
|
328
|
-
this.served.delete(key);
|
|
329
|
-
this.ingestTails.delete(key);
|
|
330
|
-
return undefined;
|
|
331
|
-
}
|
|
332
|
-
|
|
333
|
-
/**
|
|
334
|
-
* Fan the unmodified frame out: reconcile (GC) departed-subscriber queues, enqueue per-subscriber
|
|
335
|
-
* (drop-oldest under pressure), drain each queue and deliver (self in-process, others dialed, per-target
|
|
336
|
-
* isolated), then dial each resolved child cohort. One slow/dead target never blocks the loop for the rest.
|
|
337
|
-
*/
|
|
338
|
-
private fanOut(topicId: Uint8Array, pushState: PushState, n: NotificationV1): void {
|
|
339
|
-
const subscriberIds = this.directSubscribers(topicId);
|
|
340
|
-
|
|
341
|
-
// Memory bound: drop any per-subscriber queue whose id left the live set (departed / TTL-expired /
|
|
342
|
-
// withdrawn). The map can never grow past the live subscriber set + the current round (lazy GC, so it
|
|
343
|
-
// shrinks at most one fan-out round late) — this satisfies the `subscribers × queue_max × size` bound.
|
|
344
|
-
this.reconcileQueues(pushState, subscriberIds);
|
|
345
|
-
|
|
346
|
-
// Enqueue onto each subscriber's bounded queue (a slow subscriber's drop-oldest isolates to its queue).
|
|
347
|
-
pushState.enqueueForSubscribers(subscriberIds, n);
|
|
348
|
-
|
|
349
|
-
// Drain + deliver per subscriber, isolated: one dead subscriber's dial never stalls the others.
|
|
350
|
-
for (const subId of subscriberIds) {
|
|
351
|
-
const queue = pushState.perSubscriberQueue.peekQueue(subId);
|
|
352
|
-
if (queue === undefined) {
|
|
353
|
-
continue;
|
|
354
|
-
}
|
|
355
|
-
for (const m of queue.drain()) {
|
|
356
|
-
this.deliverTo(topicId, subId, m);
|
|
357
|
-
}
|
|
358
|
-
}
|
|
359
|
-
|
|
360
|
-
// Child cohorts get the unmodified frame (forwarders never re-sign). No-op until the parent/child link
|
|
361
|
-
// lands ([cohort-topic-parent-child-link]) populates `childCohorts`.
|
|
362
|
-
for (const ref of pushState.childCohorts) {
|
|
363
|
-
const target = ref.primary ?? this.resolveChildPrimary?.(ref);
|
|
364
|
-
if (target !== undefined && target !== this.selfPeerId) {
|
|
365
|
-
this.dispatch(target, n);
|
|
366
|
-
}
|
|
367
|
-
}
|
|
368
|
-
}
|
|
369
|
-
|
|
370
|
-
/** Reclaim the queues of subscribers no longer in the live set (lazy, one round late). */
|
|
371
|
-
private reconcileQueues(pushState: PushState, subscriberIds: readonly string[]): void {
|
|
372
|
-
const live = new Set(subscriberIds);
|
|
373
|
-
// Snapshot the keys: `remove` mutates the backing map, which would invalidate a live iterator.
|
|
374
|
-
for (const id of [...pushState.perSubscriberQueue.subscribers()]) {
|
|
375
|
-
if (!live.has(id)) {
|
|
376
|
-
pushState.perSubscriberQueue.remove(id);
|
|
377
|
-
}
|
|
378
|
-
}
|
|
379
|
-
}
|
|
380
|
-
|
|
381
|
-
/** Deliver one notification to one subscriber: self in-process, everyone else over the transport. */
|
|
382
|
-
private deliverTo(topicId: Uint8Array, subId: string, n: NotificationV1): void {
|
|
383
|
-
if (subId === this.selfPeerId) {
|
|
384
|
-
this.deliverInProcess(topicId, n);
|
|
385
|
-
} else {
|
|
386
|
-
this.dispatch(subId, n);
|
|
387
|
-
}
|
|
388
|
-
}
|
|
389
|
-
|
|
390
|
-
/** Route to a co-located subscription manager, isolating a throwing subscriber from the rest of the fan-out. */
|
|
391
|
-
private deliverInProcess(topicId: Uint8Array, n: NotificationV1): void {
|
|
392
|
-
if (this.deliverLocal === undefined) {
|
|
393
|
-
return;
|
|
394
|
-
}
|
|
395
|
-
try {
|
|
396
|
-
this.deliverLocal(topicId, n);
|
|
397
|
-
} catch (err) {
|
|
398
|
-
log("local delivery threw (isolated) for rev=%d: %o", n.revision, err);
|
|
399
|
-
}
|
|
400
|
-
}
|
|
401
|
-
|
|
402
|
-
/** Fire one unicast send, isolated: a synchronous throw or a rejection is swallowed, never the loop's concern. */
|
|
403
|
-
private dispatch(target: string, n: NotificationV1): void {
|
|
404
|
-
let pending: Promise<void>;
|
|
405
|
-
try {
|
|
406
|
-
pending = this.transport.send(target, n);
|
|
407
|
-
} catch (err) {
|
|
408
|
-
log("notify send to %s threw synchronously (isolated): %o", target, err);
|
|
409
|
-
return;
|
|
410
|
-
}
|
|
411
|
-
void pending.catch((err: unknown) => {
|
|
412
|
-
log("notify send to %s rejected (isolated): %o", target, err);
|
|
413
|
-
});
|
|
414
|
-
}
|
|
415
|
-
|
|
416
|
-
/** Resolve (instantiating once, behind the Edge gate) the served state for a topic. */
|
|
417
|
-
private resolveServed(topicId: Uint8Array, n: NotificationV1, key: string): ServedTopic | null {
|
|
418
|
-
const existing = this.served.get(key);
|
|
419
|
-
if (existing !== undefined) {
|
|
420
|
-
return existing; // a `ServedTopic` or a remembered `null` (Edge / subscriber-only)
|
|
421
|
-
}
|
|
422
|
-
const pushState = instantiateForwarderPushState(this.profile, this.pushStateInit(topicId, n));
|
|
423
|
-
if (pushState === undefined) {
|
|
424
|
-
this.served.set(key, null); // Edge node: remember it never forwards this topic.
|
|
425
|
-
return null;
|
|
426
|
-
}
|
|
427
|
-
const served: ServedTopic = {
|
|
428
|
-
pushState,
|
|
429
|
-
forwarder: createReactivityForwarder({ state: pushState, verifier: this.verifierFor(topicId) }),
|
|
430
|
-
};
|
|
431
|
-
this.served.set(key, served);
|
|
432
|
-
return served;
|
|
433
|
-
}
|
|
434
|
-
|
|
435
|
-
private topicKey(topicId: Uint8Array): string {
|
|
436
|
-
return bytesToB64url(topicId);
|
|
437
|
-
}
|
|
438
|
-
}
|
|
1
|
+
/**
|
|
2
|
+
* Reactivity — forwarder **host** orchestrator (`docs/reactivity.md` §Propagation, §Slow-subscriber
|
|
3
|
+
* backpressure, §Per-cohort policy).
|
|
4
|
+
*
|
|
5
|
+
* This is the piece that turns the in-process forward *decision* (db-core's {@link ReactivityForwarder})
|
|
6
|
+
* into live fan-out over the {@link ReactivityNotifyTransport}. For one {@link NotificationV1} — whether
|
|
7
|
+
* locally originated (the change-bridge's `emit` seam binds to {@link ReactivityForwarderHost.ingest}) or
|
|
8
|
+
* inbound off a dial ({@link ReactivityForwarderHost.onInbound}) — it:
|
|
9
|
+
*
|
|
10
|
+
* 1. lazily instantiates the per-collection {@link PushState} + forwarder behind the Edge policy gate
|
|
11
|
+
* ({@link instantiateForwarderPushState}: `undefined` on an Edge node ⇒ this node never forwards);
|
|
12
|
+
* 2. runs the db-core receive path (verify → dedupe → buffer) and stops on `"duplicate"` / `"untrusted"`;
|
|
13
|
+
* 3. on `"forward"`, fans the **unmodified** frame out to every direct subscriber (through the
|
|
14
|
+
* per-subscriber bounded queue, so a slow/dead subscriber's drops never stall the rest) and every
|
|
15
|
+
* child cohort.
|
|
16
|
+
*
|
|
17
|
+
* It owns the per-subscriber dequeue→dial delivery loop, the bounded-queue backpressure interaction,
|
|
18
|
+
* subscriber-queue eviction (the memory bound — a departed subscriber's queue is reclaimed lazily each
|
|
19
|
+
* fan-out round), and per-topic serialization so the replay ring + dedupe set never interleave across two
|
|
20
|
+
* concurrent notifications for the same collection.
|
|
21
|
+
*
|
|
22
|
+
* **Subscriber-id space.** `selfPeerId`, the {@link ReactivityForwarderHostDeps.directSubscribers} output,
|
|
23
|
+
* the {@link CohortRef.primary} child targets, and every {@link ReactivityNotifyTransport.send} target are
|
|
24
|
+
* the **same** string space (it is also the `perSubscriberQueue` key). This host is agnostic to the concrete
|
|
25
|
+
* encoding so long as it is consistent across all four seams; the **transport** pins which space —
|
|
26
|
+
* {@link import("./notify-transport.js").Libp2pReactivityNotifyTransport.send} calls `peerIdFromString`, so
|
|
27
|
+
* the space is the **canonical peer-id string** (NOT base64url-of-member-bytes — that would silently fail
|
|
28
|
+
* `peerIdFromString` and never dial). The {@link reactivityDirectSubscribers} adapter and the node-wiring
|
|
29
|
+
* layer ([reactivity-notification-transport]) therefore both emit peer-id strings.
|
|
30
|
+
*
|
|
31
|
+
* This module deliberately touches neither the libp2p node assembly ([reactivity-notification-transport])
|
|
32
|
+
* nor gossip ([reactivity-pushstate-gossip]); it depends only on the transport interface + db-core logic,
|
|
33
|
+
* so it is unit-testable with a fake transport.
|
|
34
|
+
*/
|
|
35
|
+
|
|
36
|
+
import {
|
|
37
|
+
reactivityTopicId,
|
|
38
|
+
b64urlToBytes,
|
|
39
|
+
bytesToB64url,
|
|
40
|
+
createReactivityForwarder,
|
|
41
|
+
instantiateForwarderPushState,
|
|
42
|
+
decodeSubscribeAppPayload,
|
|
43
|
+
TailDrainGate,
|
|
44
|
+
type NotificationV1,
|
|
45
|
+
type PeerRef,
|
|
46
|
+
type NodeProfile,
|
|
47
|
+
type PushState,
|
|
48
|
+
type PushStateInit,
|
|
49
|
+
type CohortRef,
|
|
50
|
+
type NotificationVerifier,
|
|
51
|
+
type ReactivityForwarder,
|
|
52
|
+
type RegistrationRecord,
|
|
53
|
+
type RotationRedirectV1,
|
|
54
|
+
} from "@optimystic/db-core";
|
|
55
|
+
import type { ReactivityNotifyTransport } from "./notify-transport.js";
|
|
56
|
+
import { bytesToPeerIdString } from "../cohort-topic/peer-codec.js";
|
|
57
|
+
import { createLogger } from "../logger.js";
|
|
58
|
+
|
|
59
|
+
const log = createLogger("reactivity-forwarder-host");
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* The reactivity topic id a notification belongs to: `H(tailId ‖ "reactivity")` over the notification's
|
|
63
|
+
* tail anchor. Kept in one place so it matches origination's `reactivityTailBytes` encoding and the
|
|
64
|
+
* subscriber/forwarder verifier's coord derivation byte-for-byte (both decode `tailId` as base64url first).
|
|
65
|
+
*/
|
|
66
|
+
export function reactivityNotificationTopicId(n: NotificationV1): Uint8Array {
|
|
67
|
+
return reactivityTopicId(b64urlToBytes(n.tailId));
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** The minimal cohort read the {@link reactivityDirectSubscribers} adapter needs (a {@link CoordEngine} satisfies it). */
|
|
71
|
+
export interface ReactivityRecordSource {
|
|
72
|
+
/** This cohort's locally-known direct registration records for `topicId`. */
|
|
73
|
+
records(topicId: Uint8Array): readonly RegistrationRecord[];
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* The direct-subscriber **peer-id strings** for a reactivity topic, read from a cohort's
|
|
78
|
+
* {@link RegistrationRecord} set: a record carries a subscriber iff its opaque `appState` decodes to a
|
|
79
|
+
* reactivity {@link import("@optimystic/db-core").SubscribeAppPayloadV1}. `record.participantId` is the
|
|
80
|
+
* subscriber's dialable member id (db-core's `service` pins `participantId = self`), carried as
|
|
81
|
+
* `peerIdToBytes(peerId) = utf8(peerIdString)`; this decodes it back to the canonical peer-id string via
|
|
82
|
+
* {@link bytesToPeerIdString} so the value is both the `transport.send` dial target (which calls
|
|
83
|
+
* `peerIdFromString`) and the `perSubscriberQueue` key. **The whole host runs in this peer-id-string space**
|
|
84
|
+
* — `selfPeerId`, `resolveChildPrimary`, and every `send` target must agree, or a base64url-vs-peer-id
|
|
85
|
+
* mismatch is a silent no-dial. A record whose `appState` is absent or decodes to a non-reactivity payload
|
|
86
|
+
* (e.g. a matchmaking registration sharing the cohort store) is skipped.
|
|
87
|
+
*/
|
|
88
|
+
export function reactivityDirectSubscribers(source: ReactivityRecordSource, topicId: Uint8Array): string[] {
|
|
89
|
+
const out: string[] = [];
|
|
90
|
+
for (const record of source.records(topicId)) {
|
|
91
|
+
if (record.appState === undefined) {
|
|
92
|
+
continue;
|
|
93
|
+
}
|
|
94
|
+
try {
|
|
95
|
+
decodeSubscribeAppPayload(record.appState); // throws on a non-reactivity / malformed payload
|
|
96
|
+
} catch {
|
|
97
|
+
continue; // not a reactivity subscriber — leave the record to its own application
|
|
98
|
+
}
|
|
99
|
+
out.push(bytesToPeerIdString(record.participantId));
|
|
100
|
+
}
|
|
101
|
+
return out;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Construction inputs for a {@link ReactivityForwarderHost}. */
|
|
105
|
+
export interface ReactivityForwarderHostDeps {
|
|
106
|
+
/** One-way notification transport (unicast send + inbound subscribe); fan-out dials each target through it. */
|
|
107
|
+
readonly transport: ReactivityNotifyTransport;
|
|
108
|
+
/** This node's member id, base64url — never dialed; a co-located subscriber is delivered in-process. */
|
|
109
|
+
readonly selfPeerId: string;
|
|
110
|
+
/** Node profile; gates {@link PushState} instantiation (Edge ⇒ subscriber-only, never forwards). */
|
|
111
|
+
readonly profile: NodeProfile;
|
|
112
|
+
/** Build the per-collection {@link PushStateInit} on first ingest for a topic this node serves. */
|
|
113
|
+
readonly pushStateInit: (topicId: Uint8Array, n: NotificationV1) => PushStateInit;
|
|
114
|
+
/** The notification verifier for a topic (a db-core `createNotificationVerifier` over the host's service verifier, T3). */
|
|
115
|
+
readonly verifierFor: (topicId: Uint8Array) => NotificationVerifier;
|
|
116
|
+
/** Direct-subscriber member ids (base64url) for a topic — e.g. {@link reactivityDirectSubscribers} over the cohort. */
|
|
117
|
+
readonly directSubscribers: (topicId: Uint8Array) => string[];
|
|
118
|
+
/** Resolve a child cohort's dialable primary when {@link CohortRef.primary} is absent (e.g. a FRET resolver). */
|
|
119
|
+
readonly resolveChildPrimary?: (ref: CohortRef) => string | undefined;
|
|
120
|
+
/**
|
|
121
|
+
* Route an inbound notification to a co-located subscription manager, when this node also subscribes the
|
|
122
|
+
* topic. **Must be idempotent on `(collectionId, revision)`**: on the {@link ReactivityForwarderHost.onInbound}
|
|
123
|
+
* path a node that is both a cohort member *and* a subscriber invokes this **twice** for the same
|
|
124
|
+
* notification — once in the subscriber role (directly) and once in the forwarder role (when `self` is in
|
|
125
|
+
* {@link directSubscribers}, via `fanOut`'s self-delivery). The db-core subscriber's `(collectionId,
|
|
126
|
+
* revision)` dedupe (`createReactivitySubscriber`) collapses the second call to a no-op, so a correctly
|
|
127
|
+
* wired manager delivers exactly once; a sink without that dedupe would double-deliver.
|
|
128
|
+
*/
|
|
129
|
+
readonly deliverLocal?: (topicId: Uint8Array, n: NotificationV1) => void;
|
|
130
|
+
/** Wall clock (unix ms) stamped on `receive`. Default `Date.now`. */
|
|
131
|
+
readonly clock?: () => number;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** A topic this node forwards: its live {@link PushState} and the forwarder driving the receive path over it. */
|
|
135
|
+
interface ServedTopic {
|
|
136
|
+
readonly pushState: PushState;
|
|
137
|
+
readonly forwarder: ReactivityForwarder;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* The reactivity fan-out orchestrator. Build one per node; it serves every reactivity topic the node is a
|
|
142
|
+
* cohort member for, lazily instantiating per-collection state on first ingest. Bind
|
|
143
|
+
* {@link ReactivityForwarderHost.ingest} to the origination `emit` seam and
|
|
144
|
+
* {@link ReactivityForwarderHost.onInbound} to the transport's inbound subscribe.
|
|
145
|
+
*/
|
|
146
|
+
export class ReactivityForwarderHost {
|
|
147
|
+
private readonly transport: ReactivityNotifyTransport;
|
|
148
|
+
private readonly selfPeerId: string;
|
|
149
|
+
private readonly profile: NodeProfile;
|
|
150
|
+
private readonly pushStateInit: (topicId: Uint8Array, n: NotificationV1) => PushStateInit;
|
|
151
|
+
private readonly verifierFor: (topicId: Uint8Array) => NotificationVerifier;
|
|
152
|
+
private readonly directSubscribers: (topicId: Uint8Array) => string[];
|
|
153
|
+
private readonly resolveChildPrimary?: (ref: CohortRef) => string | undefined;
|
|
154
|
+
private readonly deliverLocal?: (topicId: Uint8Array, n: NotificationV1) => void;
|
|
155
|
+
private readonly clock: () => number;
|
|
156
|
+
|
|
157
|
+
/** Per-topic served state. `ServedTopic` ⇒ forwards; `null` ⇒ resolved subscriber-only (Edge); absent ⇒ unresolved. */
|
|
158
|
+
private readonly served = new Map<string, ServedTopic | null>();
|
|
159
|
+
/** Per-topic serialization tail: an ingest chains onto its topic's prior ingest so the ring/dedupe never interleave. */
|
|
160
|
+
private readonly ingestTails = new Map<string, Promise<void>>();
|
|
161
|
+
/**
|
|
162
|
+
* Per **old-topic** drain gate: set by {@link markRotated} when this node observes the collection's tail
|
|
163
|
+
* rotate, keyed by the outgoing tail's topicId (base64url). For `T_drain` after the rotation
|
|
164
|
+
* {@link rotationRedirectFor} answers a recover request reaching the outgoing tail with the gate's
|
|
165
|
+
* {@link RotationRedirectV1} ("this moved — go to the new tree"); once the window closes the entry is
|
|
166
|
+
* evicted along with the topic's served `PushState`.
|
|
167
|
+
*/
|
|
168
|
+
private readonly rotationGates = new Map<string, TailDrainGate>();
|
|
169
|
+
|
|
170
|
+
constructor(deps: ReactivityForwarderHostDeps) {
|
|
171
|
+
this.transport = deps.transport;
|
|
172
|
+
this.selfPeerId = deps.selfPeerId;
|
|
173
|
+
this.profile = deps.profile;
|
|
174
|
+
this.pushStateInit = deps.pushStateInit;
|
|
175
|
+
this.verifierFor = deps.verifierFor;
|
|
176
|
+
this.directSubscribers = deps.directSubscribers;
|
|
177
|
+
this.resolveChildPrimary = deps.resolveChildPrimary;
|
|
178
|
+
this.deliverLocal = deps.deliverLocal;
|
|
179
|
+
this.clock = deps.clock ?? ((): number => Date.now());
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* Local origination emit **and** the inbound forwarder path: receive → forward → fan-out for one
|
|
184
|
+
* notification on `topicId`. Ingests for one topic run strictly in sequence (verify is async and the
|
|
185
|
+
* replay ring + dedupe set must not interleave); ingests for different topics proceed concurrently.
|
|
186
|
+
* Never rejects — a fan-out fault can never surface as a commit failure on the origination seam.
|
|
187
|
+
*/
|
|
188
|
+
ingest(topicId: Uint8Array, n: NotificationV1): Promise<void> {
|
|
189
|
+
const key = this.topicKey(topicId);
|
|
190
|
+
const prev = this.ingestTails.get(key) ?? Promise.resolve();
|
|
191
|
+
// Run regardless of the prior ingest's outcome; `ingestSerialized` isolates its own throws, so the
|
|
192
|
+
// chain never accumulates a rejection that would leak out of a later `ingest`.
|
|
193
|
+
const next = prev.then(
|
|
194
|
+
() => this.ingestSerialized(topicId, n, key),
|
|
195
|
+
() => this.ingestSerialized(topicId, n, key),
|
|
196
|
+
);
|
|
197
|
+
this.ingestTails.set(key, next);
|
|
198
|
+
return next;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/** One serialized ingest: resolve served state, run receive, fan out on `"forward"`. Isolates all throws. */
|
|
202
|
+
private async ingestSerialized(topicId: Uint8Array, n: NotificationV1, key: string): Promise<void> {
|
|
203
|
+
try {
|
|
204
|
+
const served = this.resolveServed(topicId, n, key);
|
|
205
|
+
if (served === null) {
|
|
206
|
+
return; // Edge / subscriber-only: this node never forwards (delivery rides onInbound → deliverLocal).
|
|
207
|
+
}
|
|
208
|
+
const decision = await served.forwarder.receive(n, this.clock());
|
|
209
|
+
if (decision !== "forward") {
|
|
210
|
+
return; // "duplicate" (already buffered) or "untrusted" (dropped before any state mutation).
|
|
211
|
+
}
|
|
212
|
+
this.fanOut(topicId, served.pushState, n);
|
|
213
|
+
} catch (err) {
|
|
214
|
+
log("ingest failed for topic=%s rev=%d (isolated): %o", key, n.revision, err);
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* Inbound notify dial: run the **subscriber** role (in-process delivery to a co-located manager) and the
|
|
220
|
+
* **forwarder** role (receive + fan-out) as applicable. A node that is both a cohort member and a
|
|
221
|
+
* subscriber does both — the forwarder dedupe + the subscriber's `(collectionId, revision)` dedupe keep
|
|
222
|
+
* it idempotent. Never rejects.
|
|
223
|
+
*/
|
|
224
|
+
async onInbound(_from: PeerRef, n: NotificationV1): Promise<void> {
|
|
225
|
+
let topicId: Uint8Array;
|
|
226
|
+
try {
|
|
227
|
+
topicId = reactivityNotificationTopicId(n);
|
|
228
|
+
} catch (err) {
|
|
229
|
+
log("onInbound: undecodable tailId on rev=%d (dropped): %o", n.revision, err);
|
|
230
|
+
return;
|
|
231
|
+
}
|
|
232
|
+
// Subscriber role first: deliver in-process to a co-located subscription manager, if any.
|
|
233
|
+
this.deliverInProcess(topicId, n);
|
|
234
|
+
// Forwarder role: ingest self-gates (Edge ⇒ no PushState; a non-member ⇒ empty fan-out).
|
|
235
|
+
await this.ingest(topicId, n);
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/** The live {@link PushState} for a served topic, or `undefined` (Edge, or not yet ingested). Test/diagnostic. */
|
|
239
|
+
pushStateFor(topicId: Uint8Array): PushState | undefined {
|
|
240
|
+
const served = this.served.get(this.topicKey(topicId));
|
|
241
|
+
return served === undefined || served === null ? undefined : served.pushState;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* Every live forwarder {@link PushState} this node currently serves: the topics it has ingested at least
|
|
246
|
+
* one notification for and instantiated state behind the Edge gate (subscriber-only `null`s and
|
|
247
|
+
* not-yet-ingested topics are skipped). The push-state-gossip driver iterates these each round to
|
|
248
|
+
* broadcast convergence state to each collection's cohort, so a member that missed an origin dial still
|
|
249
|
+
* ends up holding the replay entry.
|
|
250
|
+
*/
|
|
251
|
+
livePushStates(): PushState[] {
|
|
252
|
+
const out: PushState[] = [];
|
|
253
|
+
for (const served of this.served.values()) {
|
|
254
|
+
if (served !== null) {
|
|
255
|
+
out.push(served.pushState);
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
return out;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/**
|
|
262
|
+
* The live {@link PushState} this node serves for `collectionId` (base64url), or `undefined` if none.
|
|
263
|
+
* The served map is keyed by **topicId**, but a backfill request carries only a collectionId and a
|
|
264
|
+
* resume that lost its tail must still resolve the collection's current tail — so this scans for the
|
|
265
|
+
* served topic whose `PushState.collectionId` matches. Across a tail-rotation **drain window** a
|
|
266
|
+
* collection can briefly have two served topics (the outgoing and incoming tail); the one with the
|
|
267
|
+
* highest `lastRevision` is the current tail, so that is the one returned. (The precise drain-window
|
|
268
|
+
* redirect choreography is `reactivity-tail-rotation-transport`'s; this picks the current tail.)
|
|
269
|
+
*/
|
|
270
|
+
pushStateForCollection(collectionId: string): PushState | undefined {
|
|
271
|
+
let best: PushState | undefined;
|
|
272
|
+
for (const served of this.served.values()) {
|
|
273
|
+
if (served === null || served.pushState.collectionId !== collectionId) {
|
|
274
|
+
continue;
|
|
275
|
+
}
|
|
276
|
+
if (best === undefined || served.pushState.lastRevision > best.lastRevision) {
|
|
277
|
+
best = served.pushState;
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
return best;
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/**
|
|
284
|
+
* Record that the topic anchored on `oldTopicId` has **rotated** to a successor tail, starting a
|
|
285
|
+
* {@link TailDrainGate} so the outgoing tail bounces recover requests to the new tree for `T_drain`
|
|
286
|
+
* (`docs/reactivity.md` §Tail rotation step 2). db-core derives the redirect's `newTopicId` internally via
|
|
287
|
+
* `reactivityTopicId(newTailId)`. The trigger is origination observing the collection's `event.tailId`
|
|
288
|
+
* change ({@link reactivity-rotation-host-wiring-e2e}); this seam is called directly in unit tests.
|
|
289
|
+
*
|
|
290
|
+
* **Idempotent / chained.** A second `markRotated` for the **same** successor is a no-op; a `markRotated`
|
|
291
|
+
* to a **later** successor (higher `effectiveAtRevision`) replaces the gate — so a chained OLD→A→B rotation
|
|
292
|
+
* advances the redirect to the most recent successor and restarts its drain window from `now`. An earlier
|
|
293
|
+
* (or equal) successor leaves the existing gate untouched.
|
|
294
|
+
*/
|
|
295
|
+
markRotated(oldTopicId: Uint8Array, redirect: { newTailId: string; effectiveAtRevision: number }, now: number): void {
|
|
296
|
+
const key = this.topicKey(oldTopicId);
|
|
297
|
+
const existing = this.rotationGates.get(key);
|
|
298
|
+
if (existing !== undefined && redirect.effectiveAtRevision <= existing.rotationRedirect.effectiveAtRevision) {
|
|
299
|
+
return; // same or earlier successor — the gate already points at this-or-a-later tail.
|
|
300
|
+
}
|
|
301
|
+
this.rotationGates.set(key, new TailDrainGate({
|
|
302
|
+
rotatedAt: now,
|
|
303
|
+
newTailId: redirect.newTailId,
|
|
304
|
+
effectiveAtRevision: redirect.effectiveAtRevision,
|
|
305
|
+
}));
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/**
|
|
309
|
+
* The drain-window redirect for a recover request that reached the outgoing tail anchored on `oldTopicId`,
|
|
310
|
+
* or `undefined` if this topic never rotated / its drain window has elapsed. While the gate is draining
|
|
311
|
+
* (`isDraining(now)`) returns its {@link RotationRedirectV1}; once `T_drain` closes, evicts the gate **and**
|
|
312
|
+
* the topic's served `PushState` (the old tail originates nothing further — this also reclaims the
|
|
313
|
+
* `served` / `ingestTails` maps the 12.31 review flagged as un-evicted on rotation) and returns `undefined`,
|
|
314
|
+
* so the next request gets no reply and the subscriber re-walks / chain-reads.
|
|
315
|
+
*/
|
|
316
|
+
rotationRedirectFor(oldTopicId: Uint8Array, now: number): RotationRedirectV1 | undefined {
|
|
317
|
+
const key = this.topicKey(oldTopicId);
|
|
318
|
+
const gate = this.rotationGates.get(key);
|
|
319
|
+
if (gate === undefined) {
|
|
320
|
+
return undefined;
|
|
321
|
+
}
|
|
322
|
+
if (gate.isDraining(now)) {
|
|
323
|
+
return gate.rotationRedirect;
|
|
324
|
+
}
|
|
325
|
+
// Drain window closed: the outgoing tail is done. Drop the gate and reclaim its served state so the
|
|
326
|
+
// per-topic maps don't leak across rotations.
|
|
327
|
+
this.rotationGates.delete(key);
|
|
328
|
+
this.served.delete(key);
|
|
329
|
+
this.ingestTails.delete(key);
|
|
330
|
+
return undefined;
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
/**
|
|
334
|
+
* Fan the unmodified frame out: reconcile (GC) departed-subscriber queues, enqueue per-subscriber
|
|
335
|
+
* (drop-oldest under pressure), drain each queue and deliver (self in-process, others dialed, per-target
|
|
336
|
+
* isolated), then dial each resolved child cohort. One slow/dead target never blocks the loop for the rest.
|
|
337
|
+
*/
|
|
338
|
+
private fanOut(topicId: Uint8Array, pushState: PushState, n: NotificationV1): void {
|
|
339
|
+
const subscriberIds = this.directSubscribers(topicId);
|
|
340
|
+
|
|
341
|
+
// Memory bound: drop any per-subscriber queue whose id left the live set (departed / TTL-expired /
|
|
342
|
+
// withdrawn). The map can never grow past the live subscriber set + the current round (lazy GC, so it
|
|
343
|
+
// shrinks at most one fan-out round late) — this satisfies the `subscribers × queue_max × size` bound.
|
|
344
|
+
this.reconcileQueues(pushState, subscriberIds);
|
|
345
|
+
|
|
346
|
+
// Enqueue onto each subscriber's bounded queue (a slow subscriber's drop-oldest isolates to its queue).
|
|
347
|
+
pushState.enqueueForSubscribers(subscriberIds, n);
|
|
348
|
+
|
|
349
|
+
// Drain + deliver per subscriber, isolated: one dead subscriber's dial never stalls the others.
|
|
350
|
+
for (const subId of subscriberIds) {
|
|
351
|
+
const queue = pushState.perSubscriberQueue.peekQueue(subId);
|
|
352
|
+
if (queue === undefined) {
|
|
353
|
+
continue;
|
|
354
|
+
}
|
|
355
|
+
for (const m of queue.drain()) {
|
|
356
|
+
this.deliverTo(topicId, subId, m);
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
// Child cohorts get the unmodified frame (forwarders never re-sign). No-op until the parent/child link
|
|
361
|
+
// lands ([cohort-topic-parent-child-link]) populates `childCohorts`.
|
|
362
|
+
for (const ref of pushState.childCohorts) {
|
|
363
|
+
const target = ref.primary ?? this.resolveChildPrimary?.(ref);
|
|
364
|
+
if (target !== undefined && target !== this.selfPeerId) {
|
|
365
|
+
this.dispatch(target, n);
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/** Reclaim the queues of subscribers no longer in the live set (lazy, one round late). */
|
|
371
|
+
private reconcileQueues(pushState: PushState, subscriberIds: readonly string[]): void {
|
|
372
|
+
const live = new Set(subscriberIds);
|
|
373
|
+
// Snapshot the keys: `remove` mutates the backing map, which would invalidate a live iterator.
|
|
374
|
+
for (const id of [...pushState.perSubscriberQueue.subscribers()]) {
|
|
375
|
+
if (!live.has(id)) {
|
|
376
|
+
pushState.perSubscriberQueue.remove(id);
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
/** Deliver one notification to one subscriber: self in-process, everyone else over the transport. */
|
|
382
|
+
private deliverTo(topicId: Uint8Array, subId: string, n: NotificationV1): void {
|
|
383
|
+
if (subId === this.selfPeerId) {
|
|
384
|
+
this.deliverInProcess(topicId, n);
|
|
385
|
+
} else {
|
|
386
|
+
this.dispatch(subId, n);
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/** Route to a co-located subscription manager, isolating a throwing subscriber from the rest of the fan-out. */
|
|
391
|
+
private deliverInProcess(topicId: Uint8Array, n: NotificationV1): void {
|
|
392
|
+
if (this.deliverLocal === undefined) {
|
|
393
|
+
return;
|
|
394
|
+
}
|
|
395
|
+
try {
|
|
396
|
+
this.deliverLocal(topicId, n);
|
|
397
|
+
} catch (err) {
|
|
398
|
+
log("local delivery threw (isolated) for rev=%d: %o", n.revision, err);
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
/** Fire one unicast send, isolated: a synchronous throw or a rejection is swallowed, never the loop's concern. */
|
|
403
|
+
private dispatch(target: string, n: NotificationV1): void {
|
|
404
|
+
let pending: Promise<void>;
|
|
405
|
+
try {
|
|
406
|
+
pending = this.transport.send(target, n);
|
|
407
|
+
} catch (err) {
|
|
408
|
+
log("notify send to %s threw synchronously (isolated): %o", target, err);
|
|
409
|
+
return;
|
|
410
|
+
}
|
|
411
|
+
void pending.catch((err: unknown) => {
|
|
412
|
+
log("notify send to %s rejected (isolated): %o", target, err);
|
|
413
|
+
});
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
/** Resolve (instantiating once, behind the Edge gate) the served state for a topic. */
|
|
417
|
+
private resolveServed(topicId: Uint8Array, n: NotificationV1, key: string): ServedTopic | null {
|
|
418
|
+
const existing = this.served.get(key);
|
|
419
|
+
if (existing !== undefined) {
|
|
420
|
+
return existing; // a `ServedTopic` or a remembered `null` (Edge / subscriber-only)
|
|
421
|
+
}
|
|
422
|
+
const pushState = instantiateForwarderPushState(this.profile, this.pushStateInit(topicId, n));
|
|
423
|
+
if (pushState === undefined) {
|
|
424
|
+
this.served.set(key, null); // Edge node: remember it never forwards this topic.
|
|
425
|
+
return null;
|
|
426
|
+
}
|
|
427
|
+
const served: ServedTopic = {
|
|
428
|
+
pushState,
|
|
429
|
+
forwarder: createReactivityForwarder({ state: pushState, verifier: this.verifierFor(topicId) }),
|
|
430
|
+
};
|
|
431
|
+
this.served.set(key, served);
|
|
432
|
+
return served;
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
private topicKey(topicId: Uint8Array): string {
|
|
436
|
+
return bytesToB64url(topicId);
|
|
437
|
+
}
|
|
438
|
+
}
|