service.ts 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. import { rename, writeFile } from "node:fs/promises"
  2. const [registration, mode] = process.argv.slice(2)
  3. if (registration === undefined || mode === undefined) throw new Error("Missing service fixture arguments")
  4. let requests = 0
  5. const server = Bun.serve({
  6. port: 0,
  7. async fetch(request) {
  8. if (new URL(request.url).pathname !== "/api/health") return new Response(null, { status: 404 })
  9. requests += 1
  10. if (mode === "modern" && requests === 1) {
  11. await writeFile(registration + ".first-request", "")
  12. while (!(await Bun.file(registration + ".release").exists())) await Bun.sleep(5)
  13. return new Response(null, { status: 503 })
  14. }
  15. if (mode === "legacy") return Response.json({ healthy: true })
  16. return Response.json({ healthy: true, version: "test", pid: process.pid })
  17. },
  18. })
  19. await writeFile(
  20. registration + ".tmp",
  21. JSON.stringify({
  22. id: crypto.randomUUID(),
  23. version: mode === "legacy" ? undefined : "test",
  24. url: server.url.toString(),
  25. pid: process.pid,
  26. }),
  27. { mode: 0o600 },
  28. )
  29. await rename(registration + ".tmp", registration)
  30. const shutdown = () => {
  31. server.stop(true)
  32. process.exit()
  33. }
  34. process.on("SIGTERM", shutdown)
  35. process.on("SIGINT", shutdown)