@statewalker/webrun-streams-libp2p 0.4.0 → 0.5.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/README.md CHANGED
@@ -57,7 +57,7 @@ runs (Node or browser).
57
57
  | `duplexOverStream(stream, input, options?)` | The primitive under both: runs one call over one libp2p `Stream`. Returns an `AsyncGenerator<Uint8Array>` of the peer's bytes. |
58
58
  | `PeerGoneError` | What a call fails with when the stream ended before both sides finished it: the peer died, the connection dropped, or the stream was reset after the peer's side ended. `cause` is libp2p's close error, if any. |
59
59
  | `messageTargetOverStream(stream, options?)` | `{ target, signal }`: one stream as a pipe of `Uint8Array` messages for `multiplexPort` / `overPipe`, and an `AbortSignal` that aborts when the stream is over. `options.maxMessageBytes` caps one message. See below. |
60
- | `libp2pPortMux(options)` | Native MessagePorts: a `webrun-rpc` `PortMux` (by shape) whose every port is its own libp2p stream, for `overPorts`. `options`: `node`, `codec` (a value codec: `{ encode: serialize, decode: deserialize }` from `webrun-msgpack`), `peer` (to open ports), `onPort(port, { remotePeer, connection })` (to accept them), `protocol`, `maxMessageSize`, stream limits. See "MessagePorts over libp2p" below. |
60
+ | `libp2pPortMux(options)` | Native MessagePorts: a `webrun-rpc` `PortMux` (by shape) whose every port is its own libp2p stream, for `overPorts`. `options`: `node`, `codec` (a value codec: `{ encode: serialize, decode: deserialize }` from `webrun-msgpack`), `peer` (to open ports), `onPort(port, { remotePeer, connection })` (to accept them), `protocol`, `maxMessageSize`, stream limits. The port lifecycle (codec wrapping, messages held until a port's first listener, close signals, accept/refuse, the caller's signal, close-all) is the shared `newNativePortMux` from `@statewalker/webrun-streams`; `describePortMux` (`webrun-streams-conformance`) is its contract, run against this transport too. Messages that arrive before a port's first listener are now held for it, as over WebRTC. See "MessagePorts over libp2p" below. |
61
61
  | `DEFAULT_PORT_PROTOCOL`, `DEFAULT_PORT_MAX_MESSAGE_SIZE` | `"/webrun-ports/1.0.0"`, 256 KiB. |
62
62
  | `DEFAULT_PROTOCOL` | `"/webrun-streams/1.0.0"`. |
63
63
  | `DEFAULT_DRAIN_TIMEOUT_MS` | `300_000` (5 minutes). |
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { deserializeError, serializeError } from "@statewalker/webrun-streams";
1
+ import { deserializeError, newNativePortMux, serializeError } from "@statewalker/webrun-streams";
2
2
  //#region src/duplex-over-stream.ts
3
3
  const TYPE_DATA = 0;
4
4
  const TYPE_ERROR = 2;
@@ -895,53 +895,31 @@ async function libp2pPortMux(options) {
895
895
  const maxOutboundStreams = options.maxOutboundStreams ?? 1024;
896
896
  const protocol = options.protocol ?? "/webrun-ports/1.0.0";
897
897
  const maxMessageSize = options.maxMessageSize ?? 262144;
898
- const live = /* @__PURE__ */ new Set();
899
- let closed = false;
900
- const wrap = (stream) => {
901
- const { target: inner } = messageTargetOverStream(stream, { maxMessageBytes });
902
- const wrapped = /* @__PURE__ */ new Map();
903
- const local = new AbortController();
904
- const port = {
905
- closeSignal: AbortSignal.any([inner.closeSignal, local.signal]),
906
- get bufferedAmount() {
907
- return inner.bufferedAmount;
908
- },
909
- whenDrained: () => inner.whenDrained(),
910
- postMessage(message) {
911
- inner.postMessage(codec.encode(message));
912
- },
913
- addEventListener(_type, listener) {
914
- if (wrapped.has(listener)) return;
915
- const decoding = (event) => {
916
- let data;
917
- try {
918
- data = codec.decode(event.data);
919
- } catch (err) {
920
- stream.abort(new Error("webrun-streams-libp2p: a frame the port's codec cannot decode", { cause: err }));
921
- return;
922
- }
923
- return listener(new MessageEvent("message", { data }));
924
- };
925
- wrapped.set(listener, decoding);
926
- inner.addEventListener("message", decoding);
927
- },
928
- removeEventListener(_type, listener) {
929
- const decoding = wrapped.get(listener);
930
- if (!decoding) return;
931
- wrapped.delete(listener);
932
- inner.removeEventListener("message", decoding);
933
- },
934
- async close() {
935
- live.delete(port);
936
- if (!local.signal.aborted) local.abort(/* @__PURE__ */ new Error("webrun-streams-libp2p: port closed"));
937
- await inner.close();
938
- }
939
- };
940
- live.add(port);
941
- inner.closeSignal.addEventListener("abort", () => live.delete(port), { once: true });
942
- return port;
943
- };
898
+ /** A stream as a channel: framed bytes, and a reset to break it off (the peer hears it). */
899
+ const channelOf = (stream) => ({
900
+ pipe: messageTargetOverStream(stream, { maxMessageBytes }).target,
901
+ fail: (reason) => stream.abort(reason)
902
+ });
903
+ const dialOptions = { maxOutboundStreams };
904
+ if (runOnLimitedConnection !== void 0) dialOptions.runOnLimitedConnection = runOnLimitedConnection;
944
905
  let handled = false;
906
+ const control = newNativePortMux({
907
+ name: "webrun-streams-libp2p",
908
+ codec,
909
+ maxMessageSize,
910
+ onPort,
911
+ async open(signal) {
912
+ if (!peer) throw new Error("webrun-streams-libp2p: openPort needs `peer`");
913
+ const stream = await openGatedStream(node, peer, protocol, {
914
+ ...dialOptions,
915
+ signal
916
+ });
917
+ return channelOf(stream);
918
+ },
919
+ async stopAccepting() {
920
+ if (handled) await node.unhandle(protocol).catch(() => void 0);
921
+ }
922
+ });
945
923
  if (onPort) {
946
924
  const handleOptions = {
947
925
  maxInboundStreams,
@@ -949,58 +927,18 @@ async function libp2pPortMux(options) {
949
927
  };
950
928
  if (runOnLimitedConnection !== void 0) handleOptions.runOnLimitedConnection = runOnLimitedConnection;
951
929
  await node.handle(protocol, (stream, connection) => {
952
- if (closed) {
930
+ if (control.closed) {
953
931
  stream.abort(/* @__PURE__ */ new Error("webrun-streams-libp2p: port mux closed"));
954
932
  return;
955
933
  }
956
- const port = wrap(stream);
957
- let accepted = false;
958
- try {
959
- accepted = onPort(port, {
960
- remotePeer: connection.remotePeer,
961
- connection
962
- }) !== false;
963
- } catch {
964
- accepted = false;
965
- }
966
- if (!accepted) {
967
- live.delete(port);
968
- stream.abort(/* @__PURE__ */ new Error("webrun-streams-libp2p: port refused"));
969
- }
934
+ control.accept(channelOf(stream), {
935
+ remotePeer: connection.remotePeer,
936
+ connection
937
+ });
970
938
  }, handleOptions);
971
939
  handled = true;
972
940
  }
973
- const dialOptions = { maxOutboundStreams };
974
- if (runOnLimitedConnection !== void 0) dialOptions.runOnLimitedConnection = runOnLimitedConnection;
975
- return {
976
- maxMessageSize,
977
- async openPort(_meta, opts) {
978
- if (closed) throw new Error("webrun-streams-libp2p: port mux closed");
979
- if (!peer) throw new Error("webrun-streams-libp2p: openPort needs `peer`");
980
- const stream = await openGatedStream(node, peer, protocol, {
981
- ...dialOptions,
982
- signal: opts?.signal
983
- });
984
- if (closed) {
985
- await closeStream(stream);
986
- throw new Error("webrun-streams-libp2p: port mux closed");
987
- }
988
- const port = wrap(stream);
989
- const signal = opts?.signal;
990
- if (signal) {
991
- const onAbort = () => void port.close();
992
- signal.addEventListener("abort", onAbort, { once: true });
993
- port.closeSignal.addEventListener("abort", () => signal.removeEventListener("abort", onAbort), { once: true });
994
- }
995
- return port;
996
- },
997
- async close() {
998
- if (closed) return;
999
- closed = true;
1000
- if (handled) await node.unhandle(protocol).catch(() => void 0);
1001
- await Promise.allSettled([...live].map((p) => p.close()));
1002
- }
1003
- };
941
+ return control.mux;
1004
942
  }
1005
943
  //#endregion
1006
944
  export { DEFAULT_CLOSE_TIMEOUT_MS, DEFAULT_DRAIN_TIMEOUT_MS, DEFAULT_MAX_FRAME_BYTES, DEFAULT_MAX_MESSAGE_BYTES, DEFAULT_PORT_MAX_MESSAGE_SIZE, DEFAULT_PORT_PROTOCOL, DEFAULT_PORT_STREAM_LIMIT, DEFAULT_PROTOCOL, PeerGoneError, connect, duplexOverStream, libp2pPortMux, messageTargetOverStream, serve, serveConnections };
@@ -1,6 +1,7 @@
1
1
  import type { Connection, Libp2p, PeerId } from "@libp2p/interface";
2
2
  import type { Multiaddr } from "@multiformats/multiaddr";
3
- import { type StreamMessageTarget } from "./message-target-over-stream.js";
3
+ import { type NativePort, type ValueCodec } from "@statewalker/webrun-streams";
4
+ export type { ValueCodec };
4
5
  /** The protocol a port's stream negotiates unless told otherwise. */
5
6
  export declare const DEFAULT_PORT_PROTOCOL = "/webrun-ports/1.0.0";
6
7
  /**
@@ -9,26 +10,16 @@ export declare const DEFAULT_PORT_PROTOCOL = "/webrun-ports/1.0.0";
9
10
  * under `messageTargetOverStream`'s 64 MiB frame ceiling.
10
11
  */
11
12
  export declare const DEFAULT_PORT_MAX_MESSAGE_SIZE: number;
12
- /**
13
- * How a port's messages become bytes on its stream and back: any value the stream tier posts
14
- * (objects holding `Uint8Array` chunks, serialised errors). `webrun-msgpack`'s `serialize` and
15
- * `deserialize` fit: `{ encode: serialize, decode: deserialize }`.
16
- */
17
- export interface ValueCodec {
18
- encode(value: unknown): Uint8Array;
19
- decode(bytes: Uint8Array): unknown;
20
- }
21
- type Listener = (event: MessageEvent) => void | Promise<void>;
22
13
  /**
23
14
  * The stream limits a port mux asks libp2p for unless told otherwise: every concurrent call is a
24
15
  * stream, and libp2p's own default (32 per protocol) would reset the 33rd.
25
16
  */
26
17
  export declare const DEFAULT_PORT_STREAM_LIMIT = 1024;
27
- /** One port: a libp2p stream as a `MessageTarget` of values, with its close signal on it. */
28
- export type StreamPort = Omit<StreamMessageTarget["target"], "addEventListener" | "removeEventListener"> & {
29
- addEventListener(type: "message", listener: Listener): void;
30
- removeEventListener(type: "message", listener: Listener): void;
31
- };
18
+ /**
19
+ * One port: a libp2p stream as a `MessageTarget` of values, with its close signal on it. Built by
20
+ * the shared native port lifecycle (`newNativePortMux` in `@statewalker/webrun-streams`).
21
+ */
22
+ export type StreamPort = NativePort;
32
23
  /** What the serving side learns about a port the peer opened. */
33
24
  export interface InboundPortInfo {
34
25
  /** The peer libp2p's Noise handshake proved for the connection the stream came on. */
@@ -85,5 +76,4 @@ export interface Libp2pPortMux {
85
76
  * `connect()`. `meta` is not sent: the protocol says what a port is for.
86
77
  */
87
78
  export declare function libp2pPortMux(options: Libp2pPortMuxOptions): Promise<Libp2pPortMux>;
88
- export {};
89
79
  //# sourceMappingURL=port-mux.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"port-mux.d.ts","sourceRoot":"","sources":["../src/port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O,EAAE,oBAAoB,GAAG,OAAO,CAAC,aAAa,CAAC,CAqDzF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@statewalker/webrun-streams-libp2p",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "libp2p native multi-stream Connect/Serve adapter in the webrun-streams-* family",
@@ -30,7 +30,7 @@
30
30
  "src"
31
31
  ],
32
32
  "dependencies": {
33
- "@statewalker/webrun-streams": "^0.4.0"
33
+ "@statewalker/webrun-streams": "^0.5.0"
34
34
  },
35
35
  "peerDependencies": {
36
36
  "@libp2p/interface": "^3.0.0",
@@ -57,9 +57,9 @@
57
57
  "tsx": "^4.23.15",
58
58
  "typescript": "^7.0.2",
59
59
  "vitest": "^5.0.5",
60
- "@statewalker/webrun-msgpack": "^0.11.0",
61
- "@statewalker/webrun-rpc": "^0.12.0",
62
- "@statewalker/webrun-streams-conformance": "^0.5.0"
60
+ "@statewalker/webrun-rpc": "^0.13.0",
61
+ "@statewalker/webrun-msgpack": "^0.12.0",
62
+ "@statewalker/webrun-streams-conformance": "^0.6.0"
63
63
  },
64
64
  "sideEffects": false,
65
65
  "publishConfig": {
package/src/port-mux.ts CHANGED
@@ -7,10 +7,17 @@ import type {
7
7
  StreamHandlerOptions,
8
8
  } from "@libp2p/interface";
9
9
  import type { Multiaddr } from "@multiformats/multiaddr";
10
- import { closeStream } from "./duplex-over-stream.js";
11
- import { messageTargetOverStream, type StreamMessageTarget } from "./message-target-over-stream.js";
10
+ import {
11
+ type NativeChannel,
12
+ type NativePort,
13
+ newNativePortMux,
14
+ type ValueCodec,
15
+ } from "@statewalker/webrun-streams";
16
+ import { messageTargetOverStream } from "./message-target-over-stream.js";
12
17
  import { openGatedStream } from "./stream-gate.js";
13
18
 
19
+ export type { ValueCodec };
20
+
14
21
  /** The protocol a port's stream negotiates unless told otherwise. */
15
22
  export const DEFAULT_PORT_PROTOCOL = "/webrun-ports/1.0.0";
16
23
 
@@ -21,32 +28,17 @@ export const DEFAULT_PORT_PROTOCOL = "/webrun-ports/1.0.0";
21
28
  */
22
29
  export const DEFAULT_PORT_MAX_MESSAGE_SIZE = 256 * 1024;
23
30
 
24
- /**
25
- * How a port's messages become bytes on its stream and back: any value the stream tier posts
26
- * (objects holding `Uint8Array` chunks, serialised errors). `webrun-msgpack`'s `serialize` and
27
- * `deserialize` fit: `{ encode: serialize, decode: deserialize }`.
28
- */
29
- export interface ValueCodec {
30
- encode(value: unknown): Uint8Array;
31
- decode(bytes: Uint8Array): unknown;
32
- }
33
-
34
- type Listener = (event: MessageEvent) => void | Promise<void>;
35
-
36
31
  /**
37
32
  * The stream limits a port mux asks libp2p for unless told otherwise: every concurrent call is a
38
33
  * stream, and libp2p's own default (32 per protocol) would reset the 33rd.
39
34
  */
40
35
  export const DEFAULT_PORT_STREAM_LIMIT = 1024;
41
36
 
42
- /** One port: a libp2p stream as a `MessageTarget` of values, with its close signal on it. */
43
- export type StreamPort = Omit<
44
- StreamMessageTarget["target"],
45
- "addEventListener" | "removeEventListener"
46
- > & {
47
- addEventListener(type: "message", listener: Listener): void;
48
- removeEventListener(type: "message", listener: Listener): void;
49
- };
37
+ /**
38
+ * One port: a libp2p stream as a `MessageTarget` of values, with its close signal on it. Built by
39
+ * the shared native port lifecycle (`newNativePortMux` in `@statewalker/webrun-streams`).
40
+ */
41
+ export type StreamPort = NativePort;
50
42
 
51
43
  /** What the serving side learns about a port the peer opened. */
52
44
  export interface InboundPortInfo {
@@ -110,63 +102,33 @@ export async function libp2pPortMux(options: Libp2pPortMuxOptions): Promise<Libp
110
102
  const maxOutboundStreams = options.maxOutboundStreams ?? DEFAULT_PORT_STREAM_LIMIT;
111
103
  const protocol = options.protocol ?? DEFAULT_PORT_PROTOCOL;
112
104
  const maxMessageSize = options.maxMessageSize ?? DEFAULT_PORT_MAX_MESSAGE_SIZE;
113
- const live = new Set<StreamPort>();
114
- let closed = false;
115
105
 
116
- const wrap = (stream: Stream): StreamPort => {
117
- const { target: inner } = messageTargetOverStream(stream, { maxMessageBytes });
118
- const wrapped = new Map<Listener, Listener>();
119
- // closed here, or the stream ended: a port closed locally is closed at once, not when libp2p
120
- // finishes closing its stream
121
- const local = new AbortController();
122
- const port: StreamPort = {
123
- closeSignal: AbortSignal.any([inner.closeSignal, local.signal]),
124
- get bufferedAmount() {
125
- return inner.bufferedAmount;
126
- },
127
- whenDrained: () => inner.whenDrained(),
128
- postMessage(message: unknown) {
129
- inner.postMessage(codec.encode(message));
130
- },
131
- addEventListener(_type, listener) {
132
- if (wrapped.has(listener)) return;
133
- const decoding: Listener = (event) => {
134
- let data: unknown;
135
- try {
136
- data = codec.decode(event.data as Uint8Array);
137
- } catch (err) {
138
- // a peer speaking another codec, or a corrupt frame: fail the port, as a malformed
139
- // frame fails the stream, rather than drop the message and leave its call waiting
140
- stream.abort(
141
- new Error("webrun-streams-libp2p: a frame the port's codec cannot decode", {
142
- cause: err,
143
- }),
144
- );
145
- return;
146
- }
147
- return listener(new MessageEvent("message", { data }));
148
- };
149
- wrapped.set(listener, decoding);
150
- inner.addEventListener("message", decoding);
151
- },
152
- removeEventListener(_type, listener) {
153
- const decoding = wrapped.get(listener);
154
- if (!decoding) return;
155
- wrapped.delete(listener);
156
- inner.removeEventListener("message", decoding);
157
- },
158
- async close() {
159
- live.delete(port);
160
- if (!local.signal.aborted) local.abort(new Error("webrun-streams-libp2p: port closed"));
161
- await inner.close();
162
- },
163
- };
164
- live.add(port);
165
- inner.closeSignal.addEventListener("abort", () => live.delete(port), { once: true });
166
- return port;
167
- };
106
+ /** A stream as a channel: framed bytes, and a reset to break it off (the peer hears it). */
107
+ const channelOf = (stream: Stream): NativeChannel => ({
108
+ pipe: messageTargetOverStream(stream, { maxMessageBytes }).target,
109
+ fail: (reason) => stream.abort(reason),
110
+ });
111
+
112
+ const dialOptions: DialProtocolOptions = { maxOutboundStreams };
113
+ if (runOnLimitedConnection !== undefined)
114
+ dialOptions.runOnLimitedConnection = runOnLimitedConnection;
168
115
 
169
116
  let handled = false;
117
+ const control = newNativePortMux<InboundPortInfo>({
118
+ name: "webrun-streams-libp2p",
119
+ codec,
120
+ maxMessageSize,
121
+ onPort,
122
+ async open(signal) {
123
+ if (!peer) throw new Error("webrun-streams-libp2p: openPort needs `peer`");
124
+ const stream = await openGatedStream(node, peer, protocol, { ...dialOptions, signal });
125
+ return channelOf(stream);
126
+ },
127
+ async stopAccepting() {
128
+ if (handled) await node.unhandle(protocol).catch(() => undefined);
129
+ },
130
+ });
131
+
170
132
  if (onPort) {
171
133
  const handleOptions: StreamHandlerOptions = { maxInboundStreams, maxOutboundStreams };
172
134
  if (runOnLimitedConnection !== undefined)
@@ -174,65 +136,17 @@ export async function libp2pPortMux(options: Libp2pPortMuxOptions): Promise<Libp
174
136
  await node.handle(
175
137
  protocol,
176
138
  (stream: Stream, connection: Connection) => {
177
- if (closed) {
139
+ if (control.closed) {
178
140
  stream.abort(new Error("webrun-streams-libp2p: port mux closed"));
179
141
  return;
180
142
  }
181
- // The port is wrapped and handed over in this tick: `messageTargetOverStream` starts
182
- // reading at once, and a message with no listener yet would be dropped.
183
- const port = wrap(stream);
184
- let accepted = false;
185
- try {
186
- accepted = onPort(port, { remotePeer: connection.remotePeer, connection }) !== false;
187
- } catch {
188
- accepted = false;
189
- }
190
- if (!accepted) {
191
- live.delete(port);
192
- stream.abort(new Error("webrun-streams-libp2p: port refused"));
193
- }
143
+ // The port is built in this tick: `messageTargetOverStream` starts reading at once.
144
+ control.accept(channelOf(stream), { remotePeer: connection.remotePeer, connection });
194
145
  },
195
146
  handleOptions,
196
147
  );
197
148
  handled = true;
198
149
  }
199
150
 
200
- const dialOptions: DialProtocolOptions = { maxOutboundStreams };
201
- if (runOnLimitedConnection !== undefined)
202
- dialOptions.runOnLimitedConnection = runOnLimitedConnection;
203
-
204
- return {
205
- maxMessageSize,
206
- async openPort(_meta, opts) {
207
- if (closed) throw new Error("webrun-streams-libp2p: port mux closed");
208
- if (!peer) throw new Error("webrun-streams-libp2p: openPort needs `peer`");
209
- const stream = await openGatedStream(node, peer, protocol, {
210
- ...dialOptions,
211
- signal: opts?.signal,
212
- });
213
- if (closed) {
214
- await closeStream(stream);
215
- throw new Error("webrun-streams-libp2p: port mux closed");
216
- }
217
- const port = wrap(stream);
218
- const signal = opts?.signal;
219
- if (signal) {
220
- const onAbort = () => void port.close();
221
- signal.addEventListener("abort", onAbort, { once: true });
222
- // the caller's signal may outlive many ports: let go of this one when it closes
223
- port.closeSignal.addEventListener(
224
- "abort",
225
- () => signal.removeEventListener("abort", onAbort),
226
- { once: true },
227
- );
228
- }
229
- return port;
230
- },
231
- async close() {
232
- if (closed) return;
233
- closed = true;
234
- if (handled) await node.unhandle(protocol).catch(() => undefined);
235
- await Promise.allSettled([...live].map((p) => p.close()));
236
- },
237
- };
151
+ return control.mux as Libp2pPortMux;
238
152
  }