@sealant/sdk-next 0.40.0-next.973 → 0.40.0-next.975
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +34 -13
- package/dist/client.d.ts +12 -2
- package/dist/client.js +22 -2
- package/dist/effect/api-client.d.ts +37 -11
- package/dist/effect/api-client.js +71 -28
- package/dist/effect/config.d.ts +47 -0
- package/dist/effect/config.js +36 -0
- package/dist/effect/context.d.ts +27 -0
- package/dist/effect/context.js +29 -0
- package/dist/effect/endpoint.d.ts +10 -0
- package/dist/effect/endpoint.js +1 -0
- package/dist/effect/errors.d.ts +113 -0
- package/dist/effect/errors.js +104 -0
- package/dist/effect/events/layer.d.ts +14 -0
- package/dist/effect/events/layer.js +109 -0
- package/dist/effect/events/observe.d.ts +19 -0
- package/dist/effect/events/observe.js +15 -0
- package/dist/effect/events/service.d.ts +62 -0
- package/dist/effect/events/service.js +3 -0
- package/dist/effect/http.d.ts +42 -0
- package/dist/effect/http.js +76 -0
- package/dist/effect/index.d.ts +49 -16
- package/dist/effect/index.js +45 -17
- package/dist/effect/layer.d.ts +24 -0
- package/dist/effect/layer.js +21 -0
- package/dist/effect/operations.d.ts +107 -30
- package/dist/effect/operations.js +7 -0
- package/dist/effect/read-retry.d.ts +4 -2
- package/dist/effect/read-retry.js +9 -2
- package/dist/effect/runs/layer.d.ts +9 -0
- package/dist/effect/runs/layer.js +94 -0
- package/dist/effect/runs/service.d.ts +51 -0
- package/dist/effect/runs/service.js +3 -0
- package/dist/effect/runs/wait.d.ts +15 -0
- package/dist/effect/runs/wait.js +16 -0
- package/dist/effect/runtime.d.ts +33 -14
- package/dist/effect/runtime.js +42 -50
- package/dist/effect/sessions/attach.d.ts +12 -0
- package/dist/effect/sessions/attach.js +142 -0
- package/dist/effect/sessions/layer.d.ts +10 -0
- package/dist/effect/sessions/layer.js +149 -0
- package/dist/effect/sessions/service.d.ts +83 -0
- package/dist/effect/sessions/service.js +3 -0
- package/dist/effect/websocket.d.ts +11 -0
- package/dist/effect/websocket.js +16 -0
- package/dist/effect/workspaces/layer.d.ts +9 -0
- package/dist/effect/workspaces/layer.js +148 -0
- package/dist/effect/workspaces/service.d.ts +75 -0
- package/dist/effect/workspaces/service.js +3 -0
- package/dist/effect/workspaces/wait.d.ts +216 -0
- package/dist/effect/workspaces/wait.js +158 -0
- package/dist/facade/exec-sync.d.ts +4 -0
- package/dist/facade/exec-sync.js +38 -0
- package/dist/facade/run.js +19 -20
- package/dist/facade/session.js +75 -89
- package/dist/facade/workspace.d.ts +5 -20
- package/dist/facade/workspace.js +122 -277
- package/dist/index.d.ts +1 -0
- package/dist/index.js +2 -0
- package/dist/internal/map-error.js +20 -1
- package/dist/internal/workspace-phase.d.ts +41 -0
- package/dist/internal/workspace-phase.js +95 -0
- package/dist/types.d.ts +42 -6
- package/package.json +3 -3
package/dist/effect/runtime.js
CHANGED
|
@@ -1,64 +1,56 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* The SDK runtime
|
|
2
|
+
* The SDK runtime: the one bridge from the Promise facade to the Effect services.
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
4
|
+
* A `ManagedRuntime` over the SDK's layer, built lazily on the first call and once: the contract
|
|
5
|
+
* client, the events channel and the services, over a fetch `HttpClient` (the configured `fetch`,
|
|
6
|
+
* else the global one) and the global `WebSocket`. Every facade call runs one effect on it and
|
|
7
|
+
* surfaces a plain `SealantError` (the typed failure is squashed and mapped here). A call given an
|
|
8
|
+
* `AbortSignal` is interrupted when it aborts. `dispose()` interrupts every call still running,
|
|
9
|
+
* then releases the layer.
|
|
10
10
|
*/
|
|
11
|
-
import { Cause,
|
|
11
|
+
import { Cause, Exit, Layer, ManagedRuntime, Stream } from "effect";
|
|
12
12
|
import { toSealantError } from "../internal/map-error.js";
|
|
13
|
-
import {
|
|
13
|
+
import { fetchHttpClientFrom, HostRequestPriority, sealantConfigFrom } from "./api-client.js";
|
|
14
|
+
import { SealantLayerNoInfra } from "./layer.js";
|
|
14
15
|
import { captureCallerTrace, continueCallerTrace } from "./trace.js";
|
|
15
|
-
|
|
16
|
-
|
|
16
|
+
import { WebSocketConstructorLayer } from "./websocket.js";
|
|
17
|
+
/** The SDK's layer over the facade's resolved config, with its config in the context too. */
|
|
18
|
+
export const sdkLayer = (config) => SealantLayerNoInfra.pipe(Layer.provide([
|
|
19
|
+
fetchHttpClientFrom(config),
|
|
20
|
+
Layer.succeed(HostRequestPriority, config.requestPriority),
|
|
21
|
+
]), Layer.provideMerge(Layer.merge(sealantConfigFrom(config), WebSocketConstructorLayer)));
|
|
22
|
+
/**
|
|
23
|
+
* `stream` as an async iterable over the context `context` resolves (a runtime's, built on the
|
|
24
|
+
* first `next`), its failures mapped to plain `SealantError`s.
|
|
25
|
+
*/
|
|
26
|
+
export const iterateOn = (context, stream) => ({
|
|
27
|
+
[Symbol.asyncIterator]: () => {
|
|
28
|
+
let iterator;
|
|
29
|
+
const started = async () => {
|
|
30
|
+
iterator ??= Stream.toAsyncIterableWith(stream.pipe(Stream.mapError(toSealantError)), await context())[Symbol.asyncIterator]();
|
|
31
|
+
return iterator;
|
|
32
|
+
};
|
|
33
|
+
return {
|
|
34
|
+
next: async () => (await started()).next(),
|
|
35
|
+
return: async () => iterator?.return === undefined
|
|
36
|
+
? { done: true, value: undefined }
|
|
37
|
+
: iterator.return(undefined),
|
|
38
|
+
};
|
|
39
|
+
},
|
|
40
|
+
});
|
|
17
41
|
export const makeSdkRuntime = (config) => {
|
|
18
|
-
const
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
if (
|
|
22
|
-
built = Effect.runPromiseExit(Effect.gen(function* () {
|
|
23
|
-
const scope = yield* Scope.make();
|
|
24
|
-
const context = yield* Layer.buildWithScope(appLayer, scope);
|
|
25
|
-
// The layer provides a superset of SdkServices; narrow to the surfaced services.
|
|
26
|
-
return { context, scope };
|
|
27
|
-
})).then((exit) => {
|
|
28
|
-
if (Exit.isSuccess(exit)) {
|
|
29
|
-
return exit.value;
|
|
30
|
-
}
|
|
31
|
-
// The layer's error channel is non-`never` (e.g. SqlError: the DB pool can fail to construct),
|
|
32
|
-
// so route a build failure through the SAME funnel as operations instead of leaking a raw
|
|
33
|
-
// Effect/SQL error out of the public Promise API. Reset memoization so a transient first-build
|
|
34
|
-
// failure (DB momentarily down) can be retried instead of poisoning the runtime forever.
|
|
35
|
-
built = undefined;
|
|
36
|
-
throw toSealantError(Cause.squash(exit.cause));
|
|
37
|
-
});
|
|
38
|
-
}
|
|
39
|
-
return built;
|
|
40
|
-
};
|
|
41
|
-
const runTraced = async (effect, trace) => {
|
|
42
|
-
const { context } = await build();
|
|
43
|
-
const provided = Effect.provide(effect, context).pipe(continueCallerTrace(trace));
|
|
44
|
-
const exit = await Effect.runPromiseExit(provided);
|
|
45
|
-
if (Exit.isSuccess(exit)) {
|
|
42
|
+
const runtime = ManagedRuntime.make(sdkLayer(config));
|
|
43
|
+
const runTraced = async (effect, trace, signal) => {
|
|
44
|
+
const exit = await runtime.runPromiseExit(effect.pipe(continueCallerTrace(trace)), signal === undefined ? undefined : { signal });
|
|
45
|
+
if (Exit.isSuccess(exit))
|
|
46
46
|
return exit.value;
|
|
47
|
-
}
|
|
48
47
|
// Squash the Cause to its underlying failure/defect value, then map to a plain error.
|
|
49
48
|
throw toSealantError(Cause.squash(exit.cause));
|
|
50
49
|
};
|
|
51
50
|
return {
|
|
52
51
|
// Captured before the first `await`, while a calling Effect fiber is still current.
|
|
53
|
-
run: (effect, trace) => runTraced(effect, trace ?? captureCallerTrace(config.traceContext)),
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
return;
|
|
57
|
-
}
|
|
58
|
-
const current = built;
|
|
59
|
-
built = undefined;
|
|
60
|
-
const { scope } = await current;
|
|
61
|
-
await Effect.runPromise(Scope.close(scope, Exit.succeed(undefined)));
|
|
62
|
-
},
|
|
52
|
+
run: (effect, trace, signal) => runTraced(effect, trace ?? captureCallerTrace(config.traceContext), signal),
|
|
53
|
+
iterate: (stream) => iterateOn(runtime.context, stream),
|
|
54
|
+
dispose: () => runtime.dispose(),
|
|
63
55
|
};
|
|
64
56
|
};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { Effect, Redacted, type Scope } from "effect";
|
|
2
|
+
import { Socket } from "effect/socket";
|
|
3
|
+
import { SessionAttachError } from "../errors.js";
|
|
4
|
+
import type { AttachedSession } from "./service.js";
|
|
5
|
+
export interface AttachTarget {
|
|
6
|
+
readonly baseUrl: string;
|
|
7
|
+
readonly sessionId: string;
|
|
8
|
+
readonly ownerUserId: string;
|
|
9
|
+
readonly fromSequence: bigint;
|
|
10
|
+
readonly token: Redacted.Redacted | undefined;
|
|
11
|
+
}
|
|
12
|
+
export declare const attachSession: (target: AttachTarget) => Effect.Effect<AttachedSession, SessionAttachError, Scope.Scope | Socket.WebSocketConstructor>;
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The attach socket, `GET /v1/sessions/:sessionId/attach`, as a scoped duplex channel that keeps
|
|
3
|
+
* its place across cuts. The wire frames are `sessionAttachServerFrameSchema` and
|
|
4
|
+
* `sessionAttachClientFrameSchema` in `@sealant/api-contracts`:
|
|
5
|
+
*
|
|
6
|
+
* server → client binary = one output record; text `seq` = the next binary frame's sequence,
|
|
7
|
+
* `error` = a client frame was refused, `end` = the session ended (then close)
|
|
8
|
+
* client → server binary = input; text `resize` | `signal`
|
|
9
|
+
*
|
|
10
|
+
* One `Socket` dials a new WebSocket for each connection, its URL read when it dials: every
|
|
11
|
+
* connection asks for the sequence after the last record delivered, so a socket closed without
|
|
12
|
+
* `end` is reopened where it stopped, and a record replayed twice is dropped. The socket's writer
|
|
13
|
+
* waits while it is reopening, so input sent across a cut is delivered once it is back.
|
|
14
|
+
*/
|
|
15
|
+
import { sessionAttachServerFrameSchema, } from "@sealant/api-contracts";
|
|
16
|
+
import { Deferred, Duration, Effect, Option, Queue, Random, Redacted, Ref, Schema, Stream, } from "effect";
|
|
17
|
+
import { Socket } from "effect/socket";
|
|
18
|
+
import { SessionAttachError, SessionEndedError } from "../errors.js";
|
|
19
|
+
const decodeServerFrame = Schema.decodeUnknownOption(Schema.fromJsonString(sessionAttachServerFrameSchema));
|
|
20
|
+
/** Cuts in a row with no record received before the attachment gives up. */
|
|
21
|
+
const MAX_RECONNECTS = 8;
|
|
22
|
+
const RECONNECT_FIRST = Duration.millis(100);
|
|
23
|
+
const RECONNECT_MAX = Duration.seconds(5);
|
|
24
|
+
const OPEN_TIMEOUT = Duration.seconds(10);
|
|
25
|
+
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));
|
|
26
|
+
const encoder = new TextEncoder();
|
|
27
|
+
/** The socket's URL for a connection that starts at `from`. The token never goes in it. */
|
|
28
|
+
const attachUrl = (target, from) => {
|
|
29
|
+
const url = new URL(`/v1/sessions/${encodeURIComponent(target.sessionId)}/attach`, target.baseUrl);
|
|
30
|
+
url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
|
|
31
|
+
url.searchParams.set("fromSequence", from.toString());
|
|
32
|
+
url.searchParams.set("ownerUserId", target.ownerUserId);
|
|
33
|
+
return url.toString();
|
|
34
|
+
};
|
|
35
|
+
const closeCodeOf = (error) => error.reason instanceof Socket.SocketCloseError ? error.reason.code : undefined;
|
|
36
|
+
export const attachSession = (target) => Effect.gen(function* () {
|
|
37
|
+
const { sessionId } = target;
|
|
38
|
+
// The next sequence the consumer has not been given: what a reconnect asks for.
|
|
39
|
+
const next = yield* Ref.make(target.fromSequence);
|
|
40
|
+
const cuts = yield* Ref.make(0);
|
|
41
|
+
// Unbounded, as the socket's own buffer is: a consumer that reads `exit` and not `output`
|
|
42
|
+
// must not keep the `end` frame from being read.
|
|
43
|
+
const output = yield* Queue.unbounded();
|
|
44
|
+
const exit = yield* Deferred.make();
|
|
45
|
+
const opened = yield* Deferred.make();
|
|
46
|
+
// Closing the scope ends `output` for a consumer still reading it.
|
|
47
|
+
yield* Effect.addFinalizer(() => Queue.end(output));
|
|
48
|
+
const socket = yield* Socket.makeWebSocket(Effect.map(Ref.get(next), (from) => attachUrl(target, from)), {
|
|
49
|
+
openTimeout: OPEN_TIMEOUT,
|
|
50
|
+
...(target.token === undefined
|
|
51
|
+
? {}
|
|
52
|
+
: { headers: { authorization: `Bearer ${Redacted.value(target.token)}` } }),
|
|
53
|
+
});
|
|
54
|
+
const writer = yield* socket.writer;
|
|
55
|
+
const failWith = (error) => Effect.all([Deferred.fail(exit, error), Queue.fail(output, error)], { discard: true });
|
|
56
|
+
/** One connection: frames until the session's `end` or the socket closes. */
|
|
57
|
+
const connection = Effect.scoped(Effect.gen(function* () {
|
|
58
|
+
const reader = yield* socket.reader;
|
|
59
|
+
yield* Deferred.succeed(opened, undefined);
|
|
60
|
+
// The sequence a `seq` frame named for the binary frame after it.
|
|
61
|
+
let named;
|
|
62
|
+
for (;;) {
|
|
63
|
+
const frames = yield* reader.pull;
|
|
64
|
+
for (const frame of frames) {
|
|
65
|
+
if (typeof frame === "string") {
|
|
66
|
+
const decoded = decodeServerFrame(frame);
|
|
67
|
+
if (Option.isNone(decoded))
|
|
68
|
+
continue;
|
|
69
|
+
const server = decoded.value;
|
|
70
|
+
if (server.t === "seq")
|
|
71
|
+
named = BigInt(server.sequence);
|
|
72
|
+
else if (server.t === "error") {
|
|
73
|
+
yield* Effect.logWarning("The control plane refused a frame on the attach socket").pipe(Effect.annotateLogs({ sessionId, message: server.message }));
|
|
74
|
+
}
|
|
75
|
+
else {
|
|
76
|
+
const { t: _t, ...ended } = server;
|
|
77
|
+
yield* Deferred.succeed(exit, ended);
|
|
78
|
+
return { kind: "ended" };
|
|
79
|
+
}
|
|
80
|
+
continue;
|
|
81
|
+
}
|
|
82
|
+
const wanted = yield* Ref.get(next);
|
|
83
|
+
const sequence = named ?? wanted;
|
|
84
|
+
named = undefined;
|
|
85
|
+
// Replayed after a reconnect but already delivered: once is enough.
|
|
86
|
+
if (sequence < wanted)
|
|
87
|
+
continue;
|
|
88
|
+
yield* Queue.offer(output, { sequence, data: frame });
|
|
89
|
+
yield* Ref.set(next, sequence + 1n);
|
|
90
|
+
yield* Ref.set(cuts, 0);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
})).pipe(Effect.catchTag("SocketError", (error) => Effect.succeed({ kind: "cut", closeCode: closeCodeOf(error) })));
|
|
94
|
+
const pump = Effect.gen(function* () {
|
|
95
|
+
for (;;) {
|
|
96
|
+
const ended = yield* connection;
|
|
97
|
+
if (ended.kind === "ended") {
|
|
98
|
+
yield* Queue.end(output);
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
101
|
+
const everOpened = yield* Deferred.isDone(opened);
|
|
102
|
+
if (!everOpened) {
|
|
103
|
+
const error = new SessionAttachError({
|
|
104
|
+
sessionId,
|
|
105
|
+
message: `Could not attach to session ${sessionId}${ended.closeCode === undefined ? "" : ` (close ${String(ended.closeCode)})`}.`,
|
|
106
|
+
...(ended.closeCode === undefined ? {} : { closeCode: ended.closeCode }),
|
|
107
|
+
});
|
|
108
|
+
yield* Deferred.fail(opened, error);
|
|
109
|
+
yield* failWith(error);
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
const attempt = yield* Ref.getAndUpdate(cuts, (n) => n + 1);
|
|
113
|
+
if (attempt >= MAX_RECONNECTS) {
|
|
114
|
+
yield* failWith(new SessionAttachError({
|
|
115
|
+
sessionId,
|
|
116
|
+
message: `The attach socket for session ${sessionId} was cut ${String(attempt)} times in a row without output.`,
|
|
117
|
+
...(ended.closeCode === undefined ? {} : { closeCode: ended.closeCode }),
|
|
118
|
+
}));
|
|
119
|
+
return;
|
|
120
|
+
}
|
|
121
|
+
yield* Effect.sleep(yield* reconnectDelay(attempt));
|
|
122
|
+
}
|
|
123
|
+
});
|
|
124
|
+
yield* Effect.forkScoped(pump);
|
|
125
|
+
yield* Deferred.await(opened);
|
|
126
|
+
/** Sends a frame, or fails at once once the session has ended or the attachment failed. */
|
|
127
|
+
const send = (frame) => Effect.raceFirst(writer.write(frame).pipe(Effect.mapError((cause) => new SessionAttachError({
|
|
128
|
+
sessionId,
|
|
129
|
+
message: `Could not write to session ${sessionId}'s attach socket.`,
|
|
130
|
+
cause,
|
|
131
|
+
}))), Deferred.await(exit).pipe(Effect.flatMap((ended) => Effect.fail(new SessionEndedError({ sessionId, ended })))));
|
|
132
|
+
const control = (frame) => send(JSON.stringify(frame));
|
|
133
|
+
return {
|
|
134
|
+
sessionId,
|
|
135
|
+
output: Stream.fromQueue(output),
|
|
136
|
+
// A copy: `WebSocket.send` refuses a view over a `SharedArrayBuffer`.
|
|
137
|
+
write: (data) => send(typeof data === "string" ? encoder.encode(data) : new Uint8Array(data)),
|
|
138
|
+
resize: (cols, rows) => control({ t: "resize", cols, rows }),
|
|
139
|
+
signal: (signal) => control({ t: "signal", signal }),
|
|
140
|
+
exit: Deferred.await(exit),
|
|
141
|
+
};
|
|
142
|
+
});
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { Effect, Layer } from "effect";
|
|
2
|
+
import type { HttpClient } from "effect/http";
|
|
3
|
+
import { Socket } from "effect/socket";
|
|
4
|
+
import { SealantApiClient } from "../api-client.js";
|
|
5
|
+
import { SealantConfig } from "../config.js";
|
|
6
|
+
import { SseClient } from "../http.js";
|
|
7
|
+
import { Sessions } from "./service.js";
|
|
8
|
+
export declare const make: Effect.Effect<Sessions["Service"], never, SealantApiClient | SseClient | SealantConfig | Socket.WebSocketConstructor>;
|
|
9
|
+
export declare const layerNoDeps: Layer.Layer<Sessions, never, SealantApiClient | SseClient | SealantConfig | Socket.WebSocketConstructor>;
|
|
10
|
+
export declare const layer: Layer.Layer<Sessions, never, SealantConfig | HttpClient.HttpClient | Socket.WebSocketConstructor>;
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
import { Duration, Effect, Layer, Option, Random, Ref, Stream } from "effect";
|
|
2
|
+
import { Socket } from "effect/socket";
|
|
3
|
+
import { CurrentRequestPriority, SealantApiClient } from "../api-client.js";
|
|
4
|
+
import { SealantConfig } from "../config.js";
|
|
5
|
+
import { currentOwner } from "../context.js";
|
|
6
|
+
import { SealantTransportError, transported } from "../errors.js";
|
|
7
|
+
import { SseClient } from "../http.js";
|
|
8
|
+
import { attachSession } from "./attach.js";
|
|
9
|
+
import { Sessions, } from "./service.js";
|
|
10
|
+
const encoder = new TextEncoder();
|
|
11
|
+
const toBase64 = (data) => Buffer.from(typeof data === "string" ? encoder.encode(data) : data).toString("base64");
|
|
12
|
+
const fromBase64 = (value) => {
|
|
13
|
+
const buffer = Buffer.from(value, "base64");
|
|
14
|
+
return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
|
|
15
|
+
};
|
|
16
|
+
/** Cuts in a row with nothing received before `output` fails with the last. */
|
|
17
|
+
const OUTPUT_RECONNECTS = 10;
|
|
18
|
+
const OUTPUT_RECONNECT_FIRST = Duration.millis(250);
|
|
19
|
+
const OUTPUT_RECONNECT_MAX = Duration.seconds(5);
|
|
20
|
+
const OUTPUT_ROUTE = { method: "GET", path: "/v1/sessions/:sessionId/output/stream" };
|
|
21
|
+
export const make = Effect.gen(function* () {
|
|
22
|
+
const client = yield* SealantApiClient;
|
|
23
|
+
const sse = yield* SseClient;
|
|
24
|
+
const config = yield* SealantConfig;
|
|
25
|
+
const makeWebSocket = yield* Socket.WebSocketConstructor;
|
|
26
|
+
const owner = currentOwner.pipe(Effect.provideService(SealantConfig, config));
|
|
27
|
+
const interactive = Effect.provideService(CurrentRequestPriority, "interactive");
|
|
28
|
+
const open = Effect.fnUntraced(function* (request) {
|
|
29
|
+
const ownerUserId = yield* owner;
|
|
30
|
+
return yield* client.sessions
|
|
31
|
+
.createSession({ payload: { ...request, ownerUserId }, headers: {} })
|
|
32
|
+
.pipe(transported("Sessions.open"));
|
|
33
|
+
});
|
|
34
|
+
const openAsUser = Effect.fnUntraced(function* (request) {
|
|
35
|
+
const ownerUserId = yield* owner;
|
|
36
|
+
return yield* client.sessions
|
|
37
|
+
.createSessionAsUser({ payload: { ...request, ownerUserId }, headers: {} })
|
|
38
|
+
.pipe(transported("Sessions.openAsUser"));
|
|
39
|
+
});
|
|
40
|
+
const get = Effect.fnUntraced(function* (sessionId) {
|
|
41
|
+
const ownerUserId = yield* owner;
|
|
42
|
+
return yield* client.sessions
|
|
43
|
+
.getSession({ params: { sessionId }, headers: {}, query: { ownerUserId } })
|
|
44
|
+
.pipe(transported("Sessions.get"));
|
|
45
|
+
});
|
|
46
|
+
const list = Effect.fnUntraced(function* (query = {}) {
|
|
47
|
+
const ownerUserId = yield* owner;
|
|
48
|
+
return yield* client.sessions
|
|
49
|
+
.listSessions({ query: { ...query, ownerUserId }, headers: {} })
|
|
50
|
+
.pipe(transported("Sessions.list"));
|
|
51
|
+
});
|
|
52
|
+
const write = Effect.fnUntraced(function* (sessionId, data) {
|
|
53
|
+
const ownerUserId = yield* owner;
|
|
54
|
+
yield* client.sessions
|
|
55
|
+
.sendSessionInput({
|
|
56
|
+
params: { sessionId },
|
|
57
|
+
headers: {},
|
|
58
|
+
payload: { ownerUserId, dataBase64: toBase64(data) },
|
|
59
|
+
})
|
|
60
|
+
.pipe(interactive, transported("Sessions.write"));
|
|
61
|
+
});
|
|
62
|
+
const resize = Effect.fnUntraced(function* (sessionId, cols, rows) {
|
|
63
|
+
const ownerUserId = yield* owner;
|
|
64
|
+
yield* client.sessions
|
|
65
|
+
.resizeSession({ params: { sessionId }, headers: {}, payload: { ownerUserId, cols, rows } })
|
|
66
|
+
.pipe(interactive, transported("Sessions.resize"));
|
|
67
|
+
});
|
|
68
|
+
const signal = Effect.fnUntraced(function* (sessionId, number) {
|
|
69
|
+
const ownerUserId = yield* owner;
|
|
70
|
+
yield* client.sessions
|
|
71
|
+
.signalSession({
|
|
72
|
+
params: { sessionId },
|
|
73
|
+
headers: {},
|
|
74
|
+
payload: { ownerUserId, signal: number },
|
|
75
|
+
})
|
|
76
|
+
.pipe(interactive, transported("Sessions.signal"));
|
|
77
|
+
});
|
|
78
|
+
const close = Effect.fnUntraced(function* (sessionId) {
|
|
79
|
+
const ownerUserId = yield* owner;
|
|
80
|
+
return yield* client.sessions
|
|
81
|
+
.closeSession({ params: { sessionId }, headers: {}, payload: { ownerUserId } })
|
|
82
|
+
.pipe(interactive, transported("Sessions.close"));
|
|
83
|
+
});
|
|
84
|
+
const output = (sessionId, options = {}) => Stream.unwrap(Effect.gen(function* () {
|
|
85
|
+
const ownerUserId = yield* owner;
|
|
86
|
+
// The next sequence the consumer has not been given: what a reconnect asks for.
|
|
87
|
+
const next = yield* Ref.make(options.fromSequence ?? 0n);
|
|
88
|
+
const cuts = yield* Ref.make(0);
|
|
89
|
+
const ended = yield* Ref.make(false);
|
|
90
|
+
const connection = Stream.unwrap(Effect.map(Ref.get(next), (from) => sse.connect({
|
|
91
|
+
route: OUTPUT_ROUTE,
|
|
92
|
+
span: "sealant.sdk.sessions.output_stream",
|
|
93
|
+
path: `/v1/sessions/${encodeURIComponent(sessionId)}/output/stream`,
|
|
94
|
+
query: { fromSequence: from.toString(), ownerUserId },
|
|
95
|
+
})));
|
|
96
|
+
const deliver = (chunk) => Effect.gen(function* () {
|
|
97
|
+
// Replayed after a reconnect but already delivered: once is enough.
|
|
98
|
+
if (chunk.sequence < (yield* Ref.get(next)))
|
|
99
|
+
return false;
|
|
100
|
+
yield* Ref.set(next, chunk.sequence + 1n);
|
|
101
|
+
yield* Ref.set(cuts, 0);
|
|
102
|
+
return true;
|
|
103
|
+
});
|
|
104
|
+
const following = connection.pipe(
|
|
105
|
+
// `end` is the only sign the session ended: a body that stops without it was cut.
|
|
106
|
+
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) => ({
|
|
107
|
+
sequence: BigInt(event.id ?? "0"),
|
|
108
|
+
data: fromBase64(event.data),
|
|
109
|
+
})), Stream.filterEffect(deliver), Stream.catchTag("SealantTransportError", () => Stream.empty), Stream.concat(Stream.unwrap(Effect.map(Ref.get(ended), (done) => (done ? Stream.empty : reconnect)))));
|
|
110
|
+
const reconnect = Stream.unwrap(Effect.gen(function* () {
|
|
111
|
+
const attempt = yield* Ref.getAndUpdate(cuts, (n) => n + 1);
|
|
112
|
+
if (attempt >= OUTPUT_RECONNECTS) {
|
|
113
|
+
return Stream.fail(new SealantTransportError({
|
|
114
|
+
operation: "Sessions.output",
|
|
115
|
+
message: `The output stream of session ${sessionId} was cut ${String(attempt)} times in a row without output.`,
|
|
116
|
+
cause: undefined,
|
|
117
|
+
}));
|
|
118
|
+
}
|
|
119
|
+
const factor = yield* Random.nextBetween(0.8, 1.2);
|
|
120
|
+
yield* Effect.sleep(Duration.times(Duration.min(Duration.times(OUTPUT_RECONNECT_FIRST, 2 ** attempt), OUTPUT_RECONNECT_MAX), factor));
|
|
121
|
+
return following;
|
|
122
|
+
}));
|
|
123
|
+
return following;
|
|
124
|
+
}));
|
|
125
|
+
const attach = Effect.fn("sealant.sdk.open_attach_socket")(function* (sessionId, options = {}) {
|
|
126
|
+
const ownerUserId = options.ownerUserId ?? (yield* owner);
|
|
127
|
+
return yield* attachSession({
|
|
128
|
+
baseUrl: config.baseUrl,
|
|
129
|
+
sessionId,
|
|
130
|
+
ownerUserId,
|
|
131
|
+
fromSequence: options.fromSequence ?? 0n,
|
|
132
|
+
token: options.accessToken ?? Option.getOrUndefined(config.apiKey),
|
|
133
|
+
}).pipe(Effect.provideService(Socket.WebSocketConstructor, makeWebSocket));
|
|
134
|
+
});
|
|
135
|
+
return Sessions.of({
|
|
136
|
+
open,
|
|
137
|
+
openAsUser,
|
|
138
|
+
get,
|
|
139
|
+
list,
|
|
140
|
+
write,
|
|
141
|
+
resize,
|
|
142
|
+
signal,
|
|
143
|
+
close,
|
|
144
|
+
output,
|
|
145
|
+
attach,
|
|
146
|
+
});
|
|
147
|
+
});
|
|
148
|
+
export const layerNoDeps = Layer.effect(Sessions, make);
|
|
149
|
+
export const layer = layerNoDeps.pipe(Layer.provide([SealantApiClient.layer, SseClient.layer]));
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `Sessions`: interactive `pty` and `pipe` sessions as Effects. The request/response verbs
|
|
3
|
+
* (`write`, `resize`, `signal`) suit a control action; a terminal or a process that speaks a
|
|
4
|
+
* protocol over stdio attaches instead (`attach`): one held socket, both ways, that survives a cut.
|
|
5
|
+
*/
|
|
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";
|
|
8
|
+
import type { EndpointError } from "../endpoint.js";
|
|
9
|
+
import type { SealantStreamRefusedError, SealantTransportError, SessionAttachError, SessionEndedError } from "../errors.js";
|
|
10
|
+
/** One output record of a session: its journal sequence and its bytes, exactly as recorded. */
|
|
11
|
+
export interface SessionOutputChunk {
|
|
12
|
+
readonly sequence: bigint;
|
|
13
|
+
readonly data: Uint8Array;
|
|
14
|
+
}
|
|
15
|
+
/** A POSIX signal number: 2 is `SIGINT`, 15 `SIGTERM`. */
|
|
16
|
+
export type SessionSignal = number;
|
|
17
|
+
type Owned<T> = Omit<T, "ownerUserId">;
|
|
18
|
+
export interface OutputOptions {
|
|
19
|
+
/** The first journal sequence to read (inclusive). Default 0: the session's whole output. */
|
|
20
|
+
readonly fromSequence?: bigint | undefined;
|
|
21
|
+
}
|
|
22
|
+
export interface AttachOptions {
|
|
23
|
+
/** The first journal sequence to replay (inclusive). Default 0: the session's whole output. */
|
|
24
|
+
readonly fromSequence?: bigint | undefined;
|
|
25
|
+
/** Whose session. Default: `ActingOwner`, else the configured owner. */
|
|
26
|
+
readonly ownerUserId?: string | undefined;
|
|
27
|
+
/**
|
|
28
|
+
* Attach with this access token instead of the configured key: `session:read` watches, and
|
|
29
|
+
* `session:input` as well lets `write`, `resize` and `signal` through.
|
|
30
|
+
*/
|
|
31
|
+
readonly accessToken?: Redacted.Redacted | undefined;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* A session attached over one WebSocket, for as long as the scope it was attached in. A socket
|
|
35
|
+
* closed without the session's `end` frame (a deploy, a dropped connection) is reopened from the
|
|
36
|
+
* sequence after the last one received, so `output` carries every record once, in order, across
|
|
37
|
+
* cuts. Input sent while the socket is reopening waits for it.
|
|
38
|
+
*/
|
|
39
|
+
export interface AttachedSession {
|
|
40
|
+
readonly sessionId: string;
|
|
41
|
+
/**
|
|
42
|
+
* Output records: the replay from `fromSequence`, then live, ending when the session ends. One
|
|
43
|
+
* consumer: each record is delivered once.
|
|
44
|
+
*/
|
|
45
|
+
readonly output: Stream.Stream<SessionOutputChunk, SessionAttachError>;
|
|
46
|
+
/** Keystrokes for a `pty` session, stdin for a `pipe` one. A string is sent as UTF-8. */
|
|
47
|
+
readonly write: (data: Uint8Array | string) => Effect.Effect<void, SessionEndedError | SessionAttachError>;
|
|
48
|
+
/** Resizes a `pty` session's terminal; the control plane refuses it for a `pipe` session. */
|
|
49
|
+
readonly resize: (cols: number, rows: number) => Effect.Effect<void, SessionEndedError | SessionAttachError>;
|
|
50
|
+
/** Delivers a signal to the session's leader. */
|
|
51
|
+
readonly signal: (signal: SessionSignal) => Effect.Effect<void, SessionEndedError | SessionAttachError>;
|
|
52
|
+
/**
|
|
53
|
+
* How the session ended, once the control plane says it did (its `end` frame). Fails with
|
|
54
|
+
* `SessionAttachError` when the socket could not be kept open.
|
|
55
|
+
*/
|
|
56
|
+
readonly exit: Effect.Effect<SessionEnded, SessionAttachError>;
|
|
57
|
+
}
|
|
58
|
+
export type SessionReadError = EndpointError<"sessions", "getSession">;
|
|
59
|
+
export interface SessionsShape {
|
|
60
|
+
readonly open: (request: Owned<CreateSessionRequest>) => Effect.Effect<SessionWire, EndpointError<"sessions", "createSession">>;
|
|
61
|
+
/** Opens a session whose leader runs as a Linux user (see `workspaceProcessUserSchema`). */
|
|
62
|
+
readonly openAsUser: (request: Owned<CreateSessionAsUserRequest>) => Effect.Effect<SessionWire, EndpointError<"sessions", "createSessionAsUser">>;
|
|
63
|
+
readonly get: (sessionId: string) => Effect.Effect<SessionWire, SessionReadError>;
|
|
64
|
+
readonly list: (query?: Owned<ListSessionsQuery>) => Effect.Effect<ListSessionsResponse, EndpointError<"sessions", "listSessions">>;
|
|
65
|
+
/** Sends input in one request. */
|
|
66
|
+
readonly write: (sessionId: string, data: Uint8Array | string) => Effect.Effect<void, EndpointError<"sessions", "sendSessionInput">>;
|
|
67
|
+
readonly resize: (sessionId: string, cols: number, rows: number) => Effect.Effect<void, EndpointError<"sessions", "resizeSession">>;
|
|
68
|
+
readonly signal: (sessionId: string, signal: SessionSignal) => Effect.Effect<void, EndpointError<"sessions", "signalSession">>;
|
|
69
|
+
/** Hangs up the session; answers once the control plane has asked it to end. */
|
|
70
|
+
readonly close: (sessionId: string) => Effect.Effect<SessionWire, EndpointError<"sessions", "closeSession">>;
|
|
71
|
+
/**
|
|
72
|
+
* Output over the session's SSE stream: from `fromSequence`, then live, ending at the session's
|
|
73
|
+
* `end`. A body cut without `end` is reopened from the next sequence, with backoff; after ten
|
|
74
|
+
* cuts in a row with nothing received, the stream fails with the last.
|
|
75
|
+
*/
|
|
76
|
+
readonly output: (sessionId: string, options?: OutputOptions) => Stream.Stream<SessionOutputChunk, SealantStreamRefusedError | SealantTransportError>;
|
|
77
|
+
/** Attaches over the socket for the scope's lifetime (see {@link AttachedSession}). */
|
|
78
|
+
readonly attach: (sessionId: string, options?: AttachOptions) => Effect.Effect<AttachedSession, SessionAttachError, Scope.Scope>;
|
|
79
|
+
}
|
|
80
|
+
declare const Sessions_base: Context.ServiceClass<Sessions, "@sealant/sdk/Sessions", SessionsShape>;
|
|
81
|
+
export declare class Sessions extends Sessions_base {
|
|
82
|
+
}
|
|
83
|
+
export {};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A `WebSocketConstructor` that sends upgrade headers: the attach socket carries its API key as
|
|
3
|
+
* `Authorization: Bearer`, never in the URL, where proxy and access logs would keep it.
|
|
4
|
+
*
|
|
5
|
+
* Effect's `Socket.layerWebSocketConstructorGlobal` refuses headers, because a browser's
|
|
6
|
+
* `WebSocket` cannot send them. Node's global `WebSocket` (undici, Node 22 and later), Bun's and
|
|
7
|
+
* Deno's take them in an init object, which this passes through.
|
|
8
|
+
*/
|
|
9
|
+
import { Layer } from "effect";
|
|
10
|
+
import { Socket } from "effect/socket";
|
|
11
|
+
export declare const WebSocketConstructorLayer: Layer.Layer<Socket.WebSocketConstructor>;
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A `WebSocketConstructor` that sends upgrade headers: the attach socket carries its API key as
|
|
3
|
+
* `Authorization: Bearer`, never in the URL, where proxy and access logs would keep it.
|
|
4
|
+
*
|
|
5
|
+
* Effect's `Socket.layerWebSocketConstructorGlobal` refuses headers, because a browser's
|
|
6
|
+
* `WebSocket` cannot send them. Node's global `WebSocket` (undici, Node 22 and later), Bun's and
|
|
7
|
+
* Deno's take them in an init object, which this passes through.
|
|
8
|
+
*/
|
|
9
|
+
import { Layer } from "effect";
|
|
10
|
+
import { Socket } from "effect/socket";
|
|
11
|
+
export const WebSocketConstructorLayer = Layer.succeed(Socket.WebSocketConstructor, (url, options) => {
|
|
12
|
+
// Read at each call, not at import: the global is looked up when a socket is opened.
|
|
13
|
+
// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Node's, Bun's and Deno's global WebSocket take this init object; the DOM lib in scope does not declare it.
|
|
14
|
+
const WebSocket = globalThis.WebSocket;
|
|
15
|
+
return new WebSocket(url, options);
|
|
16
|
+
});
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { Effect, Layer } from "effect";
|
|
2
|
+
import type { HttpClient } from "effect/http";
|
|
3
|
+
import { SealantApiClient } from "../api-client.js";
|
|
4
|
+
import { SealantConfig } from "../config.js";
|
|
5
|
+
import { SealantEvents } from "../events/service.js";
|
|
6
|
+
import { Workspaces } from "./service.js";
|
|
7
|
+
export declare const make: Effect.Effect<Workspaces["Service"], never, SealantApiClient | SealantEvents | SealantConfig>;
|
|
8
|
+
export declare const layerNoDeps: Layer.Layer<Workspaces, never, SealantApiClient | SealantEvents | SealantConfig>;
|
|
9
|
+
export declare const layer: Layer.Layer<Workspaces, never, SealantConfig | HttpClient.HttpClient>;
|