@minip2p/core 0.9.1 → 0.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,833 @@
1
+ /* oxlint-disable class-methods-use-this, func-style, max-classes-per-file, max-lines, no-use-before-define -- The shared serde-shaped backend keeps the contract-complete native endpoint, value conversion, and handle maps together at the binding boundary. */
2
+
3
+ /**
4
+ * The backend shared by the shells whose native endpoint hands values over
5
+ * in `minip2p-ffi-core`'s serde shape: the Node addon (napi-rs) and the
6
+ * browser's wasm module (wasm-bindgen). Each adapter supplies its native
7
+ * endpoint and how to schedule event batches; ID mapping, value conversion,
8
+ * stream settlement and error typing live here once.
9
+ */
10
+
11
+ import { NativeCloseLatch, typedFfiError, unfinishedPeers } from "./backend.js";
12
+ import type {
13
+ BackendClosed,
14
+ BackendConnectionInfo,
15
+ BackendConnectTarget,
16
+ BackendOpenStream,
17
+ Minip2pBackend,
18
+ } from "./backend.js";
19
+ import { StreamClosedError } from "./errors.js";
20
+ import { EventDrain } from "./event-drain.js";
21
+ import { ConnectionIdMap, u64ToNumber } from "./native-ids.js";
22
+ import { SettleHandles, eventStream } from "./settle-handles.js";
23
+ import { CloseOutcome, DriverFailureKind, P2pEvent_Tags } from "./types.js";
24
+ import type {
25
+ IdentifyInfo,
26
+ KnownPeerInfo,
27
+ PathKind,
28
+ P2pEvent,
29
+ Reachability,
30
+ RelayReservationInfo,
31
+ } from "./types.js";
32
+
33
+ /**
34
+ * One SDK backend value as a serde shell encodes it: `u64` as a `number` or
35
+ * a `bigint` (napi-rs switches above `u32::MAX`; wasm-bindgen always uses
36
+ * `bigint`), and bytes as a `Uint8Array`.
37
+ */
38
+ export type NativeShape<Value> = Value extends ArrayBuffer
39
+ ? Uint8Array
40
+ : Value extends number
41
+ ? number | bigint
42
+ : Value extends string | boolean
43
+ ? Value
44
+ : Value extends readonly (infer Item)[]
45
+ ? readonly NativeShape<Item>[]
46
+ : { readonly [Key in keyof Value]: NativeShape<Value[Key]> };
47
+
48
+ export type NativeEvent = NativeShape<P2pEvent>;
49
+ export type NativeIdentifyInfo = NativeShape<IdentifyInfo>;
50
+ export type NativeKnownPeerInfo = NativeShape<KnownPeerInfo>;
51
+ export type NativeRelayReservationInfo = NativeShape<RelayReservationInfo>;
52
+ export type NativeConnectionInfo = NativeShape<BackendConnectionInfo>;
53
+ export type NativeOpenStream = NativeShape<BackendOpenStream>;
54
+ export type NativePathKind = NativeShape<PathKind>;
55
+
56
+ /**
57
+ * A native endpoint in the serde shape: the Node addon's `NodeEndpoint` and
58
+ * the wasm module's `WebEndpoint` both have this surface. Absent values are
59
+ * `null`; a failed call throws an `Error` tagged with the `FfiError`'s
60
+ * `code`, `detail` and `capability`.
61
+ */
62
+ export interface SerdeEndpoint {
63
+ start: (doorbell: () => void) => void;
64
+ close: (timeoutMs: number) => void;
65
+ peerId: () => string;
66
+ listenAddrs: () => string[];
67
+ isRunning: () => boolean;
68
+ drainEvents: (limit: number) => NativeEvent[];
69
+ connectedPeers: () => string[];
70
+ isPeerReady: (peerId: string) => boolean;
71
+ peerInfo: (peerId: string) => NativeIdentifyInfo | null;
72
+ setActive: (active: boolean) => void;
73
+ subscribe: (topic: string) => boolean;
74
+ unsubscribe: (topic: string) => boolean;
75
+ publish: (topic: string, data: Uint8Array) => void;
76
+ ping: (peerId: string) => void;
77
+ addProtocol: (protocolId: string) => void;
78
+ openStream: (peerId: string, protocolId: string) => NativeOpenStream;
79
+ sendStream: (connId: bigint, streamId: bigint, data: Uint8Array) => boolean;
80
+ closeStreamWrite: (connId: bigint, streamId: bigint) => void;
81
+ resetStream: (connId: bigint, streamId: bigint) => void;
82
+ abandonStream: (connId: bigint, streamId: bigint) => void;
83
+ streamConsumed: (connId: bigint, streamId: bigint, bytes: number) => void;
84
+ connect: (target: string | string[]) => bigint;
85
+ cancelConnect: (id: bigint) => void;
86
+ disconnect: (peerId: string) => void;
87
+ path: (peerId: string) => NativePathKind | null;
88
+ connectionInfo: (peerId: string) => NativeConnectionInfo | null;
89
+ knownPeers: () => NativeKnownPeerInfo[];
90
+ discoveryNowMs: () => bigint | null;
91
+ reachability: () => Reachability;
92
+ activeReservation: () => NativeRelayReservationInfo | null;
93
+ }
94
+
95
+ /** How one serde shell runs its native endpoint. */
96
+ export interface SerdeBackendOptions {
97
+ /** Runs a native event batch on a later turn (see {@link EventDrain}). */
98
+ readonly schedule: (task: () => void) => void;
99
+ /**
100
+ * Wraps every native call. The browser shell uses it to stop calling a
101
+ * crashed wasm instance and to pump the endpoint after each command;
102
+ * the default calls straight through.
103
+ */
104
+ readonly call?: <T>(operation: () => T) => T;
105
+ /** The shell's circuit-address helper (a module function of its native). */
106
+ readonly circuitAddress: (relayAddress: string, peerId: string) => string;
107
+ /**
108
+ * Frees the native endpoint once `close` finished and its final events
109
+ * drained; nothing calls native after it. The browser shell frees its
110
+ * wasm object here; without it, the garbage collector does.
111
+ */
112
+ readonly release?: () => void;
113
+ }
114
+
115
+ /** Native drain batch size. */
116
+ const DRAIN_LIMIT = 256;
117
+
118
+ /**
119
+ * Runs a native call outside a backend (the endpoint constructor, the key
120
+ * and address helpers), rethrowing a tagged `FfiError` as its typed SDK
121
+ * error as the backend does for its own calls.
122
+ */
123
+ export function typedNativeCall<T>(operation: () => T): T {
124
+ return translateErrors(operation);
125
+ }
126
+
127
+ /** The {@link Minip2pBackend} over a {@link SerdeEndpoint}. */
128
+ export class SerdeBackend implements Minip2pBackend {
129
+ readonly #connectionIds = new ConnectionIdMap();
130
+ readonly #endpoint: SerdeEndpoint;
131
+ readonly #options: SerdeBackendOptions;
132
+ readonly #streamIds = new StreamIdMap();
133
+ /** Native stream identities while their events are in flight (ADR 0012). */
134
+ readonly #settleHandles = new SettleHandles<[bigint, bigint]>();
135
+ readonly #close = new NativeCloseLatch();
136
+ #events: EventDrain<NativeEvent> | undefined;
137
+ #listener: ((event: P2pEvent) => void) | undefined;
138
+ #failed = false;
139
+ #started = false;
140
+
141
+ constructor(endpoint: SerdeEndpoint, options: SerdeBackendOptions) {
142
+ this.#endpoint = endpoint;
143
+ this.#options = options;
144
+ }
145
+
146
+ start(listener: (event: P2pEvent) => void): void {
147
+ this.#listener = listener;
148
+ const events = new EventDrain(
149
+ (limit) => this.#drain(limit),
150
+ (event: NativeEvent) => {
151
+ if (event.tag === P2pEvent_Tags.EndpointClosed) {
152
+ events.stop();
153
+ this.#close.settle({
154
+ outcome: event.inner.outcome,
155
+ unfinished: unfinishedPeers(event.inner.unfinished),
156
+ });
157
+ return;
158
+ }
159
+ // The SDK has stopped listening; only `EndpointClosed` matters now.
160
+ if (this.#close.requested) {
161
+ return;
162
+ }
163
+ const normalized = normalizeEvent(
164
+ event,
165
+ this.#connectionIds,
166
+ this.#streamIds
167
+ );
168
+ const stream = eventStream(normalized);
169
+ const native = nativeStreamOf(event);
170
+ if (stream !== undefined && native !== undefined) {
171
+ this.#settleHandles.hold(stream.connId, stream.streamId, native);
172
+ }
173
+ listener(normalized);
174
+ },
175
+ DRAIN_LIMIT,
176
+ this.#options.schedule
177
+ );
178
+ this.#events = events;
179
+ this.#native((native) => {
180
+ native.start(() => {
181
+ events.ring();
182
+ });
183
+ });
184
+ this.#started = true;
185
+ }
186
+
187
+ /**
188
+ * Fails the endpoint without native's help, for a native instance that
189
+ * can no longer run (a trapped wasm module): `DriverFailed` reaches the
190
+ * SDK on a later turn and `close` resolves `Failed` without calling
191
+ * native again. Idempotent. Once `close` was requested it only settles
192
+ * `close`: the SDK no longer listens for events.
193
+ */
194
+ fail(detail: string): void {
195
+ if (this.#failed) {
196
+ return;
197
+ }
198
+ this.#failed = true;
199
+ this.#events?.stop();
200
+ this.#close.settle({ outcome: CloseOutcome.Failed, unfinished: [] });
201
+ if (this.#close.requested) {
202
+ return;
203
+ }
204
+ const listener = this.#listener;
205
+ if (listener !== undefined) {
206
+ queueMicrotask(() => {
207
+ listener({
208
+ inner: { detail, kind: DriverFailureKind.Panic },
209
+ tag: P2pEvent_Tags.DriverFailed,
210
+ });
211
+ });
212
+ }
213
+ }
214
+
215
+ eventHandled(event: P2pEvent): void {
216
+ releaseTerminalIds(event, this.#streamIds);
217
+ const stream = eventStream(event);
218
+ if (stream !== undefined) {
219
+ this.#settleHandles.release(stream.connId, stream.streamId);
220
+ }
221
+ }
222
+
223
+ close(timeoutMs: number): Promise<BackendClosed> {
224
+ return this.#close.close(
225
+ this.#started,
226
+ () => {
227
+ if (!this.#failed) {
228
+ this.#native((native) => {
229
+ native.close(timeoutMs);
230
+ });
231
+ }
232
+ },
233
+ () => {
234
+ this.#events?.stop();
235
+ this.#events = undefined;
236
+ this.#options.release?.();
237
+ }
238
+ );
239
+ }
240
+
241
+ /** One native drain; a throw means native can no longer run. */
242
+ #drain(limit: number): NativeEvent[] {
243
+ try {
244
+ return this.#native((native) => native.drainEvents(limit));
245
+ } catch (error) {
246
+ this.fail(
247
+ `draining native events failed: ${error instanceof Error ? error.message : String(error)}`
248
+ );
249
+ return [];
250
+ }
251
+ }
252
+
253
+ peerId(): string {
254
+ return this.#native((native) => native.peerId());
255
+ }
256
+
257
+ listenAddrs(): string[] {
258
+ return this.#native((native) => native.listenAddrs());
259
+ }
260
+
261
+ isRunning(): boolean {
262
+ return !this.#failed && this.#native((native) => native.isRunning());
263
+ }
264
+
265
+ connectedPeers(): string[] {
266
+ return this.#native((native) => native.connectedPeers());
267
+ }
268
+
269
+ isPeerReady(peerId: string): boolean {
270
+ return this.#native((native) => native.isPeerReady(peerId));
271
+ }
272
+
273
+ peerInfo(peerId: string): IdentifyInfo | undefined {
274
+ const info = this.#native((native) => native.peerInfo(peerId));
275
+ return info === null ? undefined : identifyInfo(info);
276
+ }
277
+
278
+ knownPeers(): KnownPeerInfo[] {
279
+ return this.#native((native) => native.knownPeers()).map(knownPeer);
280
+ }
281
+
282
+ discoveryNowMs(): number | undefined {
283
+ const value = this.#native((native) => native.discoveryNowMs());
284
+ return value === null ? undefined : u64ToNumber(value, "clock");
285
+ }
286
+
287
+ activeReservation(): RelayReservationInfo | undefined {
288
+ const reservation = this.#native((native) => native.activeReservation());
289
+ return reservation === null ? undefined : relayReservation(reservation);
290
+ }
291
+
292
+ path(peerId: string): PathKind | undefined {
293
+ return this.#native((native) => native.path(peerId)) ?? undefined;
294
+ }
295
+
296
+ connectionInfo(peerId: string): BackendConnectionInfo | undefined {
297
+ const info = this.#native((native) => native.connectionInfo(peerId));
298
+ if (info === null) {
299
+ return undefined;
300
+ }
301
+ const { connId, ...rest } = info;
302
+ return {
303
+ ...rest,
304
+ connId: this.#connectionIds.toPublic(BigInt(connId)),
305
+ };
306
+ }
307
+
308
+ circuitAddress(relayAddress: string, peerId: string): string {
309
+ return this.#options.circuitAddress(relayAddress, peerId);
310
+ }
311
+
312
+ reachability(): Reachability {
313
+ return this.#native((native) => native.reachability());
314
+ }
315
+
316
+ setActive(active: boolean): void {
317
+ this.#native((native) => {
318
+ native.setActive(active);
319
+ });
320
+ }
321
+
322
+ subscribe(topic: string): boolean {
323
+ return this.#native((native) => native.subscribe(topic));
324
+ }
325
+
326
+ unsubscribe(topic: string): boolean {
327
+ return this.#native((native) => native.unsubscribe(topic));
328
+ }
329
+
330
+ publish(topic: string, data: Uint8Array): void {
331
+ this.#native((native) => {
332
+ native.publish(topic, data);
333
+ });
334
+ }
335
+
336
+ ping(peerId: string): void {
337
+ this.#native((native) => {
338
+ native.ping(peerId);
339
+ });
340
+ }
341
+
342
+ addProtocol(protocolId: string): void {
343
+ this.#native((native) => {
344
+ native.addProtocol(protocolId);
345
+ });
346
+ }
347
+
348
+ openStream(peerId: string, protocolId: string): BackendOpenStream {
349
+ const stream = this.#native((native) =>
350
+ native.openStream(peerId, protocolId)
351
+ );
352
+ const connId = this.#connectionIds.toPublic(BigInt(stream.connId));
353
+ return {
354
+ connId,
355
+ streamId: this.#streamIds.toPublic(connId, BigInt(stream.streamId)),
356
+ };
357
+ }
358
+
359
+ sendStream(connId: number, streamId: number, data: Uint8Array): boolean {
360
+ const [nativeConn, nativeStream] = this.#nativeStream(connId, streamId);
361
+ return this.#native((native) =>
362
+ native.sendStream(nativeConn, nativeStream, data)
363
+ );
364
+ }
365
+
366
+ closeStreamWrite(connId: number, streamId: number): void {
367
+ const [nativeConn, nativeStream] = this.#nativeStream(connId, streamId);
368
+ this.#native((native) => {
369
+ native.closeStreamWrite(nativeConn, nativeStream);
370
+ });
371
+ }
372
+
373
+ resetStream(connId: number, streamId: number): void {
374
+ const [nativeConn, nativeStream] = this.#nativeStream(connId, streamId);
375
+ this.#native((native) => {
376
+ native.resetStream(nativeConn, nativeStream);
377
+ });
378
+ }
379
+
380
+ abandonStream(connId: number, streamId: number): void {
381
+ const [nativeConn, nativeStream] = this.#settleStream(connId, streamId);
382
+ this.#native((native) => {
383
+ native.abandonStream(nativeConn, nativeStream);
384
+ });
385
+ }
386
+
387
+ streamConsumer(connId: number, streamId: number): (bytes: number) => void {
388
+ const [nativeConn, nativeStream] = this.#settleStream(connId, streamId);
389
+ return (bytes) => {
390
+ this.#native((native) => {
391
+ native.streamConsumed(nativeConn, nativeStream, bytes);
392
+ });
393
+ };
394
+ }
395
+
396
+ // Connect IDs are not mapped because they round-trip into native calls,
397
+ // and native allocates them well inside the safe integer range.
398
+ connect(target: BackendConnectTarget): number {
399
+ return u64ToNumber(
400
+ this.#native((native) =>
401
+ native.connect(
402
+ target.kind === "peer" ? target.peerId : [...target.addresses]
403
+ )
404
+ ),
405
+ "connectId"
406
+ );
407
+ }
408
+
409
+ cancelConnect(id: number): void {
410
+ this.#native((native) => {
411
+ native.cancelConnect(BigInt(id));
412
+ });
413
+ }
414
+
415
+ disconnect(peerId: string): void {
416
+ this.#native((native) => {
417
+ native.disconnect(peerId);
418
+ });
419
+ }
420
+
421
+ /** Runs one native call through the shell's wrapper, typing its errors. */
422
+ #native<T>(operation: (native: SerdeEndpoint) => T): T {
423
+ const { call } = this.#options;
424
+ const typed = (): T => translateErrors(() => operation(this.#endpoint));
425
+ return call === undefined ? typed() : call(typed);
426
+ }
427
+
428
+ /**
429
+ * Native connection and stream IDs for a public stream. Native names the
430
+ * stream by both, so an operation for a connection that native already
431
+ * replaced fails there instead of reaching a stream on the new connection.
432
+ * A connection whose close or replacement this adapter has already drained
433
+ * has no native ID, so the operation throws `StreamClosedError`.
434
+ */
435
+ #nativeStream(connId: number, streamId: number): [bigint, bigint] {
436
+ return [
437
+ this.#connectionIds.toNative(connId),
438
+ this.#streamIds.toNative(streamId),
439
+ ];
440
+ }
441
+
442
+ /**
443
+ * Native IDs for settling a stream: acknowledging or abandoning its bytes.
444
+ * Those still hold the native slot of a connection whose end this adapter
445
+ * already drained, so a stream with events in flight resolves through its
446
+ * settle handle once the live mapping is gone.
447
+ */
448
+ #settleStream(connId: number, streamId: number): [bigint, bigint] {
449
+ try {
450
+ return this.#nativeStream(connId, streamId);
451
+ } catch (error) {
452
+ const handle = this.#settleHandles.get(connId, streamId);
453
+ if (handle === undefined) {
454
+ throw error;
455
+ }
456
+ return handle;
457
+ }
458
+ }
459
+ }
460
+
461
+ /**
462
+ * Rethrows a native `FfiError` as its typed SDK error. The shells tag each
463
+ * error with the variant name as `code`, its detail field as `detail`, and
464
+ * an `InvalidConfig`'s capability name as `capability`; untyped variants are
465
+ * rethrown unchanged with those properties intact.
466
+ */
467
+ function translateErrors<T>(operation: () => T): T {
468
+ try {
469
+ return operation();
470
+ } catch (error) {
471
+ throw (
472
+ typedFfiError({
473
+ capability: stringProperty(error, "capability"),
474
+ detail: stringProperty(error, "detail"),
475
+ tag: stringProperty(error, "code"),
476
+ }) ?? error
477
+ );
478
+ }
479
+ }
480
+
481
+ function stringProperty(value: unknown, key: string): string | undefined {
482
+ if (value === null || typeof value !== "object") {
483
+ return undefined;
484
+ }
485
+ const property: unknown = Reflect.get(value, key);
486
+ return typeof property === "string" ? property : undefined;
487
+ }
488
+
489
+ /** Converts an Identify snapshot, copying its public key into an `ArrayBuffer`. */
490
+ function identifyInfo({
491
+ publicKey,
492
+ ...info
493
+ }: NativeIdentifyInfo): IdentifyInfo {
494
+ return {
495
+ ...info,
496
+ ...(publicKey !== undefined && { publicKey: toArrayBuffer(publicKey) }),
497
+ };
498
+ }
499
+
500
+ function knownPeer({
501
+ beaconLastSeenAgeMs,
502
+ mdnsLastSeenAgeMs,
503
+ ...peer
504
+ }: NativeKnownPeerInfo): KnownPeerInfo {
505
+ return {
506
+ ...peer,
507
+ ...(beaconLastSeenAgeMs !== undefined && {
508
+ beaconLastSeenAgeMs: u64ToNumber(
509
+ beaconLastSeenAgeMs,
510
+ "beaconLastSeenAgeMs"
511
+ ),
512
+ }),
513
+ ...(mdnsLastSeenAgeMs !== undefined && {
514
+ mdnsLastSeenAgeMs: u64ToNumber(mdnsLastSeenAgeMs, "mdnsLastSeenAgeMs"),
515
+ }),
516
+ };
517
+ }
518
+
519
+ function relayReservation({
520
+ expiresUnixSecs,
521
+ relayPeerId,
522
+ }: NativeRelayReservationInfo): RelayReservationInfo {
523
+ return {
524
+ relayPeerId,
525
+ ...(expiresUnixSecs !== undefined && {
526
+ expiresUnixSecs: u64ToNumber(expiresUnixSecs, "expiresUnixSecs"),
527
+ }),
528
+ };
529
+ }
530
+
531
+ /** Event fields carrying a native connection ID. */
532
+ const CONNECTION_ID_KEYS: ReadonlySet<string> = new Set([
533
+ "connId",
534
+ "oldConnId",
535
+ "newConnId",
536
+ ]);
537
+
538
+ /**
539
+ * Converts one value of a native `tag` event: integers to numbers, connection
540
+ * IDs through the connection map, and bytes to `ArrayBuffer`s. A stream ID is
541
+ * mapped together with the connection of the record that carries it.
542
+ */
543
+ function normalizeNativeValue(
544
+ value: unknown,
545
+ maps: NativeIdMaps,
546
+ tag: string,
547
+ key?: string
548
+ ): unknown {
549
+ if (typeof value === "bigint" || typeof value === "number") {
550
+ if (key !== undefined && CONNECTION_ID_KEYS.has(key)) {
551
+ return maps.connectionIds.toPublicInEvent(tag, key, BigInt(value));
552
+ }
553
+ // QUIC stop and close codes are 62-bit varints the remote picks: keep
554
+ // them whole.
555
+ if (key === "errorCode" || key === "code") {
556
+ return BigInt(value);
557
+ }
558
+ return key === "streamId" ? value : u64ToNumber(value, key ?? "native u64");
559
+ }
560
+ if (value instanceof Uint8Array) {
561
+ return toArrayBuffer(value);
562
+ }
563
+ if (Array.isArray(value)) {
564
+ return value.map((item) => normalizeNativeValue(item, maps, tag));
565
+ }
566
+ if (value === null || typeof value !== "object") {
567
+ return value;
568
+ }
569
+ const record: Record<string, unknown> = Object.fromEntries(
570
+ Object.entries(value).map(([itemKey, item]) => [
571
+ itemKey,
572
+ normalizeNativeValue(item, maps, tag, itemKey),
573
+ ])
574
+ );
575
+ const { connId, streamId } = record;
576
+ if (typeof streamId === "bigint" || typeof streamId === "number") {
577
+ // Public stream IDs are allocated per connection. A record without a
578
+ // connection (an endpoint error, say) cannot name a public stream.
579
+ if (typeof connId === "number") {
580
+ record.streamId = maps.streamIds.toPublic(connId, BigInt(streamId));
581
+ } else {
582
+ delete record.streamId;
583
+ }
584
+ }
585
+ return record;
586
+ }
587
+
588
+ /**
589
+ * Converts one native event to its SDK backend form, then retires the IDs it
590
+ * ends.
591
+ */
592
+ function normalizeEvent(
593
+ event: NativeEvent,
594
+ connectionIds: ConnectionIdMap,
595
+ streamIds: StreamIdMap
596
+ ): P2pEvent {
597
+ const normalized = convertEvent(event, { connectionIds, streamIds });
598
+ retireTerminalIds(normalized, connectionIds, streamIds);
599
+ return normalized;
600
+ }
601
+
602
+ /**
603
+ * Per-chunk and per-write events, and pubsub messages, convert field by
604
+ * field. Identify snapshots go through the typed {@link identifyInfo}, and a
605
+ * field-less event passes through by tag. The rest share the generic walk:
606
+ * either shell's serde shape is the SDK shape with native integers and
607
+ * bytes (see {@link NativeShape}).
608
+ */
609
+ function convertEvent(event: NativeEvent, maps: NativeIdMaps): P2pEvent {
610
+ switch (event.tag) {
611
+ case P2pEvent_Tags.StreamData: {
612
+ return {
613
+ inner: {
614
+ ...streamRef(event.inner, maps),
615
+ data: toArrayBuffer(event.inner.data),
616
+ },
617
+ tag: event.tag,
618
+ };
619
+ }
620
+ case P2pEvent_Tags.StreamWriteAccepted:
621
+ case P2pEvent_Tags.StreamRemoteWriteClosed:
622
+ case P2pEvent_Tags.StreamClosed: {
623
+ return { inner: streamRef(event.inner, maps), tag: event.tag };
624
+ }
625
+ case P2pEvent_Tags.Message: {
626
+ const { data, fromPeerId, seqno, signed, topics } = event.inner;
627
+ return {
628
+ inner: {
629
+ data: toArrayBuffer(data),
630
+ fromPeerId,
631
+ seqno: toArrayBuffer(seqno),
632
+ signed,
633
+ topics,
634
+ },
635
+ tag: event.tag,
636
+ };
637
+ }
638
+ case P2pEvent_Tags.IdentifyReceived: {
639
+ return {
640
+ inner: {
641
+ connId: maps.connectionIds.toPublic(BigInt(event.inner.connId)),
642
+ info: identifyInfo(event.inner.info),
643
+ peerId: event.inner.peerId,
644
+ },
645
+ tag: event.tag,
646
+ };
647
+ }
648
+ case P2pEvent_Tags.MdnsRecovered: {
649
+ return { tag: event.tag };
650
+ }
651
+ default: {
652
+ return {
653
+ inner: normalizeNativeValue(event.inner, maps, event.tag),
654
+ tag: event.tag,
655
+ } as P2pEvent;
656
+ }
657
+ }
658
+ }
659
+
660
+ /** The native identity of the stream a native stream event names. */
661
+ function nativeStreamOf(event: NativeEvent): [bigint, bigint] | undefined {
662
+ switch (event.tag) {
663
+ case P2pEvent_Tags.StreamReady:
664
+ case P2pEvent_Tags.StreamData:
665
+ case P2pEvent_Tags.StreamWriteAccepted:
666
+ case P2pEvent_Tags.StreamWriteStopped:
667
+ case P2pEvent_Tags.StreamRemoteWriteClosed:
668
+ case P2pEvent_Tags.StreamClosed: {
669
+ return [BigInt(event.inner.connId), BigInt(event.inner.streamId)];
670
+ }
671
+ default: {
672
+ return undefined;
673
+ }
674
+ }
675
+ }
676
+
677
+ /** The public identity of the stream a native stream event names. */
678
+ function streamRef(
679
+ inner: {
680
+ readonly peerId: string;
681
+ readonly connId: number | bigint;
682
+ readonly streamId: number | bigint;
683
+ },
684
+ maps: NativeIdMaps
685
+ ): { peerId: string; connId: number; streamId: number } {
686
+ const connId = maps.connectionIds.toPublic(BigInt(inner.connId));
687
+ return {
688
+ connId,
689
+ peerId: inner.peerId,
690
+ streamId: maps.streamIds.toPublic(connId, BigInt(inner.streamId)),
691
+ };
692
+ }
693
+
694
+ /**
695
+ * Stops new native events from reaching identifiers this event ends, so a
696
+ * reused native ID gets a fresh public number. An ended connection is
697
+ * released at once, so a stream operation queued behind its event throws
698
+ * `StreamClosedError` without reaching native; stream numbers stay resolvable
699
+ * until {@link releaseTerminalIds} runs after dispatch.
700
+ */
701
+ function retireTerminalIds(
702
+ event: P2pEvent,
703
+ connectionIds: ConnectionIdMap,
704
+ streamIds: StreamIdMap
705
+ ): void {
706
+ const connId = endedConnection(event);
707
+ if (connId !== undefined) {
708
+ connectionIds.release(connId);
709
+ streamIds.retireConnection(connId);
710
+ }
711
+ if (event.tag === P2pEvent_Tags.StreamClosed) {
712
+ streamIds.retirePublic(event.inner.streamId);
713
+ }
714
+ }
715
+
716
+ /** Frees stream identifiers this event ended, once the SDK dispatched it. */
717
+ function releaseTerminalIds(event: P2pEvent, streamIds: StreamIdMap): void {
718
+ const connId = endedConnection(event);
719
+ if (connId !== undefined) {
720
+ streamIds.deleteConnection(connId);
721
+ }
722
+ if (event.tag === P2pEvent_Tags.StreamClosed) {
723
+ streamIds.deletePublic(event.inner.streamId);
724
+ }
725
+ }
726
+
727
+ /**
728
+ * The connection this event ends. A closed or replaced connection reports no
729
+ * per-stream terminal events, so its streams end with it.
730
+ */
731
+ function endedConnection(event: P2pEvent): number | undefined {
732
+ if (event.tag === P2pEvent_Tags.ConnectionClosed) {
733
+ return event.inner.connId;
734
+ }
735
+ if (event.tag === P2pEvent_Tags.ConnectionReplaced) {
736
+ return event.inner.oldConnId;
737
+ }
738
+ return undefined;
739
+ }
740
+
741
+ /** Copies native bytes unless they already own their whole `ArrayBuffer`. */
742
+ function toArrayBuffer(bytes: Uint8Array): ArrayBuffer {
743
+ if (
744
+ bytes.buffer instanceof ArrayBuffer &&
745
+ bytes.byteOffset === 0 &&
746
+ bytes.byteLength === bytes.buffer.byteLength
747
+ ) {
748
+ return bytes.buffer;
749
+ }
750
+ return Uint8Array.from(bytes).buffer;
751
+ }
752
+
753
+ interface NativeIdMaps {
754
+ readonly connectionIds: ConnectionIdMap;
755
+ readonly streamIds: StreamIdMap;
756
+ }
757
+
758
+ /**
759
+ * Maps native stream IDs, which are unique only within their connection, to
760
+ * public numbers that never repeat. Each stream remembers its public
761
+ * connection, so a closed or replaced connection frees every stream on it.
762
+ */
763
+ class StreamIdMap {
764
+ /** Live public IDs by public connection, then native stream ID. */
765
+ readonly #publicByNative = new Map<number, Map<bigint, number>>();
766
+ readonly #streams = new Map<
767
+ number,
768
+ { readonly connId: number; readonly native: bigint }
769
+ >();
770
+ #next = 1;
771
+
772
+ toPublic(connId: number, native: bigint): number {
773
+ let byNative = this.#publicByNative.get(connId);
774
+ const existing = byNative?.get(native);
775
+ if (existing !== undefined) {
776
+ return existing;
777
+ }
778
+ if (byNative === undefined) {
779
+ byNative = new Map();
780
+ this.#publicByNative.set(connId, byNative);
781
+ }
782
+ const publicId = this.#next;
783
+ this.#next += 1;
784
+ byNative.set(native, publicId);
785
+ this.#streams.set(publicId, { connId, native });
786
+ return publicId;
787
+ }
788
+
789
+ toNative(publicId: number): bigint {
790
+ const stream = this.#streams.get(publicId);
791
+ if (stream === undefined) {
792
+ throw new StreamClosedError("The stream closed");
793
+ }
794
+ return stream.native;
795
+ }
796
+
797
+ deletePublic(publicId: number): void {
798
+ this.retirePublic(publicId);
799
+ this.#streams.delete(publicId);
800
+ }
801
+
802
+ retirePublic(publicId: number): void {
803
+ const stream = this.#streams.get(publicId);
804
+ if (stream === undefined) {
805
+ return;
806
+ }
807
+ const byNative = this.#publicByNative.get(stream.connId);
808
+ if (byNative?.get(stream.native) === publicId) {
809
+ byNative.delete(stream.native);
810
+ if (byNative.size === 0) {
811
+ this.#publicByNative.delete(stream.connId);
812
+ }
813
+ }
814
+ }
815
+
816
+ deleteConnection(connId: number): void {
817
+ for (const publicId of this.#onConnection(connId)) {
818
+ this.deletePublic(publicId);
819
+ }
820
+ }
821
+
822
+ retireConnection(connId: number): void {
823
+ for (const publicId of this.#onConnection(connId)) {
824
+ this.retirePublic(publicId);
825
+ }
826
+ }
827
+
828
+ #onConnection(connId: number): number[] {
829
+ return [...this.#streams]
830
+ .filter(([, stream]) => stream.connId === connId)
831
+ .map(([publicId]) => publicId);
832
+ }
833
+ }