Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

OpenCode2Server.live.test.ts

211 lines8.1 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { AbsolutePath, Location } from "@opencode/client/effect";
3import { assert, it } from "@effect/vitest";
4import * as Context from "effect/Context";
5import * as Effect from "effect/Effect";
6import * as Exit from "effect/Exit";
7import * as FileSystem from "effect/FileSystem";
8import * as Filter from "effect/Filter";
9import * as Layer from "effect/Layer";
10import * as Option from "effect/Option";
11import * as Path from "effect/Path";
12import * as Redacted from "effect/Redacted";
13import * as Scope from "effect/Scope";
14import * as Stream from "effect/Stream";
15import * as FetchHttpClient from "effect/http/FetchHttpClient";
16import * as ChildProcess from "effect/process/ChildProcess";
17import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
18import { describe } from "vite-plus/test";
19​
20import * as OpenCodeRuntime from "../OpenCodeRuntime.ts";
21import * as OpenCodeServerLedger from "../OpenCodeServerLedger.ts";
22import * as OpenCode2Client from "./OpenCode2Client.ts";
23import * as OpenCode2Server from "./OpenCode2Server.ts";
24​
25const binaryPath = process.env.OPENCODE2_BIN;
26​
27const isAlive = (pid: number) => {
28 try {
29 process.kill(pid, 0);
30 return true;
31 } catch {
32 return false;
33 }
34};
35​
36const stopByPid = (pid: number) =>
37 Effect.gen(function* () {
38 const signal = (name: NodeJS.Signals) => {
39 try {
40 process.kill(pid, name);
41 } catch {}
42 };
43 signal("SIGTERM");
44 for (let attempt = 0; attempt < 50 && isAlive(pid); attempt++) {
45 yield* Effect.sleep("100 millis");
46 }
47 if (isAlive(pid)) signal("SIGKILL");
48 });
49​
50const startExternalServer = Effect.fn("OpenCode2ServerLive.startExternalServer")(function* (input: {
51 readonly environment: NodeJS.ProcessEnv;
52 readonly directory: string;
53}) {
54 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
55 const child = yield* spawner.spawn(
56 ChildProcess.make(binaryPath!, ["serve", "--hostname=127.0.0.1", "--port=0"], {
57 cwd: input.directory,
58 env: input.environment,
59 }),
60 );
61 const pid = Number(child.pid);
62 yield* Effect.addFinalizer(() => stopByPid(pid));
63 const url = yield* child.stdout.pipe(
64 Stream.decodeText(),
65 Stream.splitLines,
66 Stream.filterMap(
67 Filter.fromPredicateOption((line: string) =>
68 Option.fromUndefinedOr(/server listening on\s+(https?:\/\/\S+)/i.exec(line)?.[1]),
69 ),
70 ),
71 Stream.runHead,
72 Effect.flatMap(Effect.fromOption),
73 Effect.timeout("30 seconds"),
74 );
75 return { url, pid };
76});
77​
78describe.runIf(binaryPath !== undefined)("OpenCode2Server live", () => {
79 it.live(
80 "spawns one authenticated server per instance and stops it by PID",
81 () =>
82 Effect.gen(function* () {
83 const fs = yield* FileSystem.FileSystem;
84 const path = yield* Path.Path;
85 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-opencode2-server-live-" });
86 const first = path.join(root, "first");
87 const second = path.join(root, "second");
88 yield* fs.makeDirectory(first);
89 yield* fs.makeDirectory(second);
90 const environment = {
91 PATH: process.env.PATH,
92 HOME: root,
93 XDG_CONFIG_HOME: path.join(root, "config"),
94 XDG_DATA_HOME: path.join(root, "data"),
95 XDG_STATE_HOME: path.join(root, "state"),
96 XDG_CACHE_HOME: path.join(root, "cache"),
97 OPENCODE_SERVER_PASSWORD: "ambient-password",
98 };
99​
100 const instanceScope = yield* Effect.acquireRelease(Scope.make(), (scope) =>
101 Scope.close(scope, Exit.void),
102 );
103 const server = Context.get(
104 yield* Layer.buildWithScope(
105 OpenCode2Server.layer({
106 binaryPath: binaryPath!,
107 serverUrl: "",
108 serverPassword: "",
109 directory: first,
110 environment,
111 }),
112 instanceScope,
113 ),
114 OpenCode2Server.OpenCode2Server,
115 );
116​
117 const spawned = yield* server.withConnection((connection) =>
118 Effect.gen(function* () {
119 const info = yield* connection.client.server.info();
120 const session = yield* connection.client.session.create({
121 title: "first location",
122 location: Location.PublicRef.make({ directory: AbsolutePath.make(first) }),
123 });
124 return { ...connection, pid: info.pid, session };
125 }),
126 );
127 assert.strictEqual(spawned.version, "2.0.18");
128 assert.isFalse(spawned.external);
129 assert.isTrue(isAlive(spawned.pid));
130​
131 const secondLocation = yield* server.withConnection((connection) =>
132 Effect.gen(function* () {
133 const info = yield* connection.client.server.info();
134 const session = yield* connection.client.session.create({
135 title: "second location",
136 location: Location.PublicRef.make({ directory: AbsolutePath.make(second) }),
137 });
138 return { url: connection.url, pid: info.pid, session };
139 }),
140 );
141 assert.strictEqual(secondLocation.url, spawned.url);
142 assert.strictEqual(secondLocation.pid, spawned.pid);
143 assert.strictEqual(secondLocation.session.location.directory, second);
144 assert.strictEqual(spawned.session.location.directory, first);
145​
146 const external = yield* OpenCode2Server.make({
147 binaryPath: binaryPath!,
148 serverUrl: spawned.url,
149 serverPassword: "wrong-password",
150 directory: first,
151 environment,
152 });
153 const rejected = yield* external.withConnection(() => Effect.void).pipe(Effect.flip);
154 assert.include(rejected.detail, "rejected the server password");
155 const ambient = yield* OpenCode2Server.make({
156 binaryPath: binaryPath!,
157 serverUrl: spawned.url,
158 serverPassword: environment.OPENCODE_SERVER_PASSWORD,
159 directory: first,
160 environment,
161 });
162 const ambientRejected = yield* ambient.withConnection(() => Effect.void).pipe(Effect.flip);
163 assert.include(ambientRejected.detail, "rejected the server password");
164​
165 const utf8Password = "pässwörd€";
166 const externalServer = yield* startExternalServer({
167 environment: OpenCode2Server.serverEnvironment(environment, Redacted.make(utf8Password)),
168 directory: second,
169 });
170 const utf8 = yield* OpenCode2Server.make({
171 binaryPath: binaryPath!,
172 serverUrl: externalServer.url,
173 serverPassword: utf8Password,
174 directory: second,
175 environment,
176 });
177 const utf8Connection = yield* utf8.withConnection((connection) =>
178 Effect.succeed(connection),
179 );
180 assert.strictEqual(utf8Connection.version, "2.0.18");
181 assert.isTrue(utf8Connection.external);
182 const asciiOnly = yield* OpenCode2Server.make({
183 binaryPath: binaryPath!,
184 serverUrl: externalServer.url,
185 serverPassword: "passwrd",
186 directory: second,
187 environment,
188 });
189 const asciiRejected = yield* asciiOnly.withConnection(() => Effect.void).pipe(Effect.flip);
190 assert.include(asciiRejected.detail, "rejected the server password");
191​
192 yield* Scope.close(instanceScope, Exit.void);
193 for (let attempt = 0; attempt < 50 && isAlive(-spawned.pid); attempt++) {
194 yield* Effect.sleep("100 millis");
195 }
196 assert.isFalse(isAlive(spawned.pid), `opencode serve ${spawned.pid} outlived its instance`);
197 assert.isFalse(isAlive(-spawned.pid), `a process in group ${spawned.pid} outlived it`);
198 const unreachable = yield* external.withConnection(() => Effect.void).pipe(Effect.flip);
199 assert.include(unreachable.detail, "Could not reach the OpenCode server");
200 }).pipe(
201 Effect.scoped,
202 Effect.provide(
203 Layer.mergeAll(
204 OpenCode2Client.layer,
205 OpenCodeRuntime.layer.pipe(Layer.provide(OpenCodeServerLedger.layerTest)),
206 ).pipe(Layer.provideMerge(Layer.mergeAll(NodeServices.layer, FetchHttpClient.layer))),
207 ),
208 ),
209 60_000,
210 );
211});