@sealant/sdk-next 0.40.0-next.984 → 0.40.0-next.987

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.
@@ -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
@@ -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
- return Stream.unwrap(Effect.map(open, (response) => response.stream)).pipe(Stream.decodeText(), Stream.pipeThroughChannel(Sse.decode()), Stream.mapError((cause) => {
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({
@@ -3,7 +3,8 @@
3
3
  * its place across cuts. The wire frames are `sessionAttachServerFrameSchema` and
4
4
  * `sessionAttachClientFrameSchema` in `@sealant/api-contracts`:
5
5
  *
6
- * server → client binary = one output record; text `seq` = the next binary frame's sequence,
6
+ * server → client binary = one output record; text `ready` = where the journal stood as the
7
+ * socket opened, `seq` = the next binary frame's sequence,
7
8
  * `skipped` = records the journal no longer holds were passed over,
8
9
  * `error` = a client frame was refused, `end` = the session ended (then close)
9
10
  * client → server binary = input; text `resize` | `signal`
@@ -11,9 +12,18 @@
11
12
  * One `Socket` dials a new WebSocket for each connection, its URL read when it dials: every
12
13
  * connection asks for the sequence after the last record delivered, so a socket closed without
13
14
  * `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. The
15
- * socket's writer waits while it is reopening, so input sent across a cut is delivered once it is
16
- * back. A close with 1008 (the credential was revoked or expired) is not reopened.
15
+ * sequence is past the one asked for carries `skippedFrom`: the records between are gone, and so
16
+ * does the record after a `skipped` frame. Records skipped just before the session's `end` get a
17
+ * chunk of their own with no bytes. The socket's writer waits while it is reopening, so input sent
18
+ * across a cut is delivered once it is back. A close with 1008 (the credential was revoked or
19
+ * expired) is not reopened. A connection that stayed open for {@link HEALTHY_CONNECTION} before
20
+ * it was cut starts the count of cuts in a row again, so a session held open for hours behind a
21
+ * proxy that closes idle sockets is not given up on.
22
+ *
23
+ * `replayTarget` is the first connection's `ready`, or none once any other frame comes first (a
24
+ * control plane that predates it, or a replay from the run's record) or the attachment ends. A
25
+ * connection cut before its first frame leaves it to the next. A frame refusing input (`error`)
26
+ * says nothing about the replay and does not settle it.
17
27
  *
18
28
  * `output` holds at most {@link MAX_QUEUED_RECORDS} unread records. The socket is read whether or
19
29
  * not anyone reads `output`, so `end` always reaches `exit`; a reader that falls further behind
@@ -21,7 +31,7 @@
21
31
  * `resize` and `signal` carry on.
22
32
  */
23
33
  import { sessionAttachServerFrameSchema, } from "@sealant/api-contracts";
24
- import { Cause, Deferred, Duration, Effect, Option, Queue, Random, Redacted, Ref, Schema, Stream, } from "effect";
34
+ import { Cause, Clock, Deferred, Duration, Effect, Option, Queue, Random, Redacted, Ref, Schema, Stream, } from "effect";
25
35
  import { Socket } from "effect/socket";
26
36
  import { SessionAttachError, SessionEndedError } from "../errors.js";
27
37
  const decodeServerFrame = Schema.decodeUnknownOption(Schema.fromJsonString(sessionAttachServerFrameSchema));
@@ -34,11 +44,15 @@ export const MAX_QUEUED_RECORDS = 8192;
34
44
  const POLICY_VIOLATION = 1008;
35
45
  /** Cuts in a row with no record received before the attachment gives up. */
36
46
  const MAX_RECONNECTS = 8;
47
+ /** A connection open this long before it was cut was healthy: the count of cuts starts again. */
48
+ const HEALTHY_CONNECTION = Duration.seconds(30);
37
49
  const RECONNECT_FIRST = Duration.millis(100);
38
50
  const RECONNECT_MAX = Duration.seconds(5);
39
51
  const OPEN_TIMEOUT = Duration.seconds(10);
40
52
  const reconnectDelay = (attempt) => Effect.map(Random.nextBetween(0.8, 1.2), (factor) => Duration.times(Duration.min(Duration.times(RECONNECT_FIRST, 2 ** attempt), RECONNECT_MAX), factor));
41
53
  const encoder = new TextEncoder();
54
+ /** A `ready` frame's journal sequence, or none when it is not a decimal integer. */
55
+ const journalSequence = (decimal) => /^\d+$/.test(decimal) ? Option.some(BigInt(decimal)) : Option.none();
42
56
  /** The socket's URL for a connection that starts at `from`. The token never goes in it. */
43
57
  const attachUrl = (target, from) => {
44
58
  const url = new URL(`/v1/sessions/${encodeURIComponent(target.sessionId)}/attach`, target.baseUrl);
@@ -55,6 +69,10 @@ export const attachSession = (target) => Effect.gen(function* () {
55
69
  // The next sequence the consumer has not been given: what a reconnect asks for.
56
70
  const next = yield* Ref.make(target.fromSequence);
57
71
  const cuts = yield* Ref.make(0);
72
+ // Where records a `skipped` frame said are gone began, until a record or `end` says so.
73
+ let skippedFrom;
74
+ // When the connection being read opened, for telling a healthy one from one that failed at once.
75
+ let openedAt;
58
76
  // Bounded, and never waited on: a consumer that reads `exit` and not `output` must not keep
59
77
  // the `end` frame from being read. A record that finds it full fails `output` instead.
60
78
  const output = yield* Queue.dropping(MAX_QUEUED_RECORDS);
@@ -62,8 +80,12 @@ export const attachSession = (target) => Effect.gen(function* () {
62
80
  let overflowed = false;
63
81
  const exit = yield* Deferred.make();
64
82
  const opened = yield* Deferred.make();
65
- // Closing the scope ends `output` for a consumer still reading it.
66
- yield* Effect.addFinalizer(() => Queue.end(output));
83
+ // Settled once, by the first frame or the attachment's end; later settles are no-ops.
84
+ const replayTarget = yield* Deferred.make();
85
+ const noReplayTarget = Deferred.succeed(replayTarget, Option.none());
86
+ // Closing the scope ends `output` for a consumer still reading it, and settles `replayTarget`
87
+ // for one still waiting on it.
88
+ yield* Effect.addFinalizer(() => Effect.andThen(Queue.end(output), noReplayTarget));
67
89
  const socket = yield* Socket.makeWebSocket(Effect.map(Ref.get(next), (from) => attachUrl(target, from)), {
68
90
  openTimeout: OPEN_TIMEOUT,
69
91
  ...(target.token === undefined
@@ -73,10 +95,13 @@ export const attachSession = (target) => Effect.gen(function* () {
73
95
  const writer = yield* socket.writer;
74
96
  // `output` first: a holder that ends the attachment once `exit` settles closes the scope, and
75
97
  // the scope's `Queue.end` must not beat the error to `output`.
76
- const failWith = (error) => Effect.uninterruptible(Effect.all([Queue.fail(output, error), Deferred.fail(exit, error)], { discard: true }));
98
+ const failWith = (error) => Effect.uninterruptible(Effect.all([Queue.fail(output, error), Deferred.fail(exit, error), noReplayTarget], {
99
+ discard: true,
100
+ }));
77
101
  /** One connection: frames until the session's `end` or the socket closes. */
78
102
  const connection = Effect.scoped(Effect.gen(function* () {
79
103
  const reader = yield* socket.reader;
104
+ openedAt = yield* Clock.currentTimeMillis;
80
105
  yield* Deferred.succeed(opened, undefined);
81
106
  // The sequence a `seq` frame named for the binary frame after it.
82
107
  let named;
@@ -88,30 +113,55 @@ export const attachSession = (target) => Effect.gen(function* () {
88
113
  if (Option.isNone(decoded))
89
114
  continue;
90
115
  const server = decoded.value;
116
+ if (server.t === "ready") {
117
+ yield* Deferred.succeed(replayTarget, journalSequence(server.nextSequence));
118
+ continue;
119
+ }
120
+ if (server.t !== "error")
121
+ yield* noReplayTarget;
91
122
  if (server.t === "seq")
92
123
  named = BigInt(server.sequence);
93
- // The record after it comes with a `seq` past the one asked for, which says so.
94
- else if (server.t === "skipped")
95
- continue;
124
+ else if (server.t === "skipped") {
125
+ const to = BigInt(server.to);
126
+ const wanted = yield* Ref.get(next);
127
+ if (to > wanted) {
128
+ skippedFrom ??= wanted;
129
+ yield* Ref.set(next, to);
130
+ yield* Ref.set(cuts, 0);
131
+ }
132
+ }
96
133
  else if (server.t === "error") {
97
134
  yield* Effect.logWarning("The control plane refused a frame on the attach socket").pipe(Effect.annotateLogs({ sessionId, message: server.message }));
98
135
  }
99
136
  else {
137
+ // Records skipped just before the end are said by a chunk with no bytes.
138
+ if (skippedFrom !== undefined && !overflowed) {
139
+ const sequence = yield* Ref.get(next);
140
+ yield* Queue.offer(output, {
141
+ sequence,
142
+ data: new Uint8Array(0),
143
+ skippedFrom,
144
+ });
145
+ skippedFrom = undefined;
146
+ }
100
147
  const { t: _t, ...ended } = server;
101
148
  yield* Deferred.succeed(exit, ended);
102
149
  return { kind: "ended" };
103
150
  }
104
151
  continue;
105
152
  }
153
+ yield* noReplayTarget;
106
154
  const wanted = yield* Ref.get(next);
107
155
  const sequence = named ?? wanted;
108
156
  named = undefined;
109
157
  // Replayed after a reconnect but already delivered: once is enough.
110
158
  if (sequence < wanted)
111
159
  continue;
112
- const chunk = sequence > wanted
113
- ? { sequence, data: frame, skippedFrom: wanted }
114
- : { sequence, data: frame };
160
+ const from = skippedFrom ?? (sequence > wanted ? wanted : undefined);
161
+ skippedFrom = undefined;
162
+ const chunk = from === undefined
163
+ ? { sequence, data: frame }
164
+ : { sequence, data: frame, skippedFrom: from };
115
165
  if (!overflowed && !(yield* Queue.offer(output, chunk))) {
116
166
  overflowed = true;
117
167
  yield* Queue.fail(output, new SessionAttachError({
@@ -153,6 +203,13 @@ export const attachSession = (target) => Effect.gen(function* () {
153
203
  }));
154
204
  return;
155
205
  }
206
+ // A connection that stayed open a while was healthy whatever cut it (a proxy that closes
207
+ // idle sockets, a deploy): only cuts in quick succession count to the limit.
208
+ const now = yield* Clock.currentTimeMillis;
209
+ if (openedAt !== undefined && now - openedAt >= Duration.toMillis(HEALTHY_CONNECTION)) {
210
+ yield* Ref.set(cuts, 0);
211
+ }
212
+ openedAt = undefined;
156
213
  const attempt = yield* Ref.getAndUpdate(cuts, (n) => n + 1);
157
214
  if (attempt >= MAX_RECONNECTS) {
158
215
  yield* failWith(new SessionAttachError({
@@ -193,5 +250,6 @@ export const attachSession = (target) => Effect.gen(function* () {
193
250
  resize: (cols, rows) => control({ t: "resize", cols, rows }),
194
251
  signal: (signal) => control({ t: "signal", signal }),
195
252
  exit: Deferred.await(exit),
253
+ replayTarget: Deferred.await(replayTarget),
196
254
  };
197
255
  });
@@ -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
- /** Cuts in a row with nothing received before `output` fails with the last. */
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
- // A chunk past the one asked for says the records between are gone.
97
- const deliver = (chunk) => Effect.gen(function* () {
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 (chunk.sequence < wanted)
101
- return Option.none();
102
- yield* Ref.set(next, chunk.sequence + 1n);
116
+ if (sequence < wanted)
117
+ return [];
118
+ yield* Ref.set(next, sequence + 1n);
103
119
  yield* Ref.set(cuts, 0);
104
- return Option.some(chunk.sequence > wanted ? { ...chunk, skippedFrom: wanted } : chunk);
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.tap((event) => (event.event === "end" ? Ref.set(ended, true) : Effect.void)), Stream.filter((event) => event.event === "output" && event.id !== undefined), Stream.map((event) => ({
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({
@@ -4,7 +4,7 @@
4
4
  * protocol over stdio attaches instead (`attach`): one held socket, both ways, that survives a cut.
5
5
  */
6
6
  import type { CreateSessionAsUserRequest, CreateSessionRequest, ListSessionsQuery, ListSessionsResponse, SessionEnded, SessionWire } from "@sealant/api-contracts";
7
- import { Context, type Effect, type Redacted, type Scope, type Stream } from "effect";
7
+ import { Context, type Effect, type Option, type Redacted, type Scope, type Stream } from "effect";
8
8
  import type { EndpointError } from "../endpoint.js";
9
9
  import type { SealantStreamRefusedError, SealantTransportError, SessionAttachError, SessionEndedError } from "../errors.js";
10
10
  /** One output record of a session: its journal sequence and its bytes, exactly as recorded. */
@@ -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 session's output journal rotated away the
16
- * records from `skippedFrom` up to before `sequence` before they could be sent (a
17
- * `fromSequence` older than the journal, or a reader that fell behind it). Absent when this
18
- * record follows the one before, or the sequence asked for.
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
  }
@@ -52,6 +57,20 @@ export interface AttachedSession {
52
57
  * not held up by a reader that is slow or gone.
53
58
  */
54
59
  readonly output: Stream.Stream<SessionOutputChunk, SessionAttachError>;
60
+ /**
61
+ * Where the replay ends: the journal sequence the session's next record took when the
62
+ * attachment was opened, so every record before it was already written (`0n`: none was). The
63
+ * replay has caught up once `output` has delivered, or skipped, the records before it. Compare
64
+ * it with chunk sequences only, never with a run's `outputHighWater`, which counts something
65
+ * else.
66
+ *
67
+ * `None` when the control plane does not say: one that predates it, or a settled session
68
+ * replayed from the run's record, whose output ends with its `end`. It settles on the first
69
+ * frame received, or once the attachment ends or fails, and a reconnect never changes it.
70
+ * Against a control plane that predates it, an idle session attached at the end of its output
71
+ * receives no frame, so this waits until output arrives: bound it with a timeout there.
72
+ */
73
+ readonly replayTarget: Effect.Effect<Option.Option<bigint>>;
55
74
  /** Keystrokes for a `pty` session, stdin for a `pipe` one. A string is sent as UTF-8. */
56
75
  readonly write: (data: Uint8Array | string) => Effect.Effect<void, SessionEndedError | SessionAttachError>;
57
76
  /** Resizes a `pty` session's terminal; the control plane refuses it for a `pipe` session. */
@@ -80,8 +99,10 @@ export interface SessionsShape {
80
99
  readonly close: (sessionId: string) => Effect.Effect<SessionWire, EndpointError<"sessions", "closeSession">>;
81
100
  /**
82
101
  * Output over the session's SSE stream: from `fromSequence`, then live, ending at the session's
83
- * `end`. A body cut without `end` is reopened from the next sequence, with backoff; after ten
84
- * cuts in a row with nothing received, the stream fails with the last.
102
+ * `end`. A body cut without `end`, or one that sends nothing (not even its keep-alive) for 45
103
+ * seconds, is reopened from the next sequence, with backoff; after ten cuts in a row with
104
+ * nothing received, each within 30 seconds of its connection opening, the stream fails with the
105
+ * last.
85
106
  */
86
107
  readonly output: (sessionId: string, options?: OutputOptions) => Stream.Stream<SessionOutputChunk, SealantStreamRefusedError | SealantTransportError>;
87
108
  /** Attaches over the socket for the scope's lifetime (see {@link AttachedSession}). */
@@ -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;
@@ -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
- read = await reader.read();
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.984",
3
+ "version": "0.40.0-next.987",
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.984"
29
+ "@sealant/api-contracts": "npm:@sealant/api-contracts-next@0.40.0-next.987"
30
30
  },
31
31
  "peerDependencies": {
32
32
  "effect": "^4.0.5"
33
33
  },
34
- "gitHead": "55136581c9c4b246ae59f0a65cc0d75e36084a65",
34
+ "gitHead": "2e8adb97c2ff519a2ebcf7aa3c8d788e5fd935a5",
35
35
  "publishConfig": {
36
36
  "access": "public"
37
37
  }