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
39export const make = Effect.gen(function* () {
40 const resolver = yield* ConnectionResolver.ConnectionResolver;
41 const sessions = yield* RpcSession.RpcSessionFactory;
42
43 const connect = Effect.fn("ConnectionDriver.connect")(function* (
44 entry: ConnectionCatalogEntry,
45 reportProgress: (progress: ConnectionDriverProgress) => Effect.Effect<void>,
46 ) {
47 const target = entry.target;
48 yield* Effect.annotateCurrentSpan({
49 "connection.environment.id": target.environmentId,
50 "connection.target.kind": target._tag,
51 });
52 yield* reportProgress({ stage: "preparing" });
53 const prepared = yield* resolver.prepare(entry);
54 yield* reportProgress({ stage: "opening", prepared });
55 const session = yield* sessions.connect(prepared);
56 yield* reportProgress({ stage: "synchronizing", prepared });
57 yield* session.ready;
58 return { prepared, session } satisfies EnvironmentConnectionLease;
59 });
60
61 return ConnectionDriver.of({ connect });
62});
63
64export const layer = Layer.effect(ConnectionDriver, make);