@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.
package/src/sdk.ts CHANGED
@@ -1,6 +1,10 @@
1
1
  /* oxlint-disable default-case, func-style, max-classes-per-file, no-await-in-loop, no-empty-function, no-loop-func, no-use-before-define, promise/avoid-new, promise/prefer-await-to-callbacks, promise/prefer-await-to-then, typescript/no-invalid-void-type, unicorn/consistent-function-scoping, unicorn/no-new-array, unicorn/no-useless-spread, unicorn/no-useless-undefined -- Promise adapters, sequential async iterators, void event payloads, snapshot fan-out, and bounded queues are deliberate SDK internals. */
2
2
 
3
- import type { BackendConnectTarget, Minip2pBackend } from "./backend.js";
3
+ import type {
4
+ BackendClosed,
5
+ BackendConnectTarget,
6
+ Minip2pBackend,
7
+ } from "./backend.js";
4
8
  import {
5
9
  AbortError,
6
10
  ClosedError,
@@ -16,14 +20,20 @@ import {
16
20
  TimeoutError,
17
21
  WriteBufferFullError,
18
22
  } from "./errors.js";
19
- import { P2pEvent_Tags, PathKind_Tags } from "./types.js";
23
+ import {
24
+ CloseOutcome,
25
+ ConnectionCloseReason_Tags,
26
+ P2pEvent_Tags,
27
+ PathKind_Tags,
28
+ } from "./types.js";
20
29
  import type {
21
30
  Bytes,
22
- CloseReason,
31
+ ConnectionCloseReason,
23
32
  ConnectionInfo,
24
33
  ConnectOptions,
25
34
  ConnectResult,
26
35
  ConnectTarget,
36
+ EndpointCloseReport,
27
37
  EventsOptions,
28
38
  IdentifyInfo,
29
39
  InboundStreamMeta,
@@ -37,6 +47,7 @@ import type {
37
47
  P2pEventTag,
38
48
  Path,
39
49
  PathKind,
50
+ RawConnectionCloseReason,
40
51
  Reachability,
41
52
  RelayReservationInfo,
42
53
  Unsubscribe,
@@ -48,6 +59,11 @@ declare const TextEncoder: new () => {
48
59
  };
49
60
 
50
61
  const DEFAULT_TIMEOUT_MS = 65_000;
62
+ /**
63
+ * Default close drain: the Rust `minip2p::DEFAULT_CLOSE_TIMEOUT` (500 ms)
64
+ * that `Endpoint::close` and native's `DEFAULT_STOP_TIMEOUT_MS` use.
65
+ */
66
+ const DEFAULT_CLOSE_TIMEOUT_MS = 500;
51
67
  const EVENT_QUEUE_CAP = 4096;
52
68
  const EVENT_FLUSH_BATCH = 256;
53
69
  const CONNECT_TERMINAL_CAP = 1024;
@@ -1114,7 +1130,7 @@ export class Minip2pBase {
1114
1130
  readonly #relayAddrs: readonly string[];
1115
1131
  readonly #named = new Map<EventKind, Set<(payload: AnyPayload) => void>>();
1116
1132
  readonly #catchAll = new Set<CatchAllHandler>();
1117
- readonly #closeHandlers = new Set<(reason: CloseReason) => void>();
1133
+ readonly #closeHandlers = new Set<(report: EndpointCloseReport) => void>();
1118
1134
  readonly #waiters = new Set<EventWaiter>();
1119
1135
  readonly #queue = new EventQueue(EVENT_QUEUE_CAP, (item) => {
1120
1136
  this.#releaseQueueItem(item);
@@ -1127,6 +1143,9 @@ export class Minip2pBase {
1127
1143
  #dropped = 0;
1128
1144
  #flushScheduled = false;
1129
1145
  #closed = false;
1146
+ /** Settles once the native drain finished and close observers ran. */
1147
+ #closing: Promise<EndpointCloseReport> | undefined;
1148
+ #closeReported = false;
1130
1149
 
1131
1150
  protected constructor(
1132
1151
  backend: Minip2pBackend,
@@ -1139,7 +1158,7 @@ export class Minip2pBase {
1139
1158
  this.#enqueueNative(event);
1140
1159
  });
1141
1160
  } catch (error) {
1142
- backend.close();
1161
+ void backend.close(0);
1143
1162
  throw error;
1144
1163
  }
1145
1164
  }
@@ -1295,21 +1314,43 @@ export class Minip2pBase {
1295
1314
  });
1296
1315
  }
1297
1316
 
1298
- /** Registers a one-shot endpoint shutdown observer. */
1299
- onClose(handler: (reason: CloseReason) => void): Unsubscribe {
1300
- if (this.#closed) {
1317
+ /**
1318
+ * Registers a one-shot endpoint shutdown observer. It stays registered
1319
+ * through the native close drain and fires once that finishes, with the
1320
+ * same report {@link close} resolves with. A no-op once it has fired.
1321
+ */
1322
+ onClose(handler: (report: EndpointCloseReport) => void): Unsubscribe {
1323
+ if (this.#closeReported) {
1301
1324
  return () => {};
1302
1325
  }
1303
1326
  return subscribe(this.#closeHandlers, handler);
1304
1327
  }
1305
1328
 
1306
- /** Idempotently stops the endpoint and rejects outstanding operations. */
1307
- close(): void {
1308
- this.#teardown({ reason: "close" }, new ClosedError());
1329
+ /**
1330
+ * Stops the endpoint: rejects outstanding operations and drops listeners
1331
+ * at once, then has native disconnect peers and drain for up to
1332
+ * `timeoutMs` (default 500; `0` tears down at once, best effort). Resolves
1333
+ * with the close report once the drain finished, after `onClose`
1334
+ * observers ran; it never rejects. The deadline bounds teardown time only,
1335
+ * not delivery of accepted writes: QUIC discards queued writes and TCP may
1336
+ * abort. Idempotent: a later call returns the same promise, including
1337
+ * after a driver failure closed the endpoint.
1338
+ */
1339
+ close(
1340
+ timeoutMs: number = DEFAULT_CLOSE_TIMEOUT_MS
1341
+ ): Promise<EndpointCloseReport> {
1342
+ assertTimeout(timeoutMs);
1343
+ return this.#teardown(new ClosedError(), timeoutMs);
1309
1344
  }
1310
1345
 
1346
+ /** Starts {@link close} with the default drain, without waiting for it. */
1311
1347
  [Symbol.dispose](): void {
1312
- this.close();
1348
+ void this.close();
1349
+ }
1350
+
1351
+ /** {@link close} with the default drain, for `await using`. */
1352
+ async [Symbol.asyncDispose](): Promise<void> {
1353
+ await this.close();
1313
1354
  }
1314
1355
 
1315
1356
  /** Returns this endpoint's base58 peer ID. */
@@ -1318,7 +1359,10 @@ export class Minip2pBase {
1318
1359
  return this.#backend.peerId();
1319
1360
  }
1320
1361
 
1321
- /** Returns the currently bound peer multiaddresses. */
1362
+ /**
1363
+ * Returns the currently bound peer multiaddresses. A WebTransport
1364
+ * listener's certhashes rotate; `listenAddressesChanged` says when.
1365
+ */
1322
1366
  listenAddrs(): string[] {
1323
1367
  this.#assertOpen();
1324
1368
  return this.#backend.listenAddrs();
@@ -1380,17 +1424,27 @@ export class Minip2pBase {
1380
1424
  return this.#backend.reachability();
1381
1425
  }
1382
1426
 
1383
- /** Returns the authoritative active path to `peerId`, if connected. */
1427
+ /**
1428
+ * Returns the path of `peerId`'s established connection; `undefined` only
1429
+ * while the peer is not connected.
1430
+ */
1384
1431
  path(peerId: string): Path | undefined {
1385
1432
  this.#assertOpen();
1386
1433
  const path = this.#backend.path(peerId);
1387
1434
  return path === undefined ? undefined : normalizePath(path);
1388
1435
  }
1389
1436
 
1390
- /** Returns the transport connection selected for `peerId`, if connected. */
1437
+ /**
1438
+ * Returns a snapshot of `peerId`'s established connection: its connection
1439
+ * ID, remote address, path, and Identify protocols once ready;
1440
+ * `undefined` while the peer is not connected.
1441
+ */
1391
1442
  connectionInfo(peerId: string): ConnectionInfo | undefined {
1392
1443
  this.#assertOpen();
1393
- return this.#backend.connectionInfo(peerId);
1444
+ const info = this.#backend.connectionInfo(peerId);
1445
+ return info === undefined
1446
+ ? undefined
1447
+ : { ...info, path: normalizePath(info.path) };
1394
1448
  }
1395
1449
 
1396
1450
  /** Returns whether the native driver is accepting work. */
@@ -1858,13 +1912,17 @@ export class Minip2pBase {
1858
1912
  }
1859
1913
 
1860
1914
  #dispatchNative(event: P2pEvent): void {
1915
+ // Backends resolve `close` with it instead of delivering it.
1916
+ if (event.tag === P2pEvent_Tags.EndpointClosed) {
1917
+ return;
1918
+ }
1861
1919
  if (event.tag === P2pEvent_Tags.DriverFailed) {
1862
1920
  const failure = new DriverFailedError(
1863
1921
  event.inner.kind,
1864
1922
  event.inner.detail
1865
1923
  );
1866
1924
  this.#dispatch("driverFailed", event.inner, event.inner);
1867
- this.#teardown({ error: failure, reason: "driverFailed" }, failure);
1925
+ void this.#teardown(failure, 0);
1868
1926
  return;
1869
1927
  }
1870
1928
 
@@ -2233,47 +2291,72 @@ export class Minip2pBase {
2233
2291
  }
2234
2292
  }
2235
2293
 
2236
- #teardown(reason: CloseReason, error: Error): void {
2237
- if (this.#closed) {
2238
- return;
2294
+ /**
2295
+ * Closes the endpoint once, rejecting what is outstanding with `cause`;
2296
+ * later calls return the first call's promise. A
2297
+ * {@link DriverFailedError} cause reports a `driverFailed` close.
2298
+ */
2299
+ #teardown(
2300
+ cause: ClosedError | DriverFailedError,
2301
+ timeoutMs: number
2302
+ ): Promise<EndpointCloseReport> {
2303
+ if (this.#closing !== undefined) {
2304
+ return this.#closing;
2239
2305
  }
2240
2306
  this.#closed = true;
2241
- const closeHandlers = [...this.#closeHandlers];
2242
- this.#closeHandlers.clear();
2243
2307
  this.#clearQueue();
2244
2308
  this.#dropped = 0;
2245
2309
  this.#named.clear();
2246
2310
  this.#catchAll.clear();
2311
+ // Native is asked to close before anything below can call back in: a
2312
+ // re-entrant close returns this promise.
2313
+ let closed: Promise<BackendClosed>;
2314
+ try {
2315
+ closed = this.#backend.close(timeoutMs);
2316
+ } catch {
2317
+ closed = Promise.resolve({
2318
+ outcome: CloseOutcome.Failed,
2319
+ unfinished: [],
2320
+ });
2321
+ }
2322
+ const closing = closed.then(({ outcome, unfinished }) => {
2323
+ const report: EndpointCloseReport =
2324
+ cause instanceof DriverFailedError
2325
+ ? { error: cause, reason: "driverFailed", unfinished }
2326
+ : { outcome, reason: "close", unfinished };
2327
+ this.#closeReported = true;
2328
+ const closeHandlers = [...this.#closeHandlers];
2329
+ this.#closeHandlers.clear();
2330
+ for (const handler of closeHandlers) {
2331
+ try {
2332
+ handler(report);
2333
+ } catch {
2334
+ // Close notification is outside the now-closed event queue.
2335
+ }
2336
+ }
2337
+ return report;
2338
+ });
2339
+ this.#closing = closing;
2247
2340
  for (const waiter of [...this.#waiters]) {
2248
- this.#settleWaiter(waiter, error);
2341
+ this.#settleWaiter(waiter, cause);
2249
2342
  }
2250
2343
  for (const attempt of this.#connects.values()) {
2251
- attempt.settle?.({ error, ok: false });
2344
+ attempt.settle?.({ error: cause, ok: false });
2252
2345
  }
2253
2346
  this.#connects.clear();
2254
2347
  this.#terminalConnects.clear();
2255
2348
  for (const pending of this.#pendingOpens.takeAll()) {
2256
2349
  clearPendingOpen(pending);
2257
- pending.reject(error);
2350
+ pending.reject(cause);
2258
2351
  }
2259
2352
  for (const stream of this.#streams.takeAll()) {
2260
- stream.terminal(error);
2353
+ stream.terminal(cause);
2261
2354
  }
2262
2355
  for (const ping of this.#pings.values()) {
2263
- ping.cancel(error);
2356
+ ping.cancel(cause);
2264
2357
  }
2265
2358
  this.#pings.clear();
2266
- try {
2267
- this.#backend.close();
2268
- } finally {
2269
- for (const handler of closeHandlers) {
2270
- try {
2271
- handler(reason);
2272
- } catch {
2273
- // Close notification is outside the now-closed event queue.
2274
- }
2275
- }
2276
- }
2359
+ return closing;
2277
2360
  }
2278
2361
 
2279
2362
  #assertOpen(): void {
@@ -2315,6 +2398,7 @@ function toBackendTarget(target: ConnectTarget): BackendConnectTarget {
2315
2398
  type UnnamedEventTag =
2316
2399
  | StreamP2pEvent["tag"]
2317
2400
  | typeof P2pEvent_Tags.DriverFailed
2401
+ | typeof P2pEvent_Tags.EndpointClosed
2318
2402
  | typeof P2pEvent_Tags.StreamReady;
2319
2403
  type NamedEventTag = Exclude<P2pEventTag, UnnamedEventTag>;
2320
2404
 
@@ -2335,6 +2419,7 @@ const SDK_EVENT_NAMES: {
2335
2419
  [P2pEvent_Tags.PingTimeout]: "pingTimeout",
2336
2420
  [P2pEvent_Tags.EndpointError]: "endpointError",
2337
2421
  [P2pEvent_Tags.ReachabilityChanged]: "reachabilityChanged",
2422
+ [P2pEvent_Tags.ListenAddressesChanged]: "listenAddressesChanged",
2338
2423
  [P2pEvent_Tags.PublicAddressesChanged]: "publicAddressesChanged",
2339
2424
  [P2pEvent_Tags.RelayReserved]: "relayReserved",
2340
2425
  [P2pEvent_Tags.RelayReservationLost]: "relayReservationLost",
@@ -2366,6 +2451,7 @@ function normalizeEvent(
2366
2451
  | {
2367
2452
  readonly tag:
2368
2453
  | typeof P2pEvent_Tags.DriverFailed
2454
+ | typeof P2pEvent_Tags.EndpointClosed
2369
2455
  | typeof P2pEvent_Tags.StreamReady;
2370
2456
  }
2371
2457
  >
@@ -2389,17 +2475,44 @@ function normalizeEvent(
2389
2475
  from: normalizePath(event.inner.from),
2390
2476
  to: normalizePath(event.inner.to),
2391
2477
  };
2478
+ } else if (event.tag === P2pEvent_Tags.ConnectionClosed) {
2479
+ payload = {
2480
+ ...event.inner,
2481
+ reason: normalizeCloseReason(event.inner.reason),
2482
+ };
2392
2483
  }
2393
2484
  return { payload: payload as AnyPayload, type };
2394
2485
  }
2395
2486
 
2487
+ function normalizeCloseReason(
2488
+ reason: RawConnectionCloseReason
2489
+ ): ConnectionCloseReason {
2490
+ switch (reason.tag) {
2491
+ case ConnectionCloseReason_Tags.Local: {
2492
+ return { kind: "local" };
2493
+ }
2494
+ case ConnectionCloseReason_Tags.Remote: {
2495
+ return { code: reason.inner.code, kind: "remote" };
2496
+ }
2497
+ case ConnectionCloseReason_Tags.TimedOut: {
2498
+ return { kind: "timedOut" };
2499
+ }
2500
+ case ConnectionCloseReason_Tags.Stalled: {
2501
+ return { kind: "stalled" };
2502
+ }
2503
+ case ConnectionCloseReason_Tags.Error: {
2504
+ return { kind: "error", message: reason.inner.message };
2505
+ }
2506
+ }
2507
+ }
2508
+
2396
2509
  function normalizePath(path: PathKind): Path {
2397
2510
  switch (path.tag) {
2398
- case PathKind_Tags.DirectDialed: {
2399
- return { kind: "directDialed" };
2511
+ case PathKind_Tags.Direct: {
2512
+ return { kind: "direct" };
2400
2513
  }
2401
- case PathKind_Tags.DirectPunched: {
2402
- return { kind: "directPunched" };
2514
+ case PathKind_Tags.Punched: {
2515
+ return { kind: "punched" };
2403
2516
  }
2404
2517
  case PathKind_Tags.Relayed: {
2405
2518
  return { kind: "relayed", relayPeerId: path.inner.relayPeerId };