@minip2p/core 0.8.3 → 0.10.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/dist/sdk.js CHANGED
@@ -1,7 +1,12 @@
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
  import { AbortError, ClosedError, ConnectCancelledError, ConnectFailedError, ConnectResultLostError, ConnectResultUnavailableError, DriverFailedError, EventQueueOverflowError, OpenStreamError, PeerDisconnectedError, StreamClosedError, TimeoutError, WriteBufferFullError, } from "./errors.js";
3
- import { P2pEvent_Tags, PathKind_Tags } from "./types.js";
3
+ import { CloseOutcome, ConnectionCloseReason_Tags, P2pEvent_Tags, PathKind_Tags, } from "./types.js";
4
4
  const DEFAULT_TIMEOUT_MS = 65_000;
5
+ /**
6
+ * Default close drain: the Rust `minip2p::DEFAULT_CLOSE_TIMEOUT` (500 ms)
7
+ * that `Endpoint::close` and native's `DEFAULT_STOP_TIMEOUT_MS` use.
8
+ */
9
+ const DEFAULT_CLOSE_TIMEOUT_MS = 500;
5
10
  const EVENT_QUEUE_CAP = 4096;
6
11
  const EVENT_FLUSH_BATCH = 256;
7
12
  const CONNECT_TERMINAL_CAP = 1024;
@@ -164,6 +169,31 @@ class StreamTable {
164
169
  return values;
165
170
  }
166
171
  }
172
+ /** Every connection a native event names. */
173
+ const connectionsOf = (event) => {
174
+ if (!("inner" in event)) {
175
+ return [];
176
+ }
177
+ const { inner } = event;
178
+ return [
179
+ "connId" in inner ? inner.connId : undefined,
180
+ "oldConnId" in inner ? inner.oldConnId : undefined,
181
+ "newConnId" in inner ? inner.newConnId : undefined,
182
+ ].filter((id) => typeof id === "number");
183
+ };
184
+ /**
185
+ * Native events that leave a connection unseen. Anything else naming it is
186
+ * something the application acts on or must hear about, so it keeps the
187
+ * connection's events.
188
+ */
189
+ const UNSEEN_CONNECTION_TAGS = new Set([
190
+ P2pEvent_Tags.PeerReady,
191
+ P2pEvent_Tags.IdentifyReceived,
192
+ P2pEvent_Tags.EndpointError,
193
+ P2pEvent_Tags.StreamRemoteWriteClosed,
194
+ P2pEvent_Tags.StreamWriteStopped,
195
+ P2pEvent_Tags.StreamClosed,
196
+ ]);
167
197
  /** The native per-stream event an item carries, if any. */
168
198
  const streamEventOf = (item) => item.source === "native" &&
169
199
  (item.event.tag === P2pEvent_Tags.StreamReady || isStreamEvent(item.event))
@@ -180,6 +210,15 @@ const streamEventOf = (item) => item.source === "native" &&
180
210
  * A peer-opened stream that closes without data before its `StreamReady`
181
211
  * is dispatched leaves the queue whole, so a peer opening and closing
182
212
  * streams cannot grow it; its events still reach `release`.
213
+ *
214
+ * Connections follow the same rule (ADR 0012): one that ends without data
215
+ * before any of its events was dispatched, whichever side dialed it, leaves
216
+ * with every event naming it. One replaced instead folds into its
217
+ * successor: its queued `ConnectionEstablished` is renamed to the successor
218
+ * and the `ConnectionReplaced` goes (as it does when the capacity already
219
+ * dropped that `ConnectionEstablished`). A connection the application knows
220
+ * otherwise -- a stream it opened, a ping result, an attempt or path event
221
+ * naming it -- is kept.
183
222
  */
184
223
  class EventQueue {
185
224
  #items = new Map();
@@ -191,6 +230,14 @@ class EventQueue {
191
230
  * queued item ids; `undefined` once one carried data.
192
231
  */
193
232
  #unseen = new StreamTable();
233
+ /** Connections whose `ConnectionEstablished` is queued and unseen. */
234
+ #unseenConnections = new Set();
235
+ /**
236
+ * Live connections the application learned of outside the queue, so a
237
+ * later replacement fold must not make them unseen; each leaves with its
238
+ * end.
239
+ */
240
+ #knownConnections = new Set();
194
241
  #capacity;
195
242
  #release;
196
243
  #next = 0;
@@ -207,14 +254,14 @@ class EventQueue {
207
254
  const newest = this.#newest === undefined ? undefined : this.#items.get(this.#newest);
208
255
  const merged = newest === undefined ? undefined : coalesceData(newest, item);
209
256
  if (merged !== undefined && this.#newest !== undefined) {
210
- // A data event retires no adapter IDs, so the absorbed one needs no
211
- // `eventHandled`.
212
257
  this.#items.set(this.#newest, merged);
258
+ // The absorbed event is handled: its adapter state goes now.
259
+ this.#release(item);
213
260
  return undefined;
214
261
  }
215
262
  const id = this.#next;
216
263
  this.#next += 1;
217
- if (this.#elideUnseen(item, id)) {
264
+ if (this.#elideUnseen(item, id) || this.#elideConnection(item)) {
218
265
  return undefined;
219
266
  }
220
267
  this.#items.set(id, item);
@@ -237,12 +284,105 @@ class EventQueue {
237
284
  return undefined;
238
285
  }
239
286
  const item = this.#remove(oldest);
240
- if (item?.source === "native" &&
241
- item.event.tag === P2pEvent_Tags.StreamReady) {
242
- this.#unseen.delete(item.event.inner.connId, item.event.inner.streamId);
287
+ if (item?.source === "native") {
288
+ if (item.event.tag === P2pEvent_Tags.StreamReady) {
289
+ this.#unseen.delete(item.event.inner.connId, item.event.inner.streamId);
290
+ }
291
+ for (const connId of connectionsOf(item.event)) {
292
+ this.#unseenConnections.delete(connId);
293
+ }
243
294
  }
244
295
  return item;
245
296
  }
297
+ /** The application learned of `connId` outside the queue. */
298
+ markConnectionSeen(connId) {
299
+ this.#unseenConnections.delete(connId);
300
+ this.#knownConnections.add(connId);
301
+ }
302
+ /**
303
+ * Records `item` against the unseen connections it names. Returns whether
304
+ * it ended or replaced one that carried no data, which leaves the queue
305
+ * with that connection's items instead.
306
+ */
307
+ #elideConnection(item) {
308
+ if (item.source !== "native") {
309
+ return false;
310
+ }
311
+ const { event } = item;
312
+ switch (event.tag) {
313
+ case P2pEvent_Tags.ConnectionEstablished: {
314
+ if (!this.#knownConnections.has(event.inner.connId)) {
315
+ this.#unseenConnections.add(event.inner.connId);
316
+ }
317
+ return false;
318
+ }
319
+ case P2pEvent_Tags.ConnectionClosed: {
320
+ this.#knownConnections.delete(event.inner.connId);
321
+ if (!this.#unseenConnections.delete(event.inner.connId)) {
322
+ return false;
323
+ }
324
+ this.#removeConnection(event.inner.connId);
325
+ this.#release(item);
326
+ return true;
327
+ }
328
+ case P2pEvent_Tags.ConnectionReplaced: {
329
+ const { newConnId, oldConnId } = event.inner;
330
+ this.#knownConnections.delete(oldConnId);
331
+ if (!this.#unseenConnections.delete(oldConnId)) {
332
+ return false;
333
+ }
334
+ this.#renameOpening(oldConnId, newConnId);
335
+ this.#removeConnection(oldConnId);
336
+ if (!this.#knownConnections.has(newConnId)) {
337
+ this.#unseenConnections.add(newConnId);
338
+ }
339
+ this.#release(item);
340
+ return true;
341
+ }
342
+ case P2pEvent_Tags.StreamReady: {
343
+ if (event.inner.initiatedLocally) {
344
+ this.#unseenConnections.delete(event.inner.connId);
345
+ }
346
+ return false;
347
+ }
348
+ default: {
349
+ if (!UNSEEN_CONNECTION_TAGS.has(event.tag)) {
350
+ for (const connId of connectionsOf(event)) {
351
+ this.#unseenConnections.delete(connId);
352
+ }
353
+ }
354
+ return false;
355
+ }
356
+ }
357
+ }
358
+ /** Renames the queued `ConnectionEstablished` of `from` to `to`. */
359
+ #renameOpening(from, to) {
360
+ for (const [id, queued] of this.#items) {
361
+ if (queued.source === "native" &&
362
+ queued.event.tag === P2pEvent_Tags.ConnectionEstablished &&
363
+ queued.event.inner.connId === from) {
364
+ this.#items.set(id, {
365
+ event: {
366
+ ...queued.event,
367
+ inner: { ...queued.event.inner, connId: to },
368
+ },
369
+ source: "native",
370
+ });
371
+ return;
372
+ }
373
+ }
374
+ }
375
+ /** Removes every queued item naming `connId`, releasing each. */
376
+ #removeConnection(connId) {
377
+ for (const [id, queued] of [...this.#items]) {
378
+ if (queued.source === "native" &&
379
+ connectionsOf(queued.event).includes(connId)) {
380
+ this.#remove(id);
381
+ this.#release(queued);
382
+ }
383
+ }
384
+ this.#unseen.takeConnection(connId);
385
+ }
246
386
  /**
247
387
  * Records `item` (as `id`) against an unseen peer stream. Returns whether
248
388
  * it closed one that carried no data, which leaves the queue whole.
@@ -738,6 +878,9 @@ export class Minip2pBase {
738
878
  #dropped = 0;
739
879
  #flushScheduled = false;
740
880
  #closed = false;
881
+ /** Settles once the native drain finished and close observers ran. */
882
+ #closing;
883
+ #closeReported = false;
741
884
  constructor(backend, relayAddresses) {
742
885
  this.#backend = backend;
743
886
  this.#relayAddrs = relayAddresses;
@@ -747,7 +890,7 @@ export class Minip2pBase {
747
890
  });
748
891
  }
749
892
  catch (error) {
750
- backend.close();
893
+ void backend.close(0);
751
894
  throw error;
752
895
  }
753
896
  }
@@ -871,19 +1014,38 @@ export class Minip2pBase {
871
1014
  this.#waiters.add(waiter);
872
1015
  });
873
1016
  }
874
- /** Registers a one-shot endpoint shutdown observer. */
1017
+ /**
1018
+ * Registers a one-shot endpoint shutdown observer. It stays registered
1019
+ * through the native close drain and fires once that finishes, with the
1020
+ * same report {@link close} resolves with. A no-op once it has fired.
1021
+ */
875
1022
  onClose(handler) {
876
- if (this.#closed) {
1023
+ if (this.#closeReported) {
877
1024
  return () => { };
878
1025
  }
879
1026
  return subscribe(this.#closeHandlers, handler);
880
1027
  }
881
- /** Idempotently stops the endpoint and rejects outstanding operations. */
882
- close() {
883
- this.#teardown({ reason: "close" }, new ClosedError());
1028
+ /**
1029
+ * Stops the endpoint: rejects outstanding operations and drops listeners
1030
+ * at once, then has native disconnect peers and drain for up to
1031
+ * `timeoutMs` (default 500; `0` tears down at once, best effort). Resolves
1032
+ * with the close report once the drain finished, after `onClose`
1033
+ * observers ran; it never rejects. The deadline bounds teardown time only,
1034
+ * not delivery of accepted writes: QUIC discards queued writes and TCP may
1035
+ * abort. Idempotent: a later call returns the same promise, including
1036
+ * after a driver failure closed the endpoint.
1037
+ */
1038
+ close(timeoutMs = DEFAULT_CLOSE_TIMEOUT_MS) {
1039
+ assertTimeout(timeoutMs);
1040
+ return this.#teardown(new ClosedError(), timeoutMs);
884
1041
  }
1042
+ /** Starts {@link close} with the default drain, without waiting for it. */
885
1043
  [Symbol.dispose]() {
886
- this.close();
1044
+ void this.close();
1045
+ }
1046
+ /** {@link close} with the default drain, for `await using`. */
1047
+ async [Symbol.asyncDispose]() {
1048
+ await this.close();
887
1049
  }
888
1050
  /** Returns this endpoint's base58 peer ID. */
889
1051
  peerId() {
@@ -941,16 +1103,26 @@ export class Minip2pBase {
941
1103
  this.#assertOpen();
942
1104
  return this.#backend.reachability();
943
1105
  }
944
- /** Returns the authoritative active path to `peerId`, if connected. */
1106
+ /**
1107
+ * Returns the path of `peerId`'s established connection; `undefined` only
1108
+ * while the peer is not connected.
1109
+ */
945
1110
  path(peerId) {
946
1111
  this.#assertOpen();
947
1112
  const path = this.#backend.path(peerId);
948
1113
  return path === undefined ? undefined : normalizePath(path);
949
1114
  }
950
- /** Returns the transport connection selected for `peerId`, if connected. */
1115
+ /**
1116
+ * Returns a snapshot of `peerId`'s established connection: its connection
1117
+ * ID, remote address, path, and Identify protocols once ready;
1118
+ * `undefined` while the peer is not connected.
1119
+ */
951
1120
  connectionInfo(peerId) {
952
1121
  this.#assertOpen();
953
- return this.#backend.connectionInfo(peerId);
1122
+ const info = this.#backend.connectionInfo(peerId);
1123
+ return info === undefined
1124
+ ? undefined
1125
+ : { ...info, path: normalizePath(info.path) };
954
1126
  }
955
1127
  /** Returns whether the native driver is accepting work. */
956
1128
  isRunning() {
@@ -1055,6 +1227,8 @@ export class Minip2pBase {
1055
1227
  let identity;
1056
1228
  try {
1057
1229
  identity = this.#backend.openStream(peerId, protocolId);
1230
+ // The application now knows the connection: its end must reach it.
1231
+ this.#queue.markConnectionSeen(identity.connId);
1058
1232
  }
1059
1233
  catch (error) {
1060
1234
  return Promise.reject(new OpenStreamError({
@@ -1367,10 +1541,14 @@ export class Minip2pBase {
1367
1541
  }
1368
1542
  }
1369
1543
  #dispatchNative(event) {
1544
+ // Backends resolve `close` with it instead of delivering it.
1545
+ if (event.tag === P2pEvent_Tags.EndpointClosed) {
1546
+ return;
1547
+ }
1370
1548
  if (event.tag === P2pEvent_Tags.DriverFailed) {
1371
1549
  const failure = new DriverFailedError(event.inner.kind, event.inner.detail);
1372
1550
  this.#dispatch("driverFailed", event.inner, event.inner);
1373
- this.#teardown({ error: failure, reason: "driverFailed" }, failure);
1551
+ void this.#teardown(failure, 0);
1374
1552
  return;
1375
1553
  }
1376
1554
  if (event.tag === P2pEvent_Tags.StreamReady) {
@@ -1679,49 +1857,70 @@ export class Minip2pBase {
1679
1857
  item = this.#queue.shift();
1680
1858
  }
1681
1859
  }
1682
- #teardown(reason, error) {
1683
- if (this.#closed) {
1684
- return;
1860
+ /**
1861
+ * Closes the endpoint once, rejecting what is outstanding with `cause`;
1862
+ * later calls return the first call's promise. A
1863
+ * {@link DriverFailedError} cause reports a `driverFailed` close.
1864
+ */
1865
+ #teardown(cause, timeoutMs) {
1866
+ if (this.#closing !== undefined) {
1867
+ return this.#closing;
1685
1868
  }
1686
1869
  this.#closed = true;
1687
- const closeHandlers = [...this.#closeHandlers];
1688
- this.#closeHandlers.clear();
1689
1870
  this.#clearQueue();
1690
1871
  this.#dropped = 0;
1691
1872
  this.#named.clear();
1692
1873
  this.#catchAll.clear();
1874
+ // Native is asked to close before anything below can call back in: a
1875
+ // re-entrant close returns this promise.
1876
+ let closed;
1877
+ try {
1878
+ closed = this.#backend.close(timeoutMs);
1879
+ }
1880
+ catch {
1881
+ closed = Promise.resolve({
1882
+ outcome: CloseOutcome.Failed,
1883
+ unfinished: [],
1884
+ });
1885
+ }
1886
+ const closing = closed.then(({ outcome, unfinished }) => {
1887
+ const report = cause instanceof DriverFailedError
1888
+ ? { error: cause, reason: "driverFailed", unfinished }
1889
+ : { outcome, reason: "close", unfinished };
1890
+ this.#closeReported = true;
1891
+ const closeHandlers = [...this.#closeHandlers];
1892
+ this.#closeHandlers.clear();
1893
+ for (const handler of closeHandlers) {
1894
+ try {
1895
+ handler(report);
1896
+ }
1897
+ catch {
1898
+ // Close notification is outside the now-closed event queue.
1899
+ }
1900
+ }
1901
+ return report;
1902
+ });
1903
+ this.#closing = closing;
1693
1904
  for (const waiter of [...this.#waiters]) {
1694
- this.#settleWaiter(waiter, error);
1905
+ this.#settleWaiter(waiter, cause);
1695
1906
  }
1696
1907
  for (const attempt of this.#connects.values()) {
1697
- attempt.settle?.({ error, ok: false });
1908
+ attempt.settle?.({ error: cause, ok: false });
1698
1909
  }
1699
1910
  this.#connects.clear();
1700
1911
  this.#terminalConnects.clear();
1701
1912
  for (const pending of this.#pendingOpens.takeAll()) {
1702
1913
  clearPendingOpen(pending);
1703
- pending.reject(error);
1914
+ pending.reject(cause);
1704
1915
  }
1705
1916
  for (const stream of this.#streams.takeAll()) {
1706
- stream.terminal(error);
1917
+ stream.terminal(cause);
1707
1918
  }
1708
1919
  for (const ping of this.#pings.values()) {
1709
- ping.cancel(error);
1920
+ ping.cancel(cause);
1710
1921
  }
1711
1922
  this.#pings.clear();
1712
- try {
1713
- this.#backend.close();
1714
- }
1715
- finally {
1716
- for (const handler of closeHandlers) {
1717
- try {
1718
- handler(reason);
1719
- }
1720
- catch {
1721
- // Close notification is outside the now-closed event queue.
1722
- }
1723
- }
1724
- }
1923
+ return closing;
1725
1924
  }
1726
1925
  #assertOpen() {
1727
1926
  if (this.#closed) {
@@ -1777,11 +1976,14 @@ const SDK_EVENT_NAMES = {
1777
1976
  [P2pEvent_Tags.PeerUpdated]: "peerUpdated",
1778
1977
  [P2pEvent_Tags.PeerExpired]: "peerExpired",
1779
1978
  [P2pEvent_Tags.DiscoveryDialFailed]: "discoveryDialFailed",
1979
+ [P2pEvent_Tags.MdnsFailed]: "mdnsFailed",
1980
+ [P2pEvent_Tags.MdnsRecovered]: "mdnsRecovered",
1780
1981
  [P2pEvent_Tags.DiscoveryProtocolViolation]: "discoveryProtocolViolation",
1781
1982
  };
1782
1983
  function normalizeEvent(event) {
1783
1984
  const type = SDK_EVENT_NAMES[event.tag];
1784
- let payload = event.inner;
1985
+ // A native variant without fields arrives without `inner`.
1986
+ let payload = "inner" in event ? event.inner : {};
1785
1987
  if (event.tag === P2pEvent_Tags.PathEstablished) {
1786
1988
  payload = { ...event.inner, path: normalizePath(event.inner.path) };
1787
1989
  }
@@ -1795,15 +1997,40 @@ function normalizeEvent(event) {
1795
1997
  to: normalizePath(event.inner.to),
1796
1998
  };
1797
1999
  }
2000
+ else if (event.tag === P2pEvent_Tags.ConnectionClosed) {
2001
+ payload = {
2002
+ ...event.inner,
2003
+ reason: normalizeCloseReason(event.inner.reason),
2004
+ };
2005
+ }
1798
2006
  return { payload: payload, type };
1799
2007
  }
2008
+ function normalizeCloseReason(reason) {
2009
+ switch (reason.tag) {
2010
+ case ConnectionCloseReason_Tags.Local: {
2011
+ return { kind: "local" };
2012
+ }
2013
+ case ConnectionCloseReason_Tags.Remote: {
2014
+ return { code: reason.inner.code, kind: "remote" };
2015
+ }
2016
+ case ConnectionCloseReason_Tags.TimedOut: {
2017
+ return { kind: "timedOut" };
2018
+ }
2019
+ case ConnectionCloseReason_Tags.Stalled: {
2020
+ return { kind: "stalled" };
2021
+ }
2022
+ case ConnectionCloseReason_Tags.Error: {
2023
+ return { kind: "error", message: reason.inner.message };
2024
+ }
2025
+ }
2026
+ }
1800
2027
  function normalizePath(path) {
1801
2028
  switch (path.tag) {
1802
- case PathKind_Tags.DirectDialed: {
1803
- return { kind: "directDialed" };
2029
+ case PathKind_Tags.Direct: {
2030
+ return { kind: "direct" };
1804
2031
  }
1805
- case PathKind_Tags.DirectPunched: {
1806
- return { kind: "directPunched" };
2032
+ case PathKind_Tags.Punched: {
2033
+ return { kind: "punched" };
1807
2034
  }
1808
2035
  case PathKind_Tags.Relayed: {
1809
2036
  return { kind: "relayed", relayPeerId: path.inner.relayPeerId };