server.ts 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. import { serve, type CommandChild } from "./cli"
  2. import { DEFAULT_SERVER_URL_KEY, WSL_ENABLED_KEY } from "./constants"
  3. import { store } from "./store"
  4. export type WslConfig = { enabled: boolean }
  5. export type HealthCheck = { wait: Promise<void> }
  6. export function getDefaultServerUrl(): string | null {
  7. const value = store.get(DEFAULT_SERVER_URL_KEY)
  8. return typeof value === "string" ? value : null
  9. }
  10. export function setDefaultServerUrl(url: string | null) {
  11. if (url) {
  12. store.set(DEFAULT_SERVER_URL_KEY, url)
  13. return
  14. }
  15. store.delete(DEFAULT_SERVER_URL_KEY)
  16. }
  17. export function getWslConfig(): WslConfig {
  18. const value = store.get(WSL_ENABLED_KEY)
  19. return { enabled: typeof value === "boolean" ? value : false }
  20. }
  21. export function setWslConfig(config: WslConfig) {
  22. store.set(WSL_ENABLED_KEY, config.enabled)
  23. }
  24. export function spawnLocalServer(hostname: string, port: number, password: string) {
  25. const { child, exit, events } = serve(hostname, port, password)
  26. const wait = (async () => {
  27. const url = `http://${hostname}:${port}`
  28. const ready = async () => {
  29. while (true) {
  30. await new Promise((resolve) => setTimeout(resolve, 100))
  31. if (await checkHealth(url, password)) return
  32. }
  33. }
  34. const terminated = async () => {
  35. const payload = await exit
  36. throw new Error(
  37. `Sidecar terminated before becoming healthy (code=${payload.code ?? "unknown"} signal=${
  38. payload.signal ?? "unknown"
  39. })`,
  40. )
  41. }
  42. await Promise.race([ready(), terminated()])
  43. })()
  44. return { child, health: { wait }, events }
  45. }
  46. export async function checkHealth(url: string, password?: string | null): Promise<boolean> {
  47. let healthUrl: URL
  48. try {
  49. healthUrl = new URL("/global/health", url)
  50. } catch {
  51. return false
  52. }
  53. const headers = new Headers()
  54. if (password) {
  55. const auth = Buffer.from(`opencode:${password}`).toString("base64")
  56. headers.set("authorization", `Basic ${auth}`)
  57. }
  58. try {
  59. const res = await fetch(healthUrl, {
  60. method: "GET",
  61. headers,
  62. signal: AbortSignal.timeout(3000),
  63. })
  64. return res.ok
  65. } catch {
  66. return false
  67. }
  68. }
  69. export type { CommandChild }