Open History to see the last commit
1import * as Context from "effect/Context";
2import * as Effect from "effect/Effect";
3import * as Exit from "effect/Exit";
4import * as Fiber from "effect/Fiber";
5import * as Layer from "effect/Layer";
6import * as Scope from "effect/Scope";
7import * as Semaphore from "effect/Semaphore";
8
9import * as OpenCodeRuntime from "./opencodeRuntime.ts";
10
11const OPENCODE_SERVER_IDLE_TTL = "30 seconds";
12
13interface OpenCodeServerOwnerState {
14 server: OpenCodeRuntime.OpenCodeServerProcess | null;
15 serverScope: Scope.Closeable | null;
16 borrowers: number;
17 idleCloseFiber: Fiber.Fiber<void, never> | null;
18}
19
20export class OpenCodeServerOwner extends Context.Service<
21 OpenCodeServerOwner,
22 {
23 readonly withServer: <A, E, R>(
24 use: (server: OpenCodeRuntime.OpenCodeServerProcess) => Effect.Effect<A, E, R>,
25 ) => Effect.Effect<A, E | OpenCodeRuntime.OpenCodeRuntimeError, R>;
26 }
27>()("t3/provider/OpenCodeServerOwner") {}
28
29/** Owns the lazy local OpenCode server shared by one provider instance. */
30export const make = Effect.fn("OpenCodeServerOwner.make")(function* (input: {
31 readonly binaryPath: string;
32 readonly directory: string;
33 readonly serverPassword?: string;
34 readonly environment?: NodeJS.ProcessEnv;
35}) {
36 const runtime = yield* OpenCodeRuntime.OpenCodeRuntime;
37 const ownerScope = yield* Effect.acquireRelease(Scope.make(), (scope) =>
38 Scope.close(scope, Exit.void),
39 );
40 const mutex = yield* Semaphore.make(1);
41 const state: OpenCodeServerOwnerState = {
42 server: null,
43 serverScope: null,
44 borrowers: 0,
45 idleCloseFiber: null,
46 };
47
48 const cancelIdleClose = Effect.fn("OpenCodeServerOwner.cancelIdleClose")(function* () {
49 const fiber = state.idleCloseFiber;
50 state.idleCloseFiber = null;
51 if (fiber !== null) {
52 yield* Fiber.interrupt(fiber).pipe(Effect.ignore);
53 }
54 });
55
56 const closeServer = Effect.fn("OpenCodeServerOwner.closeServer")(function* (
57 expected?: OpenCodeRuntime.OpenCodeServerProcess,
58 ) {
59 if (expected !== undefined && state.server !== expected) {
60 return;
61 }
62 const scope = state.serverScope;
63 state.server = null;
64 state.serverScope = null;
65 if (scope !== null) {
66 yield* Scope.close(scope, Exit.void).pipe(Effect.ignore);
67 }
68 });
69
70 const watchServerExit = Effect.fn("OpenCodeServerOwner.watchServerExit")(function* (
71 server: OpenCodeRuntime.OpenCodeServerProcess,
72 ) {
73 yield* server.exitCode;
74 yield* mutex.withPermit(
75 Effect.gen(function* () {
76 if (state.server !== server) {
77 return;
78 }
79 yield* cancelIdleClose();
80 yield* closeServer(server);
81 }),
82 );
83 });
84
85 const acquireServer = mutex.withPermit(
86 Effect.gen(function* () {
87 yield* cancelIdleClose();
88 if (state.server !== null) {
89 if (yield* state.server.isRunning) {
90 state.borrowers += 1;
91 return state.server;
92 }
93 yield* closeServer(state.server);
94 }
95
96 return yield* Effect.uninterruptibleMask((restore) =>
97 Effect.gen(function* () {
98 const serverScope = yield* Scope.make();
99 const started = yield* Effect.exit(
100 restore(
101 runtime
102 .startOpenCodeServerProcess({
103 binaryPath: input.binaryPath,
104 directory: input.directory,
105 ...(input.serverPassword !== undefined
106 ? { serverPassword: input.serverPassword }
107 : {}),
108 ...(input.environment ? { environment: input.environment } : {}),
109 })
110 .pipe(Effect.provideService(Scope.Scope, serverScope)),
111 ),
112 );
113 if (Exit.isFailure(started)) {
114 yield* Scope.close(serverScope, Exit.void).pipe(Effect.ignore);
115 return yield* Effect.failCause(started.cause);
116 }
117
118 const server = started.value;
119 state.server = server;
120 state.serverScope = serverScope;
121 state.borrowers = 1;
122 yield* watchServerExit(server).pipe(Effect.forkIn(ownerScope));
123 return server;
124 }),
125 );
126 }),
127 );
128
129 const releaseServer = (server: OpenCodeRuntime.OpenCodeServerProcess) =>
130 mutex.withPermit(
131 Effect.gen(function* () {
132 if (state.server !== server) {
133 return;
134 }
135 state.borrowers = Math.max(0, state.borrowers - 1);
136 if (state.borrowers > 0) {
137 return;
138 }
139 yield* cancelIdleClose();
140 state.idleCloseFiber = yield* Effect.sleep(OPENCODE_SERVER_IDLE_TTL).pipe(
141 Effect.andThen(
142 mutex.withPermit(
143 Effect.gen(function* () {
144 if (state.server !== server || state.borrowers > 0) {
145 return;
146 }
147 state.idleCloseFiber = null;
148 yield* closeServer(server);
149 }),
150 ),
151 ),
152 Effect.forkIn(ownerScope),
153 );
154 }),
155 );
156
157 yield* Effect.addFinalizer(() =>
158 mutex.withPermit(
159 Effect.gen(function* () {
160 yield* cancelIdleClose();
161 state.borrowers = 0;
162 yield* closeServer();
163 }),
164 ),
165 );
166
167 return OpenCodeServerOwner.of({
168 withServer: (use) =>
169 Effect.uninterruptibleMask((restore) =>
170 restore(acquireServer).pipe(
171 Effect.flatMap((server) =>
172 restore(use(server)).pipe(Effect.ensuring(releaseServer(server))),
173 ),
174 ),
175 ),
176 });
177});
178
179/** @public Service construction is part of the canonical Effect module API. */
180export const layer = (input: {
181 readonly binaryPath: string;
182 readonly directory: string;
183 readonly serverPassword?: string;
184 readonly environment?: NodeJS.ProcessEnv;
185}) => Layer.effect(OpenCodeServerOwner, make(input));