@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/src/backend.ts CHANGED
@@ -1,8 +1,10 @@
1
1
  import {
2
2
  BackpressureError,
3
+ InvalidConfigError,
3
4
  MessageTooLargeError,
4
5
  NotPermittedError,
5
6
  } from "./errors.js";
7
+ import { CloseOutcome, ConfigCapability } from "./types.js";
6
8
  import type {
7
9
  Bytes,
8
10
  ConnectionInfo,
@@ -15,6 +17,89 @@ import type {
15
17
  RelayReservationInfo,
16
18
  } from "./types.js";
17
19
 
20
+ /** How the native endpoint's close drain ended (`EndpointClosed`). */
21
+ export interface BackendClosed {
22
+ readonly outcome: CloseOutcome;
23
+ /** Peers whose connections were still tracked, each once. */
24
+ readonly unfinished: readonly string[];
25
+ }
26
+
27
+ /**
28
+ * The peers `EndpointClosed`'s unfinished connections name, each once. An
29
+ * inbound handshake that had not identified its peer names none.
30
+ */
31
+ export const unfinishedPeers = (
32
+ unfinished: readonly { readonly peerId?: string | undefined }[]
33
+ ): string[] => [
34
+ ...new Set(
35
+ unfinished.flatMap(({ peerId }) => (peerId === undefined ? [] : [peerId]))
36
+ ),
37
+ ];
38
+
39
+ /**
40
+ * A native adapter's side of {@link Minip2pBackend.close}: stops native once,
41
+ * then resolves with the native `EndpointClosed` the adapter hands to
42
+ * {@link settle}, or at once when no driver started.
43
+ */
44
+ export class NativeCloseLatch {
45
+ readonly #closed: Promise<BackendClosed>;
46
+ #resolve: ((closed: BackendClosed) => void) | undefined;
47
+ #closing: Promise<BackendClosed> | undefined;
48
+
49
+ constructor() {
50
+ // oxlint-disable-next-line promise/avoid-new -- Settled by a native event, not a callback API.
51
+ this.#closed = new Promise((resolve) => {
52
+ this.#resolve = resolve;
53
+ });
54
+ }
55
+
56
+ /** Whether `close` was called; later native events can be ignored. */
57
+ get requested(): boolean {
58
+ return this.#closing !== undefined;
59
+ }
60
+
61
+ /** Records the native `EndpointClosed`, which may precede `close`. */
62
+ settle(closed: BackendClosed): void {
63
+ this.#resolve?.(closed);
64
+ }
65
+
66
+ /**
67
+ * Runs `stop` on the first call, then resolves once native closed and
68
+ * `release`, if any, ran. Later calls return the same promise.
69
+ */
70
+ close(
71
+ started: boolean,
72
+ stop: () => void,
73
+ release?: () => void
74
+ ): Promise<BackendClosed> {
75
+ this.#closing ??= this.#finish(started, stop, release);
76
+ return this.#closing;
77
+ }
78
+
79
+ async #finish(
80
+ started: boolean,
81
+ stop: () => void,
82
+ release: (() => void) | undefined
83
+ ): Promise<BackendClosed> {
84
+ stop();
85
+ // Without a driver, native released the endpoint at once.
86
+ const closed = started
87
+ ? await this.#closed
88
+ : { outcome: CloseOutcome.Drained, unfinished: [] };
89
+ try {
90
+ release?.();
91
+ } catch {
92
+ // The endpoint is closed either way; the report still stands.
93
+ }
94
+ return closed;
95
+ }
96
+ }
97
+
98
+ /** A native connection snapshot: {@link ConnectionInfo} with the raw path. */
99
+ export interface BackendConnectionInfo extends Omit<ConnectionInfo, "path"> {
100
+ readonly path: PathKind;
101
+ }
102
+
18
103
  /** Full native identity allocated for an outbound stream. */
19
104
  export interface BackendOpenStream {
20
105
  /** Endpoint-local connection carrying the stream. */
@@ -40,10 +125,19 @@ export type BackendConnectTarget =
40
125
  export interface Minip2pBackend {
41
126
  /** Starts native event delivery exactly once. */
42
127
  start: (listener: (event: P2pEvent) => void) => void;
43
- /** Releases adapter state retained until an event has been dispatched. */
128
+ /**
129
+ * Releases adapter state retained until an event has been dispatched,
130
+ * elided, dropped, or coalesced into an earlier one.
131
+ */
44
132
  eventHandled?: (event: P2pEvent) => void;
45
- /** Idempotently releases the native endpoint. */
46
- close: () => void;
133
+ /**
134
+ * Requests native shutdown, draining for up to `timeoutMs` (`0` tears down
135
+ * at once), and resolves with the native `EndpointClosed`, the driver's
136
+ * last event, once the native endpoint is released. Idempotent: later
137
+ * calls return the same promise and their timeout is ignored. Resolves at
138
+ * once for a backend whose `start` failed. Never rejects.
139
+ */
140
+ close: (timeoutMs: number) => Promise<BackendClosed>;
47
141
  /** Returns the local peer ID. */
48
142
  peerId: () => string;
49
143
  /** Returns bound peer multiaddresses. */
@@ -60,10 +154,10 @@ export interface Minip2pBackend {
60
154
  discoveryNowMs: () => number | undefined;
61
155
  /** Returns the active relay reservation. */
62
156
  activeReservation: () => RelayReservationInfo | undefined;
63
- /** Returns the authoritative native path to a peer. */
157
+ /** Returns the path of a peer's established connection. */
64
158
  path: (peerId: string) => PathKind | undefined;
65
- /** Returns the transport connection selected for a peer. */
66
- connectionInfo: (peerId: string) => ConnectionInfo | undefined;
159
+ /** Returns a snapshot of a peer's established connection. */
160
+ connectionInfo: (peerId: string) => BackendConnectionInfo | undefined;
67
161
  /** Builds a circuit address through a relay. */
68
162
  circuitAddress: (relayAddress: string, peerId: string) => string;
69
163
  /** Returns the native reachability state. */
@@ -101,8 +195,10 @@ export interface Minip2pBackend {
101
195
  *
102
196
  * Called once, when the stream becomes ready; the returned function keeps
103
197
  * naming that stream after its terminal event retires the public IDs. It
104
- * throws on an over-acknowledgement and is a no-op once the stream or its
105
- * connection is gone.
198
+ * throws on an over-acknowledgement and is a no-op once the stream is
199
+ * settled. Unacknowledged bytes hold their ended connection's native slot,
200
+ * so this, and `abandonStream`, must still reach native for a stream whose
201
+ * connection ended while its events were in flight (see `SettleHandles`).
106
202
  */
107
203
  streamConsumer: (connId: number, streamId: number) => (bytes: number) => void;
108
204
  /** Half-closes the local stream write side, after any pending write. */
@@ -122,23 +218,43 @@ export interface Minip2pBackend {
122
218
  export { resolveEndpointConfig, type BackendEndpointConfig } from "./config.js";
123
219
  export { EventDrain } from "./event-drain.js";
124
220
  export { ConnectionIdMap, u64ToNumber } from "./native-ids.js";
221
+ export { SettleHandles, eventStream } from "./settle-handles.js";
125
222
  export {
223
+ ConnectionCloseReason_Tags,
126
224
  P2pEvent_Tags,
127
225
  PathKind_Tags,
128
226
  type P2pEvent,
129
227
  type P2pEventByTag,
130
228
  type PathKind,
229
+ type RawConnectionCloseReason,
131
230
  } from "./types.js";
132
231
 
133
232
  /**
134
- * Returns the typed SDK error for a native `FfiError` variant name, or
135
- * `undefined` for variants that adapters rethrow unchanged. `detail` is the
136
- * variant's detail field, when it has one.
233
+ * The parts of a native `FfiError` an adapter reads off its toolchain's error
234
+ * value: the variant name, its detail field, and an `InvalidConfig`'s
235
+ * capability as its Rust variant name.
236
+ */
237
+ export interface NativeErrorFields {
238
+ readonly tag?: string | undefined;
239
+ readonly detail?: string | undefined;
240
+ readonly capability?: string | undefined;
241
+ }
242
+
243
+ // Each capability's name is its value, so an own key is a capability.
244
+ const isConfigCapability = (name: string): name is ConfigCapability =>
245
+ Object.hasOwn(ConfigCapability, name);
246
+
247
+ /**
248
+ * Returns the typed SDK error for a native `FfiError`, or `undefined` for
249
+ * variants that adapters rethrow unchanged. An `InvalidConfig` whose
250
+ * capability is missing or unknown (native and SDK versions out of step)
251
+ * is rethrown unchanged too, rather than given a capability it did not name.
137
252
  */
138
- export const typedFfiError = (
139
- tag: string | undefined,
140
- detail: string | undefined
141
- ): Error | undefined => {
253
+ export const typedFfiError = ({
254
+ capability,
255
+ detail,
256
+ tag,
257
+ }: NativeErrorFields): Error | undefined => {
142
258
  switch (tag) {
143
259
  case "Backpressure": {
144
260
  return new BackpressureError();
@@ -149,6 +265,11 @@ export const typedFfiError = (
149
265
  case "NotPermitted": {
150
266
  return new NotPermittedError(detail);
151
267
  }
268
+ case "InvalidConfig": {
269
+ return capability !== undefined && isConfigCapability(capability)
270
+ ? new InvalidConfigError(capability, detail ?? "")
271
+ : undefined;
272
+ }
152
273
  default: {
153
274
  return undefined;
154
275
  }
package/src/errors.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  /* oxlint-disable max-classes-per-file -- Public error types are intentionally colocated. */
2
2
 
3
3
  import type {
4
+ ConfigCapability,
4
5
  DriverFailureKind,
5
6
  EndpointErrorKind,
6
7
  NatErrorKind,
@@ -30,6 +31,25 @@ export class NotPermittedError extends Error {
30
31
  }
31
32
  }
32
33
 
34
+ /**
35
+ * The endpoint configuration was invalid. `capability` names the part of the
36
+ * configuration to change; a socket the platform refused is a transport
37
+ * failure instead, and a malformed listen address an invalid-address one.
38
+ */
39
+ export class InvalidConfigError extends Error {
40
+ /** The part of the configuration that was invalid. */
41
+ readonly capability: ConfigCapability;
42
+ /** Human-readable native diagnostic. */
43
+ readonly detail: string;
44
+
45
+ constructor(capability: ConfigCapability, detail: string) {
46
+ super(detail.length > 0 ? detail : `Invalid ${capability} configuration`);
47
+ this.name = "InvalidConfigError";
48
+ this.capability = capability;
49
+ this.detail = detail;
50
+ }
51
+ }
52
+
33
53
  /** Platform-neutral operation cancellation error. */
34
54
  export class AbortError extends Error {
35
55
  constructor(message = "The operation was aborted") {
package/src/index.ts CHANGED
@@ -8,6 +8,7 @@ export {
8
8
  ConnectResultUnavailableError,
9
9
  DriverFailedError,
10
10
  EventQueueOverflowError,
11
+ InvalidConfigError,
11
12
  MessageTooLargeError,
12
13
  NotPermittedError,
13
14
  OpenStreamError,
@@ -18,17 +19,22 @@ export {
18
19
  } from "./errors.js";
19
20
  export { Minip2pBase, Stream, type StreamEventMap } from "./sdk.js";
20
21
  export {
22
+ CloseOutcome,
23
+ ConfigCapability,
21
24
  DiscoverySource,
22
25
  DriverFailureKind,
23
26
  EndpointErrorKind,
27
+ MdnsFailureKind,
24
28
  NatErrorKind,
25
29
  Reachability,
26
30
  type Bytes,
27
- type CloseReason,
31
+ type ConnectionCloseReason,
28
32
  type ConnectionInfo,
29
33
  type ConnectOptions,
30
34
  type ConnectResult,
31
35
  type ConnectTarget,
36
+ type EndpointCloseReason,
37
+ type EndpointCloseReport,
32
38
  type EventsOptions,
33
39
  type IdentifyInfo,
34
40
  type InboundStreamMeta,