@sealant/sdk-next 0.40.0-next.983 → 0.40.0-next.986
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/effect/http.d.ts +17 -1
- package/dist/effect/http.js +21 -2
- package/dist/effect/sessions/attach.js +46 -10
- package/dist/effect/sessions/layer.js +69 -12
- package/dist/effect/sessions/service.d.ts +13 -6
- package/dist/facade/record.d.ts +6 -0
- package/dist/facade/record.js +34 -18
- package/dist/facade/session.d.ts +6 -0
- package/dist/facade/session.js +33 -3
- package/dist/types.d.ts +5 -0
- package/package.json +3 -3
package/dist/effect/http.d.ts
CHANGED
|
@@ -6,8 +6,12 @@
|
|
|
6
6
|
*
|
|
7
7
|
* A request carries the same headers as every contract call (priority, trace, API key) and goes
|
|
8
8
|
* through the same `HttpClient`, but not the retry middleware: a stream reconnects itself.
|
|
9
|
+
*
|
|
10
|
+
* Every route sends a `: ping` comment every 15 seconds, so a body that sends nothing for
|
|
11
|
+
* {@link SSE_IDLE_TIMEOUT} is a connection that died without closing (a laptop that slept, a NAT or
|
|
12
|
+
* proxy that dropped it): it fails as cut, and the caller reconnects, instead of waiting forever.
|
|
9
13
|
*/
|
|
10
|
-
import { Context, Layer, Stream } from "effect";
|
|
14
|
+
import { Duration, Context, Effect, Layer, Stream } from "effect";
|
|
11
15
|
import { Sse } from "effect/encoding";
|
|
12
16
|
import { HttpClient } from "effect/http";
|
|
13
17
|
import { SealantConfig } from "./config.js";
|
|
@@ -25,7 +29,19 @@ export interface SseConnectOptions {
|
|
|
25
29
|
readonly path: string;
|
|
26
30
|
readonly query: Readonly<Record<string, string | undefined>>;
|
|
27
31
|
readonly headers?: Readonly<Record<string, string>>;
|
|
32
|
+
/**
|
|
33
|
+
* How long the body may send nothing, not even a keep-alive comment, before the connection is
|
|
34
|
+
* taken for dead and fails with `SealantTransportError`. Default {@link SSE_IDLE_TIMEOUT}.
|
|
35
|
+
*/
|
|
36
|
+
readonly idleTimeout?: Duration.Input;
|
|
37
|
+
/** Runs once the server has answered with an event stream, before its first event. */
|
|
38
|
+
readonly onOpen?: Effect.Effect<void>;
|
|
28
39
|
}
|
|
40
|
+
/**
|
|
41
|
+
* The default {@link SseConnectOptions.idleTimeout}: three of the control plane's 15-second
|
|
42
|
+
* keep-alive comments missed in a row.
|
|
43
|
+
*/
|
|
44
|
+
export declare const SSE_IDLE_TIMEOUT: Duration.Duration;
|
|
29
45
|
export interface SseClientShape {
|
|
30
46
|
/**
|
|
31
47
|
* One connection's events, ending when the body ends. A refusal a retry cannot change (4xx other
|
package/dist/effect/http.js
CHANGED
|
@@ -6,14 +6,23 @@
|
|
|
6
6
|
*
|
|
7
7
|
* A request carries the same headers as every contract call (priority, trace, API key) and goes
|
|
8
8
|
* through the same `HttpClient`, but not the retry middleware: a stream reconnects itself.
|
|
9
|
+
*
|
|
10
|
+
* Every route sends a `: ping` comment every 15 seconds, so a body that sends nothing for
|
|
11
|
+
* {@link SSE_IDLE_TIMEOUT} is a connection that died without closing (a laptop that slept, a NAT or
|
|
12
|
+
* proxy that dropped it): it fails as cut, and the caller reconnects, instead of waiting forever.
|
|
9
13
|
*/
|
|
10
|
-
import { Context, Effect, Layer, Stream } from "effect";
|
|
14
|
+
import { Duration, Context, Effect, Layer, Stream } from "effect";
|
|
11
15
|
import { Sse } from "effect/encoding";
|
|
12
16
|
import { HttpClient, HttpClientRequest } from "effect/http";
|
|
13
17
|
import { authorize, HostRequestPriority } from "./api-client.js";
|
|
14
18
|
import { SealantConfig } from "./config.js";
|
|
15
19
|
import { SealantStreamRefusedError, SealantTransportError } from "./errors.js";
|
|
16
20
|
import { traceCall } from "./trace.js";
|
|
21
|
+
/**
|
|
22
|
+
* The default {@link SseConnectOptions.idleTimeout}: three of the control plane's 15-second
|
|
23
|
+
* keep-alive comments missed in a row.
|
|
24
|
+
*/
|
|
25
|
+
export const SSE_IDLE_TIMEOUT = Duration.seconds(45);
|
|
17
26
|
/** Statuses after which asking again could get another answer. */
|
|
18
27
|
const mayChange = (status) => status === 408 || status === 429 || status >= 500;
|
|
19
28
|
const refusal = (options, response) => Effect.flatMap(response.text.pipe(Effect.orElseSucceed(() => "")), (body) => {
|
|
@@ -58,7 +67,17 @@ const make = Effect.gen(function* () {
|
|
|
58
67
|
}
|
|
59
68
|
return Effect.succeed(response);
|
|
60
69
|
}));
|
|
61
|
-
|
|
70
|
+
const idleTimeout = options.idleTimeout ?? SSE_IDLE_TIMEOUT;
|
|
71
|
+
const idle = () => Stream.fail(new SealantTransportError({
|
|
72
|
+
operation: stream,
|
|
73
|
+
message: `${stream} sent nothing for ${Duration.format(Duration.fromInputUnsafe(idleTimeout))}; the connection is taken for dead.`,
|
|
74
|
+
cause: undefined,
|
|
75
|
+
}));
|
|
76
|
+
const onOpen = options.onOpen;
|
|
77
|
+
const body = Effect.map(onOpen === undefined ? open : Effect.tap(open, () => onOpen),
|
|
78
|
+
// Timed per read of the body, so a keep-alive comment counts as much as an event.
|
|
79
|
+
(response) => response.stream.pipe(Stream.timeoutOrElse({ duration: idleTimeout, orElse: idle })));
|
|
80
|
+
return Stream.unwrap(body).pipe(Stream.decodeText(), Stream.pipeThroughChannel(Sse.decode()), Stream.mapError((cause) => {
|
|
62
81
|
if (cause instanceof SealantTransportError || cause instanceof SealantStreamRefusedError)
|
|
63
82
|
return cause;
|
|
64
83
|
return new SealantTransportError({
|
|
@@ -11,9 +11,13 @@
|
|
|
11
11
|
* One `Socket` dials a new WebSocket for each connection, its URL read when it dials: every
|
|
12
12
|
* connection asks for the sequence after the last record delivered, so a socket closed without
|
|
13
13
|
* `end` is reopened where it stopped, and a record replayed twice is dropped. A record whose
|
|
14
|
-
* sequence is past the one asked for carries `skippedFrom`: the records between are gone
|
|
15
|
-
*
|
|
16
|
-
*
|
|
14
|
+
* sequence is past the one asked for carries `skippedFrom`: the records between are gone, and so
|
|
15
|
+
* does the record after a `skipped` frame. Records skipped just before the session's `end` get a
|
|
16
|
+
* chunk of their own with no bytes. The socket's writer waits while it is reopening, so input sent
|
|
17
|
+
* across a cut is delivered once it is back. A close with 1008 (the credential was revoked or
|
|
18
|
+
* expired) is not reopened. A connection that stayed open for {@link HEALTHY_CONNECTION} before
|
|
19
|
+
* it was cut starts the count of cuts in a row again, so a session held open for hours behind a
|
|
20
|
+
* proxy that closes idle sockets is not given up on.
|
|
17
21
|
*
|
|
18
22
|
* `output` holds at most {@link MAX_QUEUED_RECORDS} unread records. The socket is read whether or
|
|
19
23
|
* not anyone reads `output`, so `end` always reaches `exit`; a reader that falls further behind
|
|
@@ -21,7 +25,7 @@
|
|
|
21
25
|
* `resize` and `signal` carry on.
|
|
22
26
|
*/
|
|
23
27
|
import { sessionAttachServerFrameSchema, } from "@sealant/api-contracts";
|
|
24
|
-
import { Cause, Deferred, Duration, Effect, Option, Queue, Random, Redacted, Ref, Schema, Stream, } from "effect";
|
|
28
|
+
import { Cause, Clock, Deferred, Duration, Effect, Option, Queue, Random, Redacted, Ref, Schema, Stream, } from "effect";
|
|
25
29
|
import { Socket } from "effect/socket";
|
|
26
30
|
import { SessionAttachError, SessionEndedError } from "../errors.js";
|
|
27
31
|
const decodeServerFrame = Schema.decodeUnknownOption(Schema.fromJsonString(sessionAttachServerFrameSchema));
|
|
@@ -34,6 +38,8 @@ export const MAX_QUEUED_RECORDS = 8192;
|
|
|
34
38
|
const POLICY_VIOLATION = 1008;
|
|
35
39
|
/** Cuts in a row with no record received before the attachment gives up. */
|
|
36
40
|
const MAX_RECONNECTS = 8;
|
|
41
|
+
/** A connection open this long before it was cut was healthy: the count of cuts starts again. */
|
|
42
|
+
const HEALTHY_CONNECTION = Duration.seconds(30);
|
|
37
43
|
const RECONNECT_FIRST = Duration.millis(100);
|
|
38
44
|
const RECONNECT_MAX = Duration.seconds(5);
|
|
39
45
|
const OPEN_TIMEOUT = Duration.seconds(10);
|
|
@@ -55,6 +61,10 @@ export const attachSession = (target) => Effect.gen(function* () {
|
|
|
55
61
|
// The next sequence the consumer has not been given: what a reconnect asks for.
|
|
56
62
|
const next = yield* Ref.make(target.fromSequence);
|
|
57
63
|
const cuts = yield* Ref.make(0);
|
|
64
|
+
// Where records a `skipped` frame said are gone began, until a record or `end` says so.
|
|
65
|
+
let skippedFrom;
|
|
66
|
+
// When the connection being read opened, for telling a healthy one from one that failed at once.
|
|
67
|
+
let openedAt;
|
|
58
68
|
// Bounded, and never waited on: a consumer that reads `exit` and not `output` must not keep
|
|
59
69
|
// the `end` frame from being read. A record that finds it full fails `output` instead.
|
|
60
70
|
const output = yield* Queue.dropping(MAX_QUEUED_RECORDS);
|
|
@@ -77,6 +87,7 @@ export const attachSession = (target) => Effect.gen(function* () {
|
|
|
77
87
|
/** One connection: frames until the session's `end` or the socket closes. */
|
|
78
88
|
const connection = Effect.scoped(Effect.gen(function* () {
|
|
79
89
|
const reader = yield* socket.reader;
|
|
90
|
+
openedAt = yield* Clock.currentTimeMillis;
|
|
80
91
|
yield* Deferred.succeed(opened, undefined);
|
|
81
92
|
// The sequence a `seq` frame named for the binary frame after it.
|
|
82
93
|
let named;
|
|
@@ -90,13 +101,29 @@ export const attachSession = (target) => Effect.gen(function* () {
|
|
|
90
101
|
const server = decoded.value;
|
|
91
102
|
if (server.t === "seq")
|
|
92
103
|
named = BigInt(server.sequence);
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
104
|
+
else if (server.t === "skipped") {
|
|
105
|
+
const to = BigInt(server.to);
|
|
106
|
+
const wanted = yield* Ref.get(next);
|
|
107
|
+
if (to > wanted) {
|
|
108
|
+
skippedFrom ??= wanted;
|
|
109
|
+
yield* Ref.set(next, to);
|
|
110
|
+
yield* Ref.set(cuts, 0);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
96
113
|
else if (server.t === "error") {
|
|
97
114
|
yield* Effect.logWarning("The control plane refused a frame on the attach socket").pipe(Effect.annotateLogs({ sessionId, message: server.message }));
|
|
98
115
|
}
|
|
99
116
|
else {
|
|
117
|
+
// Records skipped just before the end are said by a chunk with no bytes.
|
|
118
|
+
if (skippedFrom !== undefined && !overflowed) {
|
|
119
|
+
const sequence = yield* Ref.get(next);
|
|
120
|
+
yield* Queue.offer(output, {
|
|
121
|
+
sequence,
|
|
122
|
+
data: new Uint8Array(0),
|
|
123
|
+
skippedFrom,
|
|
124
|
+
});
|
|
125
|
+
skippedFrom = undefined;
|
|
126
|
+
}
|
|
100
127
|
const { t: _t, ...ended } = server;
|
|
101
128
|
yield* Deferred.succeed(exit, ended);
|
|
102
129
|
return { kind: "ended" };
|
|
@@ -109,9 +136,11 @@ export const attachSession = (target) => Effect.gen(function* () {
|
|
|
109
136
|
// Replayed after a reconnect but already delivered: once is enough.
|
|
110
137
|
if (sequence < wanted)
|
|
111
138
|
continue;
|
|
112
|
-
const
|
|
113
|
-
|
|
114
|
-
|
|
139
|
+
const from = skippedFrom ?? (sequence > wanted ? wanted : undefined);
|
|
140
|
+
skippedFrom = undefined;
|
|
141
|
+
const chunk = from === undefined
|
|
142
|
+
? { sequence, data: frame }
|
|
143
|
+
: { sequence, data: frame, skippedFrom: from };
|
|
115
144
|
if (!overflowed && !(yield* Queue.offer(output, chunk))) {
|
|
116
145
|
overflowed = true;
|
|
117
146
|
yield* Queue.fail(output, new SessionAttachError({
|
|
@@ -153,6 +182,13 @@ export const attachSession = (target) => Effect.gen(function* () {
|
|
|
153
182
|
}));
|
|
154
183
|
return;
|
|
155
184
|
}
|
|
185
|
+
// A connection that stayed open a while was healthy whatever cut it (a proxy that closes
|
|
186
|
+
// idle sockets, a deploy): only cuts in quick succession count to the limit.
|
|
187
|
+
const now = yield* Clock.currentTimeMillis;
|
|
188
|
+
if (openedAt !== undefined && now - openedAt >= Duration.toMillis(HEALTHY_CONNECTION)) {
|
|
189
|
+
yield* Ref.set(cuts, 0);
|
|
190
|
+
}
|
|
191
|
+
openedAt = undefined;
|
|
156
192
|
const attempt = yield* Ref.getAndUpdate(cuts, (n) => n + 1);
|
|
157
193
|
if (attempt >= MAX_RECONNECTS) {
|
|
158
194
|
yield* failWith(new SessionAttachError({
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Duration, Effect, Layer, Option, Random, Ref, Stream } from "effect";
|
|
1
|
+
import { Clock, Duration, Effect, Layer, Option, Random, Ref, Schema, Stream } from "effect";
|
|
2
2
|
import { Socket } from "effect/socket";
|
|
3
3
|
import { CurrentRequestPriority, SealantApiClient } from "../api-client.js";
|
|
4
4
|
import { SealantConfig } from "../config.js";
|
|
@@ -13,10 +13,20 @@ const fromBase64 = (value) => {
|
|
|
13
13
|
const buffer = Buffer.from(value, "base64");
|
|
14
14
|
return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
|
|
15
15
|
};
|
|
16
|
-
/**
|
|
16
|
+
/**
|
|
17
|
+
* Cuts in a row with nothing received before `output` fails with the last. A connection that
|
|
18
|
+
* stayed open for {@link HEALTHY_CONNECTION} starts the count again.
|
|
19
|
+
*/
|
|
17
20
|
const OUTPUT_RECONNECTS = 10;
|
|
18
21
|
const OUTPUT_RECONNECT_FIRST = Duration.millis(250);
|
|
19
22
|
const OUTPUT_RECONNECT_MAX = Duration.seconds(5);
|
|
23
|
+
/**
|
|
24
|
+
* A connection open this long before it was cut was healthy: the cut is the network's or a
|
|
25
|
+
* proxy's, not a sign the stream cannot be read, and the count of cuts in a row starts again.
|
|
26
|
+
*/
|
|
27
|
+
const HEALTHY_CONNECTION = Duration.seconds(30);
|
|
28
|
+
/** A `skipped` event's data: records `from`..`to`-1 are gone. */
|
|
29
|
+
const decodeSkipped = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Struct({ from: Schema.String, to: Schema.String })));
|
|
20
30
|
const OUTPUT_ROUTE = { method: "GET", path: "/v1/sessions/:sessionId/output/stream" };
|
|
21
31
|
export const make = Effect.gen(function* () {
|
|
22
32
|
const client = yield* SealantApiClient;
|
|
@@ -85,31 +95,78 @@ export const make = Effect.gen(function* () {
|
|
|
85
95
|
const ownerUserId = yield* owner;
|
|
86
96
|
// The next sequence the consumer has not been given: what a reconnect asks for.
|
|
87
97
|
const next = yield* Ref.make(options.fromSequence ?? 0n);
|
|
98
|
+
// Where output the server said is gone (`skipped`) began, until a chunk or the end says so.
|
|
99
|
+
const skipped = yield* Ref.make(undefined);
|
|
88
100
|
const cuts = yield* Ref.make(0);
|
|
89
101
|
const ended = yield* Ref.make(false);
|
|
102
|
+
// When the connection being read answered, for telling a cut after a healthy stretch from
|
|
103
|
+
// one that failed at once.
|
|
104
|
+
const openedAt = yield* Ref.make(undefined);
|
|
90
105
|
const connection = Stream.unwrap(Effect.map(Ref.get(next), (from) => sse.connect({
|
|
91
106
|
route: OUTPUT_ROUTE,
|
|
92
107
|
span: "sealant.sdk.sessions.output_stream",
|
|
93
108
|
path: `/v1/sessions/${encodeURIComponent(sessionId)}/output/stream`,
|
|
94
109
|
query: { fromSequence: from.toString(), ownerUserId },
|
|
110
|
+
onOpen: Effect.flatMap(Clock.currentTimeMillis, (now) => Ref.set(openedAt, now)),
|
|
95
111
|
})));
|
|
96
|
-
|
|
97
|
-
const deliver = (
|
|
112
|
+
/** A record: dropped when already delivered, else carrying where any skipped run began. */
|
|
113
|
+
const deliver = (sequence, data) => Effect.gen(function* () {
|
|
98
114
|
const wanted = yield* Ref.get(next);
|
|
99
115
|
// Replayed after a reconnect but already delivered: once is enough.
|
|
100
|
-
if (
|
|
101
|
-
return
|
|
102
|
-
yield* Ref.set(next,
|
|
116
|
+
if (sequence < wanted)
|
|
117
|
+
return [];
|
|
118
|
+
yield* Ref.set(next, sequence + 1n);
|
|
103
119
|
yield* Ref.set(cuts, 0);
|
|
104
|
-
|
|
120
|
+
const from = yield* Ref.getAndSet(skipped, undefined);
|
|
121
|
+
const skippedFrom = from ?? (sequence > wanted ? wanted : undefined);
|
|
122
|
+
return [
|
|
123
|
+
skippedFrom === undefined ? { sequence, data } : { sequence, data, skippedFrom },
|
|
124
|
+
];
|
|
105
125
|
});
|
|
126
|
+
/** Records `from`..`to`-1 are gone: the next chunk, or the end, says so. */
|
|
127
|
+
const skip = (to) => Effect.gen(function* () {
|
|
128
|
+
const wanted = yield* Ref.get(next);
|
|
129
|
+
if (to <= wanted)
|
|
130
|
+
return [];
|
|
131
|
+
yield* Ref.set(next, to);
|
|
132
|
+
yield* Ref.set(cuts, 0);
|
|
133
|
+
yield* Ref.update(skipped, (from) => from ?? wanted);
|
|
134
|
+
return [];
|
|
135
|
+
});
|
|
136
|
+
/**
|
|
137
|
+
* The session ended. Output skipped just before it gets a chunk of its own: no bytes, at
|
|
138
|
+
* the sequence after the skipped ones, so a reader that counts sequences sees the gap.
|
|
139
|
+
*/
|
|
140
|
+
const end = Effect.gen(function* () {
|
|
141
|
+
yield* Ref.set(ended, true);
|
|
142
|
+
const from = yield* Ref.getAndSet(skipped, undefined);
|
|
143
|
+
if (from === undefined)
|
|
144
|
+
return [];
|
|
145
|
+
return [{ sequence: yield* Ref.get(next), data: new Uint8Array(0), skippedFrom: from }];
|
|
146
|
+
});
|
|
147
|
+
const toChunks = (event) => {
|
|
148
|
+
if (event.event === "end")
|
|
149
|
+
return end;
|
|
150
|
+
if (event.event === "output" && event.id !== undefined) {
|
|
151
|
+
return deliver(BigInt(event.id), fromBase64(event.data));
|
|
152
|
+
}
|
|
153
|
+
if (event.event === "skipped") {
|
|
154
|
+
const range = decodeSkipped(event.data);
|
|
155
|
+
return Option.isSome(range) ? skip(BigInt(range.value.to)) : Effect.succeed([]);
|
|
156
|
+
}
|
|
157
|
+
return Effect.succeed([]);
|
|
158
|
+
};
|
|
106
159
|
const following = connection.pipe(
|
|
107
160
|
// `end` is the only sign the session ended: a body that stops without it was cut.
|
|
108
|
-
Stream.takeUntil((event) => event.event === "end"), Stream.
|
|
109
|
-
sequence: BigInt(event.id ?? "0"),
|
|
110
|
-
data: fromBase64(event.data),
|
|
111
|
-
})), Stream.mapEffect(deliver), Stream.filter(Option.isSome), Stream.map((chunk) => chunk.value), Stream.catchTag("SealantTransportError", () => Stream.empty), Stream.concat(Stream.unwrap(Effect.map(Ref.get(ended), (done) => (done ? Stream.empty : reconnect)))));
|
|
161
|
+
Stream.takeUntil((event) => event.event === "end"), Stream.mapEffect(toChunks), Stream.flattenIterable, Stream.catchTag("SealantTransportError", () => Stream.empty), Stream.concat(Stream.unwrap(Effect.map(Ref.get(ended), (done) => (done ? Stream.empty : reconnect)))));
|
|
112
162
|
const reconnect = Stream.unwrap(Effect.gen(function* () {
|
|
163
|
+
// A connection that stayed open a while was healthy whatever cut it (a proxy that
|
|
164
|
+
// closes idle streams, a deploy): only cuts in quick succession count to the limit.
|
|
165
|
+
const opened = yield* Ref.getAndSet(openedAt, undefined);
|
|
166
|
+
const now = yield* Clock.currentTimeMillis;
|
|
167
|
+
if (opened !== undefined && now - opened >= Duration.toMillis(HEALTHY_CONNECTION)) {
|
|
168
|
+
yield* Ref.set(cuts, 0);
|
|
169
|
+
}
|
|
113
170
|
const attempt = yield* Ref.getAndUpdate(cuts, (n) => n + 1);
|
|
114
171
|
if (attempt >= OUTPUT_RECONNECTS) {
|
|
115
172
|
return Stream.fail(new SealantTransportError({
|
|
@@ -12,10 +12,15 @@ export interface SessionOutputChunk {
|
|
|
12
12
|
readonly sequence: bigint;
|
|
13
13
|
readonly data: Uint8Array;
|
|
14
14
|
/**
|
|
15
|
-
* Set when records before this one are gone: the
|
|
16
|
-
*
|
|
17
|
-
* `fromSequence` older than
|
|
18
|
-
*
|
|
15
|
+
* Set when records before this one are gone: the records from `skippedFrom` up to before
|
|
16
|
+
* `sequence` could not be sent (the session's output journal rotated them away before a
|
|
17
|
+
* `fromSequence` older than it or a reader that fell behind it, the run's record lost them, or
|
|
18
|
+
* the run's output budget withheld their bytes). Absent when this record follows the one
|
|
19
|
+
* before, or the sequence asked for.
|
|
20
|
+
*
|
|
21
|
+
* The session's last chunk has no bytes when output was skipped just before it ended: it says
|
|
22
|
+
* only that the records from `skippedFrom` up to before `sequence` are gone, and no record
|
|
23
|
+
* `sequence` follows.
|
|
19
24
|
*/
|
|
20
25
|
readonly skippedFrom?: bigint;
|
|
21
26
|
}
|
|
@@ -80,8 +85,10 @@ export interface SessionsShape {
|
|
|
80
85
|
readonly close: (sessionId: string) => Effect.Effect<SessionWire, EndpointError<"sessions", "closeSession">>;
|
|
81
86
|
/**
|
|
82
87
|
* Output over the session's SSE stream: from `fromSequence`, then live, ending at the session's
|
|
83
|
-
* `end`. A body cut without `end
|
|
84
|
-
*
|
|
88
|
+
* `end`. A body cut without `end`, or one that sends nothing (not even its keep-alive) for 45
|
|
89
|
+
* seconds, is reopened from the next sequence, with backoff; after ten cuts in a row with
|
|
90
|
+
* nothing received, each within 30 seconds of its connection opening, the stream fails with the
|
|
91
|
+
* last.
|
|
85
92
|
*/
|
|
86
93
|
readonly output: (sessionId: string, options?: OutputOptions) => Stream.Stream<SessionOutputChunk, SealantStreamRefusedError | SealantTransportError>;
|
|
87
94
|
/** Attaches over the socket for the scope's lifetime (see {@link AttachedSession}). */
|
package/dist/facade/record.d.ts
CHANGED
|
@@ -8,6 +8,12 @@
|
|
|
8
8
|
import { type TimelineEntry as WireTimelineEntry } from "@sealant/api-contracts";
|
|
9
9
|
import type { RunCommand, RunRecord, TimelineEntry } from "../types.js";
|
|
10
10
|
import { type SdkContext } from "./context.js";
|
|
11
|
+
/**
|
|
12
|
+
* Entries asked for per timeline read: the server's largest page. A read that answers a full page
|
|
13
|
+
* is followed by the next, from the sequence after its last entry, until one answers short, so a
|
|
14
|
+
* record longer than any one page is read whole.
|
|
15
|
+
*/
|
|
16
|
+
export declare const TIMELINE_PAGE_SIZE = 5000;
|
|
11
17
|
/**
|
|
12
18
|
* Maps a wire entry to the public DISCRIMINATED entry: the contract's payload schemas fold
|
|
13
19
|
* `(kind, ref)` into typed `data`, degrading to the `unknown` case (raw kind + payload preserved)
|
package/dist/facade/record.js
CHANGED
|
@@ -15,6 +15,12 @@ import { bindPolling } from "./context.js";
|
|
|
15
15
|
// The transport swaps to SSE over Postgres LISTEN/NOTIFY in Stage 5 behind this same signature.
|
|
16
16
|
const TERMINAL_RUN_STATUSES = new Set(["completed", "failed", "cancelled"]);
|
|
17
17
|
const STREAM_POLL_INTERVAL_MS = 500;
|
|
18
|
+
/**
|
|
19
|
+
* Entries asked for per timeline read: the server's largest page. A read that answers a full page
|
|
20
|
+
* is followed by the next, from the sequence after its last entry, until one answers short, so a
|
|
21
|
+
* record longer than any one page is read whole.
|
|
22
|
+
*/
|
|
23
|
+
export const TIMELINE_PAGE_SIZE = 5000;
|
|
18
24
|
/**
|
|
19
25
|
* Maps a wire entry to the public DISCRIMINATED entry: the contract's payload schemas fold
|
|
20
26
|
* `(kind, ref)` into typed `data`, degrading to the `unknown` case (raw kind + payload preserved)
|
|
@@ -150,10 +156,33 @@ export const renderTranscript = (commands) => {
|
|
|
150
156
|
return `${blocks.join("\n\n")}\n`;
|
|
151
157
|
};
|
|
152
158
|
export const makeRunRecord = (ctx, runId) => {
|
|
153
|
-
const
|
|
159
|
+
const timelinePage = (from) => getRunTimelineOp(runId, {
|
|
154
160
|
ownerUserId: ctx.config.hostLocal.ownerUserId,
|
|
161
|
+
limit: String(TIMELINE_PAGE_SIZE),
|
|
155
162
|
...(from === undefined ? {} : { fromSequence: from.toString() }),
|
|
156
|
-
})
|
|
163
|
+
});
|
|
164
|
+
/**
|
|
165
|
+
* Every entry from `from` on, page by page, through `call`: each page's entries are yielded
|
|
166
|
+
* before the next page is asked for.
|
|
167
|
+
*/
|
|
168
|
+
async function* timelinePages(call, from) {
|
|
169
|
+
let next = from;
|
|
170
|
+
for (;;) {
|
|
171
|
+
const page = await call(timelinePage(next));
|
|
172
|
+
yield* page;
|
|
173
|
+
const last = page.at(-1);
|
|
174
|
+
if (page.length < TIMELINE_PAGE_SIZE || last === undefined)
|
|
175
|
+
return;
|
|
176
|
+
next = BigInt(last.sequence) + 1n;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
const inCallerTrace = (effect) => ctx.runtime.run(effect);
|
|
180
|
+
const fetchTimeline = async (from) => {
|
|
181
|
+
const entries = [];
|
|
182
|
+
for await (const entry of timelinePages(inCallerTrace, from))
|
|
183
|
+
entries.push(entry);
|
|
184
|
+
return entries;
|
|
185
|
+
};
|
|
157
186
|
return {
|
|
158
187
|
runId,
|
|
159
188
|
replay: async (options) => {
|
|
@@ -198,11 +227,7 @@ export const makeRunRecord = (ctx, runId) => {
|
|
|
198
227
|
for (;;) {
|
|
199
228
|
if (signal?.aborted === true)
|
|
200
229
|
return;
|
|
201
|
-
const
|
|
202
|
-
ownerUserId: ctx.config.hostLocal.ownerUserId,
|
|
203
|
-
...(from === undefined ? {} : { fromSequence: from.toString() }),
|
|
204
|
-
}));
|
|
205
|
-
for (const entry of wire) {
|
|
230
|
+
for await (const entry of timelinePages(call, from)) {
|
|
206
231
|
const mapped = toTimelineEntry(entry);
|
|
207
232
|
yield mapped;
|
|
208
233
|
from = mapped.sequence + 1n;
|
|
@@ -212,11 +237,7 @@ export const makeRunRecord = (ctx, runId) => {
|
|
|
212
237
|
const run = await call(getRunOp(runId, ctx.config.hostLocal.ownerUserId));
|
|
213
238
|
call = polling.poll;
|
|
214
239
|
if (TERMINAL_RUN_STATUSES.has(run.status)) {
|
|
215
|
-
const
|
|
216
|
-
ownerUserId: ctx.config.hostLocal.ownerUserId,
|
|
217
|
-
...(from === undefined ? {} : { fromSequence: from.toString() }),
|
|
218
|
-
}));
|
|
219
|
-
for (const entry of tail) {
|
|
240
|
+
for await (const entry of timelinePages(polling.run, from)) {
|
|
220
241
|
yield toTimelineEntry(entry);
|
|
221
242
|
}
|
|
222
243
|
return;
|
|
@@ -230,13 +251,8 @@ export const makeRunRecord = (ctx, runId) => {
|
|
|
230
251
|
return iterate();
|
|
231
252
|
},
|
|
232
253
|
timeline: (options) => {
|
|
233
|
-
const run = ctx.runtime;
|
|
234
254
|
async function* iterate() {
|
|
235
|
-
const
|
|
236
|
-
ownerUserId: ctx.config.hostLocal.ownerUserId,
|
|
237
|
-
...(options?.from === undefined ? {} : { fromSequence: options.from.toString() }),
|
|
238
|
-
}));
|
|
239
|
-
for (const entry of wire) {
|
|
255
|
+
for await (const entry of timelinePages(inCallerTrace, options?.from)) {
|
|
240
256
|
yield toTimelineEntry(entry);
|
|
241
257
|
}
|
|
242
258
|
}
|
package/dist/facade/session.d.ts
CHANGED
|
@@ -11,4 +11,10 @@
|
|
|
11
11
|
import type { SessionWire } from "@sealant/api-contracts";
|
|
12
12
|
import type { InteractiveSession } from "../types.js";
|
|
13
13
|
import { type SdkContext } from "./context.js";
|
|
14
|
+
/**
|
|
15
|
+
* How long one SSE connection may send nothing, not even a heartbeat, before it is taken for dead
|
|
16
|
+
* and reopened: three of the control plane's 15-second heartbeats, as the Effect client's
|
|
17
|
+
* `SSE_IDLE_TIMEOUT`.
|
|
18
|
+
*/
|
|
19
|
+
export declare const SSE_IDLE_TIMEOUT_MS = 45000;
|
|
14
20
|
export declare const makeInteractiveSession: (ctx: SdkContext, wire: SessionWire) => InteractiveSession;
|
package/dist/facade/session.js
CHANGED
|
@@ -120,8 +120,31 @@ const parseSseFrame = (block) => {
|
|
|
120
120
|
}
|
|
121
121
|
return { event, id, data: dataLines.join("\n") };
|
|
122
122
|
};
|
|
123
|
+
/**
|
|
124
|
+
* How long one SSE connection may send nothing, not even a heartbeat, before it is taken for dead
|
|
125
|
+
* and reopened: three of the control plane's 15-second heartbeats, as the Effect client's
|
|
126
|
+
* `SSE_IDLE_TIMEOUT`.
|
|
127
|
+
*/
|
|
128
|
+
export const SSE_IDLE_TIMEOUT_MS = 45_000;
|
|
129
|
+
/** A read that gave up because the connection sent nothing for the idle timeout. */
|
|
130
|
+
const IDLE = Symbol("idle");
|
|
131
|
+
/** The next read of `reader`, or {@link IDLE} once `ms` pass with nothing read. */
|
|
132
|
+
const readWithin = async (reader, ms) => {
|
|
133
|
+
let timer;
|
|
134
|
+
try {
|
|
135
|
+
return await Promise.race([
|
|
136
|
+
reader.read(),
|
|
137
|
+
new Promise((resolve) => {
|
|
138
|
+
timer = setTimeout(() => resolve(IDLE), ms);
|
|
139
|
+
}),
|
|
140
|
+
]);
|
|
141
|
+
}
|
|
142
|
+
finally {
|
|
143
|
+
clearTimeout(timer);
|
|
144
|
+
}
|
|
145
|
+
};
|
|
123
146
|
/** One connection to the session's SSE output: its chunks, then how it ended. */
|
|
124
|
-
async function* streamOverSse(ctx, sessionId, from, signal, priority, trace) {
|
|
147
|
+
async function* streamOverSse(ctx, sessionId, from, signal, priority, trace, idleTimeoutMs) {
|
|
125
148
|
const config = ctx.config;
|
|
126
149
|
const fetchImpl = config.fetch ?? fetch;
|
|
127
150
|
const url = new URL(`/v1/sessions/${sessionId}/output/stream`, config.baseUrl);
|
|
@@ -159,12 +182,18 @@ async function* streamOverSse(ctx, sessionId, from, signal, priority, trace) {
|
|
|
159
182
|
for (;;) {
|
|
160
183
|
let read;
|
|
161
184
|
try {
|
|
162
|
-
|
|
185
|
+
// Every byte resets the wait, heartbeat comments included.
|
|
186
|
+
read = await readWithin(reader, idleTimeoutMs);
|
|
163
187
|
}
|
|
164
188
|
catch {
|
|
165
189
|
// The connection dropped mid-stream (or the caller aborted): not the session's end.
|
|
166
190
|
return "cut";
|
|
167
191
|
}
|
|
192
|
+
// Silent past the idle timeout: a half-open socket that would otherwise hang the read
|
|
193
|
+
// forever. Cut, so the caller reconnects from the chunk after the last one it saw.
|
|
194
|
+
if (read === IDLE) {
|
|
195
|
+
return "cut";
|
|
196
|
+
}
|
|
168
197
|
if (read.done) {
|
|
169
198
|
return "cut";
|
|
170
199
|
}
|
|
@@ -248,6 +277,7 @@ export const makeInteractiveSession = (ctx, wire) => {
|
|
|
248
277
|
output: (options) => {
|
|
249
278
|
const from = options?.from ?? 0n;
|
|
250
279
|
const signal = options?.signal;
|
|
280
|
+
const idleTimeoutMs = options?.idleTimeoutMs ?? SSE_IDLE_TIMEOUT_MS;
|
|
251
281
|
// A function, so the check reads the signal now: an abort lands while the loop awaits.
|
|
252
282
|
const aborted = () => signal?.aborted === true;
|
|
253
283
|
// Captured when output() is called: the generator's body first runs on the first next().
|
|
@@ -260,7 +290,7 @@ export const makeInteractiveSession = (ctx, wire) => {
|
|
|
260
290
|
let failures = 0;
|
|
261
291
|
for (;;) {
|
|
262
292
|
// Only the first connection continues the caller's trace; a reconnect is its own.
|
|
263
|
-
const frames = streamOverSse(ctx, sessionId, cursor, signal, priority, connected ? undefined : trace);
|
|
293
|
+
const frames = streamOverSse(ctx, sessionId, cursor, signal, priority, connected ? undefined : trace, idleTimeoutMs);
|
|
264
294
|
let outcome;
|
|
265
295
|
let delivered = false;
|
|
266
296
|
try {
|
package/dist/types.d.ts
CHANGED
|
@@ -2421,10 +2421,15 @@ export interface InteractiveSession {
|
|
|
2421
2421
|
* Byte-exact output as a RESUMABLE stream: recorded history from `from` (inclusive; default the
|
|
2422
2422
|
* beginning), then the live tail until the session settles. Each chunk carries its durable
|
|
2423
2423
|
* sequence, so a disconnected consumer resumes with `from: lastChunk.sequence + 1n`.
|
|
2424
|
+
*
|
|
2425
|
+
* A stream connection that sends nothing (no output, no heartbeat) for `idleTimeoutMs` is taken
|
|
2426
|
+
* for dead, a half-open socket behind a proxy or a laptop that slept, and is reopened from the
|
|
2427
|
+
* next sequence. Default 45 s: three of the control plane's 15-second heartbeats.
|
|
2424
2428
|
*/
|
|
2425
2429
|
output(options?: {
|
|
2426
2430
|
readonly from?: bigint;
|
|
2427
2431
|
readonly signal?: AbortSignal;
|
|
2432
|
+
readonly idleTimeoutMs?: number;
|
|
2428
2433
|
}): AsyncIterable<SessionOutputChunk>;
|
|
2429
2434
|
/** Resize the PTY. Rejected for `pipe` sessions, which have no terminal. */
|
|
2430
2435
|
resize(cols: number, rows: number): Promise<void>;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sealant/sdk-next",
|
|
3
|
-
"version": "0.40.0-next.
|
|
3
|
+
"version": "0.40.0-next.986",
|
|
4
4
|
"description": "The fluent public SDK for Sealant — create a workspace, run a harness, replay the record.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -26,12 +26,12 @@
|
|
|
26
26
|
"node": ">=20"
|
|
27
27
|
},
|
|
28
28
|
"dependencies": {
|
|
29
|
-
"@sealant/api-contracts": "npm:@sealant/api-contracts-next@0.40.0-next.
|
|
29
|
+
"@sealant/api-contracts": "npm:@sealant/api-contracts-next@0.40.0-next.986"
|
|
30
30
|
},
|
|
31
31
|
"peerDependencies": {
|
|
32
32
|
"effect": "^4.0.5"
|
|
33
33
|
},
|
|
34
|
-
"gitHead": "
|
|
34
|
+
"gitHead": "fadde496a1a03d4cc6fbbb9cf8933a7d0a9a19bb",
|
|
35
35
|
"publishConfig": {
|
|
36
36
|
"access": "public"
|
|
37
37
|
}
|