@minip2p/core 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +9 -0
- package/dist/backend.d.ts +44 -0
- package/dist/backend.d.ts.map +1 -0
- package/dist/backend.js +2 -0
- package/dist/backend.js.map +1 -0
- package/dist/errors.d.ts +32 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +55 -0
- package/dist/errors.js.map +1 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +4 -0
- package/dist/index.js.map +1 -0
- package/dist/sdk.d.ts +89 -0
- package/dist/sdk.d.ts.map +1 -0
- package/dist/sdk.js +520 -0
- package/dist/sdk.js.map +1 -0
- package/dist/types.d.ts +306 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +93 -0
- package/dist/types.js.map +1 -0
- package/package.json +58 -0
- package/src/backend.ts +53 -0
- package/src/errors.ts +65 -0
- package/src/index.ts +33 -0
- package/src/sdk.ts +669 -0
- package/src/types.ts +336 -0
package/src/sdk.ts
ADDED
|
@@ -0,0 +1,669 @@
|
|
|
1
|
+
/* oxlint-disable func-style, max-classes-per-file, no-use-before-define, promise/avoid-new, promise/prefer-await-to-then, unicorn/no-useless-spread -- The SDK uses a private queue class, hoisted helpers and Promise adapters, schedules same-tick events on a microtask, and snapshots observer sets before callbacks mutate them. */
|
|
2
|
+
|
|
3
|
+
import type { MiniP2pBackend } from "./backend.js";
|
|
4
|
+
import {
|
|
5
|
+
ClosedError,
|
|
6
|
+
DriverFailedError,
|
|
7
|
+
PeerDisconnectedError,
|
|
8
|
+
TimeoutError,
|
|
9
|
+
} from "./errors.js";
|
|
10
|
+
import { P2pEvent_Tags } from "./types.js";
|
|
11
|
+
import type {
|
|
12
|
+
Bytes,
|
|
13
|
+
IdentifyInfo,
|
|
14
|
+
KnownPeerInfo,
|
|
15
|
+
MiniP2pEvent,
|
|
16
|
+
P2pEvent,
|
|
17
|
+
P2pEventByTag,
|
|
18
|
+
Reachability,
|
|
19
|
+
RelayReservationInfo,
|
|
20
|
+
Unsubscribe,
|
|
21
|
+
} from "./types.js";
|
|
22
|
+
|
|
23
|
+
declare const TextEncoder: new () => {
|
|
24
|
+
encode: (input: string) => Uint8Array;
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
const QUEUE_CAP = 4096;
|
|
28
|
+
const FLUSH_BATCH = 256;
|
|
29
|
+
const REPLACEABLE_EVENTS = new Set<P2pEvent_Tags>([
|
|
30
|
+
P2pEvent_Tags.ReachabilityChanged,
|
|
31
|
+
P2pEvent_Tags.PublicAddressesChanged,
|
|
32
|
+
]);
|
|
33
|
+
|
|
34
|
+
type EventHandler = (event: MiniP2pEvent) => void;
|
|
35
|
+
interface Waiter {
|
|
36
|
+
predicate: (event: MiniP2pEvent) => boolean;
|
|
37
|
+
resolve: (event: MiniP2pEvent) => void;
|
|
38
|
+
reject: (error: Error) => void;
|
|
39
|
+
timer?: ReturnType<typeof setTimeout>;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
interface EventNode {
|
|
43
|
+
readonly event: P2pEvent;
|
|
44
|
+
previous?: EventNode;
|
|
45
|
+
next?: EventNode;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* A bounded FIFO with constant-time front removal and payload eviction.
|
|
50
|
+
*
|
|
51
|
+
* Replaceable-event indexes let overflow compaction visit only candidates
|
|
52
|
+
* that can actually be discarded rather than rebuilding the entire queue.
|
|
53
|
+
*/
|
|
54
|
+
class EventQueue {
|
|
55
|
+
readonly #payloads = new Set<EventNode>();
|
|
56
|
+
readonly #replaceable = new Map<P2pEvent_Tags, Set<EventNode>>();
|
|
57
|
+
#head?: EventNode;
|
|
58
|
+
#tail?: EventNode;
|
|
59
|
+
#size = 0;
|
|
60
|
+
|
|
61
|
+
get size(): number {
|
|
62
|
+
return this.#size;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
clear(): void {
|
|
66
|
+
this.#head = undefined;
|
|
67
|
+
this.#tail = undefined;
|
|
68
|
+
this.#size = 0;
|
|
69
|
+
this.#payloads.clear();
|
|
70
|
+
this.#replaceable.clear();
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
push(event: P2pEvent): number {
|
|
74
|
+
let dropped = 0;
|
|
75
|
+
if (this.#size >= QUEUE_CAP) {
|
|
76
|
+
dropped += this.#compactReplaceable();
|
|
77
|
+
}
|
|
78
|
+
if (this.#size >= QUEUE_CAP) {
|
|
79
|
+
const payload = this.#payloads.values().next().value;
|
|
80
|
+
if (payload === undefined) {
|
|
81
|
+
this.shift();
|
|
82
|
+
} else {
|
|
83
|
+
this.#remove(payload);
|
|
84
|
+
}
|
|
85
|
+
dropped += 1;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const node: EventNode = { event, previous: this.#tail };
|
|
89
|
+
if (this.#tail === undefined) {
|
|
90
|
+
this.#head = node;
|
|
91
|
+
} else {
|
|
92
|
+
this.#tail.next = node;
|
|
93
|
+
}
|
|
94
|
+
this.#tail = node;
|
|
95
|
+
this.#size += 1;
|
|
96
|
+
this.#index(node);
|
|
97
|
+
return dropped;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
shift(): P2pEvent | undefined {
|
|
101
|
+
const node = this.#head;
|
|
102
|
+
if (node === undefined) {
|
|
103
|
+
return undefined;
|
|
104
|
+
}
|
|
105
|
+
this.#remove(node);
|
|
106
|
+
return node.event;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
#compactReplaceable(): number {
|
|
110
|
+
let dropped = 0;
|
|
111
|
+
for (const nodes of this.#replaceable.values()) {
|
|
112
|
+
if (nodes.size < 2) {
|
|
113
|
+
continue;
|
|
114
|
+
}
|
|
115
|
+
const latest = [...nodes].at(-1);
|
|
116
|
+
for (const node of [...nodes]) {
|
|
117
|
+
if (node !== latest) {
|
|
118
|
+
this.#remove(node);
|
|
119
|
+
dropped += 1;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
return dropped;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
#index(node: EventNode): void {
|
|
127
|
+
if (
|
|
128
|
+
node.event.tag === P2pEvent_Tags.Message ||
|
|
129
|
+
node.event.tag === P2pEvent_Tags.StreamData
|
|
130
|
+
) {
|
|
131
|
+
this.#payloads.add(node);
|
|
132
|
+
}
|
|
133
|
+
if (REPLACEABLE_EVENTS.has(node.event.tag)) {
|
|
134
|
+
let nodes = this.#replaceable.get(node.event.tag);
|
|
135
|
+
if (nodes === undefined) {
|
|
136
|
+
nodes = new Set();
|
|
137
|
+
this.#replaceable.set(node.event.tag, nodes);
|
|
138
|
+
}
|
|
139
|
+
nodes.add(node);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
#remove(node: EventNode): void {
|
|
144
|
+
if (node.previous === undefined) {
|
|
145
|
+
this.#head = node.next;
|
|
146
|
+
} else {
|
|
147
|
+
node.previous.next = node.next;
|
|
148
|
+
}
|
|
149
|
+
if (node.next === undefined) {
|
|
150
|
+
this.#tail = node.previous;
|
|
151
|
+
} else {
|
|
152
|
+
node.next.previous = node.previous;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
this.#payloads.delete(node);
|
|
156
|
+
const replaceable = this.#replaceable.get(node.event.tag);
|
|
157
|
+
replaceable?.delete(node);
|
|
158
|
+
if (replaceable?.size === 0) {
|
|
159
|
+
this.#replaceable.delete(node.event.tag);
|
|
160
|
+
}
|
|
161
|
+
this.#size -= 1;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Platform-neutral owner for one native minip2p endpoint.
|
|
167
|
+
*
|
|
168
|
+
* Platform packages extend this class and expose a zero-argument `create`
|
|
169
|
+
* method backed by their native adapter.
|
|
170
|
+
*/
|
|
171
|
+
export class MiniP2pBase {
|
|
172
|
+
readonly #backend: MiniP2pBackend;
|
|
173
|
+
readonly #relayAddrs: readonly string[];
|
|
174
|
+
readonly #handlers = new Set<EventHandler>();
|
|
175
|
+
readonly #waiters = new Set<Waiter>();
|
|
176
|
+
readonly #queue = new EventQueue();
|
|
177
|
+
readonly #connectResults = new Map<
|
|
178
|
+
number,
|
|
179
|
+
| P2pEventByTag<P2pEvent_Tags.PathEstablished>
|
|
180
|
+
| P2pEventByTag<P2pEvent_Tags.ConnectFailed>
|
|
181
|
+
>();
|
|
182
|
+
#overflowDropped = 0;
|
|
183
|
+
#flushScheduled = false;
|
|
184
|
+
#closed = false;
|
|
185
|
+
|
|
186
|
+
protected constructor(
|
|
187
|
+
backend: MiniP2pBackend,
|
|
188
|
+
relayAddresses: readonly string[]
|
|
189
|
+
) {
|
|
190
|
+
this.#backend = backend;
|
|
191
|
+
this.#relayAddrs = relayAddresses;
|
|
192
|
+
try {
|
|
193
|
+
this.#backend.start((event) => {
|
|
194
|
+
this.#enqueue(event);
|
|
195
|
+
});
|
|
196
|
+
} catch (error) {
|
|
197
|
+
this.#backend.close();
|
|
198
|
+
throw error;
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** Adds an event subscriber and returns an idempotent unsubscribe function. */
|
|
203
|
+
on(handler: EventHandler): Unsubscribe {
|
|
204
|
+
this.#assertOpen();
|
|
205
|
+
this.#handlers.add(handler);
|
|
206
|
+
let subscribed = true;
|
|
207
|
+
return () => {
|
|
208
|
+
if (subscribed) {
|
|
209
|
+
subscribed = false;
|
|
210
|
+
this.#handlers.delete(handler);
|
|
211
|
+
}
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/** Resolves with the first event matching `predicate`. */
|
|
216
|
+
waitFor<EventType extends MiniP2pEvent>(
|
|
217
|
+
predicate: (event: MiniP2pEvent) => event is EventType,
|
|
218
|
+
timeoutMs?: number
|
|
219
|
+
): Promise<EventType>;
|
|
220
|
+
waitFor(
|
|
221
|
+
predicate: (event: MiniP2pEvent) => boolean,
|
|
222
|
+
timeoutMs?: number
|
|
223
|
+
): Promise<MiniP2pEvent>;
|
|
224
|
+
waitFor(
|
|
225
|
+
predicate: (event: MiniP2pEvent) => boolean,
|
|
226
|
+
timeoutMs = 65_000
|
|
227
|
+
): Promise<MiniP2pEvent> {
|
|
228
|
+
this.#assertOpen();
|
|
229
|
+
assertSafeUnsignedInteger(timeoutMs, "timeoutMs");
|
|
230
|
+
|
|
231
|
+
return new Promise((resolve, reject) => {
|
|
232
|
+
const waiter: Waiter = { predicate, reject, resolve };
|
|
233
|
+
if (timeoutMs > 0) {
|
|
234
|
+
waiter.timer = setTimeout(() => {
|
|
235
|
+
this.#waiters.delete(waiter);
|
|
236
|
+
reject(new TimeoutError(timeoutMs));
|
|
237
|
+
}, timeoutMs);
|
|
238
|
+
}
|
|
239
|
+
this.#waiters.add(waiter);
|
|
240
|
+
});
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/** Requests native shutdown and releases the platform backend. */
|
|
244
|
+
close(): void {
|
|
245
|
+
if (this.#closed) {
|
|
246
|
+
return;
|
|
247
|
+
}
|
|
248
|
+
this.#closed = true;
|
|
249
|
+
this.#queue.clear();
|
|
250
|
+
this.#connectResults.clear();
|
|
251
|
+
this.#overflowDropped = 0;
|
|
252
|
+
this.#handlers.clear();
|
|
253
|
+
for (const waiter of this.#waiters) {
|
|
254
|
+
clearWaiterTimer(waiter);
|
|
255
|
+
waiter.reject(new ClosedError());
|
|
256
|
+
}
|
|
257
|
+
this.#waiters.clear();
|
|
258
|
+
this.#backend.close();
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/** Returns the endpoint's base58 peer ID. */
|
|
262
|
+
peerId(): string {
|
|
263
|
+
this.#assertOpen();
|
|
264
|
+
return this.#backend.peerId();
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/** Returns the endpoint's bound peer addresses. */
|
|
268
|
+
listenAddrs(): string[] {
|
|
269
|
+
this.#assertOpen();
|
|
270
|
+
return this.#backend.listenAddrs();
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/** Returns currently connected peer IDs. */
|
|
274
|
+
connectedPeers(): string[] {
|
|
275
|
+
this.#assertOpen();
|
|
276
|
+
return this.#backend.connectedPeers();
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/** Returns whether Identify has completed for a connected peer. */
|
|
280
|
+
isPeerReady(peerId: string): boolean {
|
|
281
|
+
this.#assertOpen();
|
|
282
|
+
return this.#backend.isPeerReady(peerId);
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/** Returns the latest Identify snapshot for a connected peer. */
|
|
286
|
+
peerInfo(peerId: string): IdentifyInfo | undefined {
|
|
287
|
+
this.#assertOpen();
|
|
288
|
+
return this.#backend.peerInfo(peerId);
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/** Returns the normalized discovery address book. */
|
|
292
|
+
knownPeers(): KnownPeerInfo[] {
|
|
293
|
+
this.#assertOpen();
|
|
294
|
+
return this.#backend.knownPeers();
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/** Returns the native discovery monotonic clock, when discovery is enabled. */
|
|
298
|
+
discoveryNowMs(): number | undefined {
|
|
299
|
+
this.#assertOpen();
|
|
300
|
+
return this.#backend.discoveryNowMs();
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/** Returns the active relay reservation, if one exists. */
|
|
304
|
+
activeReservation(): RelayReservationInfo | undefined {
|
|
305
|
+
this.#assertOpen();
|
|
306
|
+
return this.#backend.activeReservation();
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/** Returns this endpoint's currently usable circuit address, if known. */
|
|
310
|
+
get circuitAddress(): string | undefined {
|
|
311
|
+
const reservation = this.activeReservation();
|
|
312
|
+
if (reservation === undefined) {
|
|
313
|
+
return undefined;
|
|
314
|
+
}
|
|
315
|
+
const suffix = `/p2p/${reservation.relayPeerId}`;
|
|
316
|
+
const relayAddr = this.#relayAddrs.find((addr) => addr.endsWith(suffix));
|
|
317
|
+
return relayAddr === undefined
|
|
318
|
+
? undefined
|
|
319
|
+
: this.#backend.circuitAddress(relayAddr, this.peerId());
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/** Returns the current native reachability state. */
|
|
323
|
+
reachability(): Reachability {
|
|
324
|
+
this.#assertOpen();
|
|
325
|
+
return this.#backend.reachability();
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/** Returns whether the native driver is accepting work. */
|
|
329
|
+
isRunning(): boolean {
|
|
330
|
+
return !this.#closed && this.#backend.isRunning();
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
/** Selects foreground or idle native polling. */
|
|
334
|
+
setActive(active: boolean): void {
|
|
335
|
+
this.#assertOpen();
|
|
336
|
+
this.#backend.setActive(active);
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
/** Subscribes to a pubsub topic. */
|
|
340
|
+
subscribe(topic: string): boolean {
|
|
341
|
+
this.#assertOpen();
|
|
342
|
+
return this.#backend.subscribe(topic);
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
/** Withdraws a pubsub subscription. */
|
|
346
|
+
unsubscribe(topic: string): boolean {
|
|
347
|
+
this.#assertOpen();
|
|
348
|
+
return this.#backend.unsubscribe(topic);
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
/** Publishes UTF-8 text or bytes. */
|
|
352
|
+
publish(topic: string, data: string | Bytes): void {
|
|
353
|
+
this.#assertOpen();
|
|
354
|
+
this.#backend.publish(topic, toUint8Array(data));
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/** Sends an explicit ping; the result is emitted as a ping event. */
|
|
358
|
+
ping(peerId: string): void {
|
|
359
|
+
this.#assertOpen();
|
|
360
|
+
this.#backend.ping(peerId);
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
/** Waits until Identify completes for `peerId`. */
|
|
364
|
+
waitPeerReady(
|
|
365
|
+
peerId: string,
|
|
366
|
+
timeoutMs = 65_000
|
|
367
|
+
): Promise<P2pEventByTag<P2pEvent_Tags.PeerReady>> {
|
|
368
|
+
const info = this.peerInfo(peerId);
|
|
369
|
+
if (info !== undefined) {
|
|
370
|
+
return Promise.resolve({
|
|
371
|
+
inner: { peerId, protocols: info.protocols },
|
|
372
|
+
tag: P2pEvent_Tags.PeerReady,
|
|
373
|
+
});
|
|
374
|
+
}
|
|
375
|
+
return this.waitFor(
|
|
376
|
+
(
|
|
377
|
+
event
|
|
378
|
+
): event is
|
|
379
|
+
| P2pEventByTag<P2pEvent_Tags.PeerReady>
|
|
380
|
+
| P2pEventByTag<P2pEvent_Tags.ConnectionClosed> =>
|
|
381
|
+
"tag" in event &&
|
|
382
|
+
(event.tag === P2pEvent_Tags.PeerReady ||
|
|
383
|
+
event.tag === P2pEvent_Tags.ConnectionClosed) &&
|
|
384
|
+
event.inner.peerId === peerId,
|
|
385
|
+
timeoutMs
|
|
386
|
+
).then((event) => {
|
|
387
|
+
if (event.tag === P2pEvent_Tags.ConnectionClosed) {
|
|
388
|
+
throw new PeerDisconnectedError(peerId);
|
|
389
|
+
}
|
|
390
|
+
return event;
|
|
391
|
+
});
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
/** Waits for the next explicit or keepalive ping RTT for `peerId`. */
|
|
395
|
+
waitPingRtt(
|
|
396
|
+
peerId: string,
|
|
397
|
+
timeoutMs = 65_000
|
|
398
|
+
): Promise<P2pEventByTag<P2pEvent_Tags.PingRttMeasured>> {
|
|
399
|
+
return this.waitFor(
|
|
400
|
+
(event): event is P2pEventByTag<P2pEvent_Tags.PingRttMeasured> =>
|
|
401
|
+
"tag" in event &&
|
|
402
|
+
event.tag === P2pEvent_Tags.PingRttMeasured &&
|
|
403
|
+
event.inner.peerId === peerId,
|
|
404
|
+
timeoutMs
|
|
405
|
+
);
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
/** Registers an application protocol at runtime. */
|
|
409
|
+
addProtocol(protocolId: string): void {
|
|
410
|
+
this.#assertOpen();
|
|
411
|
+
this.#backend.addProtocol(protocolId);
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
/** Opens a negotiated custom-protocol stream. */
|
|
415
|
+
openStream(peerId: string, protocolId: string): number {
|
|
416
|
+
this.#assertOpen();
|
|
417
|
+
return this.#backend.openStream(peerId, protocolId);
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
/** Sends UTF-8 text or bytes on a custom-protocol stream. */
|
|
421
|
+
sendStream(peerId: string, streamId: number, data: string | Bytes): void {
|
|
422
|
+
this.#assertOpen();
|
|
423
|
+
assertSafeUnsignedInteger(streamId, "streamId");
|
|
424
|
+
this.#backend.sendStream(peerId, streamId, toUint8Array(data));
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
/** Half-closes the local write side of a stream. */
|
|
428
|
+
closeStreamWrite(peerId: string, streamId: number): void {
|
|
429
|
+
this.#assertOpen();
|
|
430
|
+
assertSafeUnsignedInteger(streamId, "streamId");
|
|
431
|
+
this.#backend.closeStreamWrite(peerId, streamId);
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
/** Resets a stream while retaining later close events. */
|
|
435
|
+
resetStream(peerId: string, streamId: number): void {
|
|
436
|
+
this.#assertOpen();
|
|
437
|
+
assertSafeUnsignedInteger(streamId, "streamId");
|
|
438
|
+
this.#backend.resetStream(peerId, streamId);
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
/** Resets and forgets a stream, suppressing later stream events. */
|
|
442
|
+
abandonStream(peerId: string, streamId: number): void {
|
|
443
|
+
this.#assertOpen();
|
|
444
|
+
assertSafeUnsignedInteger(streamId, "streamId");
|
|
445
|
+
this.#backend.abandonStream(peerId, streamId);
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
/** Starts a connection attempt and returns its endpoint-local ID. */
|
|
449
|
+
connect(peerId: string): number {
|
|
450
|
+
this.#assertOpen();
|
|
451
|
+
return this.#backend.connect(peerId);
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
/** Starts a NAT connection attempt using an explicit ordered address set. */
|
|
455
|
+
connectWithAddrs(peerId: string, addresses: readonly string[]): number {
|
|
456
|
+
this.#assertOpen();
|
|
457
|
+
return this.#backend.connectWithAddrs(peerId, addresses);
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
/** Waits for a connection attempt's first usable path or terminal failure. */
|
|
461
|
+
waitConnectResult(
|
|
462
|
+
connectId: number,
|
|
463
|
+
timeoutMs = 65_000
|
|
464
|
+
): Promise<
|
|
465
|
+
| P2pEventByTag<P2pEvent_Tags.PathEstablished>
|
|
466
|
+
| P2pEventByTag<P2pEvent_Tags.ConnectFailed>
|
|
467
|
+
> {
|
|
468
|
+
assertSafeUnsignedInteger(connectId, "connectId");
|
|
469
|
+
this.#assertOpen();
|
|
470
|
+
const result = this.#connectResults.get(connectId);
|
|
471
|
+
if (result !== undefined) {
|
|
472
|
+
return Promise.resolve(result);
|
|
473
|
+
}
|
|
474
|
+
return this.waitFor(
|
|
475
|
+
(
|
|
476
|
+
event
|
|
477
|
+
): event is
|
|
478
|
+
| P2pEventByTag<P2pEvent_Tags.PathEstablished>
|
|
479
|
+
| P2pEventByTag<P2pEvent_Tags.ConnectFailed> =>
|
|
480
|
+
"tag" in event &&
|
|
481
|
+
(event.tag === P2pEvent_Tags.PathEstablished ||
|
|
482
|
+
event.tag === P2pEvent_Tags.ConnectFailed) &&
|
|
483
|
+
event.inner.connectId === connectId,
|
|
484
|
+
timeoutMs
|
|
485
|
+
);
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
/** Starts a direct-address connection attempt. */
|
|
489
|
+
connectAddr(address: string): number {
|
|
490
|
+
this.#assertOpen();
|
|
491
|
+
return this.#backend.connectAddr(address);
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
/** Dials a direct address on every applicable local address family. */
|
|
495
|
+
dial(address: string): number[] {
|
|
496
|
+
this.#assertOpen();
|
|
497
|
+
return this.#backend.dial(address);
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
/** Dials a direct address using IPv4. */
|
|
501
|
+
dialIp4(address: string): number {
|
|
502
|
+
this.#assertOpen();
|
|
503
|
+
return this.#backend.dialIp4(address);
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
/** Dials a direct address using IPv6. */
|
|
507
|
+
dialIp6(address: string): number {
|
|
508
|
+
this.#assertOpen();
|
|
509
|
+
return this.#backend.dialIp6(address);
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
/** Suppresses future events for a known connection attempt. */
|
|
513
|
+
cancelConnect(id: number): void {
|
|
514
|
+
this.#assertOpen();
|
|
515
|
+
assertSafeUnsignedInteger(id, "connectId");
|
|
516
|
+
this.#backend.cancelConnect(id);
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
/** Closes an established connection to a peer. */
|
|
520
|
+
disconnect(peerId: string): void {
|
|
521
|
+
this.#assertOpen();
|
|
522
|
+
this.#backend.disconnect(peerId);
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
#assertOpen(): void {
|
|
526
|
+
if (this.#closed) {
|
|
527
|
+
throw new ClosedError();
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
#enqueue(event: P2pEvent): void {
|
|
532
|
+
if (this.#closed) {
|
|
533
|
+
return;
|
|
534
|
+
}
|
|
535
|
+
this.#overflowDropped += this.#queue.push(event);
|
|
536
|
+
this.#scheduleFlush();
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
#scheduleFlush(): void {
|
|
540
|
+
if (this.#flushScheduled) {
|
|
541
|
+
return;
|
|
542
|
+
}
|
|
543
|
+
this.#flushScheduled = true;
|
|
544
|
+
Promise.resolve().then(() => {
|
|
545
|
+
this.#flush();
|
|
546
|
+
});
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
#flush(): void {
|
|
550
|
+
if (this.#closed) {
|
|
551
|
+
return;
|
|
552
|
+
}
|
|
553
|
+
this.#flushScheduled = false;
|
|
554
|
+
let delivered = 0;
|
|
555
|
+
|
|
556
|
+
if (this.#overflowDropped > 0) {
|
|
557
|
+
const dropped = this.#overflowDropped;
|
|
558
|
+
this.#overflowDropped = 0;
|
|
559
|
+
this.#dispatch({ dropped, type: "queueOverflow" });
|
|
560
|
+
delivered += 1;
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
while (delivered < FLUSH_BATCH) {
|
|
564
|
+
const event = this.#queue.shift();
|
|
565
|
+
if (event === undefined) {
|
|
566
|
+
break;
|
|
567
|
+
}
|
|
568
|
+
this.#dispatch(event);
|
|
569
|
+
delivered += 1;
|
|
570
|
+
if (this.#closed) {
|
|
571
|
+
return;
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
if (this.#queue.size > 0 || this.#overflowDropped > 0) {
|
|
576
|
+
this.#flushScheduled = true;
|
|
577
|
+
setTimeout(() => {
|
|
578
|
+
this.#flush();
|
|
579
|
+
}, 0);
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
#dispatch(event: MiniP2pEvent): void {
|
|
584
|
+
if (
|
|
585
|
+
"tag" in event &&
|
|
586
|
+
(event.tag === P2pEvent_Tags.PathEstablished ||
|
|
587
|
+
event.tag === P2pEvent_Tags.ConnectFailed)
|
|
588
|
+
) {
|
|
589
|
+
this.#connectResults.set(event.inner.connectId, event);
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
if ("tag" in event && event.tag === P2pEvent_Tags.DriverFailed) {
|
|
593
|
+
this.#terminateDriver(event);
|
|
594
|
+
return;
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
for (const waiter of [...this.#waiters]) {
|
|
598
|
+
let matched: boolean;
|
|
599
|
+
try {
|
|
600
|
+
matched = waiter.predicate(event);
|
|
601
|
+
} catch (error) {
|
|
602
|
+
this.#waiters.delete(waiter);
|
|
603
|
+
clearWaiterTimer(waiter);
|
|
604
|
+
waiter.reject(asError(error));
|
|
605
|
+
continue;
|
|
606
|
+
}
|
|
607
|
+
if (matched) {
|
|
608
|
+
this.#waiters.delete(waiter);
|
|
609
|
+
clearWaiterTimer(waiter);
|
|
610
|
+
waiter.resolve(event);
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
for (const handler of [...this.#handlers]) {
|
|
615
|
+
try {
|
|
616
|
+
handler(event);
|
|
617
|
+
} catch {
|
|
618
|
+
// One host handler cannot interrupt fan-out or unwind into Rust.
|
|
619
|
+
}
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
#terminateDriver(event: P2pEventByTag<P2pEvent_Tags.DriverFailed>): void {
|
|
624
|
+
this.#closed = true;
|
|
625
|
+
this.#queue.clear();
|
|
626
|
+
this.#connectResults.clear();
|
|
627
|
+
this.#overflowDropped = 0;
|
|
628
|
+
const handlers = [...this.#handlers];
|
|
629
|
+
this.#handlers.clear();
|
|
630
|
+
const failure = new DriverFailedError(event.inner.kind, event.inner.detail);
|
|
631
|
+
for (const waiter of this.#waiters) {
|
|
632
|
+
clearWaiterTimer(waiter);
|
|
633
|
+
waiter.reject(failure);
|
|
634
|
+
}
|
|
635
|
+
this.#waiters.clear();
|
|
636
|
+
|
|
637
|
+
for (const handler of handlers) {
|
|
638
|
+
try {
|
|
639
|
+
handler(event);
|
|
640
|
+
} catch {
|
|
641
|
+
// One host handler cannot interrupt fan-out or unwind into Rust.
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
this.#backend.close();
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
function toUint8Array(value: string | Bytes): Uint8Array {
|
|
649
|
+
if (typeof value === "string") {
|
|
650
|
+
return new TextEncoder().encode(value);
|
|
651
|
+
}
|
|
652
|
+
return value instanceof Uint8Array ? value : new Uint8Array(value);
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
function assertSafeUnsignedInteger(value: number, name: string): void {
|
|
656
|
+
if (!Number.isSafeInteger(value) || value < 0) {
|
|
657
|
+
throw new RangeError(`${name} must be a non-negative safe integer`);
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
function clearWaiterTimer(waiter: Waiter): void {
|
|
662
|
+
if (waiter.timer !== undefined) {
|
|
663
|
+
clearTimeout(waiter.timer);
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
function asError(error: unknown): Error {
|
|
668
|
+
return error instanceof Error ? error : new Error(String(error));
|
|
669
|
+
}
|