service.test.ts 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. import { NodeFileSystem } from "@effect/platform-node"
  2. import { afterEach, expect, test } from "bun:test"
  3. import { Effect } from "effect"
  4. import { mkdtemp, rm, writeFile } from "node:fs/promises"
  5. import { tmpdir } from "node:os"
  6. import { join } from "node:path"
  7. import { Service, type EnsureReason } from "../src/effect/service"
  8. const fixture = join(import.meta.dir, "fixture/service.ts")
  9. const processes: Bun.Subprocess[] = []
  10. const directories: string[] = []
  11. afterEach(async () => {
  12. processes.forEach((process) => process.kill("SIGTERM"))
  13. await Promise.all(processes.splice(0).map((process) => process.exited))
  14. await Promise.all(directories.splice(0).map((directory) => rm(directory, { recursive: true, force: true })))
  15. })
  16. test("a concurrent same-version start cannot invalidate a resolved endpoint", async () => {
  17. const directory = await temp()
  18. const registration = join(directory, "service.json")
  19. spawn(registration, "modern")
  20. await waitForFile(registration)
  21. const original = await Bun.file(registration).json()
  22. const starts: EnsureReason[] = []
  23. const first = run(
  24. Service.ensure({
  25. file: registration,
  26. version: "test",
  27. command: [],
  28. onStart: (reason) => starts.push(reason),
  29. }),
  30. )
  31. await waitForFile(registration + ".first-request")
  32. const resolved = await run(Service.ensure({ file: registration, version: "test" }))
  33. expect(resolved.url).toBe(original.url)
  34. await writeFile(registration + ".release", "")
  35. await first
  36. expect(starts).toEqual([])
  37. expect(await Bun.file(registration).json()).toEqual(original)
  38. expect(await health(resolved.url)).toEqual({ healthy: true, version: "test", pid: original.pid })
  39. })
  40. test("waits for a registered service to finish starting", async () => {
  41. const directory = await temp()
  42. const registration = join(directory, "service.json")
  43. const process = spawn(registration, "starting")
  44. await waitForFile(registration)
  45. const result = run(Service.ensure({ file: registration, version: "test", command: [] }))
  46. await Bun.sleep(500)
  47. expect(process.exitCode).toBe(null)
  48. await writeFile(registration + ".release", "")
  49. expect((await result).url).toBe((await Bun.file(registration).json()).url)
  50. })
  51. test("reports a failed registered service without spawning", async () => {
  52. const directory = await temp()
  53. const registration = join(directory, "service.json")
  54. const process = spawn(registration, "failed-owner")
  55. await waitForFile(registration)
  56. await expect(run(Service.ensure({ file: registration, version: "test", command: [] }))).rejects.toThrow(
  57. "Background service failed to start",
  58. )
  59. expect(process.exitCode).toBe(null)
  60. })
  61. test("requests graceful stop of the exact service instance", async () => {
  62. const directory = await temp()
  63. const registration = join(directory, "service.json")
  64. const process = spawn(registration, "graceful")
  65. await waitForFile(registration)
  66. const info = await Bun.file(registration).json()
  67. await run(Service.stop({ file: registration }))
  68. await process.exited
  69. expect(await Bun.file(registration + ".stop").json()).toEqual({ instanceID: info.id })
  70. })
  71. test("does not spawn contenders while an incompatible service rejects replacement", async () => {
  72. const directory = await temp()
  73. const registration = join(directory, "service.json")
  74. const contender = join(directory, "contender.json")
  75. const existing = spawn(registration, "reject-stop")
  76. await waitForFile(registration)
  77. const controller = new AbortController()
  78. const starting = Effect.runPromise(
  79. Service.ensure({
  80. file: registration,
  81. version: "test",
  82. command: [process.execPath, fixture, contender, "record-start"],
  83. }).pipe(Effect.provide(NodeFileSystem.layer)),
  84. { signal: controller.signal },
  85. )
  86. await waitForFile(registration + ".stop-attempt")
  87. await Bun.sleep(500)
  88. controller.abort()
  89. await starting.catch(() => undefined)
  90. expect(await Bun.file(contender + ".started").exists()).toBe(false)
  91. expect(existing.exitCode).toBe(null)
  92. })
  93. test("a legacy health response is still replaced", async () => {
  94. const directory = await temp()
  95. const registration = join(directory, "service.json")
  96. const existing = spawn(registration, "legacy")
  97. await waitForFile(registration)
  98. const starts: EnsureReason[] = []
  99. const result = run(Service.ensure({ file: registration, command: [], onStart: (reason) => starts.push(reason) }))
  100. await expect(result).rejects.toThrow("Missing service command")
  101. expect(starts).toEqual(["version-mismatch"])
  102. await existing.exited
  103. }, 10_000)
  104. test("waits for a slow winner while bounding lock probes", async () => {
  105. const directory = await temp()
  106. const registration = join(directory, "service.json")
  107. const endpoint = await run(
  108. Service.ensure({
  109. file: registration,
  110. version: "test",
  111. command: [process.execPath, fixture, registration, "coordinated"],
  112. }),
  113. )
  114. const info = await Bun.file(registration).json()
  115. try {
  116. expect(endpoint.url).toBe(info.url)
  117. expect(await health(endpoint.url)).toEqual({ healthy: true, version: "test", pid: info.pid })
  118. expect((await Bun.file(registration + ".starts").text()).trim().split("\n")).toHaveLength(2)
  119. } finally {
  120. process.kill(info.pid, "SIGTERM")
  121. }
  122. }, 15_000)
  123. test("waits for a live contender when another contender fails", async () => {
  124. const directory = await temp()
  125. const registration = join(directory, "service.json")
  126. const endpoint = await run(
  127. Service.ensure({
  128. file: registration,
  129. version: "test",
  130. command: [process.execPath, fixture, registration, "coordinated-failed-loser"],
  131. }),
  132. )
  133. const info = await Bun.file(registration).json()
  134. try {
  135. expect(endpoint.url).toBe(info.url)
  136. } finally {
  137. process.kill(info.pid, "SIGTERM")
  138. }
  139. }, 15_000)
  140. test("reports a contender that fails to start", async () => {
  141. const directory = await temp()
  142. const registration = join(directory, "service.json")
  143. await expect(
  144. run(
  145. Service.ensure({
  146. file: registration,
  147. version: "test",
  148. command: [process.execPath, fixture, registration, "failed"],
  149. }),
  150. ),
  151. ).rejects.toThrow("Server process exited with code 1")
  152. }, 10_000)
  153. test("reports a contender terminated by a signal", async () => {
  154. const directory = await temp()
  155. const registration = join(directory, "service.json")
  156. await expect(
  157. run(
  158. Service.ensure({
  159. file: registration,
  160. version: "test",
  161. command: [process.execPath, fixture, registration, "signal"],
  162. }),
  163. ),
  164. ).rejects.toThrow(/Server process (terminated by|exited with code)/)
  165. }, 10_000)
  166. test("reports a slow contender that eventually fails", async () => {
  167. const directory = await temp()
  168. const registration = join(directory, "service.json")
  169. await expect(
  170. run(
  171. Service.ensure({
  172. file: registration,
  173. version: "test",
  174. command: [process.execPath, fixture, registration, "delayed-failed", "8000"],
  175. }),
  176. ),
  177. ).rejects.toThrow("Server process exited with code 1")
  178. }, 15_000)
  179. test("replaces an incompatible owner that appears during startup", async () => {
  180. const directory = await temp()
  181. const registration = join(directory, "service.json")
  182. const starting = run(
  183. Service.ensure({
  184. file: registration,
  185. version: "test",
  186. command: [process.execPath, fixture, registration, "delayed", "8000"],
  187. }),
  188. )
  189. await Bun.sleep(1_000)
  190. const old = spawn(registration, "old")
  191. await waitForFile(registration)
  192. const endpoint = await starting
  193. const info = await Bun.file(registration).json()
  194. try {
  195. expect(endpoint.url).toBe(info.url)
  196. expect(info.version).toBe("test")
  197. await old.exited
  198. } finally {
  199. process.kill(info.pid, "SIGTERM")
  200. }
  201. }, 20_000)
  202. function run<A, E>(effect: Effect.Effect<A, E>) {
  203. return Effect.runPromise(effect.pipe(Effect.provide(NodeFileSystem.layer)))
  204. }
  205. function spawn(registration: string, mode: string, ...args: string[]) {
  206. const subprocess = Bun.spawn([process.execPath, fixture, registration, mode, ...args], {
  207. stdout: "ignore",
  208. stderr: "inherit",
  209. })
  210. processes.push(subprocess)
  211. return subprocess
  212. }
  213. async function temp() {
  214. const directory = await mkdtemp(join(tmpdir(), "opencode-client-service-"))
  215. directories.push(directory)
  216. return directory
  217. }
  218. async function waitForFile(file: string) {
  219. for (let attempt = 0; attempt < 600; attempt++) {
  220. if (await Bun.file(file).exists()) return
  221. await Bun.sleep(5)
  222. }
  223. throw new Error(`Timed out waiting for ${file}`)
  224. }
  225. async function health(url: string) {
  226. return fetch(new URL("/api/health", url), { signal: AbortSignal.timeout(1_000) }).then((response) => response.json())
  227. }