@sixb/deploy-ssh 0.2.6 → 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 -44
  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 -1527
  7. package/dist/index.js.map +10 -16
  8. package/dist/layout.d.ts +87 -30
  9. package/dist/layout.d.ts.map +1 -1
  10. package/dist/operations.d.ts +5 -3
  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 +15 -11
  15. package/dist/render.d.ts.map +1 -1
  16. package/dist/server/manifest.d.ts +10 -4
  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 +0 -4
  23. package/dist/server/state.d.ts.map +1 -1
  24. package/dist/server/supervisor.d.ts +8 -8
  25. package/dist/server/supervisor.d.ts.map +1 -1
  26. package/dist/ssh-target.d.ts +3 -24
  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 +109 -61
  35. package/src/operations.ts +105 -65
  36. package/src/plan.ts +59 -0
  37. package/src/render.ts +54 -35
  38. package/src/server/cli.ts +16 -20
  39. package/src/server/manifest.ts +13 -6
  40. package/src/server/release-host.ts +81 -0
  41. package/src/server/release.ts +738 -0
  42. package/src/server/state.ts +1 -5
  43. package/src/server/supervisor.ts +45 -238
  44. package/src/sh.d.ts +4 -0
  45. package/src/ssh-target.ts +43 -285
  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 -48
  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 -257
  61. package/src/ci.ts +0 -88
  62. package/src/keys.ts +0 -57
  63. package/src/scripts.ts +0 -703
  64. package/src/setup.ts +0 -203
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,12 +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] [--candidate]
19
+ * status [--json] [--check]
16
20
  * logs [service] [--tail n] [--follow]
17
21
  * restart|start|stop [service]
18
- * stage <candidate-manifest>
19
- * activate|discard
20
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
21
24
  */
22
25
  const argv = process.argv.slice(2)
23
26
 
@@ -29,6 +32,14 @@ try {
29
32
  }
30
33
 
31
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
+
32
43
  // A script's arguments are anything, `--manifest` included; `ctl` appends the real one last.
33
44
  if (argv[0] === "run") {
34
45
  const [, staged, path, ...args] = argv.slice(0, -2)
@@ -64,18 +75,6 @@ async function main(): Promise<void> {
64
75
  )
65
76
  )
66
77
  return
67
- case "stage":
68
- if (!arg) throw new Error("[SshTarget] Usage: stage <candidate-manifest> --manifest <path>")
69
- console.log(
70
- await sendSupervisorCommand(await loadProcessManifest(manifestPath), "stage", {
71
- manifestPath: arg,
72
- })
73
- )
74
- return
75
- case "activate":
76
- case "discard":
77
- console.log(await sendSupervisorCommand(await loadProcessManifest(manifestPath), command))
78
- return
79
78
  default:
80
79
  throw new Error(`[SshTarget] Unknown command '${command ?? ""}'.`)
81
80
  }
@@ -84,7 +83,7 @@ async function main(): Promise<void> {
84
83
  async function status(manifest: ProcessManifest): Promise<void> {
85
84
  const state = await readProcessState(statePath(manifest))
86
85
  const running = state !== null && isPidRunning(state.supervisorPid)
87
- const sourceInstances = flag("--candidate") ? (state?.staged ?? []) : (state?.instances ?? [])
86
+ const sourceInstances = state?.instances ?? []
88
87
  const report: DeployStatus = {
89
88
  release: await readRelease(manifest.releasePath),
90
89
  running,
@@ -109,9 +108,6 @@ async function status(manifest: ProcessManifest): Promise<void> {
109
108
  (process) => process.status !== "running" || process.restarts > 0
110
109
  )
111
110
  if (!running) console.error("The supervisor is not running.")
112
- else if (flag("--candidate") && report.processes.length === 0) {
113
- console.error("No candidate processes are staged.")
114
- }
115
111
  for (const process of down) {
116
112
  const label =
117
113
  process.instance === 0 ? process.service : `${process.service}#${process.instance}`
@@ -119,7 +115,7 @@ async function status(manifest: ProcessManifest): Promise<void> {
119
115
  process.status === "running" ? `restarted ${process.restarts}x` : process.status
120
116
  console.error(`${label} ${stateText}${process.lastError ? `: ${process.lastError}` : ""}`)
121
117
  }
122
- if (!running || down.length > 0 || (flag("--candidate") && report.processes.length === 0)) {
118
+ if (!running || down.length > 0) {
123
119
  process.exit(1)
124
120
  }
125
121
  return
@@ -10,6 +10,11 @@ export interface ProcessManifest {
10
10
  readonly name: string
11
11
  /** Which port pair (`blue` or `green`) this release's HTTP services bind. */
12
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
13
18
  /** The project directory every process starts in. */
14
19
  readonly cwd: string
15
20
  /** Supervisor state, control requests, and logs live here. */
@@ -40,24 +45,25 @@ export interface ProcessServiceManifest {
40
45
 
41
46
  const SERVICE_KINDS: readonly ProcessServiceKind[] = ["http", "singleton", "workers", "script"]
42
47
 
43
- export function isOverlapSafeService(service: ProcessServiceManifest): boolean {
44
- if (service.kind) return service.kind === "http" || service.kind === "workers"
45
- return service.name === "api" || service.name === "app" || service.name === "workers"
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"
46
52
  }
47
53
 
48
54
  export async function loadProcessManifest(path: string): Promise<ProcessManifest> {
49
55
  return parseProcessManifest(JSON.parse(await readFile(path, "utf8")), path)
50
56
  }
51
57
 
52
- export function statePath(manifest: ProcessManifest): string {
58
+ export function statePath(manifest: Pick<ProcessManifest, "runDir">): string {
53
59
  return resolve(manifest.runDir, "state.json")
54
60
  }
55
61
 
56
- export function controlDir(manifest: ProcessManifest): string {
62
+ export function controlDir(manifest: Pick<ProcessManifest, "runDir">): string {
57
63
  return resolve(manifest.runDir, "control")
58
64
  }
59
65
 
60
- export function responseDir(manifest: ProcessManifest): string {
66
+ export function responseDir(manifest: Pick<ProcessManifest, "runDir">): string {
61
67
  return resolve(manifest.runDir, "responses")
62
68
  }
63
69
 
@@ -73,6 +79,7 @@ export function parseProcessManifest(value: unknown, source = "process manifest"
73
79
  version: 1,
74
80
  name: string(manifest.name, `${source}.name`),
75
81
  ...(slot === undefined ? {} : { slot }),
82
+ ...(manifest.holdExclusive === true ? { holdExclusive: true } : {}),
76
83
  cwd: string(manifest.cwd, `${source}.cwd`),
77
84
  runDir: string(manifest.runDir, `${source}.runDir`),
78
85
  logDir: string(manifest.logDir, `${source}.logDir`),
@@ -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
+ }