@peerbit/pubsub 4.1.4-07ba572 → 4.1.4-14881a0

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.
Files changed (46) hide show
  1. package/README.md +23 -20
  2. package/dist/benchmark/fanout-tree-sim-lib.d.ts +201 -0
  3. package/dist/benchmark/fanout-tree-sim-lib.d.ts.map +1 -0
  4. package/dist/benchmark/fanout-tree-sim-lib.js +1225 -0
  5. package/dist/benchmark/fanout-tree-sim-lib.js.map +1 -0
  6. package/dist/benchmark/fanout-tree-sim.d.ts +11 -0
  7. package/dist/benchmark/fanout-tree-sim.d.ts.map +1 -0
  8. package/dist/benchmark/fanout-tree-sim.js +521 -0
  9. package/dist/benchmark/fanout-tree-sim.js.map +1 -0
  10. package/dist/benchmark/index.d.ts +6 -0
  11. package/dist/benchmark/index.d.ts.map +1 -1
  12. package/dist/benchmark/index.js +38 -80
  13. package/dist/benchmark/index.js.map +1 -1
  14. package/dist/benchmark/pubsub-topic-sim-lib.d.ts +82 -0
  15. package/dist/benchmark/pubsub-topic-sim-lib.d.ts.map +1 -0
  16. package/dist/benchmark/pubsub-topic-sim-lib.js +625 -0
  17. package/dist/benchmark/pubsub-topic-sim-lib.js.map +1 -0
  18. package/dist/benchmark/pubsub-topic-sim.d.ts +9 -0
  19. package/dist/benchmark/pubsub-topic-sim.d.ts.map +1 -0
  20. package/dist/benchmark/pubsub-topic-sim.js +116 -0
  21. package/dist/benchmark/pubsub-topic-sim.js.map +1 -0
  22. package/dist/benchmark/sim/bench-utils.d.ts +25 -0
  23. package/dist/benchmark/sim/bench-utils.d.ts.map +1 -0
  24. package/dist/benchmark/sim/bench-utils.js +141 -0
  25. package/dist/benchmark/sim/bench-utils.js.map +1 -0
  26. package/dist/src/fanout-channel.d.ts +62 -0
  27. package/dist/src/fanout-channel.d.ts.map +1 -0
  28. package/dist/src/fanout-channel.js +114 -0
  29. package/dist/src/fanout-channel.js.map +1 -0
  30. package/dist/src/fanout-tree.d.ts +550 -0
  31. package/dist/src/fanout-tree.d.ts.map +1 -0
  32. package/dist/src/fanout-tree.js +4943 -0
  33. package/dist/src/fanout-tree.js.map +1 -0
  34. package/dist/src/index.d.ts +162 -39
  35. package/dist/src/index.d.ts.map +1 -1
  36. package/dist/src/index.js +1376 -455
  37. package/dist/src/index.js.map +1 -1
  38. package/dist/src/topic-root-control-plane.d.ts +43 -0
  39. package/dist/src/topic-root-control-plane.d.ts.map +1 -0
  40. package/dist/src/topic-root-control-plane.js +120 -0
  41. package/dist/src/topic-root-control-plane.js.map +1 -0
  42. package/package.json +10 -9
  43. package/src/fanout-channel.ts +150 -0
  44. package/src/fanout-tree.ts +6297 -0
  45. package/src/index.ts +1638 -593
  46. package/src/topic-root-control-plane.ts +160 -0
package/src/index.ts CHANGED
@@ -1,4 +1,7 @@
1
- import { type PeerId as Libp2pPeerId } from "@libp2p/interface";
1
+ import {
2
+ type Connection,
3
+ type PeerId as Libp2pPeerId,
4
+ } from "@libp2p/interface";
2
5
  import { PublicSignKey, getPublicKeyFromPeerId } from "@peerbit/crypto";
3
6
  import { logger as loggerFn } from "@peerbit/logger";
4
7
  import {
@@ -12,6 +15,7 @@ import {
12
15
  Subscribe,
13
16
  SubscriptionData,
14
17
  SubscriptionEvent,
18
+ TopicRootCandidates,
15
19
  UnsubcriptionEvent,
16
20
  Unsubscribe,
17
21
  } from "@peerbit/pubsub-interface";
@@ -23,6 +27,7 @@ import {
23
27
  dontThrowIfDeliveryError,
24
28
  } from "@peerbit/stream";
25
29
  import {
30
+ AcknowledgeAnyWhere,
26
31
  AcknowledgeDelivery,
27
32
  AnyWhere,
28
33
  DataMessage,
@@ -31,9 +36,10 @@ import {
31
36
  MessageHeader,
32
37
  NotStartedError,
33
38
  type PriorityOptions,
34
- SeekDelivery,
35
39
  SilentDelivery,
40
+ type WithExtraSigners,
36
41
  deliveryModeHasReceiver,
42
+ getMsgId,
37
43
  } from "@peerbit/stream-interface";
38
44
  import { AbortError, TimeoutError } from "@peerbit/time";
39
45
  import { Uint8ArrayList } from "uint8arraylist";
@@ -41,11 +47,23 @@ import {
41
47
  type DebouncedAccumulatorCounterMap,
42
48
  debouncedAccumulatorSetCounter,
43
49
  } from "./debounced-set.js";
50
+ import { FanoutChannel } from "./fanout-channel.js";
51
+ import type {
52
+ FanoutTree,
53
+ FanoutTreeChannelOptions,
54
+ FanoutTreeDataEvent,
55
+ FanoutTreeJoinOptions,
56
+ } from "./fanout-tree.js";
57
+ import { TopicRootControlPlane } from "./topic-root-control-plane.js";
58
+
59
+ export * from "./fanout-tree.js";
60
+ export * from "./fanout-channel.js";
61
+ export * from "./topic-root-control-plane.js";
44
62
 
45
63
  export const toUint8Array = (arr: Uint8ArrayList | Uint8Array) =>
46
64
  arr instanceof Uint8ArrayList ? arr.subarray() : arr;
47
65
 
48
- export const logger = loggerFn("peerbit:transport:lazysub");
66
+ export const logger = loggerFn("peerbit:transport:topic-control-plane");
49
67
  const warn = logger.newScope("warn");
50
68
  const logError = (e?: { message: string }) => {
51
69
  logger.error(e?.message);
@@ -54,476 +72,1420 @@ const logErrorIfStarted = (e?: { message: string }) => {
54
72
  e instanceof NotStartedError === false && logError(e);
55
73
  };
56
74
 
57
- export interface PeerStreamsInit {
58
- id: Libp2pPeerId;
59
- protocol: string;
60
- }
75
+ const withAbort = async <T>(promise: Promise<T>, signal?: AbortSignal): Promise<T> => {
76
+ if (!signal) return promise;
77
+ if (signal.aborted) {
78
+ throw signal.reason ?? new AbortError("Operation was aborted");
79
+ }
80
+ return new Promise<T>((resolve, reject) => {
81
+ const onAbort = () => {
82
+ cleanup();
83
+ reject(signal.reason ?? new AbortError("Operation was aborted"));
84
+ };
85
+ const cleanup = () => {
86
+ try {
87
+ signal.removeEventListener("abort", onAbort);
88
+ } catch {
89
+ // ignore
90
+ }
91
+ };
92
+ signal.addEventListener("abort", onAbort, { once: true });
93
+ promise.then(
94
+ (v) => {
95
+ cleanup();
96
+ resolve(v);
97
+ },
98
+ (e) => {
99
+ cleanup();
100
+ reject(e);
101
+ },
102
+ );
103
+ });
104
+ };
105
+
106
+ const SUBSCRIBER_CACHE_MAX_ENTRIES_HARD_CAP = 100_000;
107
+ const SUBSCRIBER_CACHE_DEFAULT_MAX_ENTRIES = 4_096;
108
+ const DEFAULT_FANOUT_PUBLISH_IDLE_CLOSE_MS = 60_000;
109
+ const DEFAULT_FANOUT_PUBLISH_MAX_EPHEMERAL_CHANNELS = 64;
110
+ const DEFAULT_PUBSUB_SHARD_COUNT = 256;
111
+ const PUBSUB_SHARD_COUNT_HARD_CAP = 16_384;
112
+ const DEFAULT_PUBSUB_SHARD_TOPIC_PREFIX = "/peerbit/pubsub-shard/1/";
113
+ const AUTO_TOPIC_ROOT_CANDIDATES_MAX = 64;
114
+
115
+ const DEFAULT_PUBSUB_FANOUT_CHANNEL_OPTIONS: Omit<
116
+ FanoutTreeChannelOptions,
117
+ "role"
118
+ > = {
119
+ msgRate: 30,
120
+ msgSize: 1024,
121
+ uploadLimitBps: 5_000_000,
122
+ maxChildren: 24,
123
+ repair: true,
124
+ };
61
125
 
62
- export type DirectSubOptions = {
63
- aggregate: boolean; // if true, we will collect topic/subscriber info for all traffic
126
+ export type TopicControlPlaneOptions = DirectStreamOptions & {
127
+ dispatchEventOnSelfPublish?: boolean;
128
+ subscriptionDebounceDelay?: number;
129
+ topicRootControlPlane?: TopicRootControlPlane;
130
+ /**
131
+ * Fanout overlay used for sharded topic delivery.
132
+ */
133
+ fanout: FanoutTree;
134
+ /**
135
+ * Base fanout channel options for shard overlays (applies to both roots and nodes).
136
+ */
137
+ fanoutChannel?: Partial<Omit<FanoutTreeChannelOptions, "role">>;
138
+ /**
139
+ * Fanout channel overrides applied only when this node is the shard root.
140
+ */
141
+ fanoutRootChannel?: Partial<Omit<FanoutTreeChannelOptions, "role">>;
142
+ /**
143
+ * Fanout channel overrides applied when joining shard overlays as a node.
144
+ *
145
+ * This is the primary knob for "leaf-only" subscribers: set `maxChildren=0`
146
+ * for non-router nodes so they never become relays under churn.
147
+ */
148
+ fanoutNodeChannel?: Partial<Omit<FanoutTreeChannelOptions, "role">>;
149
+ /**
150
+ * Fanout join options for overlay topics.
151
+ */
152
+ fanoutJoin?: FanoutTreeJoinOptions;
153
+ /**
154
+ * Number of pubsub shards (overlays) used for topic delivery.
155
+ *
156
+ * Each user-topic deterministically maps to exactly one shard topic:
157
+ * `shard = hash(topic) % shardCount`, and subscription joins that shard overlay.
158
+ *
159
+ * Default: 256.
160
+ */
161
+ shardCount?: number;
162
+ /**
163
+ * Prefix used to form internal shard topics.
164
+ *
165
+ * Default: `/peerbit/pubsub-shard/1/`.
166
+ */
167
+ shardTopicPrefix?: string;
168
+ /**
169
+ * If enabled, this node will host (open as root) every shard for which it is
170
+ * the deterministically selected root.
171
+ *
172
+ * This is intended for "router"/"supernode" deployments.
173
+ *
174
+ * Default: `false`.
175
+ */
176
+ hostShards?: boolean;
177
+ /**
178
+ * Fanout-backed topics: require a local `subscribe(topic)` before `publish(topic)` is allowed.
179
+ *
180
+ * Default: `false` (publishing without subscribing will temporarily join the overlay).
181
+ */
182
+ fanoutPublishRequiresSubscribe?: boolean;
183
+ /**
184
+ * When publishing on a fanout topic without subscribing, keep the ephemeral join
185
+ * open for this long since the last publish, then auto-leave.
186
+ *
187
+ * Default: 60s. Set to `0` to close immediately after each publish.
188
+ */
189
+ fanoutPublishIdleCloseMs?: number;
190
+ /**
191
+ * Max number of ephemeral fanout channels kept open concurrently for publish-only usage.
192
+ *
193
+ * Default: 64. Set to `0` to disable caching (channels will close after publish).
194
+ */
195
+ fanoutPublishMaxEphemeralChannels?: number;
196
+ /**
197
+ * Best-effort bound on cached remote subscribers per topic.
198
+ *
199
+ * This controls memory growth at scale and bounds `getSubscribers()` and the
200
+ * receiver lists used for routing optimizations.
201
+ */
202
+ subscriberCacheMaxEntries?: number;
64
203
  };
65
204
 
66
- export type DirectSubComponents = DirectStreamComponents;
205
+ export type TopicControlPlaneComponents = DirectStreamComponents;
67
206
 
68
207
  export type PeerId = Libp2pPeerId | PublicSignKey;
69
208
 
70
- export class DirectSub extends DirectStream<PubSubEvents> implements PubSub {
71
- public topics: Map<string, Map<string, SubscriptionData>>; // topic -> peers --> Uint8Array subscription metadata (the latest received)
72
- public peerToTopic: Map<string, Set<string>>; // peer -> topics
73
- public topicsToPeers: Map<string, Set<string>>; // topic -> peers
74
- public subscriptions: Map<string, { counter: number }>; // topic -> subscription ids
75
- public lastSubscriptionMessages: Map<string, Map<string, DataMessage>> =
76
- new Map();
209
+ const topicHash32 = (topic: string) => {
210
+ let hash = 0x811c9dc5; // FNV-1a
211
+ for (let index = 0; index < topic.length; index++) {
212
+ hash ^= topic.charCodeAt(index);
213
+ hash = (hash * 0x01000193) >>> 0;
214
+ }
215
+ return hash >>> 0;
216
+ };
217
+
218
+ /**
219
+ * Runtime control-plane implementation for pubsub topic membership + forwarding.
220
+ */
221
+ export class TopicControlPlane
222
+ extends DirectStream<PubSubEvents>
223
+ implements PubSub
224
+ {
225
+ // Tracked topics -> remote subscribers (best-effort).
226
+ public topics: Map<string, Map<string, SubscriptionData>>;
227
+ // Remote peer -> tracked topics.
228
+ public peerToTopic: Map<string, Set<string>>;
229
+ // Local topic -> reference count.
230
+ public subscriptions: Map<string, { counter: number }>;
231
+ // Local topics requested via debounced subscribe, not yet applied in `subscriptions`.
232
+ private pendingSubscriptions: Set<string>;
233
+ public lastSubscriptionMessages: Map<string, Map<string, bigint>> = new Map();
77
234
  public dispatchEventOnSelfPublish: boolean;
235
+ public readonly topicRootControlPlane: TopicRootControlPlane;
236
+ public readonly subscriberCacheMaxEntries: number;
237
+ public readonly fanout: FanoutTree;
78
238
 
79
239
  private debounceSubscribeAggregator: DebouncedAccumulatorCounterMap;
80
240
  private debounceUnsubscribeAggregator: DebouncedAccumulatorCounterMap;
81
241
 
242
+ private readonly shardCount: number;
243
+ private readonly shardTopicPrefix: string;
244
+ private readonly hostShards: boolean;
245
+ private readonly shardRootCache = new Map<string, string>();
246
+ private readonly shardTopicCache = new Map<string, string>();
247
+ private readonly shardRefCounts = new Map<string, number>();
248
+ private readonly pinnedShards = new Set<string>();
249
+
250
+ private readonly fanoutRootChannelOptions: Omit<
251
+ FanoutTreeChannelOptions,
252
+ "role"
253
+ >;
254
+ private readonly fanoutNodeChannelOptions: Omit<
255
+ FanoutTreeChannelOptions,
256
+ "role"
257
+ >;
258
+ private readonly fanoutJoinOptions?: FanoutTreeJoinOptions;
259
+ private readonly fanoutPublishRequiresSubscribe: boolean;
260
+ private readonly fanoutPublishIdleCloseMs: number;
261
+ private readonly fanoutPublishMaxEphemeralChannels: number;
262
+
263
+ // If no shard-root candidates are configured, we fall back to an "auto" mode:
264
+ // start with `[self]` and expand candidates as underlay peers connect.
265
+ // This keeps small ad-hoc networks working without explicit bootstraps.
266
+ private autoTopicRootCandidates = false;
267
+ private autoTopicRootCandidateSet?: Set<string>;
268
+ private reconcileShardOverlaysInFlight?: Promise<void>;
269
+ private autoCandidatesBroadcastTimers: Array<ReturnType<typeof setTimeout>> =
270
+ [];
271
+ private autoCandidatesGossipInterval?: ReturnType<typeof setInterval>;
272
+ private autoCandidatesGossipUntil = 0;
273
+
274
+ private fanoutChannels = new Map<
275
+ string,
276
+ {
277
+ root: string;
278
+ channel: FanoutChannel;
279
+ join: Promise<void>;
280
+ onData: (ev: CustomEvent<FanoutTreeDataEvent>) => void;
281
+ onUnicast: (ev: any) => void;
282
+ ephemeral: boolean;
283
+ lastUsedAt: number;
284
+ idleCloseTimeout?: ReturnType<typeof setTimeout>;
285
+ }
286
+ >();
287
+
82
288
  constructor(
83
- components: DirectSubComponents,
84
- props?: DirectStreamOptions & {
85
- dispatchEventOnSelfPublish?: boolean;
86
- subscriptionDebounceDelay?: number;
87
- },
289
+ components: TopicControlPlaneComponents,
290
+ props?: TopicControlPlaneOptions,
88
291
  ) {
89
- super(components, ["/lazysub/0.0.0"], props);
292
+ super(components, ["/peerbit/topic-control-plane/2.0.0"], props);
90
293
  this.subscriptions = new Map();
294
+ this.pendingSubscriptions = new Set();
91
295
  this.topics = new Map();
92
- this.topicsToPeers = new Map();
93
296
  this.peerToTopic = new Map();
297
+
298
+ this.topicRootControlPlane =
299
+ props?.topicRootControlPlane || new TopicRootControlPlane();
94
300
  this.dispatchEventOnSelfPublish =
95
301
  props?.dispatchEventOnSelfPublish || false;
302
+
303
+ if (!props?.fanout) {
304
+ throw new Error(
305
+ "TopicControlPlane requires a FanoutTree instance (options.fanout)",
306
+ );
307
+ }
308
+ this.fanout = props.fanout;
309
+
310
+ // Default to a local-only shard-root candidate set so standalone peers can
311
+ // subscribe/publish without explicit bootstraps. We'll expand candidates
312
+ // opportunistically as neighbours connect.
313
+ if (this.topicRootControlPlane.getTopicRootCandidates().length === 0) {
314
+ this.autoTopicRootCandidates = true;
315
+ this.autoTopicRootCandidateSet = new Set([this.publicKeyHash]);
316
+ this.topicRootControlPlane.setTopicRootCandidates([this.publicKeyHash]);
317
+ }
318
+
319
+ const requestedShardCount = props?.shardCount ?? DEFAULT_PUBSUB_SHARD_COUNT;
320
+ this.shardCount = Math.min(
321
+ PUBSUB_SHARD_COUNT_HARD_CAP,
322
+ Math.max(1, Math.floor(requestedShardCount)),
323
+ );
324
+ const prefix = props?.shardTopicPrefix ?? DEFAULT_PUBSUB_SHARD_TOPIC_PREFIX;
325
+ this.shardTopicPrefix = prefix.endsWith("/") ? prefix : prefix + "/";
326
+ this.hostShards = props?.hostShards ?? false;
327
+
328
+ const baseFanoutChannelOptions = {
329
+ ...DEFAULT_PUBSUB_FANOUT_CHANNEL_OPTIONS,
330
+ ...(props?.fanoutChannel || {}),
331
+ } as Omit<FanoutTreeChannelOptions, "role">;
332
+ this.fanoutRootChannelOptions = {
333
+ ...baseFanoutChannelOptions,
334
+ ...(props?.fanoutRootChannel || {}),
335
+ } as Omit<FanoutTreeChannelOptions, "role">;
336
+ this.fanoutNodeChannelOptions = {
337
+ ...baseFanoutChannelOptions,
338
+ ...(props?.fanoutNodeChannel || {}),
339
+ } as Omit<FanoutTreeChannelOptions, "role">;
340
+ this.fanoutJoinOptions = props?.fanoutJoin;
341
+
342
+ this.fanoutPublishRequiresSubscribe =
343
+ props?.fanoutPublishRequiresSubscribe ?? false;
344
+ const requestedIdleCloseMs =
345
+ props?.fanoutPublishIdleCloseMs ?? DEFAULT_FANOUT_PUBLISH_IDLE_CLOSE_MS;
346
+ this.fanoutPublishIdleCloseMs = Math.max(
347
+ 0,
348
+ Math.floor(requestedIdleCloseMs),
349
+ );
350
+ const requestedMaxEphemeral =
351
+ props?.fanoutPublishMaxEphemeralChannels ??
352
+ DEFAULT_FANOUT_PUBLISH_MAX_EPHEMERAL_CHANNELS;
353
+ this.fanoutPublishMaxEphemeralChannels = Math.max(
354
+ 0,
355
+ Math.floor(requestedMaxEphemeral),
356
+ );
357
+
358
+ const requestedSubscriberCacheMaxEntries =
359
+ props?.subscriberCacheMaxEntries ?? SUBSCRIBER_CACHE_DEFAULT_MAX_ENTRIES;
360
+ this.subscriberCacheMaxEntries = Math.min(
361
+ SUBSCRIBER_CACHE_MAX_ENTRIES_HARD_CAP,
362
+ Math.max(1, Math.floor(requestedSubscriberCacheMaxEntries)),
363
+ );
364
+
96
365
  this.debounceSubscribeAggregator = debouncedAccumulatorSetCounter(
97
366
  (set) => this._subscribe([...set.values()]),
98
367
  props?.subscriptionDebounceDelay ?? 50,
99
368
  );
369
+ // NOTE: Unsubscribe should update local state immediately and batch only the
370
+ // best-effort network announcements to avoid teardown stalls (program close).
100
371
  this.debounceUnsubscribeAggregator = debouncedAccumulatorSetCounter(
101
- (set) => this._unsubscribe([...set.values()]),
372
+ (set) => this._announceUnsubscribe([...set.values()]),
102
373
  props?.subscriptionDebounceDelay ?? 50,
103
374
  );
104
375
  }
105
376
 
106
- stop() {
377
+ /**
378
+ * Configure deterministic topic-root candidates and disable the pubsub "auto"
379
+ * candidate mode.
380
+ *
381
+ * Auto mode is a convenience for small ad-hoc networks where no bootstraps/
382
+ * routers are configured. When an explicit candidate set is provided (e.g.
383
+ * from bootstraps or a test harness), we must stop mutating/gossiping the
384
+ * candidate set; otherwise shard root resolution can diverge and overlays can
385
+ * partition (especially in sparse graphs).
386
+ */
387
+ public setTopicRootCandidates(candidates: string[]) {
388
+ this.topicRootControlPlane.setTopicRootCandidates(candidates);
389
+
390
+ // Disable auto mode and stop its background gossip/timers.
391
+ this.autoTopicRootCandidates = false;
392
+ this.autoTopicRootCandidateSet = undefined;
393
+ for (const t of this.autoCandidatesBroadcastTimers) clearTimeout(t);
394
+ this.autoCandidatesBroadcastTimers = [];
395
+ if (this.autoCandidatesGossipInterval) {
396
+ clearInterval(this.autoCandidatesGossipInterval);
397
+ this.autoCandidatesGossipInterval = undefined;
398
+ }
399
+ this.autoCandidatesGossipUntil = 0;
400
+
401
+ // Re-resolve roots under the new mapping.
402
+ this.shardRootCache.clear();
403
+ // Only candidates can become deterministic roots. Avoid doing a full shard
404
+ // scan on non-candidates in large sessions.
405
+ if (candidates.includes(this.publicKeyHash)) {
406
+ void this.hostShardRootsNow().catch(() => {});
407
+ }
408
+ this.scheduleReconcileShardOverlays();
409
+ }
410
+
411
+ public override async start() {
412
+ await this.fanout.start();
413
+ await super.start();
414
+
415
+ if (this.hostShards) {
416
+ await this.hostShardRootsNow();
417
+ }
418
+ }
419
+
420
+ public override async stop() {
421
+ for (const st of this.fanoutChannels.values()) {
422
+ if (st.idleCloseTimeout) clearTimeout(st.idleCloseTimeout);
423
+ try {
424
+ st.channel.removeEventListener("data", st.onData as any);
425
+ } catch {
426
+ // ignore
427
+ }
428
+ try {
429
+ st.channel.removeEventListener("unicast", st.onUnicast as any);
430
+ } catch {
431
+ // ignore
432
+ }
433
+ try {
434
+ // Shutdown should be bounded and not depend on network I/O.
435
+ await st.channel.leave({ notifyParent: false, kickChildren: false });
436
+ } catch {
437
+ try {
438
+ st.channel.close();
439
+ } catch {
440
+ // ignore
441
+ }
442
+ }
443
+ }
444
+ this.fanoutChannels.clear();
445
+ for (const t of this.autoCandidatesBroadcastTimers) clearTimeout(t);
446
+ this.autoCandidatesBroadcastTimers = [];
447
+ if (this.autoCandidatesGossipInterval) {
448
+ clearInterval(this.autoCandidatesGossipInterval);
449
+ this.autoCandidatesGossipInterval = undefined;
450
+ }
451
+ this.autoCandidatesGossipUntil = 0;
452
+
107
453
  this.subscriptions.clear();
454
+ this.pendingSubscriptions.clear();
108
455
  this.topics.clear();
109
456
  this.peerToTopic.clear();
110
- this.topicsToPeers.clear();
457
+ this.lastSubscriptionMessages.clear();
458
+ this.shardRootCache.clear();
459
+ this.shardTopicCache.clear();
460
+ this.shardRefCounts.clear();
461
+ this.pinnedShards.clear();
462
+
111
463
  this.debounceSubscribeAggregator.close();
112
464
  this.debounceUnsubscribeAggregator.close();
113
465
  return super.stop();
114
466
  }
115
467
 
116
- private initializeTopic(topic: string) {
117
- this.topics.get(topic) || this.topics.set(topic, new Map());
118
- this.topicsToPeers.get(topic) || this.topicsToPeers.set(topic, new Set());
468
+ public override async onPeerConnected(
469
+ peerId: Libp2pPeerId,
470
+ connection: Connection,
471
+ ) {
472
+ await super.onPeerConnected(peerId, connection);
473
+
474
+ // If we're in auto-candidate mode, expand the deterministic shard-root
475
+ // candidate set as neighbours connect, then reconcile shard overlays and
476
+ // re-announce subscriptions so membership knowledge converges.
477
+ if (!this.autoTopicRootCandidates) return;
478
+ let peerHash: string;
479
+ try {
480
+ peerHash = getPublicKeyFromPeerId(peerId).hashcode();
481
+ } catch {
482
+ return;
483
+ }
484
+ void this.maybeUpdateAutoTopicRootCandidates(peerHash);
119
485
  }
120
486
 
121
- private initializePeer(publicKey: PublicSignKey) {
122
- this.peerToTopic.get(publicKey.hashcode()) ||
123
- this.peerToTopic.set(publicKey.hashcode(), new Set());
487
+ // Ensure auto-candidate mode converges even when libp2p topology callbacks
488
+ // are delayed or only fire for one side of a connection. `addPeer()` runs for
489
+ // both inbound + outbound protocol streams once the remote public key is known.
490
+ public override addPeer(
491
+ peerId: Libp2pPeerId,
492
+ publicKey: PublicSignKey,
493
+ protocol: string,
494
+ connId: string,
495
+ ): PeerStreams {
496
+ const peer = super.addPeer(peerId, publicKey, protocol, connId);
497
+ if (this.autoTopicRootCandidates) {
498
+ void this.maybeUpdateAutoTopicRootCandidates(publicKey.hashcode());
499
+ this.scheduleAutoTopicRootCandidatesBroadcast([peer]);
500
+ }
501
+ return peer;
124
502
  }
125
503
 
126
- async subscribe(topic: string) {
127
- // this.debounceUnsubscribeAggregator.delete(topic);
128
- return this.debounceSubscribeAggregator.add({ key: topic });
504
+ private maybeDisableAutoTopicRootCandidatesIfExternallyConfigured(): boolean {
505
+ if (!this.autoTopicRootCandidates) return false;
506
+
507
+ const managed = this.autoTopicRootCandidateSet;
508
+ if (!managed) return false;
509
+
510
+ const current = this.topicRootControlPlane.getTopicRootCandidates();
511
+ const externallyConfigured =
512
+ current.length !== managed.size || current.some((c) => !managed.has(c));
513
+ if (!externallyConfigured) return false;
514
+
515
+ // Stop mutating the candidate set. Leave the externally configured candidates
516
+ // intact and reconcile shard overlays under the new mapping.
517
+ this.autoTopicRootCandidates = false;
518
+ this.autoTopicRootCandidateSet = undefined;
519
+ this.shardRootCache.clear();
520
+
521
+ // Ensure we host any shard roots we're now responsible for. This is important
522
+ // in tests where candidates may be configured before protocol streams have
523
+ // fully started; earlier `hostShardRootsNow()` attempts can be skipped,
524
+ // leading to join timeouts.
525
+ void this.hostShardRootsNow().catch(() => {});
526
+ this.scheduleReconcileShardOverlays();
527
+ return true;
129
528
  }
130
529
 
131
- /**
132
- * Subscribes to a given topic.
133
- */
134
- async _subscribe(topics: { key: string; counter: number }[]) {
135
- if (!this.started) {
136
- throw new NotStartedError();
530
+ private maybeUpdateAutoTopicRootCandidates(peerHash: string) {
531
+ if (!this.autoTopicRootCandidates) return;
532
+ if (!peerHash || peerHash === this.publicKeyHash) return;
533
+
534
+ if (this.maybeDisableAutoTopicRootCandidatesIfExternallyConfigured())
535
+ return;
536
+
537
+ const current = this.topicRootControlPlane.getTopicRootCandidates();
538
+ const managed = this.autoTopicRootCandidateSet;
539
+
540
+ if (current.includes(peerHash)) return;
541
+
542
+ managed?.add(peerHash);
543
+ const next = this.normalizeAutoTopicRootCandidates(
544
+ managed ? [...managed] : [...current, peerHash],
545
+ );
546
+ this.autoTopicRootCandidateSet = new Set(next);
547
+ this.topicRootControlPlane.setTopicRootCandidates(next);
548
+ this.shardRootCache.clear();
549
+ this.scheduleReconcileShardOverlays();
550
+
551
+ // In auto-candidate mode, shard roots are selected deterministically across
552
+ // *all* connected peers (not just those currently subscribed to a shard).
553
+ // That means a peer can be selected as root for shards it isn't using yet.
554
+ // Ensure we proactively host the shard roots we're responsible for so other
555
+ // peers can join without timing out in small ad-hoc networks.
556
+ void this.hostShardRootsNow().catch(() => {});
557
+
558
+ // Share the updated candidate set so other peers converge on the same
559
+ // deterministic mapping even in partially connected topologies.
560
+ this.scheduleAutoTopicRootCandidatesBroadcast();
561
+ }
562
+
563
+ private normalizeAutoTopicRootCandidates(candidates: string[]): string[] {
564
+ const unique = new Set<string>();
565
+ for (const c of candidates) {
566
+ if (!c) continue;
567
+ unique.add(c);
137
568
  }
569
+ unique.add(this.publicKeyHash);
570
+ const sorted = [...unique].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
571
+ return sorted.slice(0, AUTO_TOPIC_ROOT_CANDIDATES_MAX);
572
+ }
573
+
574
+ private scheduleAutoTopicRootCandidatesBroadcast(targets?: PeerStreams[]) {
575
+ if (!this.autoTopicRootCandidates) return;
576
+ if (!this.started || this.stopping) return;
138
577
 
139
- if (topics.length === 0) {
578
+ if (targets && targets.length > 0) {
579
+ void this.sendAutoTopicRootCandidates(targets).catch(() => {});
140
580
  return;
141
581
  }
142
582
 
143
- const newTopicsForTopicData: string[] = [];
144
- for (const { key: topic, counter } of topics) {
145
- let prev = this.subscriptions.get(topic);
146
- if (prev) {
147
- prev.counter += counter;
148
- } else {
149
- prev = {
150
- counter: counter,
151
- };
152
- this.subscriptions.set(topic, prev);
583
+ for (const t of this.autoCandidatesBroadcastTimers) clearTimeout(t);
584
+ this.autoCandidatesBroadcastTimers = [];
585
+
586
+ // Burst a few times to survive early "stream not writable yet" races.
587
+ const delays = [25, 500, 2_000];
588
+ for (const delayMs of delays) {
589
+ const t = setTimeout(() => {
590
+ void this.sendAutoTopicRootCandidates().catch(() => {});
591
+ }, delayMs);
592
+ t.unref?.();
593
+ this.autoCandidatesBroadcastTimers.push(t);
594
+ }
595
+
596
+ // Keep gossiping for a while after changes so partially connected topologies
597
+ // converge even under slow stream negotiation.
598
+ this.autoCandidatesGossipUntil = Date.now() + 60_000;
599
+ this.ensureAutoCandidatesGossipInterval();
600
+ }
153
601
 
154
- newTopicsForTopicData.push(topic);
155
- this.listenForSubscribers(topic);
602
+ private ensureAutoCandidatesGossipInterval() {
603
+ if (!this.autoTopicRootCandidates) return;
604
+ if (!this.started || this.stopping) return;
605
+ if (this.autoCandidatesGossipInterval) return;
606
+ this.autoCandidatesGossipInterval = setInterval(() => {
607
+ if (!this.started || this.stopping || !this.autoTopicRootCandidates)
608
+ return;
609
+ if (
610
+ this.autoCandidatesGossipUntil > 0 &&
611
+ Date.now() > this.autoCandidatesGossipUntil
612
+ ) {
613
+ if (this.autoCandidatesGossipInterval) {
614
+ clearInterval(this.autoCandidatesGossipInterval);
615
+ this.autoCandidatesGossipInterval = undefined;
616
+ }
617
+ return;
156
618
  }
619
+ void this.sendAutoTopicRootCandidates().catch(() => {});
620
+ }, 2_000);
621
+ this.autoCandidatesGossipInterval.unref?.();
622
+ }
623
+
624
+ private async sendAutoTopicRootCandidates(targets?: PeerStreams[]) {
625
+ if (!this.started) throw new NotStartedError();
626
+ const streams = targets ?? [...this.peers.values()];
627
+ if (streams.length === 0) return;
628
+
629
+ const candidates = this.topicRootControlPlane.getTopicRootCandidates();
630
+ if (candidates.length === 0) return;
631
+
632
+ const msg = new TopicRootCandidates({ candidates });
633
+ const embedded = await this.createMessage(toUint8Array(msg.bytes()), {
634
+ mode: new AnyWhere(),
635
+ priority: 1,
636
+ skipRecipientValidation: true,
637
+ } as any);
638
+ await this.publishMessage(this.publicKey, embedded, streams).catch(
639
+ dontThrowIfDeliveryError,
640
+ );
641
+ }
642
+
643
+ private mergeAutoTopicRootCandidatesFromPeer(candidates: string[]): boolean {
644
+ if (!this.autoTopicRootCandidates) return false;
645
+ if (this.maybeDisableAutoTopicRootCandidatesIfExternallyConfigured())
646
+ return false;
647
+ const managed = this.autoTopicRootCandidateSet;
648
+ if (!managed) return false;
649
+
650
+ const before = this.topicRootControlPlane.getTopicRootCandidates();
651
+ for (const c of candidates) {
652
+ if (!c) continue;
653
+ managed.add(c);
654
+ }
655
+ const next = this.normalizeAutoTopicRootCandidates([...managed]);
656
+ if (
657
+ before.length === next.length &&
658
+ before.every((c, i) => c === next[i])
659
+ ) {
660
+ return false;
157
661
  }
158
662
 
159
- if (newTopicsForTopicData.length > 0) {
160
- const message = new DataMessage({
161
- data: toUint8Array(
162
- new Subscribe({
163
- topics: newTopicsForTopicData,
164
- requestSubscribers: true,
165
- }).bytes(),
166
- ),
167
- header: new MessageHeader({
168
- priority: 1,
169
- mode: new SeekDelivery({ redundancy: 2 }),
170
- session: this.session,
171
- }),
663
+ this.autoTopicRootCandidateSet = new Set(next);
664
+ this.topicRootControlPlane.setTopicRootCandidates(next);
665
+ this.shardRootCache.clear();
666
+ this.scheduleReconcileShardOverlays();
667
+ void this.hostShardRootsNow().catch(() => {});
668
+ this.scheduleAutoTopicRootCandidatesBroadcast();
669
+ return true;
670
+ }
671
+
672
+ private scheduleReconcileShardOverlays() {
673
+ if (this.reconcileShardOverlaysInFlight) return;
674
+ this.reconcileShardOverlaysInFlight = this.reconcileShardOverlays()
675
+ .catch(() => {
676
+ // best-effort retry: fanout streams/roots might not be ready yet.
677
+ if (!this.started || this.stopping) return;
678
+ const t = setTimeout(() => this.scheduleReconcileShardOverlays(), 250);
679
+ t.unref?.();
680
+ })
681
+ .finally(() => {
682
+ this.reconcileShardOverlaysInFlight = undefined;
172
683
  });
684
+ }
173
685
 
174
- await this.publishMessage(this.publicKey, await message.sign(this.sign));
686
+ private async reconcileShardOverlays() {
687
+ if (!this.started) return;
688
+
689
+ const byShard = new Map<string, string[]>();
690
+ for (const topic of this.subscriptions.keys()) {
691
+ const shardTopic = this.getShardTopicForUserTopic(topic);
692
+ byShard.set(shardTopic, [...(byShard.get(shardTopic) ?? []), topic]);
175
693
  }
694
+
695
+ // Ensure shard overlays are joined using the current root mapping (may
696
+ // migrate channels if roots changed), then re-announce subscriptions.
697
+ await Promise.all(
698
+ [...byShard.entries()].map(async ([shardTopic, userTopics]) => {
699
+ if (userTopics.length === 0) return;
700
+ await this.ensureFanoutChannel(shardTopic, { ephemeral: false });
701
+
702
+ const msg = new Subscribe({
703
+ topics: userTopics,
704
+ requestSubscribers: true,
705
+ });
706
+ const embedded = await this.createMessage(toUint8Array(msg.bytes()), {
707
+ mode: new AnyWhere(),
708
+ priority: 1,
709
+ skipRecipientValidation: true,
710
+ } as any);
711
+ const st = this.fanoutChannels.get(shardTopic);
712
+ if (!st) return;
713
+ await st.channel.publish(toUint8Array(embedded.bytes()));
714
+ this.touchFanoutChannel(shardTopic);
715
+ }),
716
+ );
176
717
  }
177
718
 
178
- async unsubscribe(topic: string) {
179
- if (this.debounceSubscribeAggregator.has(topic)) {
180
- this.debounceSubscribeAggregator.delete(topic); // cancel subscription before it performed
181
- return false;
719
+ private isTrackedTopic(topic: string) {
720
+ return this.topics.has(topic);
721
+ }
722
+
723
+ private initializeTopic(topic: string) {
724
+ this.topics.get(topic) || this.topics.set(topic, new Map());
725
+ }
726
+
727
+ private untrackTopic(topic: string) {
728
+ const peers = this.topics.get(topic);
729
+ this.topics.delete(topic);
730
+ if (!peers) return;
731
+ for (const peerHash of peers.keys()) {
732
+ this.peerToTopic.get(peerHash)?.delete(topic);
733
+ this.lastSubscriptionMessages.get(peerHash)?.delete(topic);
734
+ if (!this.peerToTopic.get(peerHash)?.size) {
735
+ this.peerToTopic.delete(peerHash);
736
+ this.lastSubscriptionMessages.delete(peerHash);
737
+ }
182
738
  }
183
- const subscriptions = this.subscriptions.get(topic);
184
- await this.debounceUnsubscribeAggregator.add({ key: topic });
185
- return !!subscriptions;
186
739
  }
187
740
 
188
- async _unsubscribe(
189
- topics: { key: string; counter: number }[],
190
- options?: { force: boolean },
191
- ) {
192
- if (!this.started) {
193
- throw new NotStartedError();
741
+ private initializePeer(publicKey: PublicSignKey) {
742
+ this.peerToTopic.get(publicKey.hashcode()) ||
743
+ this.peerToTopic.set(publicKey.hashcode(), new Set());
744
+ }
745
+
746
+ private pruneTopicSubscribers(topic: string) {
747
+ const peers = this.topics.get(topic);
748
+ if (!peers) return;
749
+
750
+ while (peers.size > this.subscriberCacheMaxEntries) {
751
+ const oldest = peers.keys().next().value as string | undefined;
752
+ if (!oldest) break;
753
+ peers.delete(oldest);
754
+ this.peerToTopic.get(oldest)?.delete(topic);
755
+ this.lastSubscriptionMessages.get(oldest)?.delete(topic);
756
+ if (!this.peerToTopic.get(oldest)?.size) {
757
+ this.peerToTopic.delete(oldest);
758
+ this.lastSubscriptionMessages.delete(oldest);
759
+ }
194
760
  }
761
+ }
195
762
 
196
- let topicsToUnsubscribe: string[] = [];
197
- for (const { key: topic, counter } of topics) {
198
- if (counter <= 0) {
199
- continue;
763
+ private getSubscriptionOverlap(topics?: string[]) {
764
+ const subscriptions: string[] = [];
765
+ if (topics) {
766
+ for (const topic of topics) {
767
+ if (
768
+ this.subscriptions.get(topic) ||
769
+ this.pendingSubscriptions.has(topic)
770
+ ) {
771
+ subscriptions.push(topic);
772
+ }
200
773
  }
201
- const subscriptions = this.subscriptions.get(topic);
774
+ return subscriptions;
775
+ }
776
+ const seen = new Set<string>();
777
+ for (const [topic] of this.subscriptions) {
778
+ subscriptions.push(topic);
779
+ seen.add(topic);
780
+ }
781
+ for (const topic of this.pendingSubscriptions) {
782
+ if (seen.has(topic)) continue;
783
+ subscriptions.push(topic);
784
+ }
785
+ return subscriptions;
786
+ }
787
+
788
+ private clearFanoutIdleClose(st: {
789
+ idleCloseTimeout?: ReturnType<typeof setTimeout>;
790
+ }) {
791
+ if (st.idleCloseTimeout) {
792
+ clearTimeout(st.idleCloseTimeout);
793
+ st.idleCloseTimeout = undefined;
794
+ }
795
+ }
796
+
797
+ private scheduleFanoutIdleClose(topic: string) {
798
+ const st = this.fanoutChannels.get(topic);
799
+ if (!st || !st.ephemeral) return;
800
+ this.clearFanoutIdleClose(st);
801
+ if (this.fanoutPublishIdleCloseMs <= 0) return;
802
+ st.idleCloseTimeout = setTimeout(() => {
803
+ const cur = this.fanoutChannels.get(topic);
804
+ if (!cur || !cur.ephemeral) return;
805
+ const idleMs = Date.now() - cur.lastUsedAt;
806
+ if (idleMs >= this.fanoutPublishIdleCloseMs) {
807
+ void this.closeFanoutChannel(topic);
808
+ return;
809
+ }
810
+ this.scheduleFanoutIdleClose(topic);
811
+ }, this.fanoutPublishIdleCloseMs);
812
+ }
813
+
814
+ private touchFanoutChannel(topic: string) {
815
+ const st = this.fanoutChannels.get(topic);
816
+ if (!st) return;
817
+ st.lastUsedAt = Date.now();
818
+ if (st.ephemeral) {
819
+ this.scheduleFanoutIdleClose(topic);
820
+ }
821
+ }
202
822
 
203
- logger.trace(
204
- `unsubscribe from ${topic} - am subscribed with subscriptions ${JSON.stringify(subscriptions)}`,
823
+ private evictEphemeralFanoutChannels(exceptTopic?: string) {
824
+ const max = this.fanoutPublishMaxEphemeralChannels;
825
+ if (max < 0) return;
826
+ const exceptIsEphemeral = exceptTopic
827
+ ? this.fanoutChannels.get(exceptTopic)?.ephemeral === true
828
+ : false;
829
+ const keep = Math.max(0, max - (exceptIsEphemeral ? 1 : 0));
830
+
831
+ const candidates: Array<[string, { lastUsedAt: number }]> = [];
832
+ for (const [t, st] of this.fanoutChannels) {
833
+ if (!st.ephemeral) continue;
834
+ if (exceptTopic && t === exceptTopic) continue;
835
+ candidates.push([t, st]);
836
+ }
837
+ if (candidates.length <= keep) return;
838
+
839
+ candidates.sort((a, b) => a[1].lastUsedAt - b[1].lastUsedAt);
840
+ const toClose = candidates.length - keep;
841
+ for (let i = 0; i < toClose; i++) {
842
+ const t = candidates[i]![0];
843
+ void this.closeFanoutChannel(t);
844
+ }
845
+ }
846
+
847
+ private getShardTopicForUserTopic(topic: string): string {
848
+ const t = topic.toString();
849
+ const cached = this.shardTopicCache.get(t);
850
+ if (cached) return cached;
851
+ const index = topicHash32(t) % this.shardCount;
852
+ const shardTopic = `${this.shardTopicPrefix}${index}`;
853
+ this.shardTopicCache.set(t, shardTopic);
854
+ return shardTopic;
855
+ }
856
+
857
+ private async resolveShardRoot(shardTopic: string): Promise<string> {
858
+ // If someone configured topic-root candidates externally (e.g. TestSession router
859
+ // selection or Peerbit.bootstrap) after this peer entered auto mode, disable auto
860
+ // mode before we cache any roots based on a stale candidate set.
861
+ if (this.autoTopicRootCandidates) {
862
+ this.maybeDisableAutoTopicRootCandidatesIfExternallyConfigured();
863
+ }
864
+
865
+ const cached = this.shardRootCache.get(shardTopic);
866
+ if (cached) return cached;
867
+ const resolved =
868
+ await this.topicRootControlPlane.resolveTopicRoot(shardTopic);
869
+ if (!resolved) {
870
+ throw new Error(
871
+ `No root resolved for shard topic ${shardTopic}. Configure TopicRootControlPlane candidates/resolver/trackers.`,
205
872
  );
873
+ }
874
+ this.shardRootCache.set(shardTopic, resolved);
875
+ return resolved;
876
+ }
206
877
 
207
- const peersOnTopic = this.topicsToPeers.get(topic);
208
- if (peersOnTopic) {
209
- for (const peer of peersOnTopic) {
210
- this.lastSubscriptionMessages.delete(peer);
878
+ private async ensureFanoutChannel(
879
+ shardTopic: string,
880
+ options?: {
881
+ ephemeral?: boolean;
882
+ pin?: boolean;
883
+ root?: string;
884
+ signal?: AbortSignal;
885
+ },
886
+ ): Promise<void> {
887
+ const t = shardTopic.toString();
888
+ const pin = options?.pin === true;
889
+ const wantEphemeral = options?.ephemeral === true;
890
+
891
+ // Allow callers that already resolved the shard root (e.g. hostShardRootsNow)
892
+ // to pass it through to avoid a race where the candidate set changes between
893
+ // two resolve calls, causing an unnecessary (and potentially slow) join.
894
+ let root: string | undefined = options?.root;
895
+ const existing = this.fanoutChannels.get(t);
896
+ if (existing) {
897
+ root = root ?? (await this.resolveShardRoot(t));
898
+ if (root === existing.root) {
899
+ existing.lastUsedAt = Date.now();
900
+ if (existing.ephemeral && !wantEphemeral) {
901
+ existing.ephemeral = false;
902
+ this.clearFanoutIdleClose(existing);
903
+ } else if (existing.ephemeral) {
904
+ this.scheduleFanoutIdleClose(t);
211
905
  }
906
+ if (pin) this.pinnedShards.add(t);
907
+ await withAbort(existing.join, options?.signal);
908
+ return;
212
909
  }
213
910
 
214
- if (!subscriptions) {
215
- return false;
911
+ // Root mapping changed (candidate set updated): migrate to the new overlay.
912
+ await withAbort(this.closeFanoutChannel(t, { force: true }), options?.signal);
913
+ }
914
+
915
+ root = root ?? (await this.resolveShardRoot(t));
916
+ const channel = new FanoutChannel(this.fanout, { topic: t, root });
917
+
918
+ const onPayload = (payload: Uint8Array) => {
919
+ let dm: DataMessage;
920
+ try {
921
+ dm = DataMessage.from(new Uint8ArrayList(payload));
922
+ } catch {
923
+ return;
924
+ }
925
+ if (!dm?.data) return;
926
+ if (!dm.header.signatures?.signatures?.length) return;
927
+
928
+ const signedBySelf =
929
+ dm.header.signatures?.publicKeys.some((x) =>
930
+ x.equals(this.publicKey),
931
+ ) ?? false;
932
+ if (signedBySelf) return;
933
+
934
+ let pubsubMessage: PubSubMessage;
935
+ try {
936
+ pubsubMessage = PubSubMessage.from(dm.data);
937
+ } catch {
938
+ return;
939
+ }
940
+
941
+ // Fast filter before hashing/verifying.
942
+ if (pubsubMessage instanceof PubSubData) {
943
+ const forMe = pubsubMessage.topics.some((x) =>
944
+ this.subscriptions.has(x),
945
+ );
946
+ if (!forMe) return;
947
+ } else if (
948
+ pubsubMessage instanceof Subscribe ||
949
+ pubsubMessage instanceof Unsubscribe
950
+ ) {
951
+ const relevant = pubsubMessage.topics.some((x) =>
952
+ this.isTrackedTopic(x),
953
+ );
954
+ const needRespond =
955
+ pubsubMessage instanceof Subscribe && pubsubMessage.requestSubscribers
956
+ ? pubsubMessage.topics.some((x) => this.subscriptions.has(x))
957
+ : false;
958
+ if (!relevant && !needRespond) return;
959
+ } else if (pubsubMessage instanceof GetSubscribers) {
960
+ const overlap = pubsubMessage.topics.some((x) =>
961
+ this.subscriptions.has(x),
962
+ );
963
+ if (!overlap) return;
964
+ } else {
965
+ return;
216
966
  }
217
967
 
218
- if (subscriptions?.counter && subscriptions?.counter >= 0) {
219
- subscriptions.counter -= counter;
968
+ void (async () => {
969
+ const msgId = await getMsgId(payload);
970
+ const seen = this.seenCache.get(msgId);
971
+ this.seenCache.add(msgId, seen ? seen + 1 : 1);
972
+ if (seen) return;
973
+
974
+ if ((await this.verifyAndProcess(dm)) === false) {
975
+ return;
976
+ }
977
+ const sender = dm.header.signatures!.signatures[0]!.publicKey!;
978
+ await this.processShardPubSubMessage({
979
+ pubsubMessage,
980
+ message: dm,
981
+ from: sender,
982
+ shardTopic: t,
983
+ });
984
+ })();
985
+ };
986
+
987
+ const onData = (ev?: CustomEvent<FanoutTreeDataEvent>) => {
988
+ const detail = ev?.detail as FanoutTreeDataEvent | undefined;
989
+ if (!detail) return;
990
+ onPayload(detail.payload);
991
+ };
992
+ const onUnicast = (ev?: any) => {
993
+ const detail = ev?.detail as any | undefined;
994
+ if (!detail) return;
995
+ if (detail.to && detail.to !== this.publicKeyHash) return;
996
+ onPayload(detail.payload);
997
+ };
998
+ channel.addEventListener("data", onData as any);
999
+ channel.addEventListener("unicast", onUnicast as any);
1000
+
1001
+ const join = (async () => {
1002
+ try {
1003
+ if (root === this.publicKeyHash) {
1004
+ channel.openAsRoot(this.fanoutRootChannelOptions);
1005
+ return;
1006
+ }
1007
+ // Joining by root hash is much more reliable if the fanout protocol
1008
+ // stream is already established (especially in small test nets without
1009
+ // trackers/bootstraps). Best-effort only: join can still succeed via
1010
+ // trackers/other routing if this times out.
1011
+ try {
1012
+ await this.fanout.waitFor(root, {
1013
+ target: "neighbor",
1014
+ // Best-effort pre-check only: do not block subscribe/publish setup
1015
+ // for long periods if the root is not yet a direct stream neighbor.
1016
+ timeout: 1_000,
1017
+ });
1018
+ } catch {
1019
+ // ignore
1020
+ }
1021
+ const joinOpts = options?.signal
1022
+ ? { ...(this.fanoutJoinOptions ?? {}), signal: options.signal }
1023
+ : this.fanoutJoinOptions;
1024
+ await channel.join(this.fanoutNodeChannelOptions, joinOpts);
1025
+ } catch (error) {
1026
+ try {
1027
+ channel.removeEventListener("data", onData as any);
1028
+ } catch {
1029
+ // ignore
1030
+ }
1031
+ try {
1032
+ channel.removeEventListener("unicast", onUnicast as any);
1033
+ } catch {
1034
+ // ignore
1035
+ }
1036
+ try {
1037
+ channel.close();
1038
+ } catch {
1039
+ // ignore
1040
+ }
1041
+ throw error;
220
1042
  }
1043
+ })();
1044
+
1045
+ const lastUsedAt = Date.now();
1046
+ if (pin) this.pinnedShards.add(t);
1047
+ this.fanoutChannels.set(t, {
1048
+ root,
1049
+ channel,
1050
+ join,
1051
+ onData,
1052
+ onUnicast,
1053
+ ephemeral: wantEphemeral,
1054
+ lastUsedAt,
1055
+ });
1056
+ join.catch(() => {
1057
+ this.fanoutChannels.delete(t);
1058
+ });
1059
+ join
1060
+ .then(() => {
1061
+ const st = this.fanoutChannels.get(t);
1062
+ if (st?.ephemeral) this.scheduleFanoutIdleClose(t);
1063
+ })
1064
+ .catch(() => {
1065
+ // ignore
1066
+ });
1067
+ if (wantEphemeral) {
1068
+ this.evictEphemeralFanoutChannels(t);
1069
+ }
1070
+ await withAbort(join, options?.signal);
1071
+ }
221
1072
 
222
- if (!subscriptions.counter || options?.force) {
223
- topicsToUnsubscribe.push(topic);
224
- this.subscriptions.delete(topic);
225
- this.topics.delete(topic);
226
- this.topicsToPeers.delete(topic);
1073
+ private async closeFanoutChannel(
1074
+ shardTopic: string,
1075
+ options?: { force?: boolean },
1076
+ ): Promise<void> {
1077
+ const t = shardTopic.toString();
1078
+ if (!options?.force && this.pinnedShards.has(t)) return;
1079
+ if (options?.force) this.pinnedShards.delete(t);
1080
+ const st = this.fanoutChannels.get(t);
1081
+ if (!st) return;
1082
+ this.fanoutChannels.delete(t);
1083
+ this.clearFanoutIdleClose(st);
1084
+ try {
1085
+ st.channel.removeEventListener("data", st.onData as any);
1086
+ } catch {
1087
+ // ignore
1088
+ }
1089
+ try {
1090
+ st.channel.removeEventListener("unicast", st.onUnicast as any);
1091
+ } catch {
1092
+ // ignore
1093
+ }
1094
+ try {
1095
+ await st.channel.leave({ notifyParent: true });
1096
+ } catch {
1097
+ try {
1098
+ st.channel.close();
1099
+ } catch {
1100
+ // ignore
227
1101
  }
228
1102
  }
1103
+ }
229
1104
 
230
- if (topicsToUnsubscribe.length > 0) {
231
- await this.publishMessage(
232
- this.publicKey,
233
- await new DataMessage({
234
- header: new MessageHeader({
235
- mode: new AnyWhere(), // TODO make this better
236
- session: this.session,
237
- priority: 1,
238
- }),
239
- data: toUint8Array(
240
- new Unsubscribe({
241
- topics: topicsToUnsubscribe,
242
- }).bytes(),
243
- ),
244
- }).sign(this.sign),
1105
+ public async hostShardRootsNow() {
1106
+ if (!this.started) throw new NotStartedError();
1107
+ const joins: Promise<void>[] = [];
1108
+ for (let i = 0; i < this.shardCount; i++) {
1109
+ const shardTopic = `${this.shardTopicPrefix}${i}`;
1110
+ const root = await this.resolveShardRoot(shardTopic);
1111
+ if (root !== this.publicKeyHash) continue;
1112
+ joins.push(this.ensureFanoutChannel(shardTopic, { pin: true, root }));
1113
+ }
1114
+ await Promise.all(joins);
1115
+ }
1116
+
1117
+ async subscribe(topic: string) {
1118
+ this.pendingSubscriptions.add(topic);
1119
+ // `subscribe()` is debounced; start tracking immediately to avoid dropping
1120
+ // inbound subscription traffic during the debounce window.
1121
+ this.initializeTopic(topic);
1122
+ return this.debounceSubscribeAggregator.add({ key: topic });
1123
+ }
1124
+
1125
+ private async _subscribe(topics: { key: string; counter: number }[]) {
1126
+ if (!this.started) throw new NotStartedError();
1127
+ if (topics.length === 0) return;
1128
+
1129
+ const byShard = new Map<string, string[]>();
1130
+ const joins: Promise<void>[] = [];
1131
+ for (const { key: topic, counter } of topics) {
1132
+ let prev = this.subscriptions.get(topic);
1133
+ if (prev) {
1134
+ prev.counter += counter;
1135
+ this.pendingSubscriptions.delete(topic);
1136
+ continue;
1137
+ }
1138
+ this.subscriptions.set(topic, { counter });
1139
+ this.initializeTopic(topic);
1140
+ this.pendingSubscriptions.delete(topic);
1141
+
1142
+ const shardTopic = this.getShardTopicForUserTopic(topic);
1143
+ byShard.set(shardTopic, [...(byShard.get(shardTopic) ?? []), topic]);
1144
+ this.shardRefCounts.set(
1145
+ shardTopic,
1146
+ (this.shardRefCounts.get(shardTopic) ?? 0) + 1,
245
1147
  );
1148
+ joins.push(this.ensureFanoutChannel(shardTopic));
246
1149
  }
1150
+
1151
+ await Promise.all(joins);
1152
+
1153
+ // Announce subscriptions per shard overlay.
1154
+ await Promise.all(
1155
+ [...byShard.entries()].map(async ([shardTopic, userTopics]) => {
1156
+ if (userTopics.length === 0) return;
1157
+ const msg = new Subscribe({
1158
+ topics: userTopics,
1159
+ requestSubscribers: true,
1160
+ });
1161
+ const embedded = await this.createMessage(toUint8Array(msg.bytes()), {
1162
+ mode: new AnyWhere(),
1163
+ priority: 1,
1164
+ skipRecipientValidation: true,
1165
+ } as any);
1166
+ const st = this.fanoutChannels.get(shardTopic);
1167
+ if (!st)
1168
+ throw new Error(`Fanout channel missing for shard: ${shardTopic}`);
1169
+ await st.channel.publish(toUint8Array(embedded.bytes()));
1170
+ this.touchFanoutChannel(shardTopic);
1171
+ }),
1172
+ );
247
1173
  }
248
1174
 
249
- getSubscribers(topic: string): PublicSignKey[] | undefined {
250
- const remote = this.topics.get(topic.toString());
1175
+ async unsubscribe(
1176
+ topic: string,
1177
+ options?: {
1178
+ force?: boolean;
1179
+ data?: Uint8Array;
1180
+ },
1181
+ ) {
1182
+ this.pendingSubscriptions.delete(topic);
251
1183
 
252
- if (!remote) {
253
- return undefined;
1184
+ if (this.debounceSubscribeAggregator.has(topic)) {
1185
+ this.debounceSubscribeAggregator.delete(topic);
1186
+ if (!this.subscriptions.has(topic)) {
1187
+ this.untrackTopic(topic);
1188
+ }
1189
+ return false;
254
1190
  }
255
- const ret: PublicSignKey[] = [];
256
- for (const v of remote.values()) {
257
- ret.push(v.publicKey);
1191
+
1192
+ const sub = this.subscriptions.get(topic);
1193
+ if (!sub) return false;
1194
+
1195
+ if (options?.force) {
1196
+ sub.counter = 0;
1197
+ } else {
1198
+ sub.counter -= 1;
258
1199
  }
259
- if (this.subscriptions.get(topic)) {
260
- ret.push(this.publicKey);
1200
+ if (sub.counter > 0) return true;
1201
+
1202
+ // Remove local subscription immediately so `publish()`/delivery paths observe
1203
+ // the change without waiting for batched control-plane announces.
1204
+ this.subscriptions.delete(topic);
1205
+ this.untrackTopic(topic);
1206
+
1207
+ // Update shard refcount immediately. The debounced announcer will close the
1208
+ // channel if this was the last local subscription for that shard.
1209
+ const shardTopic = this.getShardTopicForUserTopic(topic);
1210
+ const next = (this.shardRefCounts.get(shardTopic) ?? 0) - 1;
1211
+ if (next <= 0) {
1212
+ this.shardRefCounts.delete(shardTopic);
1213
+ } else {
1214
+ this.shardRefCounts.set(shardTopic, next);
261
1215
  }
262
- return ret;
1216
+
1217
+ // Best-effort: do not block callers on network I/O (can hang under teardown).
1218
+ void this.debounceUnsubscribeAggregator.add({ key: topic }).catch(logErrorIfStarted);
1219
+ return true;
263
1220
  }
264
1221
 
265
- private listenForSubscribers(topic: string) {
266
- this.initializeTopic(topic);
1222
+ private async _announceUnsubscribe(topics: { key: string; counter: number }[]) {
1223
+ if (!this.started) throw new NotStartedError();
1224
+
1225
+ const byShard = new Map<string, string[]>();
1226
+ for (const { key: topic } of topics) {
1227
+ // If the topic got re-subscribed before this debounced batch ran, skip.
1228
+ if (this.subscriptions.has(topic)) continue;
1229
+ const shardTopic = this.getShardTopicForUserTopic(topic);
1230
+ byShard.set(shardTopic, [...(byShard.get(shardTopic) ?? []), topic]);
1231
+ }
1232
+
1233
+ await Promise.all(
1234
+ [...byShard.entries()].map(async ([shardTopic, userTopics]) => {
1235
+ if (userTopics.length === 0) return;
1236
+
1237
+ // Announce first.
1238
+ try {
1239
+ const msg = new Unsubscribe({ topics: userTopics });
1240
+ const embedded = await this.createMessage(toUint8Array(msg.bytes()), {
1241
+ mode: new AnyWhere(),
1242
+ priority: 1,
1243
+ skipRecipientValidation: true,
1244
+ } as any);
1245
+ const st = this.fanoutChannels.get(shardTopic);
1246
+ if (st) {
1247
+ // Best-effort: do not let a stuck proxy publish stall teardown.
1248
+ void st.channel
1249
+ .publish(toUint8Array(embedded.bytes()))
1250
+ .catch(() => {});
1251
+ this.touchFanoutChannel(shardTopic);
1252
+ }
1253
+ } catch {
1254
+ // best-effort
1255
+ }
1256
+
1257
+ // Close shard overlay if no local topics remain.
1258
+ if ((this.shardRefCounts.get(shardTopic) ?? 0) <= 0) {
1259
+ try {
1260
+ // Shutdown should be bounded and not depend on network I/O.
1261
+ await this.closeFanoutChannel(shardTopic);
1262
+ } catch {
1263
+ // best-effort
1264
+ }
1265
+ }
1266
+ }),
1267
+ );
1268
+ }
1269
+
1270
+ getSubscribers(topic: string): PublicSignKey[] | undefined {
1271
+ const t = topic.toString();
1272
+ const remote = this.topics.get(t);
1273
+ const includeSelf = this.subscriptions.has(t);
1274
+ if (!remote || remote.size == 0) {
1275
+ return includeSelf ? [this.publicKey] : undefined;
1276
+ }
1277
+ const ret: PublicSignKey[] = [];
1278
+ for (const v of remote.values()) ret.push(v.publicKey);
1279
+ if (includeSelf) ret.push(this.publicKey);
1280
+ return ret;
267
1281
  }
268
1282
 
269
1283
  async requestSubscribers(
270
1284
  topic: string | string[],
271
1285
  to?: PublicSignKey,
272
1286
  ): Promise<void> {
273
- if (!this.started) {
274
- throw new NotStartedError();
275
- }
1287
+ if (!this.started) throw new NotStartedError();
1288
+ if (topic == null) throw new Error("ERR_NOT_VALID_TOPIC");
1289
+ if (topic.length === 0) return;
276
1290
 
277
- if (topic == null) {
278
- throw new Error("ERR_NOT_VALID_TOPIC");
279
- }
1291
+ const topicsAll = (typeof topic === "string" ? [topic] : topic).map((t) =>
1292
+ t.toString(),
1293
+ );
1294
+ for (const t of topicsAll) this.initializeTopic(t);
280
1295
 
281
- if (topic.length === 0) {
282
- return;
1296
+ const byShard = new Map<string, string[]>();
1297
+ for (const t of topicsAll) {
1298
+ const shardTopic = this.getShardTopicForUserTopic(t);
1299
+ byShard.set(shardTopic, [...(byShard.get(shardTopic) ?? []), t]);
283
1300
  }
284
1301
 
285
- const topics = typeof topic === "string" ? [topic] : topic;
286
- for (const topic of topics) {
287
- this.listenForSubscribers(topic);
288
- }
1302
+ await Promise.all(
1303
+ [...byShard.entries()].map(async ([shardTopic, userTopics]) => {
1304
+ const persistent = (this.shardRefCounts.get(shardTopic) ?? 0) > 0;
1305
+ await this.ensureFanoutChannel(shardTopic, { ephemeral: !persistent });
289
1306
 
290
- return this.publishMessage(
291
- this.publicKey,
292
- await new DataMessage({
293
- data: toUint8Array(new GetSubscribers({ topics }).bytes()),
294
- header: new MessageHeader({
295
- mode: new SeekDelivery({
296
- to: to ? [to.hashcode()] : undefined,
297
- redundancy: 2,
298
- }),
299
- session: this.session,
1307
+ const msg = new GetSubscribers({ topics: userTopics });
1308
+ const embedded = await this.createMessage(toUint8Array(msg.bytes()), {
1309
+ mode: new AnyWhere(),
300
1310
  priority: 1,
301
- }),
302
- }).sign(this.sign),
303
- );
304
- }
305
-
306
- getPeersOnTopics(topics: string[]): Set<string> {
307
- const newPeers: Set<string> = new Set();
308
- if (topics?.length) {
309
- for (const topic of topics) {
310
- const peersOnTopic = this.topicsToPeers.get(topic);
311
- if (peersOnTopic) {
312
- peersOnTopic.forEach((peer) => {
313
- newPeers.add(peer);
314
- });
1311
+ skipRecipientValidation: true,
1312
+ } as any);
1313
+ const payload = toUint8Array(embedded.bytes());
1314
+
1315
+ const st = this.fanoutChannels.get(shardTopic);
1316
+ if (!st)
1317
+ throw new Error(`Fanout channel missing for shard: ${shardTopic}`);
1318
+
1319
+ if (to) {
1320
+ try {
1321
+ await st.channel.unicastToAck(to.hashcode(), payload, {
1322
+ timeoutMs: 5_000,
1323
+ });
1324
+ } catch {
1325
+ await st.channel.publish(payload);
1326
+ }
1327
+ } else {
1328
+ await st.channel.publish(payload);
315
1329
  }
316
- }
317
- }
318
- return newPeers;
319
- }
320
-
321
- /* getStreamsWithTopics(topics: string[], otherPeers?: string[]): PeerStreams[] {
322
- const peers = this.getNeighboursWithTopics(topics, otherPeers);
323
- return [...this.peers.values()].filter((s) =>
324
- peers.has(s.publicKey.hashcode())
1330
+ this.touchFanoutChannel(shardTopic);
1331
+ }),
325
1332
  );
326
- } */
327
-
328
- private shouldSendMessage(tos?: string[] | Set<string>) {
329
- if (
330
- Array.isArray(tos) &&
331
- (tos.length === 0 || (tos.length === 1 && tos[0] === this.publicKeyHash))
332
- ) {
333
- // skip this one
334
- return false;
335
- }
336
-
337
- if (
338
- tos instanceof Set &&
339
- (tos.size === 0 || (tos.size === 1 && tos.has(this.publicKeyHash)))
340
- ) {
341
- // skip this one
342
- return false;
343
- }
344
-
345
- return true;
346
1333
  }
1334
+
347
1335
  async publish(
348
1336
  data: Uint8Array | undefined,
349
1337
  options?: {
350
1338
  topics: string[];
351
1339
  } & { client?: string } & {
352
- mode?: SilentDelivery | AcknowledgeDelivery | SeekDelivery;
1340
+ mode?: SilentDelivery | AcknowledgeDelivery;
353
1341
  } & PriorityOptions &
354
- IdOptions & { signal?: AbortSignal },
1342
+ IdOptions &
1343
+ WithExtraSigners & { signal?: AbortSignal },
355
1344
  ): Promise<Uint8Array | undefined> {
356
- if (!this.started) {
357
- throw new NotStartedError();
358
- }
1345
+ if (!this.started) throw new NotStartedError();
359
1346
 
360
- const topics =
1347
+ const topicsAll =
361
1348
  (options as { topics: string[] }).topics?.map((x) => x.toString()) || [];
362
1349
 
363
1350
  const hasExplicitTOs =
364
1351
  options?.mode && deliveryModeHasReceiver(options.mode);
365
- const tos = hasExplicitTOs
366
- ? options.mode?.to
367
- : this.getPeersOnTopics(topics);
368
-
369
- // Embedd topic info before the data so that peers/relays can also use topic info to route messages efficiently
370
- const dataMessage = data
371
- ? new PubSubData({
372
- topics: topics.map((x) => x.toString()),
373
- data,
374
- strict: hasExplicitTOs,
375
- })
376
- : undefined;
377
-
378
- const bytes = dataMessage?.bytes();
379
- const silentDelivery = options?.mode instanceof SilentDelivery;
380
-
381
- // do send check before creating and signing the message
382
- if (!this.dispatchEventOnSelfPublish && !this.shouldSendMessage(tos)) {
383
- return;
384
- }
385
1352
 
386
- const message = await this.createMessage(bytes, {
387
- ...options,
388
- to: tos,
389
- skipRecipientValidation: this.dispatchEventOnSelfPublish,
390
- });
1353
+ // Explicit recipients: use DirectStream delivery (no shard broadcast).
1354
+ if (hasExplicitTOs || !data) {
1355
+ const msg = data
1356
+ ? new PubSubData({ topics: topicsAll, data, strict: true })
1357
+ : undefined;
1358
+ const message = await this.createMessage(msg?.bytes(), {
1359
+ ...options,
1360
+ skipRecipientValidation: this.dispatchEventOnSelfPublish,
1361
+ });
391
1362
 
392
- if (dataMessage) {
393
- this.dispatchEvent(
394
- new CustomEvent("publish", {
395
- detail: new PublishEvent({
396
- client: options?.client,
397
- data: dataMessage,
398
- message,
1363
+ if (msg) {
1364
+ this.dispatchEvent(
1365
+ new CustomEvent("publish", {
1366
+ detail: new PublishEvent({
1367
+ client: options?.client,
1368
+ data: msg,
1369
+ message,
1370
+ }),
399
1371
  }),
400
- }),
401
- );
402
- }
1372
+ );
1373
+ }
403
1374
 
404
- // for emitSelf we do this check here, since we don't want to send the message to ourselves
405
- if (this.dispatchEventOnSelfPublish && !this.shouldSendMessage(tos)) {
1375
+ const silentDelivery = options?.mode instanceof SilentDelivery;
1376
+ try {
1377
+ await this.publishMessage(
1378
+ this.publicKey,
1379
+ message,
1380
+ undefined,
1381
+ undefined,
1382
+ options?.signal,
1383
+ );
1384
+ } catch (error) {
1385
+ if (error instanceof DeliveryError && silentDelivery !== false) {
1386
+ return message.id;
1387
+ }
1388
+ throw error;
1389
+ }
406
1390
  return message.id;
407
1391
  }
408
1392
 
409
- // send to all the other peers
410
- try {
411
- await this.publishMessage(
412
- this.publicKey,
413
- message,
414
- undefined,
415
- undefined,
416
- options?.signal,
417
- );
418
- } catch (error) {
419
- if (error instanceof DeliveryError) {
420
- if (silentDelivery === false) {
421
- // If we are not in silent mode, we should throw the error
422
- throw error;
1393
+ if (this.fanoutPublishRequiresSubscribe) {
1394
+ for (const t of topicsAll) {
1395
+ if (!this.subscriptions.has(t)) {
1396
+ throw new Error(
1397
+ `Cannot publish to topic ${t} without subscribing (fanoutPublishRequiresSubscribe=true)`,
1398
+ );
423
1399
  }
424
- return message.id;
425
1400
  }
426
- throw error;
427
1401
  }
428
1402
 
429
- return message.id;
430
- }
1403
+ const msg = new PubSubData({ topics: topicsAll, data, strict: false });
1404
+ const embedded = await this.createMessage(toUint8Array(msg.bytes()), {
1405
+ mode: new AnyWhere(),
1406
+ priority: options?.priority,
1407
+ id: options?.id,
1408
+ extraSigners: options?.extraSigners,
1409
+ skipRecipientValidation: true,
1410
+ } as any);
1411
+
1412
+ this.dispatchEvent(
1413
+ new CustomEvent("publish", {
1414
+ detail: new PublishEvent({
1415
+ client: options?.client,
1416
+ data: msg,
1417
+ message: embedded,
1418
+ }),
1419
+ }),
1420
+ );
431
1421
 
432
- private deletePeerFromTopic(topic: string, publicKeyHash: string) {
433
- const peers = this.topics.get(topic);
434
- let change: SubscriptionData | undefined = undefined;
435
- if (peers) {
436
- change = peers.get(publicKeyHash);
1422
+ const byShard = new Map<string, string[]>();
1423
+ for (const t of topicsAll) {
1424
+ const shardTopic = this.getShardTopicForUserTopic(t);
1425
+ byShard.set(shardTopic, [...(byShard.get(shardTopic) ?? []), t]);
437
1426
  }
438
1427
 
439
- this.topics.get(topic)?.delete(publicKeyHash);
440
-
441
- this.peerToTopic.get(publicKeyHash)?.delete(topic);
442
- if (!this.peerToTopic.get(publicKeyHash)?.size) {
443
- this.peerToTopic.delete(publicKeyHash);
1428
+ for (const shardTopic of byShard.keys()) {
1429
+ const persistent = (this.shardRefCounts.get(shardTopic) ?? 0) > 0;
1430
+ await this.ensureFanoutChannel(shardTopic, {
1431
+ ephemeral: !persistent,
1432
+ signal: options?.signal,
1433
+ });
444
1434
  }
445
1435
 
446
- this.topicsToPeers.get(topic)?.delete(publicKeyHash);
447
-
448
- return change;
449
- }
450
-
451
- private getSubscriptionOverlap(topics?: string[]) {
452
- const subscriptions: string[] = [];
453
- if (topics) {
454
- for (const topic of topics) {
455
- const subscription = this.subscriptions.get(topic);
456
- if (subscription) {
457
- subscriptions.push(topic);
1436
+ const payload = toUint8Array(embedded.bytes());
1437
+ await Promise.all(
1438
+ [...byShard.keys()].map(async (shardTopic) => {
1439
+ if (options?.signal?.aborted) {
1440
+ throw new AbortError("Publish was aborted");
458
1441
  }
459
- }
460
- } else {
461
- for (const [topic, _subscription] of this.subscriptions) {
462
- subscriptions.push(topic);
1442
+ const st = this.fanoutChannels.get(shardTopic);
1443
+ if (!st) {
1444
+ throw new Error(`Fanout channel missing for shard: ${shardTopic}`);
1445
+ }
1446
+ await withAbort(st.channel.publish(payload), options?.signal);
1447
+ this.touchFanoutChannel(shardTopic);
1448
+ }),
1449
+ );
1450
+
1451
+ if (
1452
+ this.fanoutPublishIdleCloseMs == 0 ||
1453
+ this.fanoutPublishMaxEphemeralChannels == 0
1454
+ ) {
1455
+ for (const shardTopic of byShard.keys()) {
1456
+ const st = this.fanoutChannels.get(shardTopic);
1457
+ if (st?.ephemeral) await this.closeFanoutChannel(shardTopic);
463
1458
  }
464
1459
  }
465
- return subscriptions;
466
- }
467
1460
 
468
- public onPeerSession(key: PublicSignKey, session: number): void {
469
- // reset subs, the peer has restarted
470
- this.removeSubscriptions(key);
1461
+ return embedded.id;
471
1462
  }
472
1463
 
473
- public async onPeerReachable(publicKey: PublicSignKey) {
474
- // Aggregate subscribers for my topics through this new peer because if we don't do this we might end up with a situtation where
475
- // we act as a relay and relay messages for a topic, but don't forward it to this new peer because we never learned about their subscriptions
476
-
477
- const resp = super.onPeerReachable(publicKey);
478
- const stream = this.peers.get(publicKey.hashcode());
479
- const isNeigbour = !!stream;
480
-
481
- if (this.subscriptions.size > 0) {
482
- // tell the peer about all topics we subscribe to
483
- this.publishMessage(
484
- this.publicKey,
485
- await new DataMessage({
486
- data: toUint8Array(
487
- new Subscribe({
488
- topics: this.getSubscriptionOverlap(), // TODO make the protocol more efficient, do we really need to share *everything* ?
489
- requestSubscribers: true,
490
- }).bytes(),
491
- ),
492
- header: new MessageHeader({
493
- // is new neighbour ? then send to all, though that connection (potentially find new peers)
494
- // , else just try to reach the remote
495
- priority: 1,
496
- mode: new SeekDelivery({
497
- redundancy: 2,
498
- to: isNeigbour ? undefined : [publicKey.hashcode()],
499
- }),
500
- session: this.session,
501
- }),
502
- }).sign(this.sign),
503
- ).catch(dontThrowIfDeliveryError); // peer might have become unreachable immediately
504
- }
505
-
506
- return resp;
1464
+ public onPeerSession(key: PublicSignKey, _session: number): void {
1465
+ this.removeSubscriptions(key);
507
1466
  }
508
1467
 
509
- public onPeerUnreachable(publicKeyHash: string) {
1468
+ public override onPeerUnreachable(publicKeyHash: string) {
510
1469
  super.onPeerUnreachable(publicKeyHash);
511
- this.removeSubscriptions(this.peerKeyHashToPublicKey.get(publicKeyHash)!);
1470
+ const key = this.peerKeyHashToPublicKey.get(publicKeyHash);
1471
+ if (key) this.removeSubscriptions(key);
512
1472
  }
513
1473
 
514
1474
  private removeSubscriptions(publicKey: PublicSignKey) {
515
- const peerTopics = this.peerToTopic.get(publicKey.hashcode());
516
-
1475
+ const peerHash = publicKey.hashcode();
1476
+ const peerTopics = this.peerToTopic.get(peerHash);
517
1477
  const changed: string[] = [];
518
1478
  if (peerTopics) {
519
1479
  for (const topic of peerTopics) {
520
- const change = this.deletePeerFromTopic(topic, publicKey.hashcode());
521
- if (change) {
1480
+ const peers = this.topics.get(topic);
1481
+ if (!peers) continue;
1482
+ if (peers.delete(peerHash)) {
522
1483
  changed.push(topic);
523
1484
  }
524
1485
  }
525
1486
  }
526
- this.lastSubscriptionMessages.delete(publicKey.hashcode());
1487
+ this.peerToTopic.delete(peerHash);
1488
+ this.lastSubscriptionMessages.delete(peerHash);
527
1489
 
528
1490
  if (changed.length > 0) {
529
1491
  this.dispatchEvent(
@@ -537,297 +1499,309 @@ export class DirectSub extends DirectStream<PubSubEvents> implements PubSub {
537
1499
  private subscriptionMessageIsLatest(
538
1500
  message: DataMessage,
539
1501
  pubsubMessage: Subscribe | Unsubscribe,
1502
+ relevantTopics: string[],
540
1503
  ) {
541
1504
  const subscriber = message.header.signatures!.signatures[0].publicKey!;
542
- const subscriberKey = subscriber.hashcode(); // Assume first signature is the one who is signing
1505
+ const subscriberKey = subscriber.hashcode();
1506
+ const messageTimestamp = message.header.timestamp;
543
1507
 
544
- for (const topic of pubsubMessage.topics) {
1508
+ for (const topic of relevantTopics) {
545
1509
  const lastTimestamp = this.lastSubscriptionMessages
546
1510
  .get(subscriberKey)
547
- ?.get(topic)?.header.timestamp;
548
- if (lastTimestamp != null && lastTimestamp > message.header.timestamp) {
549
- return false; // message is old
1511
+ ?.get(topic);
1512
+ if (lastTimestamp != null && lastTimestamp > messageTimestamp) {
1513
+ return false;
550
1514
  }
551
1515
  }
552
1516
 
553
- for (const topic of pubsubMessage.topics) {
1517
+ for (const topic of relevantTopics) {
554
1518
  if (!this.lastSubscriptionMessages.has(subscriberKey)) {
555
1519
  this.lastSubscriptionMessages.set(subscriberKey, new Map());
556
1520
  }
557
- this.lastSubscriptionMessages.get(subscriberKey)?.set(topic, message);
1521
+ this.lastSubscriptionMessages
1522
+ .get(subscriberKey)!
1523
+ .set(topic, messageTimestamp);
558
1524
  }
559
1525
  return true;
560
1526
  }
561
1527
 
562
- private addPeersOnTopic(
563
- message: DataMessage<AcknowledgeDelivery | SilentDelivery | SeekDelivery>,
564
- topics: string[],
1528
+ private async sendFanoutUnicastOrBroadcast(
1529
+ shardTopic: string,
1530
+ targetHash: string,
1531
+ payload: Uint8Array,
565
1532
  ) {
566
- const existingPeers: Set<string> = new Set(message.header.mode.to);
567
- const allPeersOnTopic = this.getPeersOnTopics(topics);
568
-
569
- for (const existing of existingPeers) {
570
- allPeersOnTopic.add(existing);
1533
+ const st = this.fanoutChannels.get(shardTopic);
1534
+ if (!st) return;
1535
+ try {
1536
+ await st.channel.unicastToAck(targetHash, payload, { timeoutMs: 5_000 });
1537
+ return;
1538
+ } catch {
1539
+ // ignore and fall back
1540
+ }
1541
+ try {
1542
+ await st.channel.publish(payload);
1543
+ } catch {
1544
+ // ignore
571
1545
  }
572
-
573
- allPeersOnTopic.delete(this.publicKeyHash);
574
- message.header.mode.to = [...allPeersOnTopic];
575
1546
  }
576
1547
 
577
- async onDataMessage(
578
- from: PublicSignKey,
579
- stream: PeerStreams,
580
- message: DataMessage,
581
- seenBefore: number,
582
- ) {
583
- if (!message.data || message.data.length === 0) {
584
- return super.onDataMessage(from, stream, message, seenBefore);
585
- }
1548
+ private async processDirectPubSubMessage(input: {
1549
+ pubsubMessage: PubSubMessage;
1550
+ message: DataMessage;
1551
+ }): Promise<void> {
1552
+ const { pubsubMessage, message } = input;
586
1553
 
587
- if (this.shouldIgnore(message, seenBefore)) {
588
- return false;
1554
+ if (pubsubMessage instanceof TopicRootCandidates) {
1555
+ // Used only to converge deterministic shard-root candidates in auto mode.
1556
+ this.mergeAutoTopicRootCandidatesFromPeer(pubsubMessage.candidates);
1557
+ return;
589
1558
  }
590
1559
 
591
- const pubsubMessage = PubSubMessage.from(message.data);
592
1560
  if (pubsubMessage instanceof PubSubData) {
593
- if (message.header.mode instanceof AnyWhere) {
594
- throw new Error("Unexpected mode for PubSubData messages");
595
- }
1561
+ this.dispatchEvent(
1562
+ new CustomEvent("data", {
1563
+ detail: new DataEvent({
1564
+ data: pubsubMessage,
1565
+ message,
1566
+ }),
1567
+ }),
1568
+ );
1569
+ return;
1570
+ }
1571
+ }
596
1572
 
597
- /**
598
- * See if we know more subscribers of the message topics. If so, add aditional end receivers of the message
599
- */
1573
+ private async processShardPubSubMessage(input: {
1574
+ pubsubMessage: PubSubMessage;
1575
+ message: DataMessage;
1576
+ from: PublicSignKey;
1577
+ shardTopic: string;
1578
+ }): Promise<void> {
1579
+ const { pubsubMessage, message, from, shardTopic } = input;
600
1580
 
601
- const meInTOs = !!message.header.mode.to?.find(
602
- (x) => this.publicKeyHash === x,
1581
+ if (pubsubMessage instanceof PubSubData) {
1582
+ this.dispatchEvent(
1583
+ new CustomEvent("data", {
1584
+ detail: new DataEvent({
1585
+ data: pubsubMessage,
1586
+ message,
1587
+ }),
1588
+ }),
603
1589
  );
1590
+ return;
1591
+ }
604
1592
 
605
- let isForMe: boolean;
606
- if (pubsubMessage.strict) {
607
- isForMe =
608
- !!pubsubMessage.topics.find((topic) =>
609
- this.subscriptions.has(topic),
610
- ) && meInTOs;
611
- } else {
612
- isForMe =
613
- !!pubsubMessage.topics.find((topic) =>
614
- this.subscriptions.has(topic),
615
- ) ||
616
- (pubsubMessage.topics.length === 0 && meInTOs);
617
- }
1593
+ if (pubsubMessage instanceof Subscribe) {
1594
+ const sender = from;
1595
+ const senderKey = sender.hashcode();
1596
+ const relevantTopics = pubsubMessage.topics.filter((t) =>
1597
+ this.isTrackedTopic(t),
1598
+ );
618
1599
 
619
- if (isForMe) {
620
- if ((await this.verifyAndProcess(message)) === false) {
621
- warn("Recieved message that did not verify PubSubData");
622
- return false;
623
- }
624
- }
1600
+ if (
1601
+ relevantTopics.length > 0 &&
1602
+ this.subscriptionMessageIsLatest(message, pubsubMessage, relevantTopics)
1603
+ ) {
1604
+ const changed: string[] = [];
1605
+ for (const topic of relevantTopics) {
1606
+ const peers = this.topics.get(topic);
1607
+ if (!peers) continue;
1608
+ this.initializePeer(sender);
1609
+
1610
+ const existing = peers.get(senderKey);
1611
+ if (!existing || existing.session < message.header.session) {
1612
+ peers.delete(senderKey);
1613
+ peers.set(
1614
+ senderKey,
1615
+ new SubscriptionData({
1616
+ session: message.header.session,
1617
+ timestamp: message.header.timestamp,
1618
+ publicKey: sender,
1619
+ }),
1620
+ );
1621
+ changed.push(topic);
1622
+ } else {
1623
+ peers.delete(senderKey);
1624
+ peers.set(senderKey, existing);
1625
+ }
625
1626
 
626
- await this.maybeAcknowledgeMessage(stream, message, seenBefore);
1627
+ if (!existing) {
1628
+ this.peerToTopic.get(senderKey)!.add(topic);
1629
+ }
1630
+ this.pruneTopicSubscribers(topic);
1631
+ }
627
1632
 
628
- if (isForMe) {
629
- if (seenBefore === 0) {
1633
+ if (changed.length > 0) {
630
1634
  this.dispatchEvent(
631
- new CustomEvent("data", {
632
- detail: new DataEvent({
633
- data: pubsubMessage,
634
- message,
635
- }),
1635
+ new CustomEvent<SubscriptionEvent>("subscribe", {
1636
+ detail: new SubscriptionEvent(sender, changed),
636
1637
  }),
637
1638
  );
638
1639
  }
639
1640
  }
640
1641
 
641
- // Forward
642
- if (!pubsubMessage.strict) {
643
- this.addPeersOnTopic(
644
- message as DataMessage<
645
- SeekDelivery | SilentDelivery | AcknowledgeDelivery
646
- >,
647
- pubsubMessage.topics,
648
- );
1642
+ if (pubsubMessage.requestSubscribers) {
1643
+ const overlap = this.getSubscriptionOverlap(pubsubMessage.topics);
1644
+ if (overlap.length > 0) {
1645
+ const response = new Subscribe({
1646
+ topics: overlap,
1647
+ requestSubscribers: false,
1648
+ });
1649
+ const embedded = await this.createMessage(
1650
+ toUint8Array(response.bytes()),
1651
+ {
1652
+ mode: new AnyWhere(),
1653
+ priority: 1,
1654
+ skipRecipientValidation: true,
1655
+ } as any,
1656
+ );
1657
+ const payload = toUint8Array(embedded.bytes());
1658
+ await this.sendFanoutUnicastOrBroadcast(
1659
+ shardTopic,
1660
+ senderKey,
1661
+ payload,
1662
+ );
1663
+ }
649
1664
  }
1665
+ return;
1666
+ }
1667
+
1668
+ if (pubsubMessage instanceof Unsubscribe) {
1669
+ const sender = from;
1670
+ const senderKey = sender.hashcode();
1671
+ const relevantTopics = pubsubMessage.topics.filter((t) =>
1672
+ this.isTrackedTopic(t),
1673
+ );
650
1674
 
651
- // Only relay if we got additional receivers
652
- // or we are NOT subscribing ourselves (if we are not subscribing ourselves we are)
653
- // If we are not subscribing ourselves, then we don't have enough information to "stop" message propagation here
654
1675
  if (
655
- message.header.mode.to?.length ||
656
- !pubsubMessage.topics.find((topic) => this.topics.has(topic)) ||
657
- message.header.mode instanceof SeekDelivery
1676
+ relevantTopics.length > 0 &&
1677
+ this.subscriptionMessageIsLatest(message, pubsubMessage, relevantTopics)
658
1678
  ) {
659
- // DONT await this since it might introduce a dead-lock
660
- this.relayMessage(from, message).catch(logErrorIfStarted);
661
- }
662
- } else {
663
- if ((await this.verifyAndProcess(message)) === false) {
664
- warn("Recieved message that did not verify Unsubscribe");
665
- return false;
666
- }
667
-
668
- if (message.header.signatures!.signatures.length === 0) {
669
- warn("Recieved subscription message with no signers");
670
- return false;
1679
+ const changed: string[] = [];
1680
+ for (const topic of relevantTopics) {
1681
+ const peers = this.topics.get(topic);
1682
+ if (!peers) continue;
1683
+ if (peers.delete(senderKey)) {
1684
+ changed.push(topic);
1685
+ this.peerToTopic.get(senderKey)?.delete(topic);
1686
+ }
1687
+ }
1688
+ if (!this.peerToTopic.get(senderKey)?.size) {
1689
+ this.peerToTopic.delete(senderKey);
1690
+ this.lastSubscriptionMessages.delete(senderKey);
1691
+ }
1692
+ if (changed.length > 0) {
1693
+ this.dispatchEvent(
1694
+ new CustomEvent<UnsubcriptionEvent>("unsubscribe", {
1695
+ detail: new UnsubcriptionEvent(sender, changed),
1696
+ }),
1697
+ );
1698
+ }
671
1699
  }
1700
+ return;
1701
+ }
672
1702
 
673
- await this.maybeAcknowledgeMessage(stream, message, seenBefore);
1703
+ if (pubsubMessage instanceof GetSubscribers) {
1704
+ const sender = from;
1705
+ const senderKey = sender.hashcode();
1706
+ const overlap = this.getSubscriptionOverlap(pubsubMessage.topics);
1707
+ if (overlap.length === 0) return;
674
1708
 
675
- const sender = message.header.signatures!.signatures[0].publicKey!;
676
- const senderKey = sender.hashcode(); // Assume first signature is the one who is signing
1709
+ const response = new Subscribe({
1710
+ topics: overlap,
1711
+ requestSubscribers: false,
1712
+ });
1713
+ const embedded = await this.createMessage(
1714
+ toUint8Array(response.bytes()),
1715
+ {
1716
+ mode: new AnyWhere(),
1717
+ priority: 1,
1718
+ skipRecipientValidation: true,
1719
+ } as any,
1720
+ );
1721
+ const payload = toUint8Array(embedded.bytes());
1722
+ await this.sendFanoutUnicastOrBroadcast(shardTopic, senderKey, payload);
1723
+ return;
1724
+ }
1725
+ }
677
1726
 
678
- if (pubsubMessage instanceof Subscribe) {
679
- if (
680
- seenBefore === 0 &&
681
- this.subscriptionMessageIsLatest(message, pubsubMessage) &&
682
- pubsubMessage.topics.length > 0
683
- ) {
684
- const changed: string[] = [];
685
- pubsubMessage.topics.forEach((topic) => {
686
- const peers = this.topics.get(topic);
687
- if (peers == null) {
688
- return;
689
- }
690
-
691
- this.initializePeer(sender);
692
-
693
- // if no subscription data, or new subscription has data (and is newer) then overwrite it.
694
- // subscription where data is undefined is not intended to replace existing data
695
- const existingSubscription = peers.get(senderKey);
696
-
697
- if (
698
- !existingSubscription ||
699
- existingSubscription.session < message.header.session
700
- ) {
701
- peers.set(
702
- senderKey,
703
- new SubscriptionData({
704
- session: message.header.session,
705
- timestamp: message.header.timestamp, // TODO update timestamps on all messages?
706
- publicKey: sender,
707
- }),
708
- );
709
-
710
- changed.push(topic);
711
- }
712
-
713
- if (!existingSubscription) {
714
- this.topicsToPeers.get(topic)?.add(senderKey);
715
- this.peerToTopic.get(senderKey)?.add(topic);
716
- }
717
- });
1727
+ public override async onDataMessage(
1728
+ from: PublicSignKey,
1729
+ stream: PeerStreams,
1730
+ message: DataMessage,
1731
+ seenBefore: number,
1732
+ ) {
1733
+ if (!message.data || message.data.length === 0) {
1734
+ return super.onDataMessage(from, stream, message, seenBefore);
1735
+ }
1736
+ if (this.shouldIgnore(message, seenBefore)) return false;
718
1737
 
719
- if (changed.length > 0) {
720
- this.dispatchEvent(
721
- new CustomEvent<SubscriptionEvent>("subscribe", {
722
- detail: new SubscriptionEvent(sender, changed),
723
- }),
724
- );
725
- }
1738
+ let pubsubMessage: PubSubMessage;
1739
+ try {
1740
+ pubsubMessage = PubSubMessage.from(message.data);
1741
+ } catch {
1742
+ return super.onDataMessage(from, stream, message, seenBefore);
1743
+ }
726
1744
 
727
- if (pubsubMessage.requestSubscribers) {
728
- // respond if we are subscribing
729
- const mySubscriptions = this.getSubscriptionOverlap(
730
- pubsubMessage.topics,
731
- );
732
- if (mySubscriptions.length > 0) {
733
- const response = new DataMessage({
734
- data: toUint8Array(
735
- new Subscribe({
736
- topics: mySubscriptions,
737
- requestSubscribers: false,
738
- }).bytes(),
739
- ),
740
- // needs to be Ack or Silent else we will run into a infite message loop
741
- header: new MessageHeader({
742
- session: this.session,
743
- priority: 1,
744
- mode: new SeekDelivery({
745
- redundancy: 2,
746
- to: [senderKey],
747
- }),
748
- }),
749
- });
750
-
751
- this.publishMessage(
752
- this.publicKey,
753
- await response.sign(this.sign),
754
- ).catch(dontThrowIfDeliveryError);
755
- }
756
- }
757
- }
1745
+ // DirectStream only supports targeted pubsub data and a small set of utility
1746
+ // messages. All membership/control traffic is shard-only.
1747
+ if (
1748
+ !(pubsubMessage instanceof PubSubData) &&
1749
+ !(pubsubMessage instanceof TopicRootCandidates)
1750
+ ) {
1751
+ return true;
1752
+ }
758
1753
 
759
- // Forward
760
- // DONT await this since it might introduce a dead-lock
761
- this.relayMessage(from, message).catch(logErrorIfStarted);
762
- } else if (pubsubMessage instanceof Unsubscribe) {
763
- if (this.subscriptionMessageIsLatest(message, pubsubMessage)) {
764
- const changed: string[] = [];
765
-
766
- for (const unsubscription of pubsubMessage.topics) {
767
- const change = this.deletePeerFromTopic(unsubscription, senderKey);
768
- if (change) {
769
- changed.push(unsubscription);
770
- }
771
- }
1754
+ // Determine if this node should process it.
1755
+ let isForMe = false;
1756
+ if (deliveryModeHasReceiver(message.header.mode)) {
1757
+ isForMe = message.header.mode.to.includes(this.publicKeyHash);
1758
+ } else if (
1759
+ message.header.mode instanceof AnyWhere ||
1760
+ message.header.mode instanceof AcknowledgeAnyWhere
1761
+ ) {
1762
+ isForMe = true;
1763
+ }
772
1764
 
773
- if (changed.length > 0 && seenBefore === 0) {
774
- this.dispatchEvent(
775
- new CustomEvent<UnsubcriptionEvent>("unsubscribe", {
776
- detail: new UnsubcriptionEvent(sender, changed),
777
- }),
778
- );
779
- }
1765
+ if (pubsubMessage instanceof PubSubData) {
1766
+ const wantsTopic = pubsubMessage.topics.some((t) =>
1767
+ this.subscriptions.has(t) || this.pendingSubscriptions.has(t),
1768
+ );
1769
+ isForMe = pubsubMessage.strict ? isForMe && wantsTopic : wantsTopic;
1770
+ }
780
1771
 
781
- // Forwarding
782
- if (
783
- message.header.mode instanceof SeekDelivery ||
784
- message.header.mode instanceof SilentDelivery ||
785
- message.header.mode instanceof AcknowledgeDelivery
786
- ) {
787
- this.addPeersOnTopic(
788
- message as DataMessage<
789
- SeekDelivery | SilentDelivery | AcknowledgeDelivery
790
- >,
791
- pubsubMessage.topics,
792
- );
793
- }
794
- }
1772
+ if (isForMe) {
1773
+ if ((await this.verifyAndProcess(message)) === false) return false;
1774
+ await this.maybeAcknowledgeMessage(stream, message, seenBefore);
1775
+ if (seenBefore === 0) {
1776
+ await this.processDirectPubSubMessage({ pubsubMessage, message });
1777
+ }
1778
+ }
795
1779
 
796
- // DONT await this since it might introduce a dead-lock
797
- this.relayMessage(from, message).catch(logErrorIfStarted);
798
- } else if (pubsubMessage instanceof GetSubscribers) {
799
- const subscriptionsToSend: string[] = this.getSubscriptionOverlap(
800
- pubsubMessage.topics,
801
- );
802
- if (subscriptionsToSend.length > 0) {
803
- // respond
804
- this.publishMessage(
805
- this.publicKey,
806
- await new DataMessage({
807
- data: toUint8Array(
808
- new Subscribe({
809
- topics: subscriptionsToSend,
810
- requestSubscribers: false,
811
- }).bytes(),
812
- ),
813
- header: new MessageHeader({
814
- priority: 1,
815
- mode: new SilentDelivery({
816
- redundancy: 2,
817
- to: [sender.hashcode()],
818
- }),
819
- session: this.session,
820
- }),
821
- }).sign(this.sign),
822
- [stream],
823
- ).catch(dontThrowIfDeliveryError); // send back to same stream
824
- }
1780
+ // Forward direct PubSubData only (subscription control lives on fanout shards).
1781
+ if (!(pubsubMessage instanceof PubSubData)) {
1782
+ return true;
1783
+ }
825
1784
 
826
- // Forward
827
- // DONT await this since it might introduce a dead-lock
828
- this.relayMessage(from, message).catch(logErrorIfStarted);
1785
+ if (
1786
+ message.header.mode instanceof SilentDelivery ||
1787
+ message.header.mode instanceof AcknowledgeDelivery
1788
+ ) {
1789
+ if (
1790
+ message.header.mode.to.length === 1 &&
1791
+ message.header.mode.to[0] === this.publicKeyHash
1792
+ ) {
1793
+ return true;
829
1794
  }
830
1795
  }
1796
+
1797
+ const shouldForward =
1798
+ seenBefore === 0 ||
1799
+ ((message.header.mode instanceof AcknowledgeDelivery ||
1800
+ message.header.mode instanceof AcknowledgeAnyWhere) &&
1801
+ seenBefore < message.header.mode.redundancy);
1802
+ if (shouldForward) {
1803
+ this.relayMessage(from, message).catch(logErrorIfStarted);
1804
+ }
831
1805
  return true;
832
1806
  }
833
1807
  }
@@ -862,21 +1836,36 @@ export const waitForSubscribers = async (
862
1836
  });
863
1837
 
864
1838
  return new Promise<void>((resolve, reject) => {
1839
+ if (peerIdsToWait.length === 0) {
1840
+ resolve();
1841
+ return;
1842
+ }
1843
+
865
1844
  let settled = false;
866
- let counter = 0;
867
1845
  let timeout: ReturnType<typeof setTimeout> | undefined = undefined;
868
1846
  let interval: ReturnType<typeof setInterval> | undefined = undefined;
1847
+ let pollInFlight = false;
1848
+ const wanted = new Set(peerIdsToWait);
1849
+ const seen = new Set<string>();
1850
+ const pubsub = libp2p.services.pubsub;
1851
+ const shouldRejectWithTimeoutError = options?.timeout != null;
869
1852
 
870
1853
  const clear = () => {
871
- if (interval) {
872
- clearInterval(interval);
873
- interval = undefined;
874
- }
875
1854
  if (timeout) {
876
1855
  clearTimeout(timeout);
877
1856
  timeout = undefined;
878
1857
  }
1858
+ if (interval) {
1859
+ clearInterval(interval);
1860
+ interval = undefined;
1861
+ }
879
1862
  options?.signal?.removeEventListener("abort", onAbort);
1863
+ try {
1864
+ pubsub.removeEventListener("subscribe", onSubscribe);
1865
+ pubsub.removeEventListener("unsubscribe", onUnsubscribe);
1866
+ } catch {
1867
+ // ignore
1868
+ }
880
1869
  };
881
1870
 
882
1871
  const resolveOnce = () => {
@@ -897,6 +1886,47 @@ export const waitForSubscribers = async (
897
1886
  rejectOnce(new AbortError("waitForSubscribers was aborted"));
898
1887
  };
899
1888
 
1889
+ const updateSeen = (hash?: string, isSubscribed?: boolean) => {
1890
+ if (!hash) return false;
1891
+ if (!wanted.has(hash)) return false;
1892
+ if (isSubscribed) {
1893
+ seen.add(hash);
1894
+ } else {
1895
+ seen.delete(hash);
1896
+ }
1897
+ return seen.size === wanted.size;
1898
+ };
1899
+
1900
+ const reconcileFromSubscribers = (peers?: PublicSignKey[]) => {
1901
+ const current = new Set<string>();
1902
+ for (const peer of peers || []) current.add(peer.hashcode());
1903
+ for (const hash of wanted) {
1904
+ if (current.has(hash)) seen.add(hash);
1905
+ else seen.delete(hash);
1906
+ }
1907
+ if (seen.size === wanted.size) resolveOnce();
1908
+ };
1909
+
1910
+ const onSubscribe = (ev: any) => {
1911
+ const detail = ev?.detail as SubscriptionEvent | undefined;
1912
+ if (!detail) return;
1913
+ if (!detail.topics || detail.topics.length === 0) return;
1914
+ if (!detail.topics.includes(topic)) return;
1915
+ const hash = detail.from?.hashcode?.();
1916
+ if (updateSeen(hash, true)) {
1917
+ resolveOnce();
1918
+ }
1919
+ };
1920
+
1921
+ const onUnsubscribe = (ev: any) => {
1922
+ const detail = ev?.detail as UnsubcriptionEvent | undefined;
1923
+ if (!detail) return;
1924
+ if (!detail.topics || detail.topics.length === 0) return;
1925
+ if (!detail.topics.includes(topic)) return;
1926
+ const hash = detail.from?.hashcode?.();
1927
+ updateSeen(hash, false);
1928
+ };
1929
+
900
1930
  if (options?.signal?.aborted) {
901
1931
  rejectOnce(new AbortError("waitForSubscribers was aborted"));
902
1932
  return;
@@ -904,32 +1934,47 @@ export const waitForSubscribers = async (
904
1934
 
905
1935
  options?.signal?.addEventListener("abort", onAbort);
906
1936
 
907
- if (options?.timeout != null) {
1937
+ // Preserve previous behavior: without an explicit timeout, fail after ~20s.
1938
+ const timeoutMs = Math.max(0, Math.floor(options?.timeout ?? 20_000));
1939
+ if (timeoutMs > 0) {
908
1940
  timeout = setTimeout(() => {
909
- rejectOnce(new TimeoutError("waitForSubscribers timed out"));
910
- }, options.timeout);
911
- }
912
-
913
- interval = setInterval(async () => {
914
- counter += 1;
915
- if (counter > 100) {
916
1941
  rejectOnce(
917
- new Error("Failed to find expected subscribers for topic: " + topic),
1942
+ shouldRejectWithTimeoutError
1943
+ ? new TimeoutError("waitForSubscribers timed out")
1944
+ : new Error(
1945
+ "Failed to find expected subscribers for topic: " + topic,
1946
+ ),
918
1947
  );
919
- return;
920
- }
921
- try {
922
- const peers = await libp2p.services.pubsub.getSubscribers(topic);
923
- const hasAllPeers =
924
- peerIdsToWait.filter((e) => !peers?.find((x) => x.hashcode() === e))
925
- .length === 0;
1948
+ }, timeoutMs);
1949
+ }
926
1950
 
927
- if (hasAllPeers) {
928
- resolveOnce();
929
- }
930
- } catch (e) {
931
- rejectOnce(e);
932
- }
933
- }, 200);
1951
+ // Observe new subscriptions.
1952
+ try {
1953
+ void pubsub.addEventListener("subscribe", onSubscribe);
1954
+ void pubsub.addEventListener("unsubscribe", onUnsubscribe);
1955
+ } catch (e) {
1956
+ rejectOnce(e);
1957
+ return;
1958
+ }
1959
+
1960
+ const poll = () => {
1961
+ if (settled) return;
1962
+ if (pollInFlight) return;
1963
+ pollInFlight = true;
1964
+ void Promise.resolve(pubsub.getSubscribers(topic))
1965
+ .then((peers) => {
1966
+ if (settled) return;
1967
+ reconcileFromSubscribers(peers || []);
1968
+ })
1969
+ .catch((e) => rejectOnce(e))
1970
+ .finally(() => {
1971
+ pollInFlight = false;
1972
+ });
1973
+ };
1974
+
1975
+ // Polling is a fallback for cases where no event is emitted (e.g. local subscribe completion),
1976
+ // and keeps behavior stable across implementations.
1977
+ poll();
1978
+ interval = setInterval(poll, 200);
934
1979
  });
935
1980
  };