@sixb/deploy-ssh 0.2.5 → 0.2.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/README.md +51 -42
  2. package/dist/check/index.d.ts +24 -0
  3. package/dist/check/index.d.ts.map +1 -0
  4. package/dist/check/judge.d.ts +23 -0
  5. package/dist/check/judge.d.ts.map +1 -0
  6. package/dist/index.js +599 -1102
  7. package/dist/index.js.map +10 -15
  8. package/dist/layout.d.ts +91 -18
  9. package/dist/layout.d.ts.map +1 -1
  10. package/dist/operations.d.ts +5 -2
  11. package/dist/operations.d.ts.map +1 -1
  12. package/dist/plan.d.ts +25 -0
  13. package/dist/plan.d.ts.map +1 -0
  14. package/dist/render.d.ts +20 -10
  15. package/dist/render.d.ts.map +1 -1
  16. package/dist/server/manifest.d.ts +15 -3
  17. package/dist/server/manifest.d.ts.map +1 -1
  18. package/dist/server/release-host.d.ts +4 -0
  19. package/dist/server/release-host.d.ts.map +1 -0
  20. package/dist/server/release.d.ts +46 -0
  21. package/dist/server/release.d.ts.map +1 -0
  22. package/dist/server/state.d.ts +2 -0
  23. package/dist/server/state.d.ts.map +1 -1
  24. package/dist/server/supervisor.d.ts +12 -4
  25. package/dist/server/supervisor.d.ts.map +1 -1
  26. package/dist/ssh-target.d.ts +3 -18
  27. package/dist/ssh-target.d.ts.map +1 -1
  28. package/dist/transport.d.ts.map +1 -1
  29. package/package.json +3 -3
  30. package/src/bootstrap.sh +93 -0
  31. package/src/check/index.ts +117 -0
  32. package/src/check/judge.ts +299 -0
  33. package/src/check/probe.sh +99 -0
  34. package/src/layout.ts +117 -34
  35. package/src/operations.ts +104 -61
  36. package/src/plan.ts +59 -0
  37. package/src/render.ts +128 -31
  38. package/src/server/cli.ts +26 -9
  39. package/src/server/manifest.ts +42 -4
  40. package/src/server/release-host.ts +81 -0
  41. package/src/server/release.ts +738 -0
  42. package/src/server/state.ts +3 -1
  43. package/src/server/supervisor.ts +127 -55
  44. package/src/sh.d.ts +4 -0
  45. package/src/ssh-target.ts +46 -227
  46. package/src/transport.ts +28 -12
  47. package/dist/access.d.ts +0 -11
  48. package/dist/access.d.ts.map +0 -1
  49. package/dist/check.d.ts +0 -31
  50. package/dist/check.d.ts.map +0 -1
  51. package/dist/ci.d.ts +0 -27
  52. package/dist/ci.d.ts.map +0 -1
  53. package/dist/keys.d.ts +0 -13
  54. package/dist/keys.d.ts.map +0 -1
  55. package/dist/scripts.d.ts +0 -38
  56. package/dist/scripts.d.ts.map +0 -1
  57. package/dist/setup.d.ts +0 -32
  58. package/dist/setup.d.ts.map +0 -1
  59. package/src/access.ts +0 -107
  60. package/src/check.ts +0 -231
  61. package/src/ci.ts +0 -88
  62. package/src/keys.ts +0 -57
  63. package/src/scripts.ts +0 -323
  64. package/src/setup.ts +0 -203
package/src/render.ts CHANGED
@@ -1,34 +1,80 @@
1
- import type { DeployRelease } from "@sixb/core/deploy"
2
- import type { DeploymentLayout } from "./layout"
1
+ import type { DeployHttpServiceName, DeployRelease, DeployReleaseService } from "@sixb/core/deploy"
2
+ import type { DeploymentLayout, ReleaseLayout, SlotLayout } from "./layout"
3
3
  import type { ProcessManifest } from "./server/manifest"
4
+ import { drainKillTimeoutMs, INTERRUPT_LEAD_MS } from "./server/supervisor"
4
5
  import { shellQuote } from "./shell"
5
6
  import { renderUpdatePage } from "./update-page"
6
7
 
7
8
  const GENERATED = "Generated by sixb deploy. Changes are replaced on the next deploy."
8
9
 
9
- /** The supervisor's view of the release: absolute commands, full environments. */
10
+ /** Rewrites a release's HTTP services to listen on the given slot's loopback ports. */
11
+ export function releaseForSlot(
12
+ release: DeployRelease,
13
+ ports: Readonly<Record<DeployHttpServiceName, number>>
14
+ ): DeployRelease {
15
+ return {
16
+ ...release,
17
+ services: release.services.map((service) => {
18
+ if (!service.http || (service.name !== "api" && service.name !== "app")) {
19
+ return service
20
+ }
21
+ const port = ports[service.name]
22
+ return {
23
+ ...service,
24
+ command: {
25
+ ...service.command,
26
+ args: replacePortArg(service.command.args, port),
27
+ },
28
+ http: {
29
+ ...service.http,
30
+ port,
31
+ },
32
+ }
33
+ }),
34
+ }
35
+ }
36
+
37
+ function replacePortArg(args: readonly string[], port: number): string[] {
38
+ const next = [...args]
39
+ const index = next.indexOf("--port")
40
+ if (index !== -1 && index + 1 < next.length) {
41
+ next[index + 1] = String(port)
42
+ }
43
+ return next
44
+ }
45
+
46
+ /** The supervisor's view of a release in one slot: absolute commands, full environments. */
10
47
  export function renderProcessManifest(
11
48
  release: DeployRelease,
12
- layout: DeploymentLayout
49
+ input: {
50
+ readonly layout: DeploymentLayout
51
+ readonly slot: SlotLayout
52
+ readonly release: ReleaseLayout
53
+ readonly holdExclusive: boolean
54
+ }
13
55
  ): ProcessManifest {
14
- const sixb = `${layout.project}/node_modules/.bin/sixb`
56
+ const project = input.release.project
57
+ const sixb = `${project}/node_modules/.bin/sixb`
15
58
  return {
16
59
  version: 1,
17
60
  name: release.name,
18
- cwd: layout.project,
19
- runDir: layout.runDir,
20
- logDir: layout.logDir,
21
- releasePath: layout.releaseRecord,
61
+ slot: input.slot.slot,
62
+ ...(input.holdExclusive ? { holdExclusive: true } : {}),
63
+ cwd: project,
64
+ runDir: input.slot.runDir,
65
+ logDir: input.slot.logDir,
66
+ releasePath: input.layout.releaseRecord,
22
67
  env: release.env,
23
68
  services: release.services.map((service) => ({
24
69
  name: service.name,
70
+ kind: service.kind,
25
71
  processName: `${release.name}-${service.name}`,
26
- command: layout.bun,
72
+ command: input.release.bun,
27
73
  args:
28
74
  service.command.program === "sixb"
29
75
  ? [sixb, ...service.command.args]
30
76
  : [...service.command.args],
31
- env: service.env,
77
+ env: serviceEnvWithDrain(service),
32
78
  instances: service.instances,
33
79
  killTimeoutMs: service.process.killTimeoutMs,
34
80
  restartDelayMs: service.process.restartDelayMs,
@@ -37,40 +83,77 @@ export function renderProcessManifest(
37
83
  }
38
84
  }
39
85
 
40
- /** Pins the server half of this package to the project's Bun and manifest. */
41
- export function renderCtl(layout: DeploymentLayout): string {
86
+ /**
87
+ * A retiring `api` or `workers` drains until the supervisor's SIGINT, so it finishes its work on
88
+ * its own rather than being cut short. The window follows the service's own kill timeout.
89
+ */
90
+ function serviceEnvWithDrain(service: DeployReleaseService): Record<string, string> {
91
+ if (
92
+ (service.name === "api" || service.name === "workers") &&
93
+ service.env.SIXB_DRAIN_TIMEOUT_MS === undefined
94
+ ) {
95
+ const drainTimeoutMs = drainKillTimeoutMs(service.process.killTimeoutMs) - INTERRUPT_LEAD_MS
96
+
97
+ return {
98
+ SIXB_DRAIN_TIMEOUT_MS: String(drainTimeoutMs),
99
+ ...service.env,
100
+ }
101
+ }
102
+ return { ...service.env }
103
+ }
104
+
105
+ /** What a slot's service runs: its release's supervisor, with that release's Bun. */
106
+ export function renderLauncher(release: ReleaseLayout, slot: SlotLayout): string {
107
+ return renderServerCommand(release, ["supervise"], slot.manifest)
108
+ }
109
+
110
+ /** What `status`, `logs` and the other operations run: the live release's server half. */
111
+ export function renderCtl(release: ReleaseLayout, slot: SlotLayout): string {
112
+ return renderServerCommand(release, [], slot.manifest, '"$@" ')
113
+ }
114
+
115
+ function renderServerCommand(
116
+ release: ReleaseLayout,
117
+ args: readonly string[],
118
+ manifest: string,
119
+ passThrough = ""
120
+ ): string {
121
+ const bin = `${release.project}/node_modules/.bin/sixb-deploy-ssh`
122
+ const command = [release.bun, bin, ...args].map(shellQuote).join(" ")
42
123
  return [
43
124
  "#!/bin/sh",
44
125
  `# ${GENERATED}`,
45
- `exec ${shellQuote(layout.bun)} ${shellQuote(`${layout.project}/node_modules/.bin/sixb-deploy-ssh`)} "$@" --manifest ${shellQuote(layout.manifest)}`,
126
+ // A process that runs `bun` or `node` (a dependency's script) finds the release's Bun.
127
+ `PATH=${shellQuote(release.bunDir)}:"$PATH"; export PATH`,
128
+ `exec ${command} ${passThrough}--manifest ${shellQuote(manifest)}`,
46
129
  "",
47
130
  ].join("\n")
48
131
  }
49
132
 
50
133
  /**
51
- * The deployment's `systemd --user` unit. Linger starts the user's systemd at boot, so the
52
- * unit comes back after a reboot without anyone logged in.
134
+ * The slot service's template: `sixb-<name>@blue` and `sixb-<name>@green` each run their slot's
135
+ * launcher. Lingering starts the live slot's at boot. Stopping one signals only the supervisor,
136
+ * which lets its HTTP services and workers drain before systemd's stop timeout.
53
137
  */
54
- export function renderUnit(release: DeployRelease, layout: DeploymentLayout): string {
55
- // Long enough for the supervisor to stop every process with its own kill timeout.
56
- const stopSeconds =
57
- Math.ceil(
58
- Math.max(...release.services.map((service) => service.process.killTimeoutMs)) / 1000
59
- ) + 10
138
+ export function renderSlotUnit(release: DeployRelease, layout: DeploymentLayout): string {
139
+ const killTimeoutMs = Math.max(
140
+ ...release.services.map((service) => drainKillTimeoutMs(service.process.killTimeoutMs))
141
+ )
60
142
  return [
61
143
  `# ${GENERATED}`,
62
144
  "[Unit]",
63
- `Description=Sixb deployment ${release.name}`,
145
+ `Description=Sixb deployment ${release.name}, %i slot`,
64
146
  "",
65
147
  "[Service]",
66
148
  "Type=simple",
67
- `WorkingDirectory=${systemdValue(layout.project)}`,
68
- `Environment=${systemdValue(`PATH=${layout.bunDir}:/usr/local/bin:/usr/bin:/bin`)}`,
69
- `ExecStart=${systemdValue(layout.ctl)} supervise`,
149
+ `WorkingDirectory=${systemdValue(layout.root)}`,
150
+ "Environment=PATH=/usr/local/bin:/usr/bin:/bin",
151
+ `ExecStart=${systemdValue(layout.deployDir)}/%i`,
70
152
  "Restart=always",
71
153
  "RestartSec=2",
154
+ "KillMode=mixed",
72
155
  "KillSignal=SIGTERM",
73
- `TimeoutStopSec=${stopSeconds}`,
156
+ `TimeoutStopSec=${Math.ceil(killTimeoutMs / 1000) + 15}`,
74
157
  "",
75
158
  "[Install]",
76
159
  "WantedBy=default.target",
@@ -78,7 +161,7 @@ export function renderUnit(release: DeployRelease, layout: DeploymentLayout): st
78
161
  ].join("\n")
79
162
  }
80
163
 
81
- /** One site per HTTP service, forwarded to the service's loopback port. */
164
+ /** One site per HTTP service, forwarded to the active slot's loopback port. */
82
165
  export function renderCaddySnippet(release: DeployRelease): string {
83
166
  const sites = release.services.flatMap((service) => {
84
167
  if (!service.http) return []
@@ -87,7 +170,10 @@ export function renderCaddySnippet(release: DeployRelease): string {
87
170
  [
88
171
  `${service.http.domain} {`,
89
172
  ...(service.name === "api" ? compressJson() : []),
90
- `\treverse_proxy ${service.http.host}:${service.http.port}`,
173
+ `\treverse_proxy ${service.http.host}:${service.http.port} {`,
174
+ "\t\tlb_try_duration 5s",
175
+ ...(service.name === "api" ? keepWebSocketsThroughReload(service) : []),
176
+ "\t}",
91
177
  ...(pages ? updatePageOnProxyErrors() : []),
92
178
  "}",
93
179
  ].join("\n"),
@@ -96,6 +182,17 @@ export function renderCaddySnippet(release: DeployRelease): string {
96
182
  return [`# ${GENERATED}`, "", sites.join("\n\n"), ""].join("\n")
97
183
  }
98
184
 
185
+ /**
186
+ * A reload closes every WebSocket Caddy proxies unless it is told to wait, and each deploy reloads
187
+ * Caddy before the old API retires. Kept open, a browser's socket stays on the retiring API, which
188
+ * closes it with 1012 so the page reconnects without showing a drop. The wait covers the API's
189
+ * whole retiring window; the API closes its sockets as soon as it starts draining.
190
+ */
191
+ function keepWebSocketsThroughReload(service: DeployReleaseService): string[] {
192
+ const seconds = drainKillTimeoutMs(service.process.killTimeoutMs) / 1000
193
+ return [`\t\tstream_close_delay ${seconds}s`]
194
+ }
195
+
99
196
  /**
100
197
  * The API never compresses its responses, and an object query page is easily a megabyte of
101
198
  * JSON that compresses about twentyfold. Only complete JSON answers are encoded: the
@@ -117,8 +214,8 @@ function compressJson(): string[] {
117
214
  }
118
215
 
119
216
  /**
120
- * While the app is down — during a deploy, or an outage — a browser asking for a page
121
- * gets the update page instead of Caddy's bare error. Other requests keep the error.
217
+ * While the app is down — during an outage — a browser asking for a page gets the update page
218
+ * instead of Caddy's bare error. Other requests keep the error.
122
219
  */
123
220
  function updatePageOnProxyErrors(): string[] {
124
221
  return [
package/src/server/cli.ts CHANGED
@@ -1,8 +1,12 @@
1
1
  #!/usr/bin/env bun
2
2
  import { readFile } from "node:fs/promises"
3
+ import { homedir, userInfo } from "node:os"
3
4
  import type { DeployRecord, DeployStatus } from "@sixb/core/deploy"
5
+ import type { ReleasePlan } from "../plan"
4
6
  import { followLogFiles, type LogLine, readRecentLogLines, renderProcessLogLine } from "./logs"
5
7
  import { loadProcessManifest, type ProcessManifest, statePath } from "./manifest"
8
+ import { runRelease } from "./release"
9
+ import { createReleaseHost } from "./release-host"
6
10
  import { runScript } from "./run"
7
11
  import { isMissing, isPidRunning, readProcessState } from "./state"
8
12
  import { runSupervisor, type SupervisorCommand, sendSupervisorCommand } from "./supervisor"
@@ -12,10 +16,11 @@ import { runSupervisor, type SupervisorCommand, sendSupervisorCommand } from "./
12
16
  * script, which pins the Bun version and manifest. `sixb deploy` reaches it over SSH.
13
17
  *
14
18
  * supervise run the deployment's processes (the systemd unit's command)
15
- * status [--json] [--check] --check exits 1 unless every process is running
19
+ * status [--json] [--check]
16
20
  * logs [service] [--tail n] [--follow]
17
21
  * restart|start|stop [service]
18
- * run <staged> <path> [args...] run an uploaded script with `sixb run`; see ./run.ts
22
+ * run <staged> <path> [args...] run an uploaded script with `sixb run`; see ./run.ts
23
+ * release <plan> roll a release out, under the deploy lock; see ./release.ts
19
24
  */
20
25
  const argv = process.argv.slice(2)
21
26
 
@@ -27,6 +32,14 @@ try {
27
32
  }
28
33
 
29
34
  async function main(): Promise<void> {
35
+ if (argv[0] === "release") {
36
+ const planPath = argv[1]
37
+ if (!planPath) throw new Error("[SshTarget] Usage: release <plan>")
38
+ const plan = JSON.parse(await readFile(planPath, "utf8")) as ReleasePlan
39
+ await runRelease(plan, createReleaseHost(), { home: homedir(), user: userInfo().username })
40
+ return process.exit(0)
41
+ }
42
+
30
43
  // A script's arguments are anything, `--manifest` included; `ctl` appends the real one last.
31
44
  if (argv[0] === "run") {
32
45
  const [, staged, path, ...args] = argv.slice(0, -2)
@@ -40,7 +53,7 @@ async function main(): Promise<void> {
40
53
 
41
54
  const manifestPath = option("--manifest")
42
55
  if (!manifestPath) throw new Error("[SshTarget] --manifest is required.")
43
- const [command, service] = positionals()
56
+ const [command, arg] = positionals()
44
57
 
45
58
  switch (command) {
46
59
  case "supervise":
@@ -50,7 +63,7 @@ async function main(): Promise<void> {
50
63
  case "status":
51
64
  return status(await loadProcessManifest(manifestPath))
52
65
  case "logs":
53
- return logs(await loadProcessManifest(manifestPath), service)
66
+ return logs(await loadProcessManifest(manifestPath), arg)
54
67
  case "restart":
55
68
  case "start":
56
69
  case "stop":
@@ -58,7 +71,7 @@ async function main(): Promise<void> {
58
71
  await sendSupervisorCommand(
59
72
  await loadProcessManifest(manifestPath),
60
73
  command satisfies SupervisorCommand,
61
- service
74
+ { service: arg }
62
75
  )
63
76
  )
64
77
  return
@@ -70,11 +83,12 @@ async function main(): Promise<void> {
70
83
  async function status(manifest: ProcessManifest): Promise<void> {
71
84
  const state = await readProcessState(statePath(manifest))
72
85
  const running = state !== null && isPidRunning(state.supervisorPid)
86
+ const sourceInstances = state?.instances ?? []
73
87
  const report: DeployStatus = {
74
88
  release: await readRelease(manifest.releasePath),
75
89
  running,
76
90
  processes: running
77
- ? state.instances.map((instance) => ({
91
+ ? sourceInstances.map((instance) => ({
78
92
  service: instance.service,
79
93
  instance: instance.instance,
80
94
  status: instance.status,
@@ -97,10 +111,13 @@ async function status(manifest: ProcessManifest): Promise<void> {
97
111
  for (const process of down) {
98
112
  const label =
99
113
  process.instance === 0 ? process.service : `${process.service}#${process.instance}`
100
- const state = process.status === "running" ? `restarted ${process.restarts}x` : process.status
101
- console.error(`${label} ${state}${process.lastError ? `: ${process.lastError}` : ""}`)
114
+ const stateText =
115
+ process.status === "running" ? `restarted ${process.restarts}x` : process.status
116
+ console.error(`${label} ${stateText}${process.lastError ? `: ${process.lastError}` : ""}`)
117
+ }
118
+ if (!running || down.length > 0) {
119
+ process.exit(1)
102
120
  }
103
- if (!running || down.length > 0) process.exit(1)
104
121
  return
105
122
  }
106
123
  console.log(JSON.stringify(report))
@@ -1,10 +1,20 @@
1
1
  import { readFile } from "node:fs/promises"
2
2
  import { resolve } from "node:path"
3
+ import type { DeploySlot } from "../layout"
4
+
5
+ export type ProcessServiceKind = "http" | "singleton" | "workers" | "script"
3
6
 
4
7
  /** What the supervisor runs for one deployment, written by `sixb deploy` on each deploy. */
5
8
  export interface ProcessManifest {
6
9
  readonly version: 1
7
10
  readonly name: string
11
+ /** Which port pair (`blue` or `green`) this release's HTTP services bind. */
12
+ readonly slot?: DeploySlot
13
+ /**
14
+ * Leaves the singletons and project scripts stopped at start, while another slot still runs
15
+ * them: a deploy starts them here once the routes have moved. See `isExclusiveService`.
16
+ */
17
+ readonly holdExclusive?: boolean
8
18
  /** The project directory every process starts in. */
9
19
  readonly cwd: string
10
20
  /** Supervisor state, control requests, and logs live here. */
@@ -22,6 +32,7 @@ export interface ProcessManifest {
22
32
 
23
33
  export interface ProcessServiceManifest {
24
34
  readonly name: string
35
+ readonly kind?: ProcessServiceKind
25
36
  readonly processName: string
26
37
  readonly command: string
27
38
  readonly args: readonly string[]
@@ -32,19 +43,27 @@ export interface ProcessServiceManifest {
32
43
  readonly maxMemory?: string
33
44
  }
34
45
 
46
+ const SERVICE_KINDS: readonly ProcessServiceKind[] = ["http", "singleton", "workers", "script"]
47
+
48
+ /** A service two releases must never run at once: a singleton, or a project script. */
49
+ export function isExclusiveService(service: ProcessServiceManifest): boolean {
50
+ if (service.kind) return service.kind === "singleton" || service.kind === "script"
51
+ return service.name !== "api" && service.name !== "app" && service.name !== "workers"
52
+ }
53
+
35
54
  export async function loadProcessManifest(path: string): Promise<ProcessManifest> {
36
55
  return parseProcessManifest(JSON.parse(await readFile(path, "utf8")), path)
37
56
  }
38
57
 
39
- export function statePath(manifest: ProcessManifest): string {
58
+ export function statePath(manifest: Pick<ProcessManifest, "runDir">): string {
40
59
  return resolve(manifest.runDir, "state.json")
41
60
  }
42
61
 
43
- export function controlDir(manifest: ProcessManifest): string {
62
+ export function controlDir(manifest: Pick<ProcessManifest, "runDir">): string {
44
63
  return resolve(manifest.runDir, "control")
45
64
  }
46
65
 
47
- export function responseDir(manifest: ProcessManifest): string {
66
+ export function responseDir(manifest: Pick<ProcessManifest, "runDir">): string {
48
67
  return resolve(manifest.runDir, "responses")
49
68
  }
50
69
 
@@ -54,10 +73,13 @@ export function parseProcessManifest(value: unknown, source = "process manifest"
54
73
  if (!Array.isArray(manifest.services)) {
55
74
  throw new Error(`[SshTarget] ${source}.services must be an array`)
56
75
  }
76
+ const slot = parseSlot(manifest.slot, `${source}.slot`)
57
77
 
58
78
  return {
59
79
  version: 1,
60
80
  name: string(manifest.name, `${source}.name`),
81
+ ...(slot === undefined ? {} : { slot }),
82
+ ...(manifest.holdExclusive === true ? { holdExclusive: true } : {}),
61
83
  cwd: string(manifest.cwd, `${source}.cwd`),
62
84
  runDir: string(manifest.runDir, `${source}.runDir`),
63
85
  logDir: string(manifest.logDir, `${source}.logDir`),
@@ -75,9 +97,11 @@ function parseService(value: unknown, source: string): ProcessServiceManifest {
75
97
  throw new Error(`[SshTarget] ${source}.args must be an array of strings`)
76
98
  }
77
99
  const env = environment(service.env, `${source}.env`)
100
+ const kind = parseKind(service.kind, `${source}.kind`)
78
101
 
79
102
  return {
80
103
  name: string(service.name, `${source}.name`),
104
+ ...(kind === undefined ? {} : { kind }),
81
105
  processName: string(service.processName, `${source}.processName`),
82
106
  command: string(service.command, `${source}.command`),
83
107
  args: service.args,
@@ -91,6 +115,20 @@ function parseService(value: unknown, source: string): ProcessServiceManifest {
91
115
  }
92
116
  }
93
117
 
118
+ function parseSlot(value: unknown, source: string): DeploySlot | undefined {
119
+ if (value === undefined) return undefined
120
+ if (value === "blue" || value === "green") return value
121
+ throw new Error(`[SshTarget] ${source} must be 'blue' or 'green'`)
122
+ }
123
+
124
+ function parseKind(value: unknown, source: string): ProcessServiceKind | undefined {
125
+ if (value === undefined) return undefined
126
+ if (typeof value === "string" && (SERVICE_KINDS as readonly string[]).includes(value)) {
127
+ return value as ProcessServiceKind
128
+ }
129
+ throw new Error(`[SshTarget] ${source} must be one of: ${SERVICE_KINDS.join(", ")}`)
130
+ }
131
+
94
132
  function environment(value: unknown, source: string): Record<string, string> {
95
133
  const env = record(value, source)
96
134
  for (const [key, variable] of Object.entries(env)) {
@@ -114,7 +152,7 @@ function string(value: unknown, source: string): string {
114
152
  return value
115
153
  }
116
154
 
117
- function positiveInteger(value: unknown, source: string): number {
155
+ function positiveInteger(value: unknown, source: number | string): number {
118
156
  if (!Number.isInteger(value) || (value as number) < 1) {
119
157
  throw new Error(`[SshTarget] ${source} must be a positive integer`)
120
158
  }
@@ -0,0 +1,81 @@
1
+ import { readFile, rm } from "node:fs/promises"
2
+ import { join } from "node:path"
3
+ import type { ReleaseHost } from "./release"
4
+ import { isMissing, readProcessState, writeFileAtomically } from "./state"
5
+ import { sendSupervisorCommand } from "./supervisor"
6
+
7
+ /** The server itself: commands share the release's log, and systemd is the account's own. */
8
+ export function createReleaseHost(): ReleaseHost {
9
+ const run: ReleaseHost["run"] = async (command, options = {}) => {
10
+ const child = Bun.spawn([...command], {
11
+ ...(options.cwd ? { cwd: options.cwd } : {}),
12
+ env: { ...process.env, ...options.env },
13
+ stdin: "ignore",
14
+ stdout: "inherit",
15
+ stderr: "inherit",
16
+ })
17
+ return child.exited
18
+ }
19
+ const quiet = async (command: readonly string[]) => {
20
+ const child = Bun.spawn([...command], { stdin: "ignore", stdout: "pipe", stderr: "pipe" })
21
+ const [code, stdout, stderr] = await Promise.all([
22
+ child.exited,
23
+ new Response(child.stdout).text(),
24
+ new Response(child.stderr).text(),
25
+ ])
26
+ return { code, output: `${stdout}${stderr}` }
27
+ }
28
+
29
+ return {
30
+ run,
31
+ systemctl: (...args) => run(["systemctl", "--user", ...args]),
32
+ // Not `is-active`, which fails for a unit that is still stopping: a draining slot holds its
33
+ // ports, and a legacy service reads its files, until it reaches `inactive` or `failed`.
34
+ isEnabled: async (unit) =>
35
+ (await quiet(["systemctl", "--user", "is-enabled", "--quiet", unit])).code === 0,
36
+ isActive: async (unit) => {
37
+ const { output } = await quiet([
38
+ "systemctl",
39
+ "--user",
40
+ "show",
41
+ "-p",
42
+ "ActiveState",
43
+ "--value",
44
+ unit,
45
+ ])
46
+ return !["inactive", "failed", ""].includes(output.trim())
47
+ },
48
+ readRoutes: async (path) =>
49
+ readFile(path, "utf8").catch((error: unknown) => {
50
+ if (isMissing(error)) return null
51
+ throw error
52
+ }),
53
+ writeRoutes: async (path, routes) => {
54
+ if (routes === null) await rm(path, { force: true })
55
+ else await writeFileAtomically(path, routes)
56
+ },
57
+ validateCaddy: async () => {
58
+ const result = await quiet([
59
+ "caddy",
60
+ "validate",
61
+ "--config",
62
+ "/etc/caddy/Caddyfile",
63
+ "--adapter",
64
+ "caddyfile",
65
+ ])
66
+ return result.code === 0 ? null : result.output.trimEnd().split("\n").slice(-20).join("\n")
67
+ },
68
+ reloadCaddy: async () =>
69
+ (await run(["sudo", "-n", "/usr/bin/systemctl", "reload", "caddy"])) === 0,
70
+ answers: async (url) => {
71
+ const response = await fetch(url, { signal: AbortSignal.timeout(2_000) }).catch(() => null)
72
+ return response?.ok === true
73
+ },
74
+ supervise: async (runDir, command, service) => {
75
+ await sendSupervisorCommand({ runDir }, command, { service })
76
+ },
77
+ readState: (runDir) => readProcessState(join(runDir, "state.json")),
78
+ sleep: (ms) => Bun.sleep(ms),
79
+ print: (line) => console.log(line),
80
+ }
81
+ }