Skip to content

Commit fad352c

Browse files
authored
refactor(client): share the service health probe between clients (#53237)
1 parent e1b94a1 commit fad352c

3 files changed

Lines changed: 93 additions & 181 deletions

File tree

‎packages/client/src/effect/service.ts‎

Lines changed: 7 additions & 96 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
11
import { Effect, FileSystem, Option, Schedule, Schema } from "effect"
2-
import { homedir } from "node:os"
3-
import { join } from "node:path"
4-
import type { DiscoverOptions, Endpoint, EnsureOptions, StopOptions } from "../service.js"
2+
import type { DiscoverOptions, EnsureOptions, StopOptions } from "../service.js"
53
import {
64
contenderFailure,
75
contenderFinished,
@@ -11,8 +9,10 @@ import {
119
import { defaultEnsureTiming, ensureTiming, type EnsureTiming } from "../service-timing.js"
1210
import { matchesVersion } from "../service-version.js"
1311
import { PtyHandoff } from "../pty-handoff.js"
12+
import { fallback, headers, type LocalService, probeResult, same } from "../service-probe.js"
1413

1514
export * from "../service.js"
15+
export { headers }
1616
/** Contents of the local service registration file. */
1717
export type Info = import("../service.js").Info
1818

@@ -40,9 +40,9 @@ export const incumbent = Effect.fn("service.incumbent")(function* (
4040
options: DiscoverOptions & { readonly url: string },
4141
) {
4242
const info = yield* read(options.file)
43-
const found = info === undefined ? undefined : yield* probe({ ...info, url: options.url })
44-
if (found === undefined) return undefined
45-
if (!found.compatible) return undefined
43+
if (info === undefined) return undefined
44+
const found = (yield* Effect.promise(() => probeResult({ ...info, url: options.url }))).service
45+
if (!found?.compatible) return undefined
4646
if (!matchesVersion(found.version, options)) return undefined
4747
return { endpoint: found.endpoint, state: found.state }
4848
})
@@ -177,17 +177,6 @@ export const stop = Effect.fn("service.stop")(function* (options: StopOptions =
177177
if (info !== undefined) yield* terminate(info, options, ensureTiming(options))
178178
})
179179

180-
function fallback() {
181-
const state = process.env["XDG_STATE_HOME"] ?? join(homedir(), ".local", "state")
182-
return join(state, "opencode", "service.json")
183-
}
184-
185-
/** Create HTTP authentication headers for a service endpoint. */
186-
export function headers(endpoint: Endpoint) {
187-
if (endpoint.auth === undefined) return undefined
188-
return { authorization: "Basic " + btoa(endpoint.auth.username + ":" + endpoint.auth.password) }
189-
}
190-
191180
/** Schema for the local service registration file. */
192181
export const Info = Schema.Struct({
193182
id: Schema.optional(Schema.String),
@@ -198,13 +187,6 @@ export const Info = Schema.Struct({
198187
})
199188

200189
const decode = Schema.decodeUnknownEffect(Schema.fromJsonString(Info))
201-
const decodeInfo = Schema.decodeUnknownOption(
202-
Schema.Struct({
203-
version: Schema.String,
204-
pid: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
205-
}),
206-
)
207-
208190
// A missing or corrupt file means no valid info; callers treat both
209191
// the same (the registering server self-evicts, clients rediscover).
210192
const read = Effect.fnUntraced(function* (file?: string) {
@@ -214,77 +196,10 @@ const read = Effect.fnUntraced(function* (file?: string) {
214196
return yield* decode(text.value).pipe(Effect.option, Effect.map(Option.getOrUndefined))
215197
})
216198

217-
type LocalService = {
218-
readonly info: Info
219-
readonly endpoint: Endpoint
220-
readonly version?: string
221-
readonly state: "ready" | "waiting" | "failed"
222-
readonly compatible: boolean
223-
}
224-
225-
const probe = Effect.fnUntraced(function* (info: Info) {
226-
return (yield* probeResult(info)).service
227-
})
228-
229-
const probeResult = Effect.fnUntraced(function* (info: Info, timeout = defaultEnsureTiming.requestTimeout) {
230-
const endpoint = {
231-
url: info.url,
232-
auth:
233-
info.password === undefined
234-
? undefined
235-
: { type: "basic" as const, username: "opencode", password: info.password },
236-
} satisfies Endpoint
237-
const signal = AbortSignal.timeout(timeout)
238-
const result = yield* Effect.promise(() =>
239-
fetch(new URL("/api/info", info.url), { headers: headers(endpoint), signal })
240-
.then(async (response) => ({
241-
response,
242-
body: response.status === 404 ? undefined : ((await response.json()) as unknown),
243-
}))
244-
.then(
245-
(value) => ({ value }),
246-
(cause: unknown) => ({ cause }),
247-
),
248-
)
249-
if ("cause" in result) return { service: undefined, timedOut: signal.aborted }
250-
const response = result.value.response
251-
// A missing health endpoint identifies protocol incompatibility, not an older
252-
// version. Only an unmet version requirement lets ensure replace this owner.
253-
if (response.status === 404)
254-
return {
255-
service: {
256-
info,
257-
endpoint,
258-
version: info.version,
259-
state: "ready" as const,
260-
compatible: false,
261-
} satisfies LocalService,
262-
timedOut: false,
263-
}
264-
const body = result.value.body
265-
const serverInfo = decodeInfo(body)
266-
if (Option.isSome(serverInfo)) {
267-
if (serverInfo.value.pid !== info.pid) return { service: undefined, timedOut: false }
268-
if (info.version !== undefined && serverInfo.value.version !== info.version)
269-
return { service: undefined, timedOut: false }
270-
return {
271-
service: {
272-
info,
273-
endpoint,
274-
version: serverInfo.value.version,
275-
state: response.ok ? "ready" : response.status === 500 ? "failed" : "waiting",
276-
compatible: true,
277-
} satisfies LocalService,
278-
timedOut: false,
279-
}
280-
}
281-
return { service: undefined, timedOut: false }
282-
})
283-
284199
const registered = Effect.fnUntraced(function* (file?: string, timeout?: number) {
285200
const info = yield* read(file)
286201
if (info === undefined) return { info: undefined, service: undefined, timedOut: false }
287-
return { info, ...(yield* probeResult(info, timeout)) }
202+
return { info, ...(yield* Effect.promise(() => probeResult(info, timeout))) }
288203
})
289204

290205
// 50ms cadence bounded at ~5s, shared by stop escalation and each ensure
@@ -303,10 +218,6 @@ const stopped = Effect.fnUntraced(function* (pid: number) {
303218
return yield* Effect.fail(new Error(`Server process ${pid} is still running`))
304219
})
305220

306-
function same(left: Info, right: Info) {
307-
return left.id === right.id && left.version === right.version && left.url === right.url && left.pid === right.pid
308-
}
309-
310221
const terminate = Effect.fnUntraced(function* (info: Info, options: { readonly file?: string }, timing: EnsureTiming) {
311222
const current = yield* read(options.file)
312223
if (current === undefined || !same(current, info)) return

‎packages/client/src/promise/service.ts‎

Lines changed: 2 additions & 85 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
11
import { readFile, rm } from "node:fs/promises"
2-
import { homedir } from "node:os"
3-
import { join } from "node:path"
42
import type { DiscoverOptions, Endpoint, Info, EnsureOptions, StopOptions } from "../service.js"
53
import {
64
contenderFailure,
@@ -11,8 +9,10 @@ import {
119
import { defaultEnsureTiming, ensureTiming, type EnsureTiming } from "../service-timing.js"
1210
import { matchesVersion } from "../service-version.js"
1311
import { PtyHandoff } from "../pty-handoff.js"
12+
import { fallback, headers, probeResult, same } from "../service-probe.js"
1413

1514
export * from "../service.js"
15+
export { headers }
1616

1717
// Find, start, and stop the local opencode background service.
1818
//
@@ -148,18 +148,6 @@ export async function stop(options: StopOptions = {}) {
148148
if (info !== undefined) await terminate(info, options, ensureTiming(options))
149149
}
150150

151-
function fallback() {
152-
return join(process.env["XDG_STATE_HOME"] ?? join(homedir(), ".local", "state"), "opencode", "service.json")
153-
}
154-
155-
/** Create HTTP authentication headers for a service endpoint. */
156-
export function headers(endpoint: Endpoint) {
157-
if (endpoint.auth === undefined) return undefined
158-
return {
159-
authorization: "Basic " + Buffer.from(endpoint.auth.username + ":" + endpoint.auth.password).toString("base64"),
160-
}
161-
}
162-
163151
async function read(file?: string) {
164152
const text = await readFile(file ?? fallback(), "utf8").catch(() => undefined)
165153
if (text === undefined) return undefined
@@ -170,73 +158,6 @@ async function read(file?: string) {
170158
}
171159
}
172160

173-
type LocalService = {
174-
readonly info: Info
175-
readonly endpoint: Endpoint
176-
readonly version?: string
177-
readonly state: "ready" | "waiting" | "failed"
178-
readonly compatible: boolean
179-
}
180-
181-
async function probeResult(info: Info, timeout = defaultEnsureTiming.requestTimeout) {
182-
const endpoint = {
183-
url: info.url,
184-
auth:
185-
info.password === undefined
186-
? undefined
187-
: { type: "basic" as const, username: "opencode", password: info.password },
188-
} satisfies Endpoint
189-
const signal = AbortSignal.timeout(timeout)
190-
const result = await fetch(new URL("/api/info", info.url), { headers: headers(endpoint), signal })
191-
.then(async (response) => ({
192-
response,
193-
body: response.status === 404 ? undefined : ((await response.json()) as unknown),
194-
}))
195-
.then(
196-
(value) => ({ value }),
197-
(cause: unknown) => ({ cause }),
198-
)
199-
if ("cause" in result) return { service: undefined, timedOut: signal.aborted }
200-
const response = result.value.response
201-
// A missing health endpoint identifies protocol incompatibility, not an older
202-
// version. Only an unmet version requirement lets ensure replace this owner.
203-
if (response.status === 404)
204-
return {
205-
service: {
206-
info,
207-
endpoint,
208-
version: info.version,
209-
state: "ready" as const,
210-
compatible: false,
211-
} satisfies LocalService,
212-
timedOut: false,
213-
}
214-
const serverInfo = decodeInfo(result.value.body)
215-
if (serverInfo !== undefined) {
216-
if (serverInfo.pid !== info.pid) return { service: undefined, timedOut: false }
217-
if (info.version !== undefined && serverInfo.version !== info.version)
218-
return { service: undefined, timedOut: false }
219-
return {
220-
service: {
221-
info,
222-
endpoint,
223-
version: serverInfo.version,
224-
state: response.ok ? "ready" : response.status === 500 ? "failed" : "waiting",
225-
compatible: true,
226-
} satisfies LocalService,
227-
timedOut: false,
228-
}
229-
}
230-
return { service: undefined, timedOut: false }
231-
}
232-
233-
function decodeInfo(input: unknown) {
234-
if (typeof input !== "object" || input === null) return
235-
if (!("version" in input) || typeof input.version !== "string") return
236-
if (!("pid" in input) || typeof input.pid !== "number" || !Number.isInteger(input.pid) || input.pid < 0) return
237-
return { version: input.version, pid: input.pid }
238-
}
239-
240161
async function registered(file?: string, timeout?: number) {
241162
const info = await read(file)
242163
if (info === undefined) return { info: undefined, service: undefined, timedOut: false }
@@ -266,10 +187,6 @@ async function waitUntilStopped(pid: number, timing: EnsureTiming) {
266187
return false
267188
}
268189

269-
function same(left: Info, right: Info) {
270-
return left.id === right.id && left.version === right.version && left.url === right.url && left.pid === right.pid
271-
}
272-
273190
async function terminate(info: Info, options: { readonly file?: string }, timing: EnsureTiming) {
274191
const current = await read(options.file)
275192
if (current === undefined || !same(current, info)) return
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
import { homedir } from "node:os"
2+
import { join } from "node:path"
3+
import type { Endpoint, Info } from "./service.js"
4+
import { defaultEnsureTiming } from "./service-timing.js"
5+
6+
// Shared by the Effect and Promise clients. Keep this module free of Effect so the
7+
// Promise client never loads the Effect runtime.
8+
9+
export type LocalService = {
10+
readonly info: Info
11+
readonly endpoint: Endpoint
12+
readonly version?: string
13+
readonly state: "ready" | "waiting" | "failed"
14+
readonly compatible: boolean
15+
}
16+
17+
/** The default registration file. */
18+
export function fallback() {
19+
return join(process.env["XDG_STATE_HOME"] ?? join(homedir(), ".local", "state"), "opencode", "service.json")
20+
}
21+
22+
/** Whether two registrations describe the same service instance. */
23+
export function same(left: Info, right: Info) {
24+
return left.id === right.id && left.version === right.version && left.url === right.url && left.pid === right.pid
25+
}
26+
27+
/** Ask a registered owner for its health and classify the answer. */
28+
export async function probeResult(info: Info, timeout = defaultEnsureTiming.requestTimeout) {
29+
const endpoint = {
30+
url: info.url,
31+
auth: info.password === undefined ? undefined : { type: "basic", username: "opencode", password: info.password },
32+
} satisfies Endpoint
33+
const signal = AbortSignal.timeout(timeout)
34+
const result = await fetch(new URL("/api/info", info.url), { headers: headers(endpoint), signal })
35+
.then(async (response) => ({
36+
response,
37+
body: response.status === 404 ? undefined : ((await response.json()) as unknown),
38+
}))
39+
.catch(() => undefined)
40+
if (result === undefined) return { service: undefined, timedOut: signal.aborted }
41+
const response = result.response
42+
// A missing health endpoint identifies protocol incompatibility, not an older
43+
// version. Only an unmet version requirement lets ensure replace this owner.
44+
if (response.status === 404)
45+
return {
46+
service: {
47+
info,
48+
endpoint,
49+
version: info.version,
50+
state: "ready",
51+
compatible: false,
52+
} satisfies LocalService,
53+
timedOut: false,
54+
}
55+
const serverInfo = decodeInfo(result.body)
56+
if (serverInfo === undefined) return { service: undefined, timedOut: false }
57+
if (serverInfo.pid !== info.pid) return { service: undefined, timedOut: false }
58+
if (info.version !== undefined && serverInfo.version !== info.version) return { service: undefined, timedOut: false }
59+
return {
60+
service: {
61+
info,
62+
endpoint,
63+
version: serverInfo.version,
64+
state: response.ok ? "ready" : response.status === 500 ? "failed" : "waiting",
65+
compatible: true,
66+
} satisfies LocalService,
67+
timedOut: false,
68+
}
69+
}
70+
71+
/** Create HTTP authentication headers for a service endpoint. */
72+
export function headers(endpoint: Endpoint) {
73+
if (endpoint.auth === undefined) return undefined
74+
return {
75+
authorization: "Basic " + Buffer.from(endpoint.auth.username + ":" + endpoint.auth.password).toString("base64"),
76+
}
77+
}
78+
79+
function decodeInfo(input: unknown) {
80+
if (typeof input !== "object" || input === null) return
81+
if (!("version" in input) || typeof input.version !== "string") return
82+
if (!("pid" in input) || typeof input.pid !== "number" || !Number.isInteger(input.pid) || input.pid < 0) return
83+
return { version: input.version, pid: input.pid }
84+
}

0 commit comments

Comments
 (0)