@statewalker/webrun-streams-libp2p 0.5.0 → 0.7.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/index.js CHANGED
@@ -1,3 +1,5 @@
1
+ import { deserialize, serialize } from "@statewalker/webrun-msgpack";
2
+ import { connect as connect$1, overPorts, serve as serve$1 } from "@statewalker/webrun-rpc";
1
3
  import { deserializeError, newNativePortMux, serializeError } from "@statewalker/webrun-streams";
2
4
  //#region src/duplex-over-stream.ts
3
5
  const TYPE_DATA = 0;
@@ -17,6 +19,9 @@ const TYPE_ERROR = 2;
17
19
  * the transfer would complete anyway; a peer slower than that is
18
20
  * indistinguishable from one that has stopped reading altogether. Override via
19
21
  * `drainTimeoutMs` when a deployment knows better.
22
+ *
23
+ * @deprecated The deprecated protocol's (statewalker/webrun-wire#153): kept for
24
+ * one release, as the shim `connect`/`serve` run for older peers, then removed.
20
25
  */
21
26
  const DEFAULT_DRAIN_TIMEOUT_MS = 3e5;
22
27
  /**
@@ -46,6 +51,9 @@ const DEFAULT_DRAIN_TIMEOUT_MS = 3e5;
46
51
  * of sixty.
47
52
  *
48
53
  * Exported so a deployment that knows its links can lower it deliberately.
54
+ *
55
+ * @deprecated The deprecated protocol's (statewalker/webrun-wire#153): kept for
56
+ * one release, as the shim `connect`/`serve` run for older peers, then removed.
49
57
  */
50
58
  const DEFAULT_CLOSE_TIMEOUT_MS = DEFAULT_DRAIN_TIMEOUT_MS;
51
59
  /**
@@ -85,6 +93,9 @@ const textDecoder = new TextDecoder();
85
93
  * JSON-serialised `Error`). Normal end-of-input is signalled by libp2p's
86
94
  * `close()`. The frame layer exists so we can preserve `Error` fidelity
87
95
  * across the wire (yamux's native stream reset only carries "stream reset").
96
+ *
97
+ * @deprecated The deprecated protocol's (statewalker/webrun-wire#153): kept for
98
+ * one release, as the shim `connect`/`serve` run for older peers, then removed.
88
99
  */
89
100
  async function* duplexOverStream(stream, input, opts = {}) {
90
101
  let peerEndedCalled = false;
@@ -476,6 +487,15 @@ function decodeVarint(buf, start) {
476
487
  throw new Error("decodeVarint: truncated");
477
488
  }
478
489
  //#endregion
490
+ //#region src/shared.ts
491
+ /**
492
+ * The protocol id `connect`/`serve` are configured with unless told otherwise.
493
+ * Their calls negotiate `portProtocolOf(protocol)` (with `/window`); the id
494
+ * itself is the deprecated protocol, still served and dialled as a fallback
495
+ * for one release (statewalker/webrun-wire#153).
496
+ */
497
+ const DEFAULT_PROTOCOL = "/webrun-streams/1.0.0";
498
+ //#endregion
479
499
  //#region src/stream-gate.ts
480
500
  const streamGates = /* @__PURE__ */ new WeakMap();
481
501
  function streamGateFor(node, peer) {
@@ -515,10 +535,11 @@ function connectionOf(node, stream) {
515
535
  * the same peer from the same node, since they share its connection.
516
536
  */
517
537
  async function openGatedStream(node, peer, proto, dialOptions) {
538
+ const protocols = Array.isArray(proto) ? proto : [proto];
518
539
  const gate = streamGateFor(node, peer);
519
540
  while (!isProven(gate)) {
520
541
  if (gate.firstOpening == null) {
521
- const opening = node.dialProtocol(peer, [proto], dialOptions);
542
+ const opening = node.dialProtocol(peer, protocols, dialOptions);
522
543
  gate.firstOpening = opening;
523
544
  try {
524
545
  const stream = await opening;
@@ -530,11 +551,10 @@ async function openGatedStream(node, peer, proto, dialOptions) {
530
551
  }
531
552
  await gate.firstOpening.catch(() => void 0);
532
553
  }
533
- return node.dialProtocol(peer, [proto], dialOptions);
554
+ return node.dialProtocol(peer, protocols, dialOptions);
534
555
  }
535
556
  //#endregion
536
- //#region src/connect-serve.ts
537
- const DEFAULT_PROTOCOL = "/webrun-streams/1.0.0";
557
+ //#region src/legacy-connect-serve.ts
538
558
  /**
539
559
  * Builds the options object passed to `node.dialProtocol`/`node.handle`,
540
560
  * omitting any field the caller didn't supply rather than setting it to
@@ -556,8 +576,10 @@ function definedOptions(fields) {
556
576
  /**
557
577
  * Caller-side: each `call(input)` opens a new libp2p `Stream` via
558
578
  * `node.dialProtocol(peer, [protocol])` and runs the call over it.
579
+ *
580
+ * @deprecated See the module comment.
559
581
  */
560
- const connect = async ({ node, peer, protocol, drainTimeoutMs, readHighWaterBytes, maxFrameBytes, maxOutboundStreams, runOnLimitedConnection }) => {
582
+ const legacyConnect = async ({ node, peer, protocol, drainTimeoutMs, readHighWaterBytes, maxFrameBytes, maxOutboundStreams, runOnLimitedConnection }) => {
561
583
  const proto = protocol ?? "/webrun-streams/1.0.0";
562
584
  const dialOptions = definedOptions({
563
585
  maxOutboundStreams,
@@ -605,16 +627,12 @@ const connect = async ({ node, peer, protocol, drainTimeoutMs, readHighWaterByte
605
627
  };
606
628
  };
607
629
  /**
608
- * Server-side: registers `node.handle(protocol, ...)`. Each inbound stream is
609
- * wrapped as a `Duplex` and handed to `handler`. Identity-unaware; use
610
- * `serveConnections` when the handler needs to know who is calling.
611
- */
612
- const serve = async (params, handler) => serveConnections(params, () => handler);
613
- /**
614
- * Like `serve`, but the handler is built per inbound stream and is told which
615
- * peer libp2p proved on that connection.
630
+ * Server-side: registers `node.handle(protocol, ...)`. The handler is built per
631
+ * inbound stream and is told which peer libp2p proved on that connection.
632
+ *
633
+ * @deprecated See the module comment.
616
634
  */
617
- async function serveConnections({ node, protocol, drainTimeoutMs, readHighWaterBytes, maxFrameBytes, maxInboundStreams, maxOutboundStreams, runOnLimitedConnection }, makeHandler) {
635
+ async function legacyServeConnections({ node, protocol, drainTimeoutMs, readHighWaterBytes, maxFrameBytes, maxInboundStreams, maxOutboundStreams, runOnLimitedConnection }, makeHandler) {
618
636
  const proto = protocol ?? "/webrun-streams/1.0.0";
619
637
  const handleOptions = definedOptions({
620
638
  maxInboundStreams,
@@ -861,6 +879,14 @@ function toBytes(message) {
861
879
  /** The protocol a port's stream negotiates unless told otherwise. */
862
880
  const DEFAULT_PORT_PROTOCOL = "/webrun-ports/1.0.0";
863
881
  /**
882
+ * The protocol a windowed port's stream negotiates, for a mux whose ports
883
+ * negotiate `protocol`: `protocol` with `/window` appended. A mux with
884
+ * `window` dials it first and falls back to `protocol`, and serves both.
885
+ */
886
+ function windowProtocolOf(protocol) {
887
+ return `${protocol}/window`;
888
+ }
889
+ /**
864
890
  * 256 KiB: what one message on a port may carry before `webrun-rpc`'s stream tier chunks a body.
865
891
  * A port waits for each chunk's confirmation, so a larger chunk means fewer round trips; well
866
892
  * under `messageTargetOverStream`'s 64 MiB frame ceiling.
@@ -890,17 +916,32 @@ const DEFAULT_PORT_STREAM_LIMIT = 1024;
890
916
  * `connect()`. `meta` is not sent: the protocol says what a port is for.
891
917
  */
892
918
  async function libp2pPortMux(options) {
919
+ return openLibp2pPortMux(options, DEFAULT_PORT_STREAM_LIMIT);
920
+ }
921
+ /**
922
+ * {@link libp2pPortMux}, with `streamLimit` as the default of both stream
923
+ * limits; `undefined` leaves libp2p's own defaults (what `connect`/`serve`
924
+ * have always passed through). Internal.
925
+ */
926
+ async function openLibp2pPortMux(options, streamLimit) {
893
927
  const { node, peer, codec, onPort, maxMessageBytes, runOnLimitedConnection } = options;
894
- const maxInboundStreams = options.maxInboundStreams ?? 1024;
895
- const maxOutboundStreams = options.maxOutboundStreams ?? 1024;
928
+ const maxInboundStreams = options.maxInboundStreams ?? streamLimit;
929
+ const maxOutboundStreams = options.maxOutboundStreams ?? streamLimit;
896
930
  const protocol = options.protocol ?? "/webrun-ports/1.0.0";
897
931
  const maxMessageSize = options.maxMessageSize ?? 262144;
898
- /** A stream as a channel: framed bytes, and a reset to break it off (the peer hears it). */
932
+ const { window } = options;
933
+ const windowProtocol = windowProtocolOf(protocol);
934
+ /**
935
+ * A stream as a channel: framed bytes, and a reset to break it off (the peer hears it). The
936
+ * protocol it negotiated says whether both ends run the window.
937
+ */
899
938
  const channelOf = (stream) => ({
900
939
  pipe: messageTargetOverStream(stream, { maxMessageBytes }).target,
901
- fail: (reason) => stream.abort(reason)
940
+ fail: (reason) => stream.abort(reason),
941
+ ...window !== void 0 && stream.protocol === windowProtocol ? { window: "agreed" } : {}
902
942
  });
903
- const dialOptions = { maxOutboundStreams };
943
+ const dialOptions = {};
944
+ if (maxOutboundStreams !== void 0) dialOptions.maxOutboundStreams = maxOutboundStreams;
904
945
  if (runOnLimitedConnection !== void 0) dialOptions.runOnLimitedConnection = runOnLimitedConnection;
905
946
  let handled = false;
906
947
  const control = newNativePortMux({
@@ -908,25 +949,28 @@ async function libp2pPortMux(options) {
908
949
  codec,
909
950
  maxMessageSize,
910
951
  onPort,
952
+ window,
911
953
  async open(signal) {
912
954
  if (!peer) throw new Error("webrun-streams-libp2p: openPort needs `peer`");
913
- const stream = await openGatedStream(node, peer, protocol, {
955
+ const stream = await openGatedStream(node, peer, window !== void 0 ? [windowProtocol, protocol] : protocol, {
914
956
  ...dialOptions,
915
957
  signal
916
958
  });
917
959
  return channelOf(stream);
918
960
  },
919
961
  async stopAccepting() {
920
- if (handled) await node.unhandle(protocol).catch(() => void 0);
962
+ if (!handled) return;
963
+ const served = window !== void 0 ? [protocol, windowProtocol] : [protocol];
964
+ await node.unhandle(served).catch(() => void 0);
921
965
  }
922
966
  });
923
967
  if (onPort) {
924
- const handleOptions = {
925
- maxInboundStreams,
926
- maxOutboundStreams
927
- };
968
+ const handleOptions = {};
969
+ if (maxInboundStreams !== void 0) handleOptions.maxInboundStreams = maxInboundStreams;
970
+ if (maxOutboundStreams !== void 0) handleOptions.maxOutboundStreams = maxOutboundStreams;
928
971
  if (runOnLimitedConnection !== void 0) handleOptions.runOnLimitedConnection = runOnLimitedConnection;
929
- await node.handle(protocol, (stream, connection) => {
972
+ const served = window !== void 0 ? [protocol, windowProtocol] : [protocol];
973
+ await node.handle(served, (stream, connection) => {
930
974
  if (control.closed) {
931
975
  stream.abort(/* @__PURE__ */ new Error("webrun-streams-libp2p: port mux closed"));
932
976
  return;
@@ -941,4 +985,237 @@ async function libp2pPortMux(options) {
941
985
  return control.mux;
942
986
  }
943
987
  //#endregion
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 };
988
+ //#region src/connect-serve.ts
989
+ /**
990
+ * 4 MiB: the port window `connect`/`serve` grant unless told otherwise — the
991
+ * most one call moves per round trip, and the most a producer runs ahead of a
992
+ * consumer that stopped reading (statewalker/webrun-wire#153).
993
+ *
994
+ * A call moves at most `window / RTT`, so the window should be at least the
995
+ * link's bandwidth-delay product: 4 MiB covers 200 Mbit/s at 100 ms
996
+ * (2.5 MB). Raise it for faster or longer links; lower it (not below 64 KiB)
997
+ * to bound memory per call more tightly where the BDP is small — a window far
998
+ * above the bottleneck's queue only adds latency (bufferbloat).
999
+ */
1000
+ const DEFAULT_WINDOW = 4194304;
1001
+ /**
1002
+ * The protocol a call's stream negotiates for `connect`/`serve` configured
1003
+ * with `protocol`: `protocol` with `/ports` appended, and `/window` after it
1004
+ * when both ends run the window (always, between two releases from this one
1005
+ * on). `protocol` itself is the deprecated protocol, still served, and dialled
1006
+ * when a peer refuses this one.
1007
+ */
1008
+ function portProtocolOf(protocol) {
1009
+ return `${protocol}/ports`;
1010
+ }
1011
+ /** What a call's messages are on the wire: msgpack, as `webrun-rpc`'s stream tier posts them. */
1012
+ const codec = {
1013
+ encode: serialize,
1014
+ decode: deserialize
1015
+ };
1016
+ /**
1017
+ * Caller-side: each `call(input)` is one port of a windowed native port mux
1018
+ * (`libp2pPortMux`): one libp2p stream negotiating {@link portProtocolOf}
1019
+ * `protocol` with `/window`, over which `webrun-rpc`'s stream tier runs the
1020
+ * call, pipelining up to the server's window per round trip. Streams are
1021
+ * opened through the early-stream gate, so a burst of calls on a fresh
1022
+ * connection does not kill its muxer.
1023
+ *
1024
+ * Against an older server, which refuses that protocol, the call falls back to
1025
+ * the deprecated protocol on `protocol` itself, and the node remembers that
1026
+ * for the connection, so later calls to that peer dial it directly. The
1027
+ * fallback is removed in the next release.
1028
+ */
1029
+ const connect = async (params) => {
1030
+ const { node, peer, maxFrameBytes, maxOutboundStreams, runOnLimitedConnection } = params;
1031
+ const protocol = params.protocol ?? "/webrun-streams/1.0.0";
1032
+ const ports = await connect$1({
1033
+ mux: overPorts(() => openLibp2pPortMux({
1034
+ node,
1035
+ peer,
1036
+ codec,
1037
+ protocol: portProtocolOf(protocol),
1038
+ window: params.window ?? 4194304,
1039
+ maxMessageBytes: maxFrameBytes,
1040
+ maxOutboundStreams,
1041
+ runOnLimitedConnection
1042
+ }, void 0)),
1043
+ timeout: params.timeout
1044
+ });
1045
+ const legacy = await legacyConnect({
1046
+ node,
1047
+ peer,
1048
+ protocol,
1049
+ drainTimeoutMs: params.drainTimeoutMs,
1050
+ readHighWaterBytes: params.readHighWaterBytes,
1051
+ maxFrameBytes,
1052
+ maxOutboundStreams,
1053
+ runOnLimitedConnection
1054
+ });
1055
+ const call = (input) => {
1056
+ if (isLegacyPeer(node, peer, protocol)) return legacy.call(input);
1057
+ return withFallback(ports.call(input), () => legacy.call(input), (err) => {
1058
+ if (!isUnsupportedProtocol(err)) return false;
1059
+ markLegacyPeer(node, peer, protocol);
1060
+ return true;
1061
+ });
1062
+ };
1063
+ return {
1064
+ call,
1065
+ async close() {
1066
+ await Promise.allSettled([ports.close(), legacy.close()]);
1067
+ }
1068
+ };
1069
+ };
1070
+ /**
1071
+ * Server-side: serves each call as one port of a windowed native port mux
1072
+ * (`<protocol>/ports`, with and without `/window`), and runs `handler` on it.
1073
+ * Older callers are still answered on `protocol` itself, the deprecated
1074
+ * protocol, until the next release. Identity-unaware; use `serveConnections`
1075
+ * when the handler needs to know who is calling.
1076
+ */
1077
+ const serve = async (params, handler) => serveConnections(params, () => handler);
1078
+ /**
1079
+ * Like `serve`, but the handler is built per call and is told which peer
1080
+ * libp2p proved on the connection the call came on.
1081
+ */
1082
+ async function serveConnections(params, makeHandler) {
1083
+ const { node, maxFrameBytes, maxInboundStreams, maxOutboundStreams, runOnLimitedConnection } = params;
1084
+ const protocol = params.protocol ?? "/webrun-streams/1.0.0";
1085
+ let arriving;
1086
+ const stopPorts = await serve$1({
1087
+ mux: overPorts((onPort) => openLibp2pPortMux({
1088
+ node,
1089
+ codec,
1090
+ protocol: portProtocolOf(protocol),
1091
+ window: params.window ?? 4194304,
1092
+ maxMessageBytes: maxFrameBytes,
1093
+ maxInboundStreams,
1094
+ maxOutboundStreams,
1095
+ runOnLimitedConnection,
1096
+ onPort: onPort && ((port, info) => {
1097
+ arriving = info;
1098
+ try {
1099
+ return onPort(port, info);
1100
+ } finally {
1101
+ arriving = void 0;
1102
+ }
1103
+ })
1104
+ }, void 0)),
1105
+ timeout: params.timeout
1106
+ }, (input) => {
1107
+ const info = arriving;
1108
+ if (!info) throw new Error("webrun-streams-libp2p: a call arrived without its connection");
1109
+ return makeHandler({ remotePeer: info.remotePeer })(input);
1110
+ });
1111
+ let stopLegacy;
1112
+ try {
1113
+ stopLegacy = await legacyServeConnections({
1114
+ node,
1115
+ protocol,
1116
+ drainTimeoutMs: params.drainTimeoutMs,
1117
+ readHighWaterBytes: params.readHighWaterBytes,
1118
+ maxFrameBytes,
1119
+ maxInboundStreams,
1120
+ maxOutboundStreams,
1121
+ runOnLimitedConnection
1122
+ }, makeHandler);
1123
+ } catch (err) {
1124
+ await stopPorts();
1125
+ throw err;
1126
+ }
1127
+ let torn = false;
1128
+ return async () => {
1129
+ if (torn) return;
1130
+ torn = true;
1131
+ await Promise.all([stopPorts(), stopLegacy()]);
1132
+ };
1133
+ }
1134
+ /** Whether `err` says the peer speaks none of the protocols dialled. */
1135
+ function isUnsupportedProtocol(err) {
1136
+ return err instanceof Error && err.name === "UnsupportedProtocolError";
1137
+ }
1138
+ /**
1139
+ * `primary`, except that when its first `next()` rejects with an error
1140
+ * `fallBack` accepts — the port protocol refused, before any of the input was
1141
+ * read — the call runs on `fallback()` instead. `return()` and `throw()` go
1142
+ * straight to the current call, so a consumer that gives up on a pending
1143
+ * `next()` is heard at once, as by the call itself.
1144
+ */
1145
+ function withFallback(primary, fallback, fallBack) {
1146
+ let current = primary;
1147
+ let settled = false;
1148
+ const wrapped = {
1149
+ async next(...args) {
1150
+ if (settled) return current.next(...args);
1151
+ try {
1152
+ const result = await current.next(...args);
1153
+ settled = true;
1154
+ return result;
1155
+ } catch (err) {
1156
+ if (settled || !fallBack(err)) {
1157
+ settled = true;
1158
+ throw err;
1159
+ }
1160
+ settled = true;
1161
+ current = fallback();
1162
+ return current.next(...args);
1163
+ }
1164
+ },
1165
+ return(value) {
1166
+ settled = true;
1167
+ return current.return(value);
1168
+ },
1169
+ throw(error) {
1170
+ settled = true;
1171
+ return current.throw(error);
1172
+ },
1173
+ [Symbol.asyncIterator]() {
1174
+ return wrapped;
1175
+ }
1176
+ };
1177
+ const asyncDispose = Symbol.asyncDispose;
1178
+ if (asyncDispose) Object.defineProperty(wrapped, asyncDispose, {
1179
+ value: async () => {
1180
+ await wrapped.return(void 0);
1181
+ },
1182
+ configurable: true,
1183
+ writable: true
1184
+ });
1185
+ return wrapped;
1186
+ }
1187
+ /**
1188
+ * Peers known to refuse the port protocol, per local node, by peer and
1189
+ * protocol: the connection the refusal came on (`null` when the node cannot
1190
+ * tell), so a peer that restarts upgraded is probed again on its next
1191
+ * connection.
1192
+ */
1193
+ const legacyPeers = /* @__PURE__ */ new WeakMap();
1194
+ const legacyKey = (peer, protocol) => `${peer.toString()} ${protocol}`;
1195
+ function isLegacyPeer(node, peer, protocol) {
1196
+ const peers = legacyPeers.get(node);
1197
+ const mark = peers?.get(legacyKey(peer, protocol));
1198
+ if (!mark) return false;
1199
+ if (mark.connection == null || mark.connection.status === "open") return true;
1200
+ peers?.delete(legacyKey(peer, protocol));
1201
+ return false;
1202
+ }
1203
+ function markLegacyPeer(node, peer, protocol) {
1204
+ let peers = legacyPeers.get(node);
1205
+ if (!peers) {
1206
+ peers = /* @__PURE__ */ new Map();
1207
+ legacyPeers.set(node, peers);
1208
+ }
1209
+ peers.set(legacyKey(peer, protocol), { connection: connectionTo(node, peer) });
1210
+ }
1211
+ /**
1212
+ * The open connection to `peer`, when `node` can list its connections (a
1213
+ * narrow stand-in may offer only `dialProtocol`).
1214
+ */
1215
+ function connectionTo(node, peer) {
1216
+ if (typeof node.getConnections !== "function") return null;
1217
+ const target = peer.toString();
1218
+ return node.getConnections().find((c) => c.status === "open" && (c.remotePeer.toString() === target || c.remoteAddr.toString() === target || target.endsWith(`/p2p/${c.remotePeer.toString()}`))) ?? null;
1219
+ }
1220
+ //#endregion
1221
+ 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, DEFAULT_WINDOW, PeerGoneError, connect, duplexOverStream, libp2pPortMux, messageTargetOverStream, portProtocolOf, serve, serveConnections };
@@ -0,0 +1,116 @@
1
+ /**
2
+ * The deprecated protocol of `connect`/`serve` (statewalker/webrun-wire#153):
3
+ * one call per libp2p stream on `protocol` itself, framed by
4
+ * `duplexOverStream`, with its own flow control (yamux pause/resume and a
5
+ * paced reader). Releases up to 0.6.0 spoke only this.
6
+ *
7
+ * Kept for one release as a compatibility shim on both ends: `serve` still
8
+ * answers old callers on it, and `connect` falls back to it against an old
9
+ * server. Removed in the release after the one that introduced the port
10
+ * protocol, together with `duplexOverStream`.
11
+ *
12
+ * @deprecated Use `connect`/`serve`, which run over the windowed native port mux.
13
+ */
14
+ import type { Libp2p, PeerId } from "@libp2p/interface";
15
+ import type { Multiaddr } from "@multiformats/multiaddr";
16
+ import type { Connect } from "@statewalker/webrun-streams";
17
+ import { type ServeConnectionsHandler } from "./shared.js";
18
+ /** @deprecated See the module comment. */
19
+ export interface LegacyConnectParams {
20
+ node: Libp2p;
21
+ peer: PeerId | Multiaddr;
22
+ /** libp2p protocol id; defaults to `/webrun-streams/1.0.0`. */
23
+ protocol?: string;
24
+ /**
25
+ * How long to wait for a backpressured stream to drain before dropping the
26
+ * peer; defaults to `DEFAULT_DRAIN_TIMEOUT_MS` (5 minutes).
27
+ */
28
+ drainTimeoutMs?: number;
29
+ /**
30
+ * Response bytes held while the caller is not reading before the stream is
31
+ * paused; see `DuplexOverStreamOptions.readHighWaterBytes` (default 64 KiB).
32
+ */
33
+ readHighWaterBytes?: number;
34
+ /**
35
+ * The largest frame payload accepted from the peer; past it, or on a
36
+ * malformed frame header, the call fails and the stream is aborted. See
37
+ * `DuplexOverStreamOptions.maxFrameBytes` (default 64 MiB).
38
+ */
39
+ maxFrameBytes?: number;
40
+ /**
41
+ * How many outgoing streams for this protocol libp2p allows to be open at
42
+ * the same time on one connection; passed through to `node.dialProtocol`.
43
+ * Left unset, libp2p's own default (64) applies.
44
+ */
45
+ maxOutboundStreams?: number;
46
+ /**
47
+ * Opt-in to dialing over a connection with limits on how much data can be
48
+ * transferred or how long it can be open for (e.g. a relayed circuit);
49
+ * passed through to `node.dialProtocol`. Left unset, libp2p refuses to open
50
+ * this protocol's stream on such a connection — this package does not
51
+ * decide that trade-off for the caller, it only exposes the knob.
52
+ */
53
+ runOnLimitedConnection?: boolean;
54
+ }
55
+ /** @deprecated See the module comment. */
56
+ export interface LegacyServeParams {
57
+ node: Libp2p;
58
+ /** libp2p protocol id; defaults to `/webrun-streams/1.0.0`. */
59
+ protocol?: string;
60
+ /**
61
+ * How long to wait for a backpressured stream to drain before dropping the
62
+ * peer; defaults to `DEFAULT_DRAIN_TIMEOUT_MS` (5 minutes). This is the only
63
+ * bound on a peer that requests something and then stops reading without
64
+ * closing, since the caller-side `.return`/abort escape does not exist here.
65
+ */
66
+ drainTimeoutMs?: number;
67
+ /**
68
+ * Request bytes held while the handler is not reading before the stream is
69
+ * paused; see `DuplexOverStreamOptions.readHighWaterBytes` (default 64 KiB).
70
+ */
71
+ readHighWaterBytes?: number;
72
+ /**
73
+ * The largest frame payload accepted from the peer; past it, or on a
74
+ * malformed frame header, the call fails and the stream is aborted. See
75
+ * `DuplexOverStreamOptions.maxFrameBytes` (default 64 MiB).
76
+ */
77
+ maxFrameBytes?: number;
78
+ /**
79
+ * How many incoming streams for this protocol libp2p allows to be open at
80
+ * the same time on one connection; passed through to `node.handle`. Left
81
+ * unset, libp2p's own default (32) applies — past it, a new inbound stream
82
+ * is reset rather than queued, so a caller that opens one stream per
83
+ * in-flight request will start seeing rejected calls above that count.
84
+ */
85
+ maxInboundStreams?: number;
86
+ /**
87
+ * How many outgoing streams for this protocol libp2p allows to be open at
88
+ * the same time on one connection; passed through to `node.handle`. Left
89
+ * unset, libp2p's own default (64) applies.
90
+ */
91
+ maxOutboundStreams?: number;
92
+ /**
93
+ * Opt-in to accepting streams for this protocol over a connection with
94
+ * limits on how much data can be transferred or how long it can be open
95
+ * for (e.g. a relayed circuit); passed through to `node.handle`. Left
96
+ * unset, libp2p refuses to open this protocol's stream on such a
97
+ * connection — this package does not decide that trade-off for the
98
+ * consumer, it only exposes the knob.
99
+ */
100
+ runOnLimitedConnection?: boolean;
101
+ }
102
+ /**
103
+ * Caller-side: each `call(input)` opens a new libp2p `Stream` via
104
+ * `node.dialProtocol(peer, [protocol])` and runs the call over it.
105
+ *
106
+ * @deprecated See the module comment.
107
+ */
108
+ export declare const legacyConnect: Connect<LegacyConnectParams>;
109
+ /**
110
+ * Server-side: registers `node.handle(protocol, ...)`. The handler is built per
111
+ * inbound stream and is told which peer libp2p proved on that connection.
112
+ *
113
+ * @deprecated See the module comment.
114
+ */
115
+ export declare function legacyServeConnections({ node, protocol, drainTimeoutMs, readHighWaterBytes, maxFrameBytes, maxInboundStreams, maxOutboundStreams, runOnLimitedConnection, }: LegacyServeParams, makeHandler: ServeConnectionsHandler): Promise<() => Promise<void>>;
116
+ //# sourceMappingURL=legacy-connect-serve.d.ts.map
@@ -0,0 +1 @@
1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C;AAqBD;;;;;GAKG;AACH,eAAO,MAAM,aAAa,EAAE,OAAO,CAAC,mBAAmB,CA8FtD,CAAC;AAEF;;;;;GAKG;AACH,wBAAsB,sBAAsB,CAC1C,EACE,IAAI,EACJ,QAAQ,EACR,cAAc,EACd,kBAAkB,EAClB,aAAa,EACb,iBAAiB,EACjB,kBAAkB,EAClB,sBAAsB,GACvB,EAAE,iBAAiB,EACpB,WAAW,EAAE,uBAAuB,GACnC,OAAO,CAAC,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC,CAgE9B"}
@@ -4,6 +4,12 @@ import { type NativePort, type ValueCodec } from "@statewalker/webrun-streams";
4
4
  export type { ValueCodec };
5
5
  /** The protocol a port's stream negotiates unless told otherwise. */
6
6
  export declare const DEFAULT_PORT_PROTOCOL = "/webrun-ports/1.0.0";
7
+ /**
8
+ * The protocol a windowed port's stream negotiates, for a mux whose ports
9
+ * negotiate `protocol`: `protocol` with `/window` appended. A mux with
10
+ * `window` dials it first and falls back to `protocol`, and serves both.
11
+ */
12
+ export declare function windowProtocolOf(protocol: string): string;
7
13
  /**
8
14
  * 256 KiB: what one message on a port may carry before `webrun-rpc`'s stream tier chunks a body.
9
15
  * A port waits for each chunk's confirmation, so a larger chunk means fewer round trips; well
@@ -48,8 +54,21 @@ export interface Libp2pPortMuxOptions {
48
54
  /** Default {@link DEFAULT_PORT_STREAM_LIMIT}. */
49
55
  maxOutboundStreams?: number;
50
56
  runOnLimitedConnection?: boolean;
57
+ /**
58
+ * Per-port flow control, in bytes (off when unset; from 64 KiB,
59
+ * `MIN_PORT_WINDOW` in `@statewalker/webrun-streams`): the most this end holds of a port's messages
60
+ * delivered and not yet consumed (statewalker/webrun-wire#153). A port
61
+ * whose two ends both set it negotiates {@link windowProtocolOf} `protocol`,
62
+ * and `webrun-rpc`'s stream tier then pipelines its chunks, up to the
63
+ * peer's window in flight, instead of waiting for each chunk's
64
+ * confirmation; against a mux without it (an older peer) the port
65
+ * negotiates `protocol` and runs as before. 1-4 MiB is a reasonable range:
66
+ * the most one call moves per round trip, and the most a producer runs
67
+ * ahead of a consumer that stopped reading.
68
+ */
69
+ window?: number;
51
70
  }
52
- /** A `webrun-rpc` `PortMux` by shape; this package imports nothing from it. */
71
+ /** A `webrun-rpc` `PortMux` by shape; the port mux imports nothing from it. */
53
72
  export interface Libp2pPortMux {
54
73
  openPort(meta?: unknown, options?: {
55
74
  signal?: AbortSignal;
@@ -76,4 +95,10 @@ export interface Libp2pPortMux {
76
95
  * `connect()`. `meta` is not sent: the protocol says what a port is for.
77
96
  */
78
97
  export declare function libp2pPortMux(options: Libp2pPortMuxOptions): Promise<Libp2pPortMux>;
98
+ /**
99
+ * {@link libp2pPortMux}, with `streamLimit` as the default of both stream
100
+ * limits; `undefined` leaves libp2p's own defaults (what `connect`/`serve`
101
+ * have always passed through). Internal.
102
+ */
103
+ export declare function openLibp2pPortMux(options: Libp2pPortMuxOptions, streamLimit: number | undefined): Promise<Libp2pPortMux>;
79
104
  //# sourceMappingURL=port-mux.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"port-mux.d.ts","sourceRoot":"","sources":["../src/port-mux.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,UAAU,EAEV,MAAM,EACN,MAAM,EAGP,MAAM,mBAAmB,CAAC;AAC3B,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,yBAAyB,CAAC;AACzD,OAAO,EAEL,KAAK,UAAU,EAEf,KAAK,UAAU,EAChB,MAAM,6BAA6B,CAAC;AAIrC,YAAY,EAAE,UAAU,EAAE,CAAC;AAE3B,qEAAqE;AACrE,eAAO,MAAM,qBAAqB,wBAAwB,CAAC;AAE3D;;;;GAIG;AACH,eAAO,MAAM,6BAA6B,QAAa,CAAC;AAExD;;;GAGG;AACH,eAAO,MAAM,yBAAyB,OAAO,CAAC;AAE9C;;;GAGG;AACH,MAAM,MAAM,UAAU,GAAG,UAAU,CAAC;AAEpC,iEAAiE;AACjE,MAAM,WAAW,eAAe;IA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AM,CAAC;CACjB;AAED,+EAA+E;AAC/E,MAAM,WAAW,aAAa;IAC5B,QAAQ,CAAC,IAAI,CAAC,EAAE,OAAO,EAAE,OAAO,CAAC,EAAE;QAAE,MAAM,CAAC,EAAE,WAAW,CAAA;KAAE,GAAG,OAAO,CAAC,UAAU,CAAC,CAAC;IAClF,KAAK,CAAC,MAAM,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACvC,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC;CACjC;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAsB,aAAa,CAAC,OAAO,EAAE,oBAAoB,GAAG,OAAO,CAAC,aAAa,CAAC,CAEzF;AAED;;;;GAIG;AACH,wBAAsB,iBAAiB,CACrC,OAAO,EAAE,oBAAoB,EAC7B,WAAW,EAAE,MAAM,GAAG,SAAS,GAC9B,OAAO,CAAC,aAAa,CAAC,CAsExB"}
@@ -0,0 +1,26 @@
1
+ import type { PeerId } from "@libp2p/interface";
2
+ import type { Duplex } from "@statewalker/webrun-streams";
3
+ /**
4
+ * The protocol id `connect`/`serve` are configured with unless told otherwise.
5
+ * Their calls negotiate `portProtocolOf(protocol)` (with `/window`); the id
6
+ * itself is the deprecated protocol, still served and dialled as a fallback
7
+ * for one release (statewalker/webrun-wire#153).
8
+ */
9
+ export declare const DEFAULT_PROTOCOL = "/webrun-streams/1.0.0";
10
+ /** What the serving side knows about the connection a call arrived on. */
11
+ export interface ConnectionContext {
12
+ /**
13
+ * The peer id libp2p's Noise handshake proved for this connection. This is
14
+ * the only identity claim on the serving side that cannot be forged by the
15
+ * request payload.
16
+ */
17
+ remotePeer: PeerId;
18
+ }
19
+ /**
20
+ * Builds a handler for one inbound call. Called once per call (one port, or one
21
+ * stream of the deprecated protocol), so the connection stays reachable in the
22
+ * returned Duplex's closure — `Duplex` is bytes-only (ADR-0004) and gains no
23
+ * new parameter.
24
+ */
25
+ export type ServeConnectionsHandler = (context: ConnectionContext) => Duplex;
26
+ //# sourceMappingURL=shared.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"shared.d.ts","sourceRoot":"","sources":["../src/shared.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,6BAA6B,CAAC;AAE1D;;;;;GAKG;AACH,eAAO,MAAM,gBAAgB,0BAA0B,CAAC;AAExD,0EAA0E;AAC1E,MAAM,WAAW,iBAAiB;IAChC;;;;OAIG;IACH,UAAU,EAAE,MAAM,CAAC;CACpB;AAED;;;;;GAKG;AACH,MAAM,MAAM,uBAAuB,GAAG,CAAC,OAAO,EAAE,iBAAiB,KAAK,MAAM,CAAC"}
@@ -6,5 +6,5 @@ import type { Multiaddr } from "@multiformats/multiaddr";
6
6
  * (`maxEarlyStreams`). Shared by `connect()` and `libp2pPortMux`, and by every caller dialling
7
7
  * the same peer from the same node, since they share its connection.
8
8
  */
9
- export declare function openGatedStream(node: Libp2p, peer: PeerId | Multiaddr, proto: string, dialOptions?: DialProtocolOptions): Promise<Stream>;
9
+ export declare function openGatedStream(node: Libp2p, peer: PeerId | Multiaddr, proto: string | string[], dialOptions?: DialProtocolOptions): Promise<Stream>;
10
10
  //# sourceMappingURL=stream-gate.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"stream-gate.d.ts","sourceRoot":"","sources":["../src/stream-gate.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAc,mBAAmB,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AACjG,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,yBAAyB,CAAC;AA+CzD;;;;;GAKG;AACH,wBAAsB,eAAe,CACnC,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,MAAM,GAAG,SAAS,EACxB,KAAK,EAAE,MAAM,EACb,WAAW,CAAC,EAAE,mBAAmB,GAChC,OAAO,CAAC,MAAM,CAAC,CAiBjB"}
1
+ {"version":3,"file":"stream-gate.d.ts","sourceRoot":"","sources":["../src/stream-gate.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAc,mBAAmB,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AACjG,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,yBAAyB,CAAC;AA+CzD;;;;;GAKG;AACH,wBAAsB,eAAe,CACnC,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,MAAM,GAAG,SAAS,EACxB,KAAK,EAAE,MAAM,GAAG,MAAM,EAAE,EACxB,WAAW,CAAC,EAAE,mBAAmB,GAChC,OAAO,CAAC,MAAM,CAAC,CAmBjB"}