service-smoke.ts 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. #!/usr/bin/env bun
  2. import { Service } from "@opencode-ai/client/effect/service"
  3. import { ServiceStatus } from "@opencode-ai/protocol/groups/health"
  4. import { Schema } from "effect"
  5. import fs from "node:fs/promises"
  6. import os from "node:os"
  7. import path from "node:path"
  8. const nodeBuild = process.argv.includes("--node")
  9. const target = `cli${nodeBuild ? "-node" : ""}-${process.platform === "win32" ? "windows" : process.platform}-${process.arch}`
  10. const directory = path.join(import.meta.dir, "..", "dist", ...(nodeBuild ? ["node"] : []), target, "bin")
  11. const binary = path.join(directory, `opencode2${nodeBuild ? "-node" : ""}${process.platform === "win32" ? ".exe" : ""}`)
  12. if (!(await Bun.file(binary).exists())) throw new Error(`Missing compiled CLI in ${directory}`)
  13. const root = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), "opencode-service-smoke-")))
  14. const env = {
  15. ...process.env,
  16. HOME: root,
  17. USERPROFILE: root,
  18. OPENCODE_DB: path.join(root, "opencode.db"),
  19. OPENCODE_TEST_HOME: root,
  20. XDG_CACHE_HOME: path.join(root, "cache"),
  21. XDG_CONFIG_HOME: path.join(root, "config"),
  22. XDG_DATA_HOME: path.join(root, "data"),
  23. XDG_STATE_HOME: path.join(root, "state"),
  24. }
  25. const processes: Array<ReturnType<typeof Bun.spawn>> = []
  26. const errors: Array<Promise<string>> = []
  27. let failure: unknown
  28. try {
  29. await fs.mkdir(path.join(root, ".opencode"))
  30. spawnService()
  31. spawnService()
  32. const registration = await waitForRegistration()
  33. const info = await Schema.decodeUnknownPromise(Service.Info)(await Bun.file(registration).json())
  34. if (info.id === undefined || info.password === undefined) throw new Error("Registration is missing service identity")
  35. const credential = btoa(`opencode:${info.password}`)
  36. const headers = { authorization: "Basic " + credential }
  37. const token = encodeURIComponent(credential)
  38. const health = await waitForReady(info.url, headers)
  39. if (health.pid !== info.pid) throw new Error("Health process does not match registration")
  40. const tokenHealth = await fetch(new URL(`/api/health?auth_token=${token}`, info.url), {
  41. signal: AbortSignal.timeout(5_000),
  42. })
  43. if (tokenHealth.status !== 200) throw new Error("Compiled service rejected query authentication")
  44. const tokenOpenApi = await fetch(new URL(`/openapi.json?auth_token=${token}`, info.url), {
  45. signal: AbortSignal.timeout(5_000),
  46. })
  47. if (tokenOpenApi.status !== 200) throw new Error("Compiled application rejected query authentication")
  48. if ((await pluginIDs(info.url, headers)).includes("smoke")) throw new Error("Smoke plugin existed before creation")
  49. const plugin = path.join(root, ".opencode", "plugins", "smoke.ts")
  50. await fs.mkdir(path.dirname(plugin), { recursive: true })
  51. await fs.writeFile(plugin, pluginSource())
  52. await waitForPlugin(info.url, headers)
  53. const unauthorizedHealth = await fetch(new URL("/api/health", info.url), {
  54. signal: AbortSignal.timeout(5_000),
  55. })
  56. if (unauthorizedHealth.status !== 401) throw new Error("Compiled service exposed health without authentication")
  57. const unauthorizedOpenApi = await fetch(new URL("/openapi.json", info.url), {
  58. signal: AbortSignal.timeout(5_000),
  59. })
  60. if (unauthorizedOpenApi.status !== 401)
  61. throw new Error("Compiled service exposed application routes without authentication")
  62. const unauthorizedStop = await fetch(new URL("/api/service/stop", info.url), {
  63. method: "POST",
  64. headers: { "content-type": "application/json" },
  65. body: JSON.stringify({ instanceID: info.id }),
  66. signal: AbortSignal.timeout(5_000),
  67. })
  68. if (unauthorizedStop.status !== 401) throw new Error("Compiled service accepted unauthenticated stop")
  69. const winner = processes.find((process) => process.pid === info.pid)
  70. const loser = processes.find((process) => process.pid !== info.pid)
  71. if (!winner || !loser) throw new Error("Compiled contenders did not elect one registered owner")
  72. if (!(await exitsWithin(loser, 10_000))) throw new Error("Losing compiled contender did not exit")
  73. const stopped = await Schema.decodeUnknownPromise(ServiceStatus.StopResponse)(
  74. await fetch(new URL("/api/service/stop", info.url), {
  75. method: "POST",
  76. headers: { ...headers, "content-type": "application/json" },
  77. body: JSON.stringify({ instanceID: info.id }),
  78. signal: AbortSignal.timeout(5_000),
  79. }).then((response) => response.json()),
  80. )
  81. if (!stopped.accepted) throw new Error("Compiled service rejected exact-instance stop")
  82. if (!(await exitsWithin(winner, 10_000))) throw new Error("Compiled service did not stop")
  83. for (let attempt = 0; attempt < 200 && (await Bun.file(registration).exists()); attempt++) await Bun.sleep(25)
  84. if (await Bun.file(registration).exists()) throw new Error("Compiled service registration was not removed")
  85. } catch (cause) {
  86. failure = cause
  87. } finally {
  88. processes.forEach((process) => process.kill())
  89. await Promise.all(processes.map((process) => process.exited))
  90. if (failure)
  91. errors.push(fs.readFile(path.join(root, "data", "opencode", "log", "opencode.log"), "utf8").catch(() => ""))
  92. }
  93. const output = await Promise.all(errors)
  94. await fs.rm(root, { recursive: true, force: true })
  95. if (failure)
  96. throw new Error(output.filter(Boolean).join("\n") || "Compiled service lifecycle smoke test failed", {
  97. cause: failure,
  98. })
  99. function spawnService() {
  100. const process = Bun.spawn([binary, "serve", "--service"], { env, stdout: "ignore", stderr: "pipe" })
  101. processes.push(process)
  102. errors.push(new Response(process.stderr).text())
  103. return process
  104. }
  105. async function waitForRegistration() {
  106. const directory = path.join(root, "state", "opencode")
  107. for (let attempt = 0; attempt < 400; attempt++) {
  108. const files = await fs.readdir(directory).catch(() => [])
  109. const file = files.find(
  110. (file) => file === "service.json" || (file.startsWith("service-") && file.endsWith(".json")),
  111. )
  112. if (file) return path.join(directory, file)
  113. await Bun.sleep(25)
  114. }
  115. throw new Error("Compiled service did not publish registration")
  116. }
  117. async function waitForReady(url: string, headers: HeadersInit) {
  118. const deadline = Date.now() + 20_000
  119. while (Date.now() < deadline) {
  120. const response = await fetch(new URL("/api/health", url), {
  121. headers,
  122. signal: AbortSignal.timeout(1_000),
  123. }).catch(() => undefined)
  124. if (response?.ok) return Schema.decodeUnknownPromise(ServiceStatus.Health)(await response.json())
  125. await Bun.sleep(25)
  126. }
  127. throw new Error("Compiled service did not become ready")
  128. }
  129. function exitsWithin(process: Bun.Subprocess, milliseconds: number) {
  130. return Promise.race([process.exited.then(() => true), Bun.sleep(milliseconds).then(() => false)])
  131. }
  132. function pluginSource() {
  133. return 'export default { id: "smoke", setup: async () => {} }\n'
  134. }
  135. async function pluginIDs(url: string, headers: HeadersInit) {
  136. const endpoint = new URL("/api/plugin", url)
  137. endpoint.searchParams.set("location[directory]", root)
  138. const response = await fetch(endpoint, { headers, signal: AbortSignal.timeout(5_000) })
  139. const body: unknown = await response.json()
  140. if (typeof body !== "object" || body === null || !("data" in body) || !Array.isArray(body.data)) {
  141. throw new Error("Compiled service returned an invalid plugin list")
  142. }
  143. return body.data.flatMap((plugin) =>
  144. typeof plugin === "object" && plugin !== null && "id" in plugin && typeof plugin.id === "string" ? [plugin.id] : [],
  145. )
  146. }
  147. async function waitForPlugin(url: string, headers: HeadersInit) {
  148. const deadline = Date.now() + 10_000
  149. while (Date.now() < deadline) {
  150. if ((await pluginIDs(url, headers)).includes("smoke")) return
  151. await Bun.sleep(25)
  152. }
  153. throw new Error("Compiled service did not discover the created plugin")
  154. }