@minip2p/core 0.7.3 → 0.7.5

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.
@@ -0,0 +1,87 @@
1
+ /* oxlint-disable no-await-in-loop, promise/avoid-new -- Each bounded batch intentionally yields one event-loop turn before the next synchronous native drain. */
2
+
3
+ const DEFAULT_BATCH_LIMIT = 256;
4
+
5
+ /** Runs a task on a later event-loop turn. */
6
+ type Scheduler = (task: () => void) => void;
7
+
8
+ const scheduleOnNextTurn: Scheduler = (task) => {
9
+ setTimeout(task, 0);
10
+ };
11
+
12
+ /**
13
+ * Coalesces native doorbells and drains bounded event batches off the
14
+ * callback stack, yielding one scheduler turn between batches. Errors that
15
+ * `deliver` throws synchronously are swallowed so an application callback or
16
+ * a malformed event cannot stop draining. The default scheduler is `setTimeout(task, 0)`; Node passes
17
+ * `setImmediate` to skip the timer granularity.
18
+ */
19
+ export class EventDrain<Event> {
20
+ readonly #drain: (limit: number) => Event[];
21
+ readonly #deliver: (event: Event) => void;
22
+ readonly #limit: number;
23
+ readonly #schedule: Scheduler;
24
+ #pending = false;
25
+ #running = false;
26
+ #stopped = false;
27
+
28
+ constructor(
29
+ drain: (limit: number) => Event[],
30
+ deliver: (event: Event) => void,
31
+ limit = DEFAULT_BATCH_LIMIT,
32
+ schedule: Scheduler = scheduleOnNextTurn
33
+ ) {
34
+ this.#drain = drain;
35
+ this.#deliver = deliver;
36
+ this.#limit = limit;
37
+ this.#schedule = schedule;
38
+ }
39
+
40
+ ring(): void {
41
+ if (this.#stopped) {
42
+ return;
43
+ }
44
+ this.#pending = true;
45
+ if (!this.#running) {
46
+ this.#running = true;
47
+ this.#schedule(() => {
48
+ void this.#run();
49
+ });
50
+ }
51
+ }
52
+
53
+ stop(): void {
54
+ this.#stopped = true;
55
+ this.#pending = false;
56
+ }
57
+
58
+ async #run(): Promise<void> {
59
+ try {
60
+ while (!this.#stopped && this.#pending) {
61
+ this.#pending = false;
62
+ let batch = this.#drain(this.#limit);
63
+ while (!this.#stopped && batch.length > 0) {
64
+ for (const event of batch) {
65
+ try {
66
+ this.#deliver(event);
67
+ } catch {
68
+ // Application callbacks cannot break native event delivery.
69
+ }
70
+ }
71
+ await new Promise<void>((resolve) => {
72
+ this.#schedule(resolve);
73
+ });
74
+ if (this.#stopped) {
75
+ break;
76
+ }
77
+ batch = this.#drain(this.#limit);
78
+ }
79
+ }
80
+ } finally {
81
+ this.#running = false;
82
+ if (this.#pending && !this.#stopped) {
83
+ this.ring();
84
+ }
85
+ }
86
+ }
87
+ }
package/src/index.ts CHANGED
@@ -14,6 +14,7 @@ export {
14
14
  PeerDisconnectedError,
15
15
  StreamClosedError,
16
16
  TimeoutError,
17
+ WriteBufferFullError,
17
18
  } from "./errors.js";
18
19
  export { Minip2pBase, Stream, type StreamEventMap } from "./sdk.js";
19
20
  export {
@@ -0,0 +1,66 @@
1
+ import { StreamClosedError } from "./errors.js";
2
+
3
+ /**
4
+ * Converts a native `u64` to a number, throwing when it leaves JavaScript's
5
+ * safe integer range. Native integers arrive as `bigint` (UniFFI) or as
6
+ * `number | bigint` (napi-rs, which only switches to `bigint` above
7
+ * `u32::MAX`).
8
+ */
9
+ export const u64ToNumber = (value: bigint | number, name: string): number => {
10
+ const number = Number(value);
11
+ if (!Number.isSafeInteger(number) || number < 0) {
12
+ throw new RangeError(`${name} exceeds JavaScript's safe integer range`);
13
+ }
14
+ return number;
15
+ };
16
+
17
+ /**
18
+ * Maps native `u64` connection identities to small public numbers.
19
+ *
20
+ * Native connection IDs span the full `u64` range, so they cannot round-trip
21
+ * through a JavaScript `number`. Each endpoint owns one map so a native ID
22
+ * resolves to the same public ID in events and synchronous results. Adapters
23
+ * release an entry once its `ConnectionClosed`, or the `ConnectionReplaced`
24
+ * that retires it, is normalized, which bounds the map by live connections.
25
+ * Public numbers come from a counter that never repeats, so an event arriving
26
+ * after the release gets a fresh number instead of aliasing a live connection.
27
+ */
28
+ export class ConnectionIdMap {
29
+ readonly #publicByNative = new Map<bigint, number>();
30
+ readonly #nativeByPublic = new Map<number, bigint>();
31
+ #next = 1;
32
+
33
+ toPublic(native: bigint): number {
34
+ const existing = this.#publicByNative.get(native);
35
+ if (existing !== undefined) {
36
+ return existing;
37
+ }
38
+ const publicId = this.#next;
39
+ this.#next += 1;
40
+ this.#publicByNative.set(native, publicId);
41
+ this.#nativeByPublic.set(publicId, native);
42
+ return publicId;
43
+ }
44
+
45
+ /**
46
+ * The native ID behind a public one. Stream operations pass it back so
47
+ * native rejects a stream whose connection it already replaced. A released
48
+ * connection throws `StreamClosedError`: its stream operation can run after
49
+ * the release but before the SDK dispatches the ending event.
50
+ */
51
+ toNative(publicId: number): bigint {
52
+ const native = this.#nativeByPublic.get(publicId);
53
+ if (native === undefined) {
54
+ throw new StreamClosedError("The stream's connection ended");
55
+ }
56
+ return native;
57
+ }
58
+
59
+ release(publicId: number): void {
60
+ const native = this.#nativeByPublic.get(publicId);
61
+ if (native !== undefined) {
62
+ this.#nativeByPublic.delete(publicId);
63
+ this.#publicByNative.delete(native);
64
+ }
65
+ }
66
+ }