@minip2p/node 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.
- package/README.md +1 -1
- package/dist/adapter.d.ts.map +1 -1
- package/dist/adapter.js +14 -506
- package/dist/adapter.js.map +1 -1
- package/dist/addon.d.ts +11 -4
- package/dist/native-shape.d.ts +4 -18
- package/dist/native-shape.d.ts.map +1 -1
- package/dist/native-shape.js +3 -5
- package/dist/native-shape.js.map +1 -1
- package/package.json +9 -9
- package/src/adapter.ts +25 -670
- package/src/addon.d.ts +11 -4
- package/src/native-shape.ts +12 -35
package/src/adapter.ts
CHANGED
|
@@ -1,302 +1,29 @@
|
|
|
1
|
-
/* oxlint-disable
|
|
1
|
+
/* oxlint-disable func-style, no-use-before-define -- Hoisted helpers keep the public entry points first. */
|
|
2
2
|
|
|
3
|
-
import { Minip2pBase
|
|
4
|
-
import type {
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
KnownPeerInfo,
|
|
9
|
-
Minip2pConfig,
|
|
10
|
-
Reachability,
|
|
11
|
-
RelayReservationInfo,
|
|
12
|
-
} from "@minip2p/core";
|
|
13
|
-
import {
|
|
14
|
-
ConnectionIdMap,
|
|
15
|
-
EventDrain,
|
|
16
|
-
P2pEvent_Tags,
|
|
17
|
-
SettleHandles,
|
|
18
|
-
eventStream,
|
|
19
|
-
resolveEndpointConfig,
|
|
20
|
-
typedFfiError,
|
|
21
|
-
u64ToNumber,
|
|
22
|
-
} from "@minip2p/core/backend";
|
|
23
|
-
import type {
|
|
24
|
-
BackendConnectTarget,
|
|
25
|
-
BackendOpenStream,
|
|
26
|
-
Minip2pBackend,
|
|
27
|
-
PathKind,
|
|
28
|
-
P2pEvent,
|
|
29
|
-
} from "@minip2p/core/backend";
|
|
3
|
+
import { Minip2pBase } from "@minip2p/core";
|
|
4
|
+
import type { Bytes, Minip2pConfig } from "@minip2p/core";
|
|
5
|
+
import { resolveEndpointConfig } from "@minip2p/core/backend";
|
|
6
|
+
import type { Minip2pBackend } from "@minip2p/core/backend";
|
|
7
|
+
import { SerdeBackend, typedNativeCall } from "@minip2p/core/serde-backend";
|
|
30
8
|
|
|
31
|
-
import type {
|
|
32
|
-
NativeEvent,
|
|
33
|
-
NativeIdentifyInfo,
|
|
34
|
-
NativeKnownPeerInfo,
|
|
35
|
-
NativeRelayReservationInfo,
|
|
36
|
-
} from "./native-shape.js";
|
|
37
9
|
import { nativeBinding } from "./native.js";
|
|
38
|
-
import type { NativeEndpoint } from "./native.js";
|
|
39
10
|
|
|
40
|
-
|
|
41
|
-
const
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
()
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
resolveEndpointConfig(config)
|
|
57
|
-
)
|
|
58
|
-
);
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
start(listener: (event: P2pEvent) => void): void {
|
|
62
|
-
const events = new EventDrain(
|
|
63
|
-
(limit) => this.#endpoint.drainEvents(limit),
|
|
64
|
-
(event: NativeEvent) => {
|
|
65
|
-
const normalized = normalizeEvent(
|
|
66
|
-
event,
|
|
67
|
-
this.#connectionIds,
|
|
68
|
-
this.#streamIds
|
|
69
|
-
);
|
|
70
|
-
const stream = eventStream(normalized);
|
|
71
|
-
const native = nativeStreamOf(event);
|
|
72
|
-
if (stream !== undefined && native !== undefined) {
|
|
73
|
-
this.#settleHandles.hold(stream.connId, stream.streamId, native);
|
|
74
|
-
}
|
|
75
|
-
listener(normalized);
|
|
76
|
-
},
|
|
77
|
-
DRAIN_LIMIT,
|
|
78
|
-
// One check-phase turn keeps native callbacks out of the caller's stack
|
|
79
|
-
// without paying the timer granularity for every bounded batch.
|
|
80
|
-
(task) => {
|
|
81
|
-
setImmediate(task);
|
|
82
|
-
}
|
|
83
|
-
);
|
|
84
|
-
this.#events = events;
|
|
85
|
-
translateErrors(() => {
|
|
86
|
-
this.#endpoint.start(() => {
|
|
87
|
-
events.ring();
|
|
88
|
-
});
|
|
89
|
-
});
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
eventHandled(event: P2pEvent): void {
|
|
93
|
-
releaseTerminalIds(event, this.#streamIds);
|
|
94
|
-
const stream = eventStream(event);
|
|
95
|
-
if (stream !== undefined) {
|
|
96
|
-
this.#settleHandles.release(stream.connId, stream.streamId);
|
|
97
|
-
}
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
close(): void {
|
|
101
|
-
this.#endpoint.close();
|
|
102
|
-
this.#events?.stop();
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
peerId(): string {
|
|
106
|
-
return this.#endpoint.peerId();
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
listenAddrs(): string[] {
|
|
110
|
-
return this.#endpoint.listenAddrs();
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
isRunning(): boolean {
|
|
114
|
-
return this.#endpoint.isRunning();
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
connectedPeers(): string[] {
|
|
118
|
-
return translateErrors(() => this.#endpoint.connectedPeers());
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
isPeerReady(peerId: string): boolean {
|
|
122
|
-
return translateErrors(() => this.#endpoint.isPeerReady(peerId));
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
peerInfo(peerId: string): IdentifyInfo | undefined {
|
|
126
|
-
const info = translateErrors(() => this.#endpoint.peerInfo(peerId));
|
|
127
|
-
return info === null ? undefined : identifyInfo(info);
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
knownPeers(): KnownPeerInfo[] {
|
|
131
|
-
return translateErrors(() => this.#endpoint.knownPeers()).map(knownPeer);
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
discoveryNowMs(): number | undefined {
|
|
135
|
-
const value = translateErrors(() => this.#endpoint.discoveryNowMs());
|
|
136
|
-
return value === null ? undefined : u64ToNumber(value, "clock");
|
|
137
|
-
}
|
|
138
|
-
|
|
139
|
-
activeReservation(): RelayReservationInfo | undefined {
|
|
140
|
-
const reservation = translateErrors(() =>
|
|
141
|
-
this.#endpoint.activeReservation()
|
|
142
|
-
);
|
|
143
|
-
return reservation === null ? undefined : relayReservation(reservation);
|
|
144
|
-
}
|
|
145
|
-
|
|
146
|
-
path(peerId: string): PathKind | undefined {
|
|
147
|
-
return translateErrors(() => this.#endpoint.path(peerId)) ?? undefined;
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
connectionInfo(peerId: string): ConnectionInfo | undefined {
|
|
151
|
-
const info = translateErrors(() => this.#endpoint.connectionInfo(peerId));
|
|
152
|
-
if (info === null) {
|
|
153
|
-
return undefined;
|
|
154
|
-
}
|
|
155
|
-
const { connId, ...rest } = info;
|
|
156
|
-
return {
|
|
157
|
-
...rest,
|
|
158
|
-
connId: this.#connectionIds.toPublic(BigInt(connId)),
|
|
159
|
-
};
|
|
160
|
-
}
|
|
161
|
-
|
|
162
|
-
circuitAddress(relayAddress: string, peerId: string): string {
|
|
163
|
-
return circuitAddress(relayAddress, peerId);
|
|
164
|
-
}
|
|
165
|
-
|
|
166
|
-
reachability(): Reachability {
|
|
167
|
-
return translateErrors(() => this.#endpoint.reachability());
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
setActive(active: boolean): void {
|
|
171
|
-
this.#endpoint.setActive(active);
|
|
172
|
-
}
|
|
173
|
-
|
|
174
|
-
subscribe(topic: string): boolean {
|
|
175
|
-
return translateErrors(() => this.#endpoint.subscribe(topic));
|
|
176
|
-
}
|
|
177
|
-
|
|
178
|
-
unsubscribe(topic: string): boolean {
|
|
179
|
-
return translateErrors(() => this.#endpoint.unsubscribe(topic));
|
|
180
|
-
}
|
|
181
|
-
|
|
182
|
-
publish(topic: string, data: Uint8Array): void {
|
|
183
|
-
translateErrors(() => {
|
|
184
|
-
this.#endpoint.publish(topic, data);
|
|
185
|
-
});
|
|
186
|
-
}
|
|
187
|
-
|
|
188
|
-
ping(peerId: string): void {
|
|
189
|
-
translateErrors(() => {
|
|
190
|
-
this.#endpoint.ping(peerId);
|
|
191
|
-
});
|
|
192
|
-
}
|
|
193
|
-
|
|
194
|
-
addProtocol(protocolId: string): void {
|
|
195
|
-
translateErrors(() => {
|
|
196
|
-
this.#endpoint.addProtocol(protocolId);
|
|
197
|
-
});
|
|
198
|
-
}
|
|
199
|
-
|
|
200
|
-
openStream(peerId: string, protocolId: string): BackendOpenStream {
|
|
201
|
-
const stream = translateErrors(() =>
|
|
202
|
-
this.#endpoint.openStream(peerId, protocolId)
|
|
203
|
-
);
|
|
204
|
-
const connId = this.#connectionIds.toPublic(BigInt(stream.connId));
|
|
205
|
-
return {
|
|
206
|
-
connId,
|
|
207
|
-
streamId: this.#streamIds.toPublic(connId, BigInt(stream.streamId)),
|
|
208
|
-
};
|
|
209
|
-
}
|
|
210
|
-
|
|
211
|
-
sendStream(connId: number, streamId: number, data: Uint8Array): boolean {
|
|
212
|
-
return translateErrors(() =>
|
|
213
|
-
this.#endpoint.sendStream(...this.#nativeStream(connId, streamId), data)
|
|
214
|
-
);
|
|
215
|
-
}
|
|
216
|
-
|
|
217
|
-
closeStreamWrite(connId: number, streamId: number): void {
|
|
218
|
-
translateErrors(() => {
|
|
219
|
-
this.#endpoint.closeStreamWrite(...this.#nativeStream(connId, streamId));
|
|
220
|
-
});
|
|
221
|
-
}
|
|
222
|
-
|
|
223
|
-
resetStream(connId: number, streamId: number): void {
|
|
224
|
-
translateErrors(() => {
|
|
225
|
-
this.#endpoint.resetStream(...this.#nativeStream(connId, streamId));
|
|
226
|
-
});
|
|
227
|
-
}
|
|
228
|
-
|
|
229
|
-
abandonStream(connId: number, streamId: number): void {
|
|
230
|
-
translateErrors(() => {
|
|
231
|
-
this.#endpoint.abandonStream(...this.#settleStream(connId, streamId));
|
|
232
|
-
});
|
|
233
|
-
}
|
|
234
|
-
|
|
235
|
-
streamConsumer(connId: number, streamId: number): (bytes: number) => void {
|
|
236
|
-
const [nativeConn, nativeStream] = this.#settleStream(connId, streamId);
|
|
237
|
-
return (bytes) => {
|
|
238
|
-
translateErrors(() => {
|
|
239
|
-
this.#endpoint.streamConsumed(nativeConn, nativeStream, bytes);
|
|
240
|
-
});
|
|
241
|
-
};
|
|
242
|
-
}
|
|
243
|
-
|
|
244
|
-
/**
|
|
245
|
-
* Native connection and stream IDs for a public stream. Native names the
|
|
246
|
-
* stream by both, so an operation for a connection that native already
|
|
247
|
-
* replaced fails there instead of reaching a stream on the new connection.
|
|
248
|
-
* A connection whose close or replacement this adapter has already drained
|
|
249
|
-
* has no native ID, so the operation throws `StreamClosedError`.
|
|
250
|
-
*/
|
|
251
|
-
#nativeStream(connId: number, streamId: number): [bigint, bigint] {
|
|
252
|
-
return [
|
|
253
|
-
this.#connectionIds.toNative(connId),
|
|
254
|
-
this.#streamIds.toNative(streamId),
|
|
255
|
-
];
|
|
256
|
-
}
|
|
257
|
-
|
|
258
|
-
/**
|
|
259
|
-
* Native IDs for settling a stream: acknowledging or abandoning its bytes.
|
|
260
|
-
* Those still hold the native slot of a connection whose end this adapter
|
|
261
|
-
* already drained, so a stream with events in flight resolves through its
|
|
262
|
-
* settle handle once the live mapping is gone.
|
|
263
|
-
*/
|
|
264
|
-
#settleStream(connId: number, streamId: number): [bigint, bigint] {
|
|
265
|
-
try {
|
|
266
|
-
return this.#nativeStream(connId, streamId);
|
|
267
|
-
} catch (error) {
|
|
268
|
-
const handle = this.#settleHandles.get(connId, streamId);
|
|
269
|
-
if (handle === undefined) {
|
|
270
|
-
throw error;
|
|
271
|
-
}
|
|
272
|
-
return handle;
|
|
273
|
-
}
|
|
274
|
-
}
|
|
275
|
-
|
|
276
|
-
// Connect IDs are not mapped because they round-trip into native calls,
|
|
277
|
-
// and native allocates them well inside the safe integer range.
|
|
278
|
-
connect(target: BackendConnectTarget): number {
|
|
279
|
-
return u64ToNumber(
|
|
280
|
-
translateErrors(() =>
|
|
281
|
-
this.#endpoint.connect(
|
|
282
|
-
target.kind === "peer" ? target.peerId : [...target.addresses]
|
|
283
|
-
)
|
|
284
|
-
),
|
|
285
|
-
"connectId"
|
|
286
|
-
);
|
|
287
|
-
}
|
|
288
|
-
|
|
289
|
-
cancelConnect(id: number): void {
|
|
290
|
-
translateErrors(() => {
|
|
291
|
-
this.#endpoint.cancelConnect(BigInt(id));
|
|
292
|
-
});
|
|
293
|
-
}
|
|
294
|
-
|
|
295
|
-
disconnect(peerId: string): void {
|
|
296
|
-
translateErrors(() => {
|
|
297
|
-
this.#endpoint.disconnect(peerId);
|
|
298
|
-
});
|
|
299
|
-
}
|
|
11
|
+
function nodeBackend(config: Minip2pConfig): Minip2pBackend {
|
|
12
|
+
const endpoint = typedNativeCall(
|
|
13
|
+
() =>
|
|
14
|
+
new nativeBinding.NodeEndpoint(
|
|
15
|
+
toUint8Array(config.secretKey),
|
|
16
|
+
resolveEndpointConfig(config)
|
|
17
|
+
)
|
|
18
|
+
);
|
|
19
|
+
return new SerdeBackend(endpoint, {
|
|
20
|
+
circuitAddress,
|
|
21
|
+
// One check-phase turn keeps native callbacks out of the caller's stack
|
|
22
|
+
// without paying the timer granularity for every bounded batch.
|
|
23
|
+
schedule: (task) => {
|
|
24
|
+
setImmediate(task);
|
|
25
|
+
},
|
|
26
|
+
});
|
|
300
27
|
}
|
|
301
28
|
|
|
302
29
|
/** High-level Node.js owner for one native minip2p endpoint. */
|
|
@@ -307,7 +34,7 @@ export class Minip2p extends Minip2pBase {
|
|
|
307
34
|
|
|
308
35
|
/** Constructs and starts a Node.js endpoint. */
|
|
309
36
|
static create(config: Minip2pConfig): Minip2p {
|
|
310
|
-
return new Minip2p(
|
|
37
|
+
return new Minip2p(nodeBackend(config), config.relays ?? []);
|
|
311
38
|
}
|
|
312
39
|
}
|
|
313
40
|
|
|
@@ -318,391 +45,19 @@ export function generateSecretKey(): Uint8Array {
|
|
|
318
45
|
|
|
319
46
|
/** Derives a peer ID from raw Ed25519 secret key material. */
|
|
320
47
|
export function peerIdFromSecretKey(secretKey: Bytes): string {
|
|
321
|
-
return
|
|
48
|
+
return typedNativeCall(() =>
|
|
322
49
|
nativeBinding.peerIdFromSecretKey(toUint8Array(secretKey))
|
|
323
50
|
);
|
|
324
51
|
}
|
|
325
52
|
|
|
326
53
|
/** Builds a circuit multiaddress through a direct relay address. */
|
|
327
54
|
export function circuitAddress(relayAddress: string, peerId: string): string {
|
|
328
|
-
return
|
|
55
|
+
return typedNativeCall(() =>
|
|
329
56
|
nativeBinding.circuitAddress(relayAddress, peerId)
|
|
330
57
|
);
|
|
331
58
|
}
|
|
332
59
|
|
|
333
|
-
/**
|
|
334
|
-
* Rethrows a native `FfiError` as its typed SDK error. The addon tags each
|
|
335
|
-
* error with the variant name as `code`, its detail field as `detail`, and
|
|
336
|
-
* an `InvalidConfig`'s capability name as `capability`; untyped variants are
|
|
337
|
-
* rethrown unchanged with those properties intact.
|
|
338
|
-
*/
|
|
339
|
-
function translateErrors<T>(operation: () => T): T {
|
|
340
|
-
try {
|
|
341
|
-
return operation();
|
|
342
|
-
} catch (error) {
|
|
343
|
-
throw (
|
|
344
|
-
typedFfiError({
|
|
345
|
-
capability: stringProperty(error, "capability"),
|
|
346
|
-
detail: stringProperty(error, "detail"),
|
|
347
|
-
tag: stringProperty(error, "code"),
|
|
348
|
-
}) ?? error
|
|
349
|
-
);
|
|
350
|
-
}
|
|
351
|
-
}
|
|
352
|
-
|
|
353
|
-
function stringProperty(value: unknown, key: string): string | undefined {
|
|
354
|
-
if (value === null || typeof value !== "object") {
|
|
355
|
-
return undefined;
|
|
356
|
-
}
|
|
357
|
-
const property: unknown = Reflect.get(value, key);
|
|
358
|
-
return typeof property === "string" ? property : undefined;
|
|
359
|
-
}
|
|
360
|
-
|
|
361
60
|
/** A view napi-rs can read; the addon copies it before the call returns. */
|
|
362
61
|
function toUint8Array(value: Bytes): Uint8Array {
|
|
363
62
|
return value instanceof Uint8Array ? value : new Uint8Array(value);
|
|
364
63
|
}
|
|
365
|
-
|
|
366
|
-
/** Converts an Identify snapshot, copying its public key into an `ArrayBuffer`. */
|
|
367
|
-
function identifyInfo({
|
|
368
|
-
publicKey,
|
|
369
|
-
...info
|
|
370
|
-
}: NativeIdentifyInfo): IdentifyInfo {
|
|
371
|
-
return {
|
|
372
|
-
...info,
|
|
373
|
-
...(publicKey !== undefined && { publicKey: toArrayBuffer(publicKey) }),
|
|
374
|
-
};
|
|
375
|
-
}
|
|
376
|
-
|
|
377
|
-
function knownPeer({
|
|
378
|
-
beaconLastSeenAgeMs,
|
|
379
|
-
mdnsLastSeenAgeMs,
|
|
380
|
-
...peer
|
|
381
|
-
}: NativeKnownPeerInfo): KnownPeerInfo {
|
|
382
|
-
return {
|
|
383
|
-
...peer,
|
|
384
|
-
...(beaconLastSeenAgeMs !== undefined && {
|
|
385
|
-
beaconLastSeenAgeMs: u64ToNumber(
|
|
386
|
-
beaconLastSeenAgeMs,
|
|
387
|
-
"beaconLastSeenAgeMs"
|
|
388
|
-
),
|
|
389
|
-
}),
|
|
390
|
-
...(mdnsLastSeenAgeMs !== undefined && {
|
|
391
|
-
mdnsLastSeenAgeMs: u64ToNumber(mdnsLastSeenAgeMs, "mdnsLastSeenAgeMs"),
|
|
392
|
-
}),
|
|
393
|
-
};
|
|
394
|
-
}
|
|
395
|
-
|
|
396
|
-
function relayReservation({
|
|
397
|
-
expiresUnixSecs,
|
|
398
|
-
relayPeerId,
|
|
399
|
-
}: NativeRelayReservationInfo): RelayReservationInfo {
|
|
400
|
-
return {
|
|
401
|
-
relayPeerId,
|
|
402
|
-
...(expiresUnixSecs !== undefined && {
|
|
403
|
-
expiresUnixSecs: u64ToNumber(expiresUnixSecs, "expiresUnixSecs"),
|
|
404
|
-
}),
|
|
405
|
-
};
|
|
406
|
-
}
|
|
407
|
-
|
|
408
|
-
/** Event fields carrying a native connection ID. */
|
|
409
|
-
const CONNECTION_ID_KEYS: ReadonlySet<string> = new Set([
|
|
410
|
-
"connId",
|
|
411
|
-
"oldConnId",
|
|
412
|
-
"newConnId",
|
|
413
|
-
]);
|
|
414
|
-
|
|
415
|
-
/**
|
|
416
|
-
* Converts one value of a native `tag` event: integers to numbers, connection
|
|
417
|
-
* IDs through the connection map, and bytes to `ArrayBuffer`s. A stream ID is
|
|
418
|
-
* mapped together with the connection of the record that carries it.
|
|
419
|
-
*/
|
|
420
|
-
function normalizeNativeValue(
|
|
421
|
-
value: unknown,
|
|
422
|
-
maps: NativeIdMaps,
|
|
423
|
-
tag: string,
|
|
424
|
-
key?: string
|
|
425
|
-
): unknown {
|
|
426
|
-
if (typeof value === "bigint" || typeof value === "number") {
|
|
427
|
-
if (key !== undefined && CONNECTION_ID_KEYS.has(key)) {
|
|
428
|
-
return maps.connectionIds.toPublicInEvent(tag, key, BigInt(value));
|
|
429
|
-
}
|
|
430
|
-
// A QUIC stop code is a 62-bit varint the remote picks: keep it whole.
|
|
431
|
-
if (key === "errorCode") {
|
|
432
|
-
return BigInt(value);
|
|
433
|
-
}
|
|
434
|
-
return key === "streamId" ? value : u64ToNumber(value, key ?? "native u64");
|
|
435
|
-
}
|
|
436
|
-
if (value instanceof Uint8Array) {
|
|
437
|
-
return toArrayBuffer(value);
|
|
438
|
-
}
|
|
439
|
-
if (Array.isArray(value)) {
|
|
440
|
-
return value.map((item) => normalizeNativeValue(item, maps, tag));
|
|
441
|
-
}
|
|
442
|
-
if (value === null || typeof value !== "object") {
|
|
443
|
-
return value;
|
|
444
|
-
}
|
|
445
|
-
const record: Record<string, unknown> = Object.fromEntries(
|
|
446
|
-
Object.entries(value).map(([itemKey, item]) => [
|
|
447
|
-
itemKey,
|
|
448
|
-
normalizeNativeValue(item, maps, tag, itemKey),
|
|
449
|
-
])
|
|
450
|
-
);
|
|
451
|
-
const { connId, streamId } = record;
|
|
452
|
-
if (typeof streamId === "bigint" || typeof streamId === "number") {
|
|
453
|
-
// Public stream IDs are allocated per connection. A record without a
|
|
454
|
-
// connection (an endpoint error, say) cannot name a public stream.
|
|
455
|
-
if (typeof connId === "number") {
|
|
456
|
-
record.streamId = maps.streamIds.toPublic(connId, BigInt(streamId));
|
|
457
|
-
} else {
|
|
458
|
-
delete record.streamId;
|
|
459
|
-
}
|
|
460
|
-
}
|
|
461
|
-
return record;
|
|
462
|
-
}
|
|
463
|
-
|
|
464
|
-
/**
|
|
465
|
-
* Converts one native event to its SDK backend form, then retires the IDs it
|
|
466
|
-
* ends.
|
|
467
|
-
*/
|
|
468
|
-
function normalizeEvent(
|
|
469
|
-
event: NativeEvent,
|
|
470
|
-
connectionIds: ConnectionIdMap,
|
|
471
|
-
streamIds: StreamIdMap
|
|
472
|
-
): P2pEvent {
|
|
473
|
-
const normalized = convertEvent(event, { connectionIds, streamIds });
|
|
474
|
-
retireTerminalIds(normalized, connectionIds, streamIds);
|
|
475
|
-
return normalized;
|
|
476
|
-
}
|
|
477
|
-
|
|
478
|
-
/**
|
|
479
|
-
* Per-chunk and per-write events, and pubsub messages, convert field by
|
|
480
|
-
* field. Identify snapshots go through the typed {@link identifyInfo}, and a
|
|
481
|
-
* field-less event passes through by tag. The rest share the generic walk: the addon's serde shape is the SDK shape with
|
|
482
|
-
* napi-rs integers and buffers (see `native-shape.ts`).
|
|
483
|
-
*/
|
|
484
|
-
function convertEvent(event: NativeEvent, maps: NativeIdMaps): P2pEvent {
|
|
485
|
-
switch (event.tag) {
|
|
486
|
-
case P2pEvent_Tags.StreamData: {
|
|
487
|
-
return {
|
|
488
|
-
inner: {
|
|
489
|
-
...streamRef(event.inner, maps),
|
|
490
|
-
data: toArrayBuffer(event.inner.data),
|
|
491
|
-
},
|
|
492
|
-
tag: event.tag,
|
|
493
|
-
};
|
|
494
|
-
}
|
|
495
|
-
case P2pEvent_Tags.StreamWriteAccepted:
|
|
496
|
-
case P2pEvent_Tags.StreamRemoteWriteClosed:
|
|
497
|
-
case P2pEvent_Tags.StreamClosed: {
|
|
498
|
-
return { inner: streamRef(event.inner, maps), tag: event.tag };
|
|
499
|
-
}
|
|
500
|
-
case P2pEvent_Tags.Message: {
|
|
501
|
-
const { data, fromPeerId, seqno, signed, topics } = event.inner;
|
|
502
|
-
return {
|
|
503
|
-
inner: {
|
|
504
|
-
data: toArrayBuffer(data),
|
|
505
|
-
fromPeerId,
|
|
506
|
-
seqno: toArrayBuffer(seqno),
|
|
507
|
-
signed,
|
|
508
|
-
topics,
|
|
509
|
-
},
|
|
510
|
-
tag: event.tag,
|
|
511
|
-
};
|
|
512
|
-
}
|
|
513
|
-
case P2pEvent_Tags.IdentifyReceived: {
|
|
514
|
-
return {
|
|
515
|
-
inner: {
|
|
516
|
-
connId: maps.connectionIds.toPublic(BigInt(event.inner.connId)),
|
|
517
|
-
info: identifyInfo(event.inner.info),
|
|
518
|
-
peerId: event.inner.peerId,
|
|
519
|
-
},
|
|
520
|
-
tag: event.tag,
|
|
521
|
-
};
|
|
522
|
-
}
|
|
523
|
-
case P2pEvent_Tags.MdnsRecovered: {
|
|
524
|
-
return { tag: event.tag };
|
|
525
|
-
}
|
|
526
|
-
default: {
|
|
527
|
-
return {
|
|
528
|
-
inner: normalizeNativeValue(event.inner, maps, event.tag),
|
|
529
|
-
tag: event.tag,
|
|
530
|
-
} as P2pEvent;
|
|
531
|
-
}
|
|
532
|
-
}
|
|
533
|
-
}
|
|
534
|
-
|
|
535
|
-
/** The native identity of the stream a native stream event names. */
|
|
536
|
-
function nativeStreamOf(event: NativeEvent): [bigint, bigint] | undefined {
|
|
537
|
-
switch (event.tag) {
|
|
538
|
-
case P2pEvent_Tags.StreamReady:
|
|
539
|
-
case P2pEvent_Tags.StreamData:
|
|
540
|
-
case P2pEvent_Tags.StreamWriteAccepted:
|
|
541
|
-
case P2pEvent_Tags.StreamWriteStopped:
|
|
542
|
-
case P2pEvent_Tags.StreamRemoteWriteClosed:
|
|
543
|
-
case P2pEvent_Tags.StreamClosed: {
|
|
544
|
-
return [BigInt(event.inner.connId), BigInt(event.inner.streamId)];
|
|
545
|
-
}
|
|
546
|
-
default: {
|
|
547
|
-
return undefined;
|
|
548
|
-
}
|
|
549
|
-
}
|
|
550
|
-
}
|
|
551
|
-
|
|
552
|
-
/** The public identity of the stream a native stream event names. */
|
|
553
|
-
function streamRef(
|
|
554
|
-
inner: {
|
|
555
|
-
readonly peerId: string;
|
|
556
|
-
readonly connId: number | bigint;
|
|
557
|
-
readonly streamId: number | bigint;
|
|
558
|
-
},
|
|
559
|
-
maps: NativeIdMaps
|
|
560
|
-
): { peerId: string; connId: number; streamId: number } {
|
|
561
|
-
const connId = maps.connectionIds.toPublic(BigInt(inner.connId));
|
|
562
|
-
return {
|
|
563
|
-
connId,
|
|
564
|
-
peerId: inner.peerId,
|
|
565
|
-
streamId: maps.streamIds.toPublic(connId, BigInt(inner.streamId)),
|
|
566
|
-
};
|
|
567
|
-
}
|
|
568
|
-
|
|
569
|
-
/**
|
|
570
|
-
* Stops new native events from reaching identifiers this event ends, so a
|
|
571
|
-
* reused native ID gets a fresh public number. An ended connection is
|
|
572
|
-
* released at once, so a stream operation queued behind its event throws
|
|
573
|
-
* `StreamClosedError` without reaching native; stream numbers stay resolvable
|
|
574
|
-
* until {@link releaseTerminalIds} runs after dispatch.
|
|
575
|
-
*/
|
|
576
|
-
function retireTerminalIds(
|
|
577
|
-
event: P2pEvent,
|
|
578
|
-
connectionIds: ConnectionIdMap,
|
|
579
|
-
streamIds: StreamIdMap
|
|
580
|
-
): void {
|
|
581
|
-
const connId = endedConnection(event);
|
|
582
|
-
if (connId !== undefined) {
|
|
583
|
-
connectionIds.release(connId);
|
|
584
|
-
streamIds.retireConnection(connId);
|
|
585
|
-
}
|
|
586
|
-
if (event.tag === P2pEvent_Tags.StreamClosed) {
|
|
587
|
-
streamIds.retirePublic(event.inner.streamId);
|
|
588
|
-
}
|
|
589
|
-
}
|
|
590
|
-
|
|
591
|
-
/** Frees stream identifiers this event ended, once the SDK dispatched it. */
|
|
592
|
-
function releaseTerminalIds(event: P2pEvent, streamIds: StreamIdMap): void {
|
|
593
|
-
const connId = endedConnection(event);
|
|
594
|
-
if (connId !== undefined) {
|
|
595
|
-
streamIds.deleteConnection(connId);
|
|
596
|
-
}
|
|
597
|
-
if (event.tag === P2pEvent_Tags.StreamClosed) {
|
|
598
|
-
streamIds.deletePublic(event.inner.streamId);
|
|
599
|
-
}
|
|
600
|
-
}
|
|
601
|
-
|
|
602
|
-
/**
|
|
603
|
-
* The connection this event ends. A closed or replaced connection reports no
|
|
604
|
-
* per-stream terminal events, so its streams end with it.
|
|
605
|
-
*/
|
|
606
|
-
function endedConnection(event: P2pEvent): number | undefined {
|
|
607
|
-
if (event.tag === P2pEvent_Tags.ConnectionClosed) {
|
|
608
|
-
return event.inner.connId;
|
|
609
|
-
}
|
|
610
|
-
if (event.tag === P2pEvent_Tags.ConnectionReplaced) {
|
|
611
|
-
return event.inner.oldConnId;
|
|
612
|
-
}
|
|
613
|
-
return undefined;
|
|
614
|
-
}
|
|
615
|
-
|
|
616
|
-
/** Copies native bytes unless they already own their whole `ArrayBuffer`. */
|
|
617
|
-
function toArrayBuffer(bytes: Uint8Array): ArrayBuffer {
|
|
618
|
-
if (
|
|
619
|
-
bytes.buffer instanceof ArrayBuffer &&
|
|
620
|
-
bytes.byteOffset === 0 &&
|
|
621
|
-
bytes.byteLength === bytes.buffer.byteLength
|
|
622
|
-
) {
|
|
623
|
-
return bytes.buffer;
|
|
624
|
-
}
|
|
625
|
-
return Uint8Array.from(bytes).buffer;
|
|
626
|
-
}
|
|
627
|
-
|
|
628
|
-
interface NativeIdMaps {
|
|
629
|
-
readonly connectionIds: ConnectionIdMap;
|
|
630
|
-
readonly streamIds: StreamIdMap;
|
|
631
|
-
}
|
|
632
|
-
|
|
633
|
-
/**
|
|
634
|
-
* Maps native stream IDs, which are unique only within their connection, to
|
|
635
|
-
* public numbers that never repeat. Each stream remembers its public
|
|
636
|
-
* connection, so a closed or replaced connection frees every stream on it.
|
|
637
|
-
*/
|
|
638
|
-
class StreamIdMap {
|
|
639
|
-
/** Live public IDs by public connection, then native stream ID. */
|
|
640
|
-
readonly #publicByNative = new Map<number, Map<bigint, number>>();
|
|
641
|
-
readonly #streams = new Map<
|
|
642
|
-
number,
|
|
643
|
-
{ readonly connId: number; readonly native: bigint }
|
|
644
|
-
>();
|
|
645
|
-
#next = 1;
|
|
646
|
-
|
|
647
|
-
toPublic(connId: number, native: bigint): number {
|
|
648
|
-
let byNative = this.#publicByNative.get(connId);
|
|
649
|
-
const existing = byNative?.get(native);
|
|
650
|
-
if (existing !== undefined) {
|
|
651
|
-
return existing;
|
|
652
|
-
}
|
|
653
|
-
if (byNative === undefined) {
|
|
654
|
-
byNative = new Map();
|
|
655
|
-
this.#publicByNative.set(connId, byNative);
|
|
656
|
-
}
|
|
657
|
-
const publicId = this.#next;
|
|
658
|
-
this.#next += 1;
|
|
659
|
-
byNative.set(native, publicId);
|
|
660
|
-
this.#streams.set(publicId, { connId, native });
|
|
661
|
-
return publicId;
|
|
662
|
-
}
|
|
663
|
-
|
|
664
|
-
toNative(publicId: number): bigint {
|
|
665
|
-
const stream = this.#streams.get(publicId);
|
|
666
|
-
if (stream === undefined) {
|
|
667
|
-
throw new StreamClosedError("The stream closed");
|
|
668
|
-
}
|
|
669
|
-
return stream.native;
|
|
670
|
-
}
|
|
671
|
-
|
|
672
|
-
deletePublic(publicId: number): void {
|
|
673
|
-
this.retirePublic(publicId);
|
|
674
|
-
this.#streams.delete(publicId);
|
|
675
|
-
}
|
|
676
|
-
|
|
677
|
-
retirePublic(publicId: number): void {
|
|
678
|
-
const stream = this.#streams.get(publicId);
|
|
679
|
-
if (stream === undefined) {
|
|
680
|
-
return;
|
|
681
|
-
}
|
|
682
|
-
const byNative = this.#publicByNative.get(stream.connId);
|
|
683
|
-
if (byNative?.get(stream.native) === publicId) {
|
|
684
|
-
byNative.delete(stream.native);
|
|
685
|
-
if (byNative.size === 0) {
|
|
686
|
-
this.#publicByNative.delete(stream.connId);
|
|
687
|
-
}
|
|
688
|
-
}
|
|
689
|
-
}
|
|
690
|
-
|
|
691
|
-
deleteConnection(connId: number): void {
|
|
692
|
-
for (const publicId of this.#onConnection(connId)) {
|
|
693
|
-
this.deletePublic(publicId);
|
|
694
|
-
}
|
|
695
|
-
}
|
|
696
|
-
|
|
697
|
-
retireConnection(connId: number): void {
|
|
698
|
-
for (const publicId of this.#onConnection(connId)) {
|
|
699
|
-
this.retirePublic(publicId);
|
|
700
|
-
}
|
|
701
|
-
}
|
|
702
|
-
|
|
703
|
-
#onConnection(connId: number): number[] {
|
|
704
|
-
return [...this.#streams]
|
|
705
|
-
.filter(([, stream]) => stream.connId === connId)
|
|
706
|
-
.map(([publicId]) => publicId);
|
|
707
|
-
}
|
|
708
|
-
}
|