Open History to see the last commit
1import * as Context from "effect/Context";
2import * as Effect from "effect/Effect";
3import * as Layer from "effect/Layer";
4import type * as Scope from "effect/Scope";
5
6import type { ConnectionCatalogEntry } from "./catalog.ts";
7import type {
8 ConnectionAttemptError,
9 ConnectionAttemptStage,
10 PreparedConnection,
11} from "./model.ts";
12import * as ConnectionResolver from "./resolver.ts";
13import * as RpcSession from "../rpc/session.ts";
14
15export type ConnectionDriverProgress =
16 | {
17 readonly stage: "preparing";
18 }
19 | {
20 readonly stage: Exclude<ConnectionAttemptStage, "preparing">;
21 readonly prepared: PreparedConnection;
22 };
23
24export interface EnvironmentConnectionLease {
25 readonly prepared: PreparedConnection;
26 readonly session: RpcSession.RpcSession;
27}
28
29export class ConnectionDriver extends Context.Service<
30 ConnectionDriver,
31 {
32 readonly connect: (
33 entry: ConnectionCatalogEntry,
34 reportProgress: (progress: ConnectionDriverProgress) => Effect.Effect<void>,
35 ) => Effect.Effect<EnvironmentConnectionLease, ConnectionAttemptError, Scope.Scope>;
36 }
37>()("@t3tools/client-runtime/connection/driver/ConnectionDriver") {}
38
39/** @public Service construction is part of the canonical Effect module API. */
40export const make = Effect.gen(function* () {
41 const resolver = yield* ConnectionResolver.ConnectionResolver;
42 const sessions = yield* RpcSession.RpcSessionFactory;
43
44 const connect = Effect.fn("ConnectionDriver.connect")(function* (
45 entry: ConnectionCatalogEntry,
46 reportProgress: (progress: ConnectionDriverProgress) => Effect.Effect<void>,
47 ) {
48 const target = entry.target;
49 yield* Effect.annotateCurrentSpan({
50 "connection.environment.id": target.environmentId,
51 "connection.target.kind": target._tag,
52 });
53 yield* reportProgress({ stage: "preparing" });
54 const prepared = yield* resolver.prepare(entry);
55 yield* reportProgress({ stage: "opening", prepared });
56 const session = yield* sessions.connect(prepared);
57 yield* reportProgress({ stage: "synchronizing", prepared });
58 yield* session.ready;
59 return { prepared, session } satisfies EnvironmentConnectionLease;
60 });
61
62 return ConnectionDriver.of({ connect });
63});
64
65export const layer = Layer.effect(ConnectionDriver, make);