@buildanagent/harness 0.0.0-bootstrap.0 → 0.1.0-alpha.28
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/LICENSE +54 -0
- package/LICENSE-APACHE +202 -0
- package/LICENSE-MIT +21 -0
- package/README.md +717 -0
- package/dist/ablation.d.ts +2 -0
- package/dist/ablation.js +3 -0
- package/dist/ablation.js.map +1 -0
- package/dist/completion/check.d.ts +64 -0
- package/dist/completion/check.js +152 -0
- package/dist/completion/check.js.map +1 -0
- package/dist/completion/checks.d.ts +45 -0
- package/dist/completion/checks.js +173 -0
- package/dist/completion/checks.js.map +1 -0
- package/dist/completion/flags.d.ts +25 -0
- package/dist/completion/flags.js +87 -0
- package/dist/completion/flags.js.map +1 -0
- package/dist/completion/index.d.ts +8 -0
- package/dist/completion/index.js +9 -0
- package/dist/completion/index.js.map +1 -0
- package/dist/completion/snapshot.d.ts +33 -0
- package/dist/completion/snapshot.js +83 -0
- package/dist/completion/snapshot.js.map +1 -0
- package/dist/context/cap.d.ts +32 -0
- package/dist/context/cap.js +50 -0
- package/dist/context/cap.js.map +1 -0
- package/dist/context/estimate.d.ts +18 -0
- package/dist/context/estimate.js +20 -0
- package/dist/context/estimate.js.map +1 -0
- package/dist/context/file-spill.d.ts +5 -0
- package/dist/context/file-spill.js +25 -0
- package/dist/context/file-spill.js.map +1 -0
- package/dist/context/index.d.ts +10 -0
- package/dist/context/index.js +10 -0
- package/dist/context/index.js.map +1 -0
- package/dist/context/mask.d.ts +27 -0
- package/dist/context/mask.js +71 -0
- package/dist/context/mask.js.map +1 -0
- package/dist/context/mid-turn.d.ts +40 -0
- package/dist/context/mid-turn.js +82 -0
- package/dist/context/mid-turn.js.map +1 -0
- package/dist/context/policy.d.ts +9 -0
- package/dist/context/policy.js +140 -0
- package/dist/context/policy.js.map +1 -0
- package/dist/context/spill-ledger.d.ts +25 -0
- package/dist/context/spill-ledger.js +54 -0
- package/dist/context/spill-ledger.js.map +1 -0
- package/dist/context/spill.d.ts +6 -0
- package/dist/context/spill.js +14 -0
- package/dist/context/spill.js.map +1 -0
- package/dist/context/summarize.d.ts +53 -0
- package/dist/context/summarize.js +204 -0
- package/dist/context/summarize.js.map +1 -0
- package/dist/context/summary-template.d.ts +29 -0
- package/dist/context/summary-template.js +69 -0
- package/dist/context/summary-template.js.map +1 -0
- package/dist/context/types.d.ts +150 -0
- package/dist/context/types.js +2 -0
- package/dist/context/types.js.map +1 -0
- package/dist/context/write-cap.d.ts +19 -0
- package/dist/context/write-cap.js +41 -0
- package/dist/context/write-cap.js.map +1 -0
- package/dist/create-harness.d.ts +7 -0
- package/dist/create-harness.js +21 -0
- package/dist/create-harness.js.map +1 -0
- package/dist/credentials/addresses.d.ts +14 -0
- package/dist/credentials/addresses.js +144 -0
- package/dist/credentials/addresses.js.map +1 -0
- package/dist/credentials/allowlist.d.ts +34 -0
- package/dist/credentials/allowlist.js +77 -0
- package/dist/credentials/allowlist.js.map +1 -0
- package/dist/credentials/egress-proxy.d.ts +70 -0
- package/dist/credentials/egress-proxy.js +482 -0
- package/dist/credentials/egress-proxy.js.map +1 -0
- package/dist/credentials/index.d.ts +9 -0
- package/dist/credentials/index.js +10 -0
- package/dist/credentials/index.js.map +1 -0
- package/dist/credentials/scrub.d.ts +16 -0
- package/dist/credentials/scrub.js +93 -0
- package/dist/credentials/scrub.js.map +1 -0
- package/dist/errors.d.ts +56 -0
- package/dist/errors.js +63 -0
- package/dist/errors.js.map +1 -0
- package/dist/extensions/compose.d.ts +27 -0
- package/dist/extensions/compose.js +83 -0
- package/dist/extensions/compose.js.map +1 -0
- package/dist/extensions/context-files-node.d.ts +28 -0
- package/dist/extensions/context-files-node.js +74 -0
- package/dist/extensions/context-files-node.js.map +1 -0
- package/dist/extensions/context-files.d.ts +68 -0
- package/dist/extensions/context-files.js +214 -0
- package/dist/extensions/context-files.js.map +1 -0
- package/dist/extensions/digest.d.ts +6 -0
- package/dist/extensions/digest.js +68 -0
- package/dist/extensions/digest.js.map +1 -0
- package/dist/extensions/index.d.ts +10 -0
- package/dist/extensions/index.js +10 -0
- package/dist/extensions/index.js.map +1 -0
- package/dist/extensions/load.d.ts +42 -0
- package/dist/extensions/load.js +211 -0
- package/dist/extensions/load.js.map +1 -0
- package/dist/extensions/lock.d.ts +8 -0
- package/dist/extensions/lock.js +95 -0
- package/dist/extensions/lock.js.map +1 -0
- package/dist/extensions/node.d.ts +10 -0
- package/dist/extensions/node.js +11 -0
- package/dist/extensions/node.js.map +1 -0
- package/dist/extensions/project-dirs.d.ts +24 -0
- package/dist/extensions/project-dirs.js +97 -0
- package/dist/extensions/project-dirs.js.map +1 -0
- package/dist/extensions/skills-node.d.ts +34 -0
- package/dist/extensions/skills-node.js +123 -0
- package/dist/extensions/skills-node.js.map +1 -0
- package/dist/extensions/skills.d.ts +51 -0
- package/dist/extensions/skills.js +175 -0
- package/dist/extensions/skills.js.map +1 -0
- package/dist/extensions/trust-file.d.ts +3 -0
- package/dist/extensions/trust-file.js +62 -0
- package/dist/extensions/trust-file.js.map +1 -0
- package/dist/extensions/trust-store-node.d.ts +10 -0
- package/dist/extensions/trust-store-node.js +33 -0
- package/dist/extensions/trust-store-node.js.map +1 -0
- package/dist/extensions/types.d.ts +42 -0
- package/dist/extensions/types.js +2 -0
- package/dist/extensions/types.js.map +1 -0
- package/dist/harness.d.ts +156 -0
- package/dist/harness.js +2 -0
- package/dist/harness.js.map +1 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +5 -0
- package/dist/index.js.map +1 -0
- package/dist/mcp/connection.d.ts +22 -0
- package/dist/mcp/connection.js +267 -0
- package/dist/mcp/connection.js.map +1 -0
- package/dist/mcp/content.d.ts +27 -0
- package/dist/mcp/content.js +177 -0
- package/dist/mcp/content.js.map +1 -0
- package/dist/mcp/errors.d.ts +19 -0
- package/dist/mcp/errors.js +21 -0
- package/dist/mcp/errors.js.map +1 -0
- package/dist/mcp/index.d.ts +10 -0
- package/dist/mcp/index.js +10 -0
- package/dist/mcp/index.js.map +1 -0
- package/dist/mcp/manager.d.ts +7 -0
- package/dist/mcp/manager.js +173 -0
- package/dist/mcp/manager.js.map +1 -0
- package/dist/mcp/record.d.ts +7 -0
- package/dist/mcp/record.js +20 -0
- package/dist/mcp/record.js.map +1 -0
- package/dist/mcp/stdio.d.ts +39 -0
- package/dist/mcp/stdio.js +382 -0
- package/dist/mcp/stdio.js.map +1 -0
- package/dist/mcp/types.d.ts +172 -0
- package/dist/mcp/types.js +2 -0
- package/dist/mcp/types.js.map +1 -0
- package/dist/memory/index.d.ts +2 -0
- package/dist/memory/index.js +3 -0
- package/dist/memory/index.js.map +1 -0
- package/dist/permissions/default-rules.d.ts +7 -0
- package/dist/permissions/default-rules.js +42 -0
- package/dist/permissions/default-rules.js.map +1 -0
- package/dist/permissions/errors.d.ts +11 -0
- package/dist/permissions/errors.js +14 -0
- package/dist/permissions/errors.js.map +1 -0
- package/dist/permissions/index.d.ts +9 -0
- package/dist/permissions/index.js +9 -0
- package/dist/permissions/index.js.map +1 -0
- package/dist/permissions/match.d.ts +33 -0
- package/dist/permissions/match.js +287 -0
- package/dist/permissions/match.js.map +1 -0
- package/dist/permissions/pipeline.d.ts +9 -0
- package/dist/permissions/pipeline.js +235 -0
- package/dist/permissions/pipeline.js.map +1 -0
- package/dist/permissions/rules.d.ts +22 -0
- package/dist/permissions/rules.js +74 -0
- package/dist/permissions/rules.js.map +1 -0
- package/dist/permissions/shadow.d.ts +5 -0
- package/dist/permissions/shadow.js +22 -0
- package/dist/permissions/shadow.js.map +1 -0
- package/dist/permissions/types.d.ts +104 -0
- package/dist/permissions/types.js +2 -0
- package/dist/permissions/types.js.map +1 -0
- package/dist/sandbox/base.d.ts +35 -0
- package/dist/sandbox/base.js +60 -0
- package/dist/sandbox/base.js.map +1 -0
- package/dist/sandbox/docker/index.d.ts +35 -0
- package/dist/sandbox/docker/index.js +448 -0
- package/dist/sandbox/docker/index.js.map +1 -0
- package/dist/sandbox/errors.d.ts +16 -0
- package/dist/sandbox/errors.js +22 -0
- package/dist/sandbox/errors.js.map +1 -0
- package/dist/sandbox/host-files.d.ts +63 -0
- package/dist/sandbox/host-files.js +248 -0
- package/dist/sandbox/host-files.js.map +1 -0
- package/dist/sandbox/index.d.ts +8 -0
- package/dist/sandbox/index.js +8 -0
- package/dist/sandbox/index.js.map +1 -0
- package/dist/sandbox/none.d.ts +17 -0
- package/dist/sandbox/none.js +108 -0
- package/dist/sandbox/none.js.map +1 -0
- package/dist/sandbox/process.d.ts +61 -0
- package/dist/sandbox/process.js +253 -0
- package/dist/sandbox/process.js.map +1 -0
- package/dist/sandbox/spawn-env.d.ts +20 -0
- package/dist/sandbox/spawn-env.js +128 -0
- package/dist/sandbox/spawn-env.js.map +1 -0
- package/dist/sandbox/srt/index.d.ts +35 -0
- package/dist/sandbox/srt/index.js +264 -0
- package/dist/sandbox/srt/index.js.map +1 -0
- package/dist/sandbox/srt/settings.d.ts +48 -0
- package/dist/sandbox/srt/settings.js +31 -0
- package/dist/sandbox/srt/settings.js.map +1 -0
- package/dist/sandbox/types.d.ts +88 -0
- package/dist/sandbox/types.js +6 -0
- package/dist/sandbox/types.js.map +1 -0
- package/dist/server/answers.d.ts +16 -0
- package/dist/server/answers.js +43 -0
- package/dist/server/answers.js.map +1 -0
- package/dist/server/connection.d.ts +99 -0
- package/dist/server/connection.js +309 -0
- package/dist/server/connection.js.map +1 -0
- package/dist/server/dispatcher.d.ts +86 -0
- package/dist/server/dispatcher.js +800 -0
- package/dist/server/dispatcher.js.map +1 -0
- package/dist/server/index.d.ts +13 -0
- package/dist/server/index.js +12 -0
- package/dist/server/index.js.map +1 -0
- package/dist/server/local-transport.d.ts +44 -0
- package/dist/server/local-transport.js +103 -0
- package/dist/server/local-transport.js.map +1 -0
- package/dist/server/outbox.d.ts +31 -0
- package/dist/server/outbox.js +130 -0
- package/dist/server/outbox.js.map +1 -0
- package/dist/server/params.d.ts +25 -0
- package/dist/server/params.js +112 -0
- package/dist/server/params.js.map +1 -0
- package/dist/server/protocol.schema.json +2448 -0
- package/dist/server/rpc-session.d.ts +43 -0
- package/dist/server/rpc-session.js +167 -0
- package/dist/server/rpc-session.js.map +1 -0
- package/dist/server/stdio-streams.d.ts +67 -0
- package/dist/server/stdio-streams.js +218 -0
- package/dist/server/stdio-streams.js.map +1 -0
- package/dist/server/stdio.d.ts +59 -0
- package/dist/server/stdio.js +189 -0
- package/dist/server/stdio.js.map +1 -0
- package/dist/server/websocket.d.ts +106 -0
- package/dist/server/websocket.js +327 -0
- package/dist/server/websocket.js.map +1 -0
- package/dist/session/approvals.d.ts +81 -0
- package/dist/session/approvals.js +217 -0
- package/dist/session/approvals.js.map +1 -0
- package/dist/session/code-call-log.d.ts +42 -0
- package/dist/session/code-call-log.js +63 -0
- package/dist/session/code-call-log.js.map +1 -0
- package/dist/session/code-call-result.d.ts +19 -0
- package/dist/session/code-call-result.js +95 -0
- package/dist/session/code-call-result.js.map +1 -0
- package/dist/session/code-call.d.ts +49 -0
- package/dist/session/code-call.js +345 -0
- package/dist/session/code-call.js.map +1 -0
- package/dist/session/effect-scope.d.ts +11 -0
- package/dist/session/effect-scope.js +10 -0
- package/dist/session/effect-scope.js.map +1 -0
- package/dist/session/errors.d.ts +19 -0
- package/dist/session/errors.js +27 -0
- package/dist/session/errors.js.map +1 -0
- package/dist/session/file-index.d.ts +8 -0
- package/dist/session/file-index.js +70 -0
- package/dist/session/file-index.js.map +1 -0
- package/dist/session/file-key-store.d.ts +16 -0
- package/dist/session/file-key-store.js +169 -0
- package/dist/session/file-key-store.js.map +1 -0
- package/dist/session/file-lock.d.ts +52 -0
- package/dist/session/file-lock.js +324 -0
- package/dist/session/file-lock.js.map +1 -0
- package/dist/session/index.d.ts +22 -0
- package/dist/session/index.js +20 -0
- package/dist/session/index.js.map +1 -0
- package/dist/session/jsonl-store.d.ts +37 -0
- package/dist/session/jsonl-store.js +386 -0
- package/dist/session/jsonl-store.js.map +1 -0
- package/dist/session/jsonl.d.ts +9 -0
- package/dist/session/jsonl.js +10 -0
- package/dist/session/jsonl.js.map +1 -0
- package/dist/session/lock.d.ts +19 -0
- package/dist/session/lock.js +2 -0
- package/dist/session/lock.js.map +1 -0
- package/dist/session/memory-store.d.ts +12 -0
- package/dist/session/memory-store.js +60 -0
- package/dist/session/memory-store.js.map +1 -0
- package/dist/session/migrate.d.ts +41 -0
- package/dist/session/migrate.js +86 -0
- package/dist/session/migrate.js.map +1 -0
- package/dist/session/pointer.d.ts +15 -0
- package/dist/session/pointer.js +22 -0
- package/dist/session/pointer.js.map +1 -0
- package/dist/session/rebuild.d.ts +53 -0
- package/dist/session/rebuild.js +230 -0
- package/dist/session/rebuild.js.map +1 -0
- package/dist/session/resume.d.ts +26 -0
- package/dist/session/resume.js +128 -0
- package/dist/session/resume.js.map +1 -0
- package/dist/session/retention.d.ts +97 -0
- package/dist/session/retention.js +702 -0
- package/dist/session/retention.js.map +1 -0
- package/dist/session/runner.d.ts +156 -0
- package/dist/session/runner.js +656 -0
- package/dist/session/runner.js.map +1 -0
- package/dist/session/scheduler.d.ts +47 -0
- package/dist/session/scheduler.js +85 -0
- package/dist/session/scheduler.js.map +1 -0
- package/dist/session/secret-key-store.d.ts +47 -0
- package/dist/session/secret-key-store.js +79 -0
- package/dist/session/secret-key-store.js.map +1 -0
- package/dist/session/session.d.ts +106 -0
- package/dist/session/session.js +353 -0
- package/dist/session/session.js.map +1 -0
- package/dist/session/sticky.d.ts +48 -0
- package/dist/session/sticky.js +232 -0
- package/dist/session/sticky.js.map +1 -0
- package/dist/session/store.d.ts +108 -0
- package/dist/session/store.js +163 -0
- package/dist/session/store.js.map +1 -0
- package/dist/telemetry/index.d.ts +2 -0
- package/dist/telemetry/index.js +3 -0
- package/dist/telemetry/index.js.map +1 -0
- package/dist/testing/fake-sandbox.d.ts +34 -0
- package/dist/testing/fake-sandbox.js +221 -0
- package/dist/testing/fake-sandbox.js.map +1 -0
- package/dist/testing/index.d.ts +10 -0
- package/dist/testing/index.js +11 -0
- package/dist/testing/index.js.map +1 -0
- package/dist/testing/key-store-conformance.d.ts +22 -0
- package/dist/testing/key-store-conformance.js +97 -0
- package/dist/testing/key-store-conformance.js.map +1 -0
- package/dist/testing/run-cases.d.ts +21 -0
- package/dist/testing/run-cases.js +20 -0
- package/dist/testing/run-cases.js.map +1 -0
- package/dist/testing/sandbox-conformance.d.ts +64 -0
- package/dist/testing/sandbox-conformance.js +361 -0
- package/dist/testing/sandbox-conformance.js.map +1 -0
- package/dist/testing/scheduler-conformance.d.ts +32 -0
- package/dist/testing/scheduler-conformance.js +72 -0
- package/dist/testing/scheduler-conformance.js.map +1 -0
- package/dist/testing/store-conformance.d.ts +21 -0
- package/dist/testing/store-conformance.js +320 -0
- package/dist/testing/store-conformance.js.map +1 -0
- package/dist/tools/errors.d.ts +13 -0
- package/dist/tools/errors.js +17 -0
- package/dist/tools/errors.js.map +1 -0
- package/dist/tools/index.d.ts +8 -0
- package/dist/tools/index.js +8 -0
- package/dist/tools/index.js.map +1 -0
- package/dist/tools/registry.d.ts +3 -0
- package/dist/tools/registry.js +234 -0
- package/dist/tools/registry.js.map +1 -0
- package/dist/tools/tool-search.d.ts +30 -0
- package/dist/tools/tool-search.js +118 -0
- package/dist/tools/tool-search.js.map +1 -0
- package/dist/tools/types.d.ts +106 -0
- package/dist/tools/types.js +2 -0
- package/dist/tools/types.js.map +1 -0
- package/llms.txt +435 -0
- package/package.json +119 -5
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The stdio transport: one client on a byte stream in each direction, one JSON-RPC message per line. It reads with the
|
|
3
|
+
* protocol's `JsonlFramer`, which splits on `\n` only, checks each message's envelope with `decode()`, and hands it to
|
|
4
|
+
* a dispatcher connection. What the server sends goes out through `encode()`. When the output is full, the connection's
|
|
5
|
+
* queue waits for it to drain before it hands over the next message. A client that stops reading therefore slows the
|
|
6
|
+
* server down instead of growing its memory, because the queue bounds what waits, as `outbox.ts` says. The input goes
|
|
7
|
+
* on being read meanwhile, and the connection's limit of 128 unanswered commands bounds what a client that sends
|
|
8
|
+
* without reading costs.
|
|
9
|
+
*
|
|
10
|
+
* The output carries protocol lines and nothing else. The transport's own diagnostics go to `log`, which a host points
|
|
11
|
+
* at stderr. The file is portable: it takes Node or Web streams by their shape and imports no Node module, so a Worker
|
|
12
|
+
* can serve it without a rewrite.
|
|
13
|
+
*/
|
|
14
|
+
import { ErrorCodes, JsonlFramer } from "@buildanagent/protocol";
|
|
15
|
+
import { checkWriteTimeout, messageOf, RpcSession } from "./rpc-session.js";
|
|
16
|
+
import { chunkReader, lineWriter, Stopper, } from "./stdio-streams.js";
|
|
17
|
+
const encoder = new TextEncoder();
|
|
18
|
+
/**
|
|
19
|
+
* Serves one client over a pair of byte streams, one JSON-RPC 2.0 message per line, and resolves once the client is
|
|
20
|
+
* done. `buildanagent rpc` calls it with `process.stdin`, `process.stdout` and a `log` that writes to stderr.
|
|
21
|
+
*
|
|
22
|
+
* Each line is read with the protocol's framer, which splits on `\n` only, and checked with `decode()`. A line that
|
|
23
|
+
* isn't JSON is answered with `ParseError`, and a message without a valid envelope, or a line over `maxLineBytes`,
|
|
24
|
+
* with `InvalidRequest`; the error carries the request's id when it could be read and `null` otherwise. A malformed
|
|
25
|
+
* response, one that carries `result` or `error`, is only logged, because JSON-RPC never answers a response. A bad
|
|
26
|
+
* line never ends the stream. The transport stops once 128 of its error answers wait on a full output, because the
|
|
27
|
+
* client is sending bad lines without reading.
|
|
28
|
+
*
|
|
29
|
+
* What the server sends waits for the output to take it, so a client that stops reading holds the server's queue, and
|
|
30
|
+
* the dispatcher drops live events past the queue size instead of buffering them.
|
|
31
|
+
*
|
|
32
|
+
* The end of the input is the client's goodbye. The transport answers every command it has read, waits until each
|
|
33
|
+
* line already sent is written, then closes the connection and resolves. A turn the client started goes on in the
|
|
34
|
+
* dispatcher, but its events have nowhere to go, so a client that wants `turn/settled` keeps its input open until that
|
|
35
|
+
* arrives. An input that fails is logged and then treated as an end. Once the input has ended, the output must take
|
|
36
|
+
* each queued line within `writeTimeoutMs`, 30 seconds by default; when one line takes longer, the transport stops and
|
|
37
|
+
* logs why. The transport resolves
|
|
38
|
+
* without waiting, and logs why, when the output fails or closes, when the dispatcher closes the connection or when
|
|
39
|
+
* `signal` aborts. It never ends, closes or cancels either stream: it removes its listeners and releases its locks,
|
|
40
|
+
* and the host owns the rest. A `writeTimeoutMs` that is not a whole number from 1 to 2,147,483,647 or `Infinity`
|
|
41
|
+
* rejects with a `HarnessError`, code `invalid_transport_options`, before the transport connects.
|
|
42
|
+
*/
|
|
43
|
+
export async function stdioTransport(dispatcher, io, options = {}) {
|
|
44
|
+
// Checked before the session connects, so a bad option leaves no connection behind.
|
|
45
|
+
const writeTimeoutMs = checkWriteTimeout(options.writeTimeoutMs);
|
|
46
|
+
await new StdioSession(dispatcher, io, options, writeTimeoutMs).run(options.signal);
|
|
47
|
+
}
|
|
48
|
+
/** One client's run of the transport: the connection, what it waits for, and why it stopped, if it stopped early. */
|
|
49
|
+
class StdioSession {
|
|
50
|
+
#log;
|
|
51
|
+
#stopper = new Stopper();
|
|
52
|
+
#writer;
|
|
53
|
+
#reader;
|
|
54
|
+
#framer;
|
|
55
|
+
#rpc;
|
|
56
|
+
#writeTimeoutMs;
|
|
57
|
+
/** Restarts the write timeout's clock while `#output()` waits, each time the output takes a line. */
|
|
58
|
+
#restart;
|
|
59
|
+
/**
|
|
60
|
+
* Connects first, because a closed dispatcher throws, and only then takes the streams, so a failure leaves neither a
|
|
61
|
+
* listener nor a lock on them. A stream that can't be taken, such as a locked Web stream, closes the connection and
|
|
62
|
+
* releases what was taken before it.
|
|
63
|
+
*/
|
|
64
|
+
constructor(dispatcher, io, options, writeTimeoutMs) {
|
|
65
|
+
this.#log = io.log ?? (() => undefined);
|
|
66
|
+
this.#writeTimeoutMs = writeTimeoutMs;
|
|
67
|
+
this.#framer = new JsonlFramer(options.maxLineBytes === undefined ? {} : { maxLineBytes: options.maxLineBytes });
|
|
68
|
+
this.#rpc = new RpcSession(dispatcher, {
|
|
69
|
+
label: "stdio",
|
|
70
|
+
log: this.#log,
|
|
71
|
+
write: (line) => this.#writer.write(encoder.encode(line)),
|
|
72
|
+
stop: (why) => this.#stopper.stop(why),
|
|
73
|
+
});
|
|
74
|
+
try {
|
|
75
|
+
this.#writer = lineWriter(io.output, this.#stopper, () => this.#restart?.());
|
|
76
|
+
}
|
|
77
|
+
catch (error) {
|
|
78
|
+
this.#rpc.close();
|
|
79
|
+
throw error;
|
|
80
|
+
}
|
|
81
|
+
try {
|
|
82
|
+
this.#reader = chunkReader(io.input);
|
|
83
|
+
}
|
|
84
|
+
catch (error) {
|
|
85
|
+
this.#writer.release();
|
|
86
|
+
this.#rpc.close();
|
|
87
|
+
throw error;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
async run(signal) {
|
|
91
|
+
const onAbort = () => this.#stopper.stop("the signal aborted");
|
|
92
|
+
if (signal?.aborted)
|
|
93
|
+
onAbort();
|
|
94
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
95
|
+
let reason;
|
|
96
|
+
try {
|
|
97
|
+
if (await this.#read())
|
|
98
|
+
await this.#drain();
|
|
99
|
+
}
|
|
100
|
+
finally {
|
|
101
|
+
reason = this.#stopper.reason;
|
|
102
|
+
signal?.removeEventListener("abort", onAbort);
|
|
103
|
+
this.#rpc.close();
|
|
104
|
+
this.#reader.release();
|
|
105
|
+
this.#writer.release();
|
|
106
|
+
// Ends any wait still subscribed, so nothing outlives the run.
|
|
107
|
+
this.#stopper.stop("the transport finished");
|
|
108
|
+
}
|
|
109
|
+
if (reason !== undefined)
|
|
110
|
+
this.#log(`stdio: stopped: ${reason}`);
|
|
111
|
+
}
|
|
112
|
+
/** Feeds the input to the framer until it ends or fails, which returns true, or the transport stops, which returns false. */
|
|
113
|
+
async #read() {
|
|
114
|
+
while (!this.#stopper.stopped) {
|
|
115
|
+
let next;
|
|
116
|
+
try {
|
|
117
|
+
next = await this.#stopper.until(this.#reader.next());
|
|
118
|
+
}
|
|
119
|
+
catch (error) {
|
|
120
|
+
// A failed input ends the client's stream as its end does, so what it sent is still answered.
|
|
121
|
+
this.#log(`stdio: the input failed: ${messageOf(error)}`);
|
|
122
|
+
return true;
|
|
123
|
+
}
|
|
124
|
+
if (next === undefined)
|
|
125
|
+
return false;
|
|
126
|
+
if (next.done) {
|
|
127
|
+
this.#take(this.#framer.end());
|
|
128
|
+
return true;
|
|
129
|
+
}
|
|
130
|
+
this.#take(this.#framer.push(typeof next.value === "string" ? encoder.encode(next.value) : next.value));
|
|
131
|
+
}
|
|
132
|
+
return false;
|
|
133
|
+
}
|
|
134
|
+
#take(framed) {
|
|
135
|
+
for (const result of framed) {
|
|
136
|
+
if (this.#stopper.stopped)
|
|
137
|
+
return;
|
|
138
|
+
if (result.ok)
|
|
139
|
+
this.#rpc.handle(result.value);
|
|
140
|
+
else
|
|
141
|
+
this.#rpc.refuse(result.error, ErrorCodes.ParseError, "a line");
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* Waits, after the input ended, for every command read to have its response queued, for the connection's queue to
|
|
146
|
+
* hand the last of them out, and for the output to write every line. Stops early if the transport is stopped. The
|
|
147
|
+
* commands take as long as their handlers do; only the waits on the output count against `writeTimeoutMs`.
|
|
148
|
+
*/
|
|
149
|
+
async #drain() {
|
|
150
|
+
while (this.#rpc.commands.size > 0 && !this.#stopper.stopped)
|
|
151
|
+
await this.#stopper.until(Promise.all([...this.#rpc.commands]));
|
|
152
|
+
// The queue hands a message out only after the last one's delivery settled, so wait until none is in flight.
|
|
153
|
+
for (let current = this.#rpc.delivering; current !== undefined && !this.#stopper.stopped; current = this.#rpc.delivering) {
|
|
154
|
+
await this.#output(current);
|
|
155
|
+
}
|
|
156
|
+
if (!this.#stopper.stopped)
|
|
157
|
+
await this.#output(this.#writer.flushed());
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* Waits for what `wait` waits on, or stops the transport once the output takes no line for `writeTimeoutMs`. The
|
|
161
|
+
* limit is per line: the timer restarts only when the output takes a whole line, because neither kind of output
|
|
162
|
+
* reports progress within one, so a single line that takes longer stops the transport however steadily the client
|
|
163
|
+
* reads it. The timer is cleared however the wait ends, so none outlives it.
|
|
164
|
+
*/
|
|
165
|
+
async #output(wait) {
|
|
166
|
+
const ms = this.#writeTimeoutMs;
|
|
167
|
+
if (ms === Number.POSITIVE_INFINITY) {
|
|
168
|
+
await this.#stopper.until(wait);
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
let timer;
|
|
172
|
+
const arm = () => {
|
|
173
|
+
globalThis.clearTimeout(timer);
|
|
174
|
+
timer = globalThis.setTimeout(() => {
|
|
175
|
+
this.#stopper.stop(`the output took no line for ${ms} ms after the input ended`);
|
|
176
|
+
}, ms);
|
|
177
|
+
};
|
|
178
|
+
this.#restart = arm;
|
|
179
|
+
arm();
|
|
180
|
+
try {
|
|
181
|
+
await this.#stopper.until(wait);
|
|
182
|
+
}
|
|
183
|
+
finally {
|
|
184
|
+
this.#restart = undefined;
|
|
185
|
+
globalThis.clearTimeout(timer);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
//# sourceMappingURL=stdio.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"stdio.js","sourceRoot":"","sources":["../../src/server/stdio.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AACH,OAAO,EAAE,UAAU,EAAsB,WAAW,EAAE,MAAM,wBAAwB,CAAC;AAErF,OAAO,EAAE,iBAAiB,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAC5E,OAAO,EAEL,WAAW,EAEX,UAAU,EAGV,OAAO,GACR,MAAM,oBAAoB,CAAC;AAoC5B,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;AAElC;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,MAAM,CAAC,KAAK,UAAU,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OAAO;QACT,CAAC;QACD,IAAI,KAA2D,CAAC;QAChE,MAAM,GAAG,GAAG,GAAG,EAAE;YACf,UAAU,CAAC,YAAY,CAAC,KAAK,CAAC,CAAC;YAC/B,KAAK,GAAG,UAAU,CAAC,UAAU,CAAC,GAAG,EAAE;gBACjC,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,+BAA+B,EAAE,2BAA2B,CAAC,CAAC;YACnF,CAAC,EAAE,EAAE,CAAC,CAAC;QACT,CAAC,CAAC;QACF,IAAI,CAAC,QAAQ,GAAG,GAAG,CAAC;QACpB,GAAG,EAAE,CAAC;QACN,IAAI,CAAC;YACH,MAAM,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QAClC,CAAC;gBAAS,CAAC;YACT,IAAI,CAAC,QAAQ,GAAG,SAAS,CAAC;YAC1B,UAAU,CAAC,YAAY,CAAC,KAAK,CAAC,CAAC;QACjC,CAAC;IACH,CAAC;CACF","sourcesContent":["/**\n * The stdio transport: one client on a byte stream in each direction, one JSON-RPC message per line. It reads with the\n * protocol's `JsonlFramer`, which splits on `\\n` only, checks each message's envelope with `decode()`, and hands it to\n * a dispatcher connection. What the server sends goes out through `encode()`. When the output is full, the connection's\n * queue waits for it to drain before it hands over the next message. A client that stops reading therefore slows the\n * server down instead of growing its memory, because the queue bounds what waits, as `outbox.ts` says. The input goes\n * on being read meanwhile, and the connection's limit of 128 unanswered commands bounds what a client that sends\n * without reading costs.\n *\n * The output carries protocol lines and nothing else. The transport's own diagnostics go to `log`, which a host points\n * at stderr. The file is portable: it takes Node or Web streams by their shape and imports no Node module, so a Worker\n * can serve it without a rewrite.\n */\nimport { ErrorCodes, type FramedMessage, JsonlFramer } from \"@buildanagent/protocol\";\nimport type { Dispatcher } from \"./dispatcher.js\";\nimport { checkWriteTimeout, messageOf, RpcSession } from \"./rpc-session.js\";\nimport {\n type ChunkReader,\n chunkReader,\n type LineWriter,\n lineWriter,\n type StdioInput,\n type StdioOutput,\n Stopper,\n} from \"./stdio-streams.js\";\n\nexport type { NodeInput, NodeOutput, StdioInput, StdioOutput } from \"./stdio-streams.js\";\n\n/** The streams `stdioTransport()` serves a client over. */\nexport interface StdioIo {\n /** What the client sends. Its end is the client's goodbye. */\n readonly input: StdioInput;\n /** What the server sends: protocol lines only. */\n readonly output: StdioOutput;\n /**\n * Takes one line of the transport's own diagnostics, such as a malformed line it answered with an error. Point it at\n * stderr, never at `output`. A line never holds what the client sent. Default: diagnostics are dropped.\n */\n readonly log?: (line: string) => void;\n}\n\n/** What `stdioTransport()` takes besides the dispatcher and the streams. */\nexport interface StdioOptions {\n /** The most bytes one input line may hold, newline excluded. A longer line is answered with an error. Default 8 MiB. */\n readonly maxLineBytes?: number;\n /** Stops the transport now: the connection closes, and nothing more is read or waited for. */\n readonly signal?: AbortSignal;\n /**\n * How long, in milliseconds, the output may take to take each queued line once the input has ended. The limit is per\n * line: the clock starts when the transport begins to wait for the output and restarts each time the output takes a\n * whole line, because an output reports no progress within a line. A client that goes on reading is therefore cut\n * off only when one line takes longer than this, so a host that sends very large lines to slow clients raises it. A\n * client that has closed its input and takes no line for this long ends the transport: it logs why and closes the\n * connection, as for a failed output. While the input is open there is no timeout, because the queue already bounds\n * what a slow client costs, and the time the dispatcher takes to answer a command does not count. A whole number\n * from 1 to 2,147,483,647, or `Infinity` to wait forever. Default 30,000 (30 seconds).\n */\n readonly writeTimeoutMs?: number;\n}\n\nconst encoder = new TextEncoder();\n\n/**\n * Serves one client over a pair of byte streams, one JSON-RPC 2.0 message per line, and resolves once the client is\n * done. `buildanagent rpc` calls it with `process.stdin`, `process.stdout` and a `log` that writes to stderr.\n *\n * Each line is read with the protocol's framer, which splits on `\\n` only, and checked with `decode()`. A line that\n * isn't JSON is answered with `ParseError`, and a message without a valid envelope, or a line over `maxLineBytes`,\n * with `InvalidRequest`; the error carries the request's id when it could be read and `null` otherwise. A malformed\n * response, one that carries `result` or `error`, is only logged, because JSON-RPC never answers a response. A bad\n * line never ends the stream. The transport stops once 128 of its error answers wait on a full output, because the\n * client is sending bad lines without reading.\n *\n * What the server sends waits for the output to take it, so a client that stops reading holds the server's queue, and\n * the dispatcher drops live events past the queue size instead of buffering them.\n *\n * The end of the input is the client's goodbye. The transport answers every command it has read, waits until each\n * line already sent is written, then closes the connection and resolves. A turn the client started goes on in the\n * dispatcher, but its events have nowhere to go, so a client that wants `turn/settled` keeps its input open until that\n * arrives. An input that fails is logged and then treated as an end. Once the input has ended, the output must take\n * each queued line within `writeTimeoutMs`, 30 seconds by default; when one line takes longer, the transport stops and\n * logs why. The transport resolves\n * without waiting, and logs why, when the output fails or closes, when the dispatcher closes the connection or when\n * `signal` aborts. It never ends, closes or cancels either stream: it removes its listeners and releases its locks,\n * and the host owns the rest. A `writeTimeoutMs` that is not a whole number from 1 to 2,147,483,647 or `Infinity`\n * rejects with a `HarnessError`, code `invalid_transport_options`, before the transport connects.\n */\nexport async function stdioTransport(dispatcher: Dispatcher, io: StdioIo, options: StdioOptions = {}): Promise<void> {\n // Checked before the session connects, so a bad option leaves no connection behind.\n const writeTimeoutMs = checkWriteTimeout(options.writeTimeoutMs);\n await new StdioSession(dispatcher, io, options, writeTimeoutMs).run(options.signal);\n}\n\n/** One client's run of the transport: the connection, what it waits for, and why it stopped, if it stopped early. */\nclass StdioSession {\n readonly #log: (line: string) => void;\n readonly #stopper = new Stopper();\n readonly #writer: LineWriter;\n readonly #reader: ChunkReader;\n readonly #framer: JsonlFramer;\n readonly #rpc: RpcSession;\n readonly #writeTimeoutMs: number;\n /** Restarts the write timeout's clock while `#output()` waits, each time the output takes a line. */\n #restart: (() => void) | undefined;\n\n /**\n * Connects first, because a closed dispatcher throws, and only then takes the streams, so a failure leaves neither a\n * listener nor a lock on them. A stream that can't be taken, such as a locked Web stream, closes the connection and\n * releases what was taken before it.\n */\n constructor(dispatcher: Dispatcher, io: StdioIo, options: StdioOptions, writeTimeoutMs: number) {\n this.#log = io.log ?? (() => undefined);\n this.#writeTimeoutMs = writeTimeoutMs;\n this.#framer = new JsonlFramer(options.maxLineBytes === undefined ? {} : { maxLineBytes: options.maxLineBytes });\n this.#rpc = new RpcSession(dispatcher, {\n label: \"stdio\",\n log: this.#log,\n write: (line) => this.#writer.write(encoder.encode(line)),\n stop: (why) => this.#stopper.stop(why),\n });\n try {\n this.#writer = lineWriter(io.output, this.#stopper, () => this.#restart?.());\n } catch (error) {\n this.#rpc.close();\n throw error;\n }\n try {\n this.#reader = chunkReader(io.input);\n } catch (error) {\n this.#writer.release();\n this.#rpc.close();\n throw error;\n }\n }\n\n async run(signal: AbortSignal | undefined): Promise<void> {\n const onAbort = () => this.#stopper.stop(\"the signal aborted\");\n if (signal?.aborted) onAbort();\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n let reason: string | undefined;\n try {\n if (await this.#read()) await this.#drain();\n } finally {\n reason = this.#stopper.reason;\n signal?.removeEventListener(\"abort\", onAbort);\n this.#rpc.close();\n this.#reader.release();\n this.#writer.release();\n // Ends any wait still subscribed, so nothing outlives the run.\n this.#stopper.stop(\"the transport finished\");\n }\n if (reason !== undefined) this.#log(`stdio: stopped: ${reason}`);\n }\n\n /** Feeds the input to the framer until it ends or fails, which returns true, or the transport stops, which returns false. */\n async #read(): Promise<boolean> {\n while (!this.#stopper.stopped) {\n let next: IteratorResult<Uint8Array | string, undefined> | undefined;\n try {\n next = await this.#stopper.until(this.#reader.next());\n } catch (error) {\n // A failed input ends the client's stream as its end does, so what it sent is still answered.\n this.#log(`stdio: the input failed: ${messageOf(error)}`);\n return true;\n }\n if (next === undefined) return false;\n if (next.done) {\n this.#take(this.#framer.end());\n return true;\n }\n this.#take(this.#framer.push(typeof next.value === \"string\" ? encoder.encode(next.value) : next.value));\n }\n return false;\n }\n\n #take(framed: readonly FramedMessage[]): void {\n for (const result of framed) {\n if (this.#stopper.stopped) return;\n if (result.ok) this.#rpc.handle(result.value);\n else this.#rpc.refuse(result.error, ErrorCodes.ParseError, \"a line\");\n }\n }\n\n /**\n * Waits, after the input ended, for every command read to have its response queued, for the connection's queue to\n * hand the last of them out, and for the output to write every line. Stops early if the transport is stopped. The\n * commands take as long as their handlers do; only the waits on the output count against `writeTimeoutMs`.\n */\n async #drain(): Promise<void> {\n while (this.#rpc.commands.size > 0 && !this.#stopper.stopped)\n await this.#stopper.until(Promise.all([...this.#rpc.commands]));\n // The queue hands a message out only after the last one's delivery settled, so wait until none is in flight.\n for (\n let current = this.#rpc.delivering;\n current !== undefined && !this.#stopper.stopped;\n current = this.#rpc.delivering\n ) {\n await this.#output(current);\n }\n if (!this.#stopper.stopped) await this.#output(this.#writer.flushed());\n }\n\n /**\n * Waits for what `wait` waits on, or stops the transport once the output takes no line for `writeTimeoutMs`. The\n * limit is per line: the timer restarts only when the output takes a whole line, because neither kind of output\n * reports progress within one, so a single line that takes longer stops the transport however steadily the client\n * reads it. The timer is cleared however the wait ends, so none outlives it.\n */\n async #output(wait: PromiseLike<void>): Promise<void> {\n const ms = this.#writeTimeoutMs;\n if (ms === Number.POSITIVE_INFINITY) {\n await this.#stopper.until(wait);\n return;\n }\n let timer: ReturnType<typeof globalThis.setTimeout> | undefined;\n const arm = () => {\n globalThis.clearTimeout(timer);\n timer = globalThis.setTimeout(() => {\n this.#stopper.stop(`the output took no line for ${ms} ms after the input ended`);\n }, ms);\n };\n this.#restart = arm;\n arm();\n try {\n await this.#stopper.until(wait);\n } finally {\n this.#restart = undefined;\n globalThis.clearTimeout(timer);\n }\n }\n}\n"]}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import type { Dispatcher } from "./dispatcher.js";
|
|
2
|
+
/** A message event as the transport reads it: `data` is a string for a text frame and anything else for binary. */
|
|
3
|
+
export interface WebSocketMessageEvent {
|
|
4
|
+
readonly data: unknown;
|
|
5
|
+
}
|
|
6
|
+
/** A close event as the transport reads it. Its `reason` is the peer's text, so the transport never logs it. */
|
|
7
|
+
export interface WebSocketCloseEvent {
|
|
8
|
+
readonly code: number;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* A WebSocket as the transport uses it: the methods of the standard `WebSocket` interface, which the global `WebSocket`
|
|
12
|
+
* of Node and browsers fits. A server-side socket must already be accepted and open when the transport takes it.
|
|
13
|
+
*/
|
|
14
|
+
export interface WebSocketLike {
|
|
15
|
+
/** 1 while the socket is open; 2 and 3 once it is closing or closed. */
|
|
16
|
+
readonly readyState: number;
|
|
17
|
+
/**
|
|
18
|
+
* The bytes sent but not yet handed to the network, which the transport's backpressure reads. A socket without it is
|
|
19
|
+
* taken never to be full, so the transport writes to it without waiting.
|
|
20
|
+
*/
|
|
21
|
+
readonly bufferedAmount?: number;
|
|
22
|
+
/** Sends one text frame. */
|
|
23
|
+
send(data: string): void;
|
|
24
|
+
/**
|
|
25
|
+
* Closes the socket with a status code and a short reason. It may throw for a code it refuses, as the standard
|
|
26
|
+
* `WebSocket` does for any code but 1000 and 3000 to 4999.
|
|
27
|
+
*/
|
|
28
|
+
close(code?: number, reason?: string): void;
|
|
29
|
+
/** Adds the listener the transport reads frames with. */
|
|
30
|
+
addEventListener(type: "message", listener: (event: WebSocketMessageEvent) => void): void;
|
|
31
|
+
/** Adds the listener that tells the transport the peer closed the socket. */
|
|
32
|
+
addEventListener(type: "close", listener: (event: WebSocketCloseEvent) => void): void;
|
|
33
|
+
/** Adds the listener that tells the transport the socket failed. */
|
|
34
|
+
addEventListener(type: "error", listener: (event: unknown) => void): void;
|
|
35
|
+
/** Removes the frame listener when the transport stops. */
|
|
36
|
+
removeEventListener(type: "message", listener: (event: WebSocketMessageEvent) => void): void;
|
|
37
|
+
/** Removes the close listener when the transport stops. */
|
|
38
|
+
removeEventListener(type: "close", listener: (event: WebSocketCloseEvent) => void): void;
|
|
39
|
+
/** Removes the failure listener when the transport stops. */
|
|
40
|
+
removeEventListener(type: "error", listener: (event: unknown) => void): void;
|
|
41
|
+
}
|
|
42
|
+
/** What `webSocketTransport()` takes besides the dispatcher and the socket. */
|
|
43
|
+
export interface WebSocketOptions {
|
|
44
|
+
/**
|
|
45
|
+
* The most bytes one frame may hold: a text frame counted as UTF-8 without one trailing `\n` and then one trailing
|
|
46
|
+
* `\r`, as the stdio transport counts a line, and a binary frame by its byte length, which the transport reads
|
|
47
|
+
* without reading the data. A longer frame is answered with `InvalidRequest`, and the transport then closes the
|
|
48
|
+
* socket with code 1009, or 4009 on a socket that refuses 1009. Default 8 MiB, the stdio transport's bound on a line.
|
|
49
|
+
*/
|
|
50
|
+
readonly maxMessageBytes?: number;
|
|
51
|
+
/**
|
|
52
|
+
* How many bytes may wait in the socket's send buffer before the transport waits for it to drain. While it waits,
|
|
53
|
+
* the connection's queue holds the next message and drops live events past its size. Default 1 MiB.
|
|
54
|
+
*/
|
|
55
|
+
readonly maxBufferedBytes?: number;
|
|
56
|
+
/**
|
|
57
|
+
* How long, in milliseconds, the send buffer may stay over `maxBufferedBytes` without shrinking. The clock restarts
|
|
58
|
+
* each time the buffer shrinks, so a peer that reads slowly is never cut off; one that reads nothing for this long
|
|
59
|
+
* stops the transport, which logs why and closes the socket with code 1008, or 4008 on a socket that refuses 1008.
|
|
60
|
+
* The buffer is checked every 25 ms, so the stop comes up to 25 ms late. A whole number from 1 to 2,147,483,647, or
|
|
61
|
+
* `Infinity` to wait forever. Default 30,000.
|
|
62
|
+
*/
|
|
63
|
+
readonly writeTimeoutMs?: number;
|
|
64
|
+
/** Stops the transport now: the connection closes, and the socket is closed with code 1000. */
|
|
65
|
+
readonly signal?: AbortSignal;
|
|
66
|
+
/**
|
|
67
|
+
* Takes one line of the transport's own diagnostics, such as a frame it answered with an error or why it stopped. A
|
|
68
|
+
* line never holds what the client sent. Default: diagnostics are dropped.
|
|
69
|
+
*/
|
|
70
|
+
readonly log?: (line: string) => void;
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Serves one client over one open WebSocket, one JSON-RPC 2.0 message per text frame, and resolves once the client is
|
|
74
|
+
* gone or the transport stops. The host accepts the socket, and whatever authenticates the peer happens there: the
|
|
75
|
+
* transport authenticates nobody, so whoever holds the socket acts as the dispatcher's user.
|
|
76
|
+
*
|
|
77
|
+
* Each frame must hold exactly one message, one line of JSON; a trailing newline is allowed and not needed. A frame
|
|
78
|
+
* that isn't JSON, or holds a lone surrogate, is answered with `ParseError`. A binary frame, a frame with more than one
|
|
79
|
+
* line or none, a batch, and a message without a valid envelope are answered with `InvalidRequest`. The transport
|
|
80
|
+
* never decodes a binary frame, so a binary, empty, multi-message or batch frame, and one that isn't JSON, is answered
|
|
81
|
+
* with a `null` id; a message whose envelope is bad but holds a valid id is answered with that id. A malformed
|
|
82
|
+
* response is only logged, because JSON-RPC never answers a response. None of these ends the transport, except a
|
|
83
|
+
* frame over `maxMessageBytes`, text or binary, after which the socket is closed with code 1009. The transport also
|
|
84
|
+
* stops once 128 of its error answers wait on a full send buffer. Each message the server sends is one text frame
|
|
85
|
+
* with no trailing newline.
|
|
86
|
+
*
|
|
87
|
+
* What the server sends waits while the socket's `bufferedAmount` is over `maxBufferedBytes`, so a client that stops
|
|
88
|
+
* reading holds the connection's queue, which drops live events past its size instead of buffering them. A buffer
|
|
89
|
+
* that does not shrink for `writeTimeoutMs` stops the transport.
|
|
90
|
+
*
|
|
91
|
+
* The transport serves one socket. A client that reconnects comes back on a new socket, which the host serves with a
|
|
92
|
+
* new call, and sends `session/open` with `fromSeq` to get the entries it missed; the dispatcher keeps the session,
|
|
93
|
+
* its running turn and its pending requests meanwhile.
|
|
94
|
+
*
|
|
95
|
+
* The peer's close, or a socket error, stops the transport, and it logs the close code but never the peer's reason.
|
|
96
|
+
* It closes the socket only when it stops itself: with 1008 when the client breaks a bound (128 error answers or
|
|
97
|
+
* refusals unread, or a send buffer that never drains), 1009 for a frame that is too big, 1011 when the socket's
|
|
98
|
+
* `send()` throws or the socket is still open after an error, and 1000 when `signal` aborts. The standard `WebSocket`
|
|
99
|
+
* lets a client close only with 1000 or 3000 to 4999, so the global `WebSocket` of Node and browsers throws for 1008,
|
|
100
|
+
* 1009 and 1011; a socket that throws for one of them is closed with 4008, 4009 or 4011 instead, with the same reason.
|
|
101
|
+
* A socket that throws for that code too is left as it is, and the transport logs the error's name, never its message,
|
|
102
|
+
* and still resolves. However it stops, it removes its listeners and closes the connection. A turn the client started
|
|
103
|
+
* goes on in the dispatcher. An option out of range, or a socket that is not open, rejects with a `HarnessError`, code
|
|
104
|
+
* `invalid_transport_options`, before the transport connects.
|
|
105
|
+
*/
|
|
106
|
+
export declare function webSocketTransport(dispatcher: Dispatcher, socket: WebSocketLike, options?: WebSocketOptions): Promise<void>;
|
|
@@ -0,0 +1,327 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The WebSocket transport: one client on one socket, one JSON-RPC message per text frame. It takes the socket by the
|
|
3
|
+
* standard `WebSocket` interface that Node and browsers share, so it needs no library and imports no Node module. Each
|
|
4
|
+
* frame goes through the protocol's `JsonlFramer` as one line, so the rules for `\r` and U+2028 are the stdio
|
|
5
|
+
* transport's, and then through the same `RpcSession` that stdio uses, so a bad message gets the same answer. A text
|
|
6
|
+
* frame arrives as a JavaScript string, never as bytes, so the framer's UTF-8 check can't fail; the transport refuses
|
|
7
|
+
* a string with a lone surrogate itself, because UTF-8 can't carry one.
|
|
8
|
+
*
|
|
9
|
+
* A socket reports no event when its send buffer empties, so the transport polls `bufferedAmount` while the buffer is
|
|
10
|
+
* over its bound. One poll timer runs at a time, shared by every message that waits, and it is cleared once there is
|
|
11
|
+
* room or the transport stops.
|
|
12
|
+
*/
|
|
13
|
+
import { ErrorCodes, JsonlFramer, ProtocolError } from "@buildanagent/protocol";
|
|
14
|
+
import { HarnessError } from "../errors.js";
|
|
15
|
+
import { checkWriteTimeout, RpcSession } from "./rpc-session.js";
|
|
16
|
+
import { Stopper } from "./stdio-streams.js";
|
|
17
|
+
const OPEN = 1;
|
|
18
|
+
const DEFAULT_MAX_MESSAGE_BYTES = 8 * 1024 * 1024;
|
|
19
|
+
const DEFAULT_MAX_BUFFERED_BYTES = 1024 * 1024;
|
|
20
|
+
/** How often a full send buffer is checked for room. */
|
|
21
|
+
const POLL_MS = 25;
|
|
22
|
+
/** WebSocket close codes (RFC 6455 §7.4.1). */
|
|
23
|
+
const NORMAL = 1000;
|
|
24
|
+
const POLICY_VIOLATION = 1008;
|
|
25
|
+
const MESSAGE_TOO_BIG = 1009;
|
|
26
|
+
const INTERNAL_ERROR = 1011;
|
|
27
|
+
/** Where the codes applications may use start (RFC 6455 §7.4.2): 1008 falls back to 4008. */
|
|
28
|
+
const APPLICATION_CODES = 4000;
|
|
29
|
+
/** A close frame's reason holds at most 123 bytes of UTF-8 (RFC 6455 §5.5.1). */
|
|
30
|
+
const MAX_CLOSE_REASON_BYTES = 123;
|
|
31
|
+
const encoder = new TextEncoder();
|
|
32
|
+
const NEWLINE = encoder.encode("\n");
|
|
33
|
+
/** `reason` cut to the bytes a close frame holds, on a whole character: `encodeInto()` writes only whole ones. */
|
|
34
|
+
function closeReason(reason) {
|
|
35
|
+
const { read } = encoder.encodeInto(reason, new Uint8Array(MAX_CLOSE_REASON_BYTES));
|
|
36
|
+
return reason.slice(0, read);
|
|
37
|
+
}
|
|
38
|
+
function checkBytes(name, value, fallback) {
|
|
39
|
+
if (value === undefined)
|
|
40
|
+
return fallback;
|
|
41
|
+
if (Number.isSafeInteger(value) && value > 0)
|
|
42
|
+
return value;
|
|
43
|
+
throw new HarnessError("invalid_transport_options", `${name} must be a whole number of at least 1, got ${value}`);
|
|
44
|
+
}
|
|
45
|
+
/** A refusal the transport makes of a frame itself, before any JSON is read. */
|
|
46
|
+
const refusal = (message) => new ProtocolError("invalid_request", message, { rpcCode: ErrorCodes.InvalidRequest, requestId: null });
|
|
47
|
+
/** A frame text with a lone surrogate, which has no UTF-8 form; `\p{Surrogate}` with `u` matches no paired one. */
|
|
48
|
+
const LONE_SURROGATE = /\p{Surrogate}/u;
|
|
49
|
+
/** The refusal of a frame UTF-8 can't carry, as the framer refuses a line that isn't UTF-8. */
|
|
50
|
+
const notUtf8 = () => new ProtocolError("invalid_json", "a frame is not valid UTF-8 JSON", {
|
|
51
|
+
rpcCode: ErrorCodes.ParseError,
|
|
52
|
+
requestId: null,
|
|
53
|
+
});
|
|
54
|
+
/**
|
|
55
|
+
* A binary frame's size in bytes, read from its `byteLength` (an `ArrayBuffer`, a typed array or a `Buffer`) or its
|
|
56
|
+
* `size` (a `Blob`) without reading its data, or `undefined` when it has neither.
|
|
57
|
+
*/
|
|
58
|
+
function binarySize(data) {
|
|
59
|
+
if (typeof data !== "object" || data === null)
|
|
60
|
+
return undefined;
|
|
61
|
+
const size = "byteLength" in data ? data.byteLength : "size" in data ? data.size : undefined;
|
|
62
|
+
return typeof size === "number" ? size : undefined;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* `text` without one trailing `\n` and then one trailing `\r`, which the framer drops from a stdio line before it
|
|
66
|
+
* counts the line, so a frame ending in `\r\n`, `\n` or a lone `\r` is bounded as that line is.
|
|
67
|
+
*/
|
|
68
|
+
function withoutNewline(text) {
|
|
69
|
+
const line = text.endsWith("\n") ? text.slice(0, -1) : text;
|
|
70
|
+
return line.endsWith("\r") ? line.slice(0, -1) : line;
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Serves one client over one open WebSocket, one JSON-RPC 2.0 message per text frame, and resolves once the client is
|
|
74
|
+
* gone or the transport stops. The host accepts the socket, and whatever authenticates the peer happens there: the
|
|
75
|
+
* transport authenticates nobody, so whoever holds the socket acts as the dispatcher's user.
|
|
76
|
+
*
|
|
77
|
+
* Each frame must hold exactly one message, one line of JSON; a trailing newline is allowed and not needed. A frame
|
|
78
|
+
* that isn't JSON, or holds a lone surrogate, is answered with `ParseError`. A binary frame, a frame with more than one
|
|
79
|
+
* line or none, a batch, and a message without a valid envelope are answered with `InvalidRequest`. The transport
|
|
80
|
+
* never decodes a binary frame, so a binary, empty, multi-message or batch frame, and one that isn't JSON, is answered
|
|
81
|
+
* with a `null` id; a message whose envelope is bad but holds a valid id is answered with that id. A malformed
|
|
82
|
+
* response is only logged, because JSON-RPC never answers a response. None of these ends the transport, except a
|
|
83
|
+
* frame over `maxMessageBytes`, text or binary, after which the socket is closed with code 1009. The transport also
|
|
84
|
+
* stops once 128 of its error answers wait on a full send buffer. Each message the server sends is one text frame
|
|
85
|
+
* with no trailing newline.
|
|
86
|
+
*
|
|
87
|
+
* What the server sends waits while the socket's `bufferedAmount` is over `maxBufferedBytes`, so a client that stops
|
|
88
|
+
* reading holds the connection's queue, which drops live events past its size instead of buffering them. A buffer
|
|
89
|
+
* that does not shrink for `writeTimeoutMs` stops the transport.
|
|
90
|
+
*
|
|
91
|
+
* The transport serves one socket. A client that reconnects comes back on a new socket, which the host serves with a
|
|
92
|
+
* new call, and sends `session/open` with `fromSeq` to get the entries it missed; the dispatcher keeps the session,
|
|
93
|
+
* its running turn and its pending requests meanwhile.
|
|
94
|
+
*
|
|
95
|
+
* The peer's close, or a socket error, stops the transport, and it logs the close code but never the peer's reason.
|
|
96
|
+
* It closes the socket only when it stops itself: with 1008 when the client breaks a bound (128 error answers or
|
|
97
|
+
* refusals unread, or a send buffer that never drains), 1009 for a frame that is too big, 1011 when the socket's
|
|
98
|
+
* `send()` throws or the socket is still open after an error, and 1000 when `signal` aborts. The standard `WebSocket`
|
|
99
|
+
* lets a client close only with 1000 or 3000 to 4999, so the global `WebSocket` of Node and browsers throws for 1008,
|
|
100
|
+
* 1009 and 1011; a socket that throws for one of them is closed with 4008, 4009 or 4011 instead, with the same reason.
|
|
101
|
+
* A socket that throws for that code too is left as it is, and the transport logs the error's name, never its message,
|
|
102
|
+
* and still resolves. However it stops, it removes its listeners and closes the connection. A turn the client started
|
|
103
|
+
* goes on in the dispatcher. An option out of range, or a socket that is not open, rejects with a `HarnessError`, code
|
|
104
|
+
* `invalid_transport_options`, before the transport connects.
|
|
105
|
+
*/
|
|
106
|
+
export async function webSocketTransport(dispatcher, socket, options = {}) {
|
|
107
|
+
const limits = {
|
|
108
|
+
maxMessageBytes: checkBytes("maxMessageBytes", options.maxMessageBytes, DEFAULT_MAX_MESSAGE_BYTES),
|
|
109
|
+
maxBufferedBytes: checkBytes("maxBufferedBytes", options.maxBufferedBytes, DEFAULT_MAX_BUFFERED_BYTES),
|
|
110
|
+
writeTimeoutMs: checkWriteTimeout(options.writeTimeoutMs),
|
|
111
|
+
};
|
|
112
|
+
if (socket.readyState !== OPEN) {
|
|
113
|
+
throw new HarnessError("invalid_transport_options", "the socket must be open when the transport takes it");
|
|
114
|
+
}
|
|
115
|
+
await new WebSocketSession(dispatcher, socket, options.log ?? (() => undefined), limits).run(options.signal);
|
|
116
|
+
}
|
|
117
|
+
/** One socket's run of the transport, and the close code it owes the socket if it stops itself. */
|
|
118
|
+
class WebSocketSession {
|
|
119
|
+
#socket;
|
|
120
|
+
#log;
|
|
121
|
+
#limits;
|
|
122
|
+
#stopper = new Stopper();
|
|
123
|
+
#framer;
|
|
124
|
+
#rpc;
|
|
125
|
+
/** The code to close the socket with once the run ends, or `undefined` when the peer already closed it. */
|
|
126
|
+
#closeCode = POLICY_VIOLATION;
|
|
127
|
+
/** The one wait for room while the send buffer is full, shared by every message sent meanwhile. */
|
|
128
|
+
#full;
|
|
129
|
+
constructor(dispatcher, socket, log, limits) {
|
|
130
|
+
this.#socket = socket;
|
|
131
|
+
this.#log = log;
|
|
132
|
+
this.#limits = limits;
|
|
133
|
+
// The frame is checked against the bound before it is framed, so the framer's own bound never cuts it.
|
|
134
|
+
this.#framer = new JsonlFramer({ maxLineBytes: limits.maxMessageBytes });
|
|
135
|
+
this.#rpc = new RpcSession(dispatcher, {
|
|
136
|
+
label: "websocket",
|
|
137
|
+
log,
|
|
138
|
+
write: (line) => this.#send(line),
|
|
139
|
+
// The client broke a bound, or the dispatcher closed the connection for refusals it left unread.
|
|
140
|
+
stop: (why) => this.#stop(why, POLICY_VIOLATION),
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
async run(signal) {
|
|
144
|
+
const stopped = new Promise((resolve) => this.#stopper.onStop(resolve));
|
|
145
|
+
const onMessage = (event) => this.#receive(event.data);
|
|
146
|
+
const onClose = (event) => {
|
|
147
|
+
const code = Number.isInteger(event.code) ? ` with code ${event.code}` : "";
|
|
148
|
+
this.#stop(`the peer closed the socket${code}`, undefined);
|
|
149
|
+
};
|
|
150
|
+
// A standard socket closes after an error, and #closeSocket skips one that is no longer open; an adapter whose
|
|
151
|
+
// socket stays open after an error is closed as a server failure.
|
|
152
|
+
const onError = () => this.#stop("the socket failed", INTERNAL_ERROR);
|
|
153
|
+
const onAbort = () => this.#stop("the signal aborted", NORMAL);
|
|
154
|
+
this.#socket.addEventListener("message", onMessage);
|
|
155
|
+
this.#socket.addEventListener("close", onClose);
|
|
156
|
+
this.#socket.addEventListener("error", onError);
|
|
157
|
+
if (signal?.aborted)
|
|
158
|
+
onAbort();
|
|
159
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
160
|
+
try {
|
|
161
|
+
await stopped;
|
|
162
|
+
}
|
|
163
|
+
finally {
|
|
164
|
+
signal?.removeEventListener("abort", onAbort);
|
|
165
|
+
this.#socket.removeEventListener("message", onMessage);
|
|
166
|
+
this.#socket.removeEventListener("close", onClose);
|
|
167
|
+
this.#socket.removeEventListener("error", onError);
|
|
168
|
+
this.#rpc.close();
|
|
169
|
+
}
|
|
170
|
+
const reason = this.#stopper.reason ?? "the transport finished";
|
|
171
|
+
this.#closeSocket(reason);
|
|
172
|
+
this.#log(`websocket: stopped: ${reason}`);
|
|
173
|
+
}
|
|
174
|
+
/** Stops the run once, remembering the close code the socket is owed: `undefined` when the peer already closed it. */
|
|
175
|
+
#stop(why, closeCode) {
|
|
176
|
+
if (this.#stopper.stopped)
|
|
177
|
+
return;
|
|
178
|
+
this.#closeCode = closeCode;
|
|
179
|
+
this.#stopper.stop(why);
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* Closes the socket with the code it is owed. The standard `WebSocket` lets a client close only with 1000 or 3000 to
|
|
183
|
+
* 4999 and throws for any other code, so a socket that refuses 1008, 1009 or 1011 is closed with 4008, 4009 or 4011,
|
|
184
|
+
* the same code in the range applications may use.
|
|
185
|
+
*/
|
|
186
|
+
#closeSocket(reason) {
|
|
187
|
+
const code = this.#closeCode;
|
|
188
|
+
if (code === undefined || this.#socket.readyState !== OPEN)
|
|
189
|
+
return;
|
|
190
|
+
const text = closeReason(reason);
|
|
191
|
+
let failure = this.#tryClose(code, text);
|
|
192
|
+
if (failure !== undefined && code !== NORMAL)
|
|
193
|
+
failure = this.#tryClose(APPLICATION_CODES + (code - NORMAL), text);
|
|
194
|
+
if (failure === undefined)
|
|
195
|
+
return;
|
|
196
|
+
const name = failure instanceof Error ? failure.name : "unknown error";
|
|
197
|
+
this.#log(`websocket: the socket could not be closed: ${name}`);
|
|
198
|
+
}
|
|
199
|
+
/** Calls `close()`, and returns what it threw, or `undefined` once it closed. */
|
|
200
|
+
#tryClose(code, reason) {
|
|
201
|
+
try {
|
|
202
|
+
this.#socket.close(code, reason);
|
|
203
|
+
return undefined;
|
|
204
|
+
}
|
|
205
|
+
catch (error) {
|
|
206
|
+
return error ?? new Error("close() threw");
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
/** Reads one frame: refuses what is not one text message, and hands the message to the session. */
|
|
210
|
+
#receive(data) {
|
|
211
|
+
if (this.#stopper.stopped)
|
|
212
|
+
return;
|
|
213
|
+
if (typeof data !== "string") {
|
|
214
|
+
this.#refuseBinary(data);
|
|
215
|
+
return;
|
|
216
|
+
}
|
|
217
|
+
const text = withoutNewline(data);
|
|
218
|
+
if (this.#tooBig(text)) {
|
|
219
|
+
this.#refuseTooBig();
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
222
|
+
// `TextEncoder` would write a lone surrogate as U+FFFD, so the frame is refused as stdio refuses bad UTF-8.
|
|
223
|
+
if (LONE_SURROGATE.test(text)) {
|
|
224
|
+
this.#rpc.refuse(notUtf8(), ErrorCodes.ParseError, "a frame");
|
|
225
|
+
return;
|
|
226
|
+
}
|
|
227
|
+
// The framer skips blank lines, so a newline left after the trailing one is refused here, before framing.
|
|
228
|
+
if (text.includes("\n")) {
|
|
229
|
+
this.#rpc.refuse(refusal("a frame must hold one message, on one line"), ErrorCodes.InvalidRequest, "a frame");
|
|
230
|
+
return;
|
|
231
|
+
}
|
|
232
|
+
const framed = this.#framer.push(encoder.encode(text));
|
|
233
|
+
framed.push(...this.#framer.push(NEWLINE));
|
|
234
|
+
// With no newline inside, the frame is one line: blank, which the framer skips, or one message.
|
|
235
|
+
const [only] = framed;
|
|
236
|
+
if (only === undefined) {
|
|
237
|
+
this.#rpc.refuse(refusal("a frame must hold a message"), ErrorCodes.InvalidRequest, "a frame");
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
240
|
+
if (only.ok)
|
|
241
|
+
this.#rpc.handle(only.value);
|
|
242
|
+
else
|
|
243
|
+
this.#rpc.refuse(only.error, ErrorCodes.ParseError, "a frame");
|
|
244
|
+
}
|
|
245
|
+
/** Refuses a binary frame, without reading its data: a frame over the bound also stops the transport. */
|
|
246
|
+
#refuseBinary(data) {
|
|
247
|
+
const size = binarySize(data);
|
|
248
|
+
if (size !== undefined && size > this.#limits.maxMessageBytes)
|
|
249
|
+
this.#refuseTooBig();
|
|
250
|
+
else
|
|
251
|
+
this.#rpc.refuse(refusal("a frame must be text, not binary"), ErrorCodes.InvalidRequest, "a frame");
|
|
252
|
+
}
|
|
253
|
+
/** Answers a frame over the bound, then stops the transport, which closes the socket with 1009. */
|
|
254
|
+
#refuseTooBig() {
|
|
255
|
+
const why = `a frame went over the bound of ${this.#limits.maxMessageBytes} bytes`;
|
|
256
|
+
this.#rpc.refuse(refusal(why), ErrorCodes.InvalidRequest, "a frame");
|
|
257
|
+
this.#stop(why, MESSAGE_TOO_BIG);
|
|
258
|
+
}
|
|
259
|
+
/** Whether `text` holds more UTF-8 bytes than the bound, encoding it only when its length can't tell. */
|
|
260
|
+
#tooBig(text) {
|
|
261
|
+
const bound = this.#limits.maxMessageBytes;
|
|
262
|
+
// A UTF-16 code unit takes one to three bytes, and a pair of them four.
|
|
263
|
+
if (text.length > bound)
|
|
264
|
+
return true;
|
|
265
|
+
if (text.length * 3 <= bound)
|
|
266
|
+
return false;
|
|
267
|
+
return encoder.encode(text).length > bound;
|
|
268
|
+
}
|
|
269
|
+
/** Sends one line as a frame and, when the send buffer is over its bound, returns the wait for room. */
|
|
270
|
+
#send(line) {
|
|
271
|
+
if (this.#stopper.stopped)
|
|
272
|
+
return undefined;
|
|
273
|
+
try {
|
|
274
|
+
// `encode()` ends the line with `\n`; a frame is already one message, so it goes without.
|
|
275
|
+
this.#socket.send(line.slice(0, -1));
|
|
276
|
+
}
|
|
277
|
+
catch (error) {
|
|
278
|
+
// The socket may still be open, so it is closed as a server failure; the error's message is not logged.
|
|
279
|
+
this.#stop(`the socket refused a frame: ${error instanceof Error ? error.name : "unknown error"}`, INTERNAL_ERROR);
|
|
280
|
+
return undefined;
|
|
281
|
+
}
|
|
282
|
+
if (this.#buffered() <= this.#limits.maxBufferedBytes)
|
|
283
|
+
return undefined;
|
|
284
|
+
this.#full ??= this.#room();
|
|
285
|
+
return this.#full;
|
|
286
|
+
}
|
|
287
|
+
#buffered() {
|
|
288
|
+
const amount = this.#socket.bufferedAmount;
|
|
289
|
+
return typeof amount === "number" && Number.isFinite(amount) ? amount : 0;
|
|
290
|
+
}
|
|
291
|
+
/**
|
|
292
|
+
* Resolves once the send buffer is back within its bound, or the transport stops. It checks every 25 ms with one
|
|
293
|
+
* timer at a time, and stops the transport once the buffer has not shrunk for `writeTimeoutMs`. The timer is cleared
|
|
294
|
+
* however the wait ends.
|
|
295
|
+
*/
|
|
296
|
+
#room() {
|
|
297
|
+
return new Promise((resolve) => {
|
|
298
|
+
let timer;
|
|
299
|
+
let last = this.#buffered();
|
|
300
|
+
let idleMs = 0;
|
|
301
|
+
const done = () => {
|
|
302
|
+
globalThis.clearTimeout(timer);
|
|
303
|
+
off();
|
|
304
|
+
this.#full = undefined;
|
|
305
|
+
resolve();
|
|
306
|
+
};
|
|
307
|
+
const off = this.#stopper.onStop(done);
|
|
308
|
+
const poll = () => {
|
|
309
|
+
const now = this.#buffered();
|
|
310
|
+
if (now <= this.#limits.maxBufferedBytes) {
|
|
311
|
+
done();
|
|
312
|
+
return;
|
|
313
|
+
}
|
|
314
|
+
idleMs = now < last ? 0 : idleMs + POLL_MS;
|
|
315
|
+
last = now;
|
|
316
|
+
if (idleMs >= this.#limits.writeTimeoutMs) {
|
|
317
|
+
// Stopping ends this wait through `done`.
|
|
318
|
+
this.#stop(`the peer read nothing for ${this.#limits.writeTimeoutMs} ms`, POLICY_VIOLATION);
|
|
319
|
+
return;
|
|
320
|
+
}
|
|
321
|
+
timer = globalThis.setTimeout(poll, POLL_MS);
|
|
322
|
+
};
|
|
323
|
+
timer = globalThis.setTimeout(poll, POLL_MS);
|
|
324
|
+
});
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
//# sourceMappingURL=websocket.js.map
|