hazo_env 0.10.4 → 0.12.1

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 (53) hide show
  1. package/CHANGE_LOG.md +79 -0
  2. package/config/hazo_env_config.ini.sample +61 -0
  3. package/dist/cli.js +329 -0
  4. package/dist/deploy/build.d.ts +91 -0
  5. package/dist/deploy/build.d.ts.map +1 -0
  6. package/dist/deploy/build.js +389 -0
  7. package/dist/deploy/clean.d.ts +63 -0
  8. package/dist/deploy/clean.d.ts.map +1 -0
  9. package/dist/deploy/clean.js +135 -0
  10. package/dist/deploy/index.d.ts +13 -0
  11. package/dist/deploy/index.d.ts.map +1 -0
  12. package/dist/deploy/index.js +22 -0
  13. package/dist/deploy/init.d.ts +20 -0
  14. package/dist/deploy/init.d.ts.map +1 -0
  15. package/dist/deploy/init.js +131 -0
  16. package/dist/deploy/peer.d.ts +18 -0
  17. package/dist/deploy/peer.d.ts.map +1 -0
  18. package/dist/deploy/peer.js +48 -0
  19. package/dist/deploy/pm2-start.d.ts +100 -0
  20. package/dist/deploy/pm2-start.d.ts.map +1 -0
  21. package/dist/deploy/pm2-start.js +228 -0
  22. package/dist/deploy/rollback.d.ts +22 -0
  23. package/dist/deploy/rollback.d.ts.map +1 -0
  24. package/dist/deploy/rollback.js +196 -0
  25. package/dist/deploy/runner.d.ts +8 -0
  26. package/dist/deploy/runner.d.ts.map +1 -0
  27. package/dist/deploy/runner.js +35 -0
  28. package/dist/deploy/state.d.ts +19 -0
  29. package/dist/deploy/state.d.ts.map +1 -0
  30. package/dist/deploy/state.js +52 -0
  31. package/dist/deploy/status.d.ts +54 -0
  32. package/dist/deploy/status.d.ts.map +1 -0
  33. package/dist/deploy/status.js +182 -0
  34. package/dist/deploy/switch.d.ts +40 -0
  35. package/dist/deploy/switch.d.ts.map +1 -0
  36. package/dist/deploy/switch.js +183 -0
  37. package/dist/deploy/types.d.ts +96 -0
  38. package/dist/deploy/types.d.ts.map +1 -0
  39. package/dist/deploy/types.js +16 -0
  40. package/dist/deploy/verify.d.ts +41 -0
  41. package/dist/deploy/verify.d.ts.map +1 -0
  42. package/dist/deploy/verify.js +214 -0
  43. package/dist/index.d.ts +2 -0
  44. package/dist/index.d.ts.map +1 -1
  45. package/dist/index.js +3 -0
  46. package/dist/resolve/connect.d.ts.map +1 -1
  47. package/dist/resolve/connect.js +15 -1
  48. package/dist/resolve/deploy.d.ts +8 -0
  49. package/dist/resolve/deploy.d.ts.map +1 -0
  50. package/dist/resolve/deploy.js +140 -0
  51. package/dist/types/index.d.ts +10 -0
  52. package/dist/types/index.d.ts.map +1 -1
  53. package/package.json +12 -12
@@ -0,0 +1,196 @@
1
+ // hazo_env/src/deploy/rollback.ts — `deploy rollback`: reverse the last `deploy switch`
2
+ //
3
+ // One-command recovery from a bad deploy: puts the PREVIOUS live build back
4
+ // on the production port, without the operator having to remember which
5
+ // directory was previously live or what port it ran on.
6
+ //
7
+ // This is switch.ts's exact pm2 pattern, run in the opposite direction — see
8
+ // switch.ts's header for the full rationale (two rounds of real bug fixes)
9
+ // behind "pm2 delete, then startNamedPm2Process from a per-call temp config
10
+ // file", which this file reuses without alteration.
11
+ //
12
+ // Flow:
13
+ // 1. Read state. No state file -> abort ("deploy init" hasn't run).
14
+ // 2. No `previous_live_dir` recorded -> abort ("nothing to roll back" — either
15
+ // no switch has ever run, or a prior rollback already consumed it; see
16
+ // "previous_live_dir after rollback" below for why this field is NOT
17
+ // repopulated by rollback itself).
18
+ // 3. `last_build` newer than `last_switch` -> abort (see "the stale-build
19
+ // guard" below) — a build has happened in the standby dir since the
20
+ // last switch, so the previous live build rollback would otherwise
21
+ // promote no longer exists.
22
+ // 4. Read the git ref of the dir being restored to live FIRST, before
23
+ // anything is stopped/started — mirrors switch.ts step 2 exactly, for
24
+ // the same reason: it's read-only, so there's no ordering reason to
25
+ // delay it, and delaying it risks a late failure leaving state stale
26
+ // relative to a rollback that already happened in reality.
27
+ // 5. Delete the CURRENT live PM2 registration, tolerant-delete any
28
+ // `<app_name>-staging` registration (defense in depth — see below),
29
+ // then fresh-start the previous-live dir on the PRODUCTION port under
30
+ // the PLAIN app name — all via the shared `promoteDirFresh` helper
31
+ // (`src/deploy/pm2-start.ts`), the exact same primitive `deploy switch`
32
+ // uses, in the opposite direction. On failure, `promoteDirFresh` itself
33
+ // attempts to restore whatever WAS live (the dir rollback was trying to
34
+ // replace), and reports plainly whether that restoration succeeded.
35
+ // 6. Update state atomically: the restored dir becomes `live_dir`, the dir
36
+ // that was live becomes `standby_dir`, `previous_live_dir` is cleared,
37
+ // `last_switch` + the git ref read in step 4 recorded.
38
+ //
39
+ // The stale-build guard (step 3): after a switch, `standby_dir ===
40
+ // previous_live_dir` (both point at the dir switch just demoted). If the
41
+ // operator then runs `deploy build` in that dir — the normal workflow for
42
+ // testing the NEXT release — build.ts's `pre_build_cmd` (typically `rm -rf
43
+ // .next`) and rebuild wipe out the actual previous-production artifact in
44
+ // place; the directory still exists and still has the right git history,
45
+ // but the build that was actually serving production traffic before the
46
+ // switch no longer exists on disk. Nothing about that `deploy build` run
47
+ // clears `previous_live_dir` — it has no reason to touch rollback's
48
+ // bookkeeping — so a subsequent `deploy rollback` would promote the
49
+ // FRESHLY BUILT code while claiming to restore the previous production
50
+ // build, and would do so silently. Guarded by comparing `state.last_build`
51
+ // against `state.last_switch` (both ISO timestamps `DeployState` already
52
+ // tracks): if a build has completed since the last switch, rollback is no
53
+ // longer safe and aborts with a clear explanation instead. A missing
54
+ // `last_build` means no build has ever run in this app's lifetime, which
55
+ // is trivially "no build since the switch" — safe to proceed.
56
+ //
57
+ // Defense in depth — tolerant staging cleanup (step 5): the dir rollback
58
+ // restores was never built as a staging candidate in THIS cycle (it was
59
+ // simply live before the last switch), so there is normally no
60
+ // `<app_name>-staging` registration pointing at it to worry about.
61
+ // Included anyway, tolerant of "not found", as a second line of defense:
62
+ // if the stale-build guard above is ever bypassed (bug, manually edited
63
+ // state file, clock skew) and `deploy build` HAS left a staging
64
+ // registration against this same dir, this limits the blast radius the
65
+ // same way switch.ts's own staging cleanup does, rather than leaving a
66
+ // stale registration for the next `deploy build` to collide with.
67
+ //
68
+ // previous_live_dir after rollback: deliberately CLEARED (not repopulated),
69
+ // not carried forward. Rollback's own net effect is identical to running
70
+ // `deploy switch` again on the pre-rollback state (live and standby swap
71
+ // back to what they were before the switch rollback is undoing) — so if
72
+ // `previous_live_dir` were set to the dir rollback just vacated, a second
73
+ // `deploy rollback` would silently toggle live/standby back and forth
74
+ // forever with no real "previous" to roll back to, which is not a
75
+ // recovery operation; it's just repeatedly re-running switch under a
76
+ // misleading command name. Clearing it means a second `deploy rollback`
77
+ // correctly aborts with "nothing to roll back" until a fresh `deploy
78
+ // switch` runs and records a new, meaningful `previous_live_dir`.
79
+ import path from 'node:path';
80
+ import { readState, updateState } from './state.js';
81
+ import { promoteDirFresh, PromoteDirFreshError } from './pm2-start.js';
82
+ /** Thrown when there's nothing to roll back, or a fatal step fails. */
83
+ export class RollbackAbortError extends Error {
84
+ constructor(message) {
85
+ super(message);
86
+ this.name = 'RollbackAbortError';
87
+ }
88
+ }
89
+ /**
90
+ * Reverse the last `deploy switch`: put the previously-live build back on
91
+ * the production port. See this file's header for the full step-by-step
92
+ * rationale.
93
+ */
94
+ export function runRollback(config, runner) {
95
+ // Step 1: read state.
96
+ const state = readState(config.app_name);
97
+ if (!state) {
98
+ throw new RollbackAbortError(`No deploy state found for "${config.app_name}" — nothing to roll back. Run "deploy init" first.`);
99
+ }
100
+ // Step 2: nothing to reverse if no switch has run (or a prior rollback
101
+ // already consumed the recorded previous_live_dir — see header).
102
+ if (!state.previous_live_dir) {
103
+ throw new RollbackAbortError(`No previous switch recorded for "${config.app_name}" — nothing to roll back. ` +
104
+ `"deploy rollback" only reverses a "deploy switch" that hasn't already been rolled back.`);
105
+ }
106
+ // Step 3: abort if the standby dir has been rebuilt since the last
107
+ // switch — the previous live build no longer exists (see "the
108
+ // stale-build guard" in the header). A missing last_build means no build
109
+ // has ever run; that's trivially "no build since the switch".
110
+ if (state.last_build && state.last_switch && state.last_build > state.last_switch) {
111
+ // Wording note (fix round): `last_build` here does not necessarily mean
112
+ // a build actually SUCCEEDED since the last switch — since build.ts
113
+ // (Fix 3) now writes a provisional `last_build` the moment the pipeline
114
+ // reaches its first destructive step (git pull), this guard also trips
115
+ // for a build attempt that was interrupted (e.g. Ctrl+C after `rm -rf
116
+ // .next` already ran) or that failed partway through. Either way the
117
+ // standby dir may no longer hold the artifact that was actually live
118
+ // before the switch, so the wording below covers both "it succeeded and
119
+ // got promoted" and "an attempt merely ran" without claiming more than
120
+ // is known.
121
+ throw new RollbackAbortError(`A build has run on standby since the last switch (last_build ${state.last_build} is newer than ` +
122
+ `last_switch ${state.last_switch}) — the previous live build may no longer be intact (it may have been ` +
123
+ `rebuilt, or partially rebuilt, in place by "deploy build"). Cannot safely roll back.`);
124
+ }
125
+ const currentLiveDir = path.resolve(state.live_dir);
126
+ const restoreDir = path.resolve(state.previous_live_dir);
127
+ // Step 4: read the restored dir's git ref FIRST, before anything is
128
+ // stopped/started — mirrors switch.ts step 2 (see header).
129
+ const gitRef = runner.exec('git rev-parse HEAD', { cwd: restoreDir }).trim();
130
+ // Step 5: delete the current live PM2 registration, tolerant-delete any
131
+ // stray `<app_name>-staging` registration (defense in depth — see
132
+ // header), then fresh-start the previous-live dir on the production
133
+ // port — all via the shared helper (see header). On failure,
134
+ // promoteDirFresh itself attempts to bring the build rollback was trying
135
+ // to replace back up so production isn't silently left down, and
136
+ // reports plainly whether that worked.
137
+ let stagingDeleteWarning;
138
+ try {
139
+ // stagingDeleted (a plain boolean) isn't currently surfaced in
140
+ // RunRollbackResult — this is defense in depth (see header), not the
141
+ // normal path. stagingDeleteWarning IS surfaced (Fix 4b): a REAL
142
+ // deletion failure (not just "nothing to delete") would otherwise be
143
+ // silently swallowed, leaving a stale registration for the next
144
+ // `deploy build` to collide with.
145
+ const promoteResult = promoteDirFresh(runner, {
146
+ fromDir: currentLiveDir,
147
+ toDir: restoreDir,
148
+ name: config.app_name,
149
+ port: config.prod_port,
150
+ stagingName: `${config.app_name}-staging`,
151
+ toLabel: 'previous live app',
152
+ fromLabel: 'the build that was live before this rollback attempt',
153
+ });
154
+ stagingDeleteWarning = promoteResult.stagingDeleteWarning;
155
+ }
156
+ catch (e) {
157
+ if (e instanceof PromoteDirFreshError) {
158
+ throw new RollbackAbortError(e.message);
159
+ }
160
+ throw e;
161
+ }
162
+ // Step 6: update state atomically. The restored dir becomes live, the dir
163
+ // that was live becomes standby, previous_live_dir is cleared (see
164
+ // header — deliberately not repopulated). git_ref was already resolved
165
+ // in step 4, before anything was touched.
166
+ const newState = updateState(config.app_name, {
167
+ live_dir: restoreDir,
168
+ live_port: config.prod_port,
169
+ standby_dir: currentLiveDir,
170
+ staging_port: config.staging_port,
171
+ previous_live_dir: undefined,
172
+ last_switch: new Date().toISOString(),
173
+ git_ref: gitRef,
174
+ pm2_process: config.app_name,
175
+ });
176
+ // Fix 7: persist the pm2 process list after a successful promotion. Without
177
+ // this, a server reboot's `pm2 resurrect` (if configured to run on boot)
178
+ // could bring back the OLD pm2 registration while the state file already
179
+ // claims the restored dir is live — a silent divergence. Non-fatal: the
180
+ // rollback itself already succeeded, so a failed `pm2 save` is only a
181
+ // warning, never a reason to report the rollback as failed.
182
+ const saveResult = runner.spawn('pm2 save');
183
+ const pm2SaveWarning = saveResult.code !== 0
184
+ ? `"pm2 save" failed after rollback (exit ${saveResult.code}): ${saveResult.stderr || saveResult.stdout || 'no output'} — ` +
185
+ `a server reboot's "pm2 resurrect" may restore the OLD pm2 process list even though this rollback ` +
186
+ `succeeded. Run "pm2 save" manually.`
187
+ : undefined;
188
+ return {
189
+ restoredLiveDir: restoreDir,
190
+ newStandbyDir: currentLiveDir,
191
+ prodPort: config.prod_port,
192
+ state: newState,
193
+ stagingDeleteWarning,
194
+ pm2SaveWarning,
195
+ };
196
+ }
@@ -0,0 +1,8 @@
1
+ import type { CommandRunner } from './types.js';
2
+ export interface RunnerOpts {
3
+ cwd?: string;
4
+ env?: Record<string, string>;
5
+ }
6
+ /** The real CommandRunner, used outside of tests. */
7
+ export declare const nodeCommandRunner: CommandRunner;
8
+ //# sourceMappingURL=runner.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runner.d.ts","sourceRoot":"","sources":["../../src/deploy/runner.ts"],"names":[],"mappings":"AAYA,OAAO,KAAK,EAAiB,aAAa,EAAE,MAAM,YAAY,CAAC;AAE/D,MAAM,WAAW,UAAU;IACzB,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,GAAG,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CAC9B;AAED,qDAAqD;AACrD,eAAO,MAAM,iBAAiB,EAAE,aAuB/B,CAAC"}
@@ -0,0 +1,35 @@
1
+ // hazo_env/src/deploy/runner.ts — Production CommandRunner
2
+ //
3
+ // Wraps child_process.execSync/spawnSync. This is the ONLY place in the
4
+ // deploy module that touches child_process directly — every orchestration
5
+ // function (build/verify/switch/rollback/...) takes a CommandRunner and
6
+ // calls it, so tests can inject a mock instead of this implementation.
7
+ //
8
+ // Shell-string execution is intentional here, mirroring envsync/exec.ts's
9
+ // runShell: deploy commands (build_cmd, install_cmd, post_switch_cmd, ...)
10
+ // are operator-supplied values from hazo_env_config.ini, not end-user input.
11
+ import { execSync, spawnSync } from 'node:child_process';
12
+ /** The real CommandRunner, used outside of tests. */
13
+ export const nodeCommandRunner = {
14
+ exec(cmd, opts) {
15
+ const result = execSync(cmd, {
16
+ cwd: opts?.cwd,
17
+ env: opts?.env ? { ...process.env, ...opts.env } : undefined,
18
+ encoding: 'utf-8',
19
+ });
20
+ return result.toString().trim();
21
+ },
22
+ spawn(cmd, opts) {
23
+ const result = spawnSync(cmd, {
24
+ cwd: opts?.cwd,
25
+ env: opts?.env ? { ...process.env, ...opts.env } : undefined,
26
+ shell: true,
27
+ encoding: 'utf-8',
28
+ });
29
+ return {
30
+ code: result.status ?? -1,
31
+ stdout: result.stdout?.toString() ?? '',
32
+ stderr: result.stderr?.toString() ?? '',
33
+ };
34
+ },
35
+ };
@@ -0,0 +1,19 @@
1
+ import type { DeployState } from './types.js';
2
+ /** Directory holding all app state files: ~/.hazo-deploy */
3
+ export declare function getStateDir(): string;
4
+ /** Full path to a given app's state file: ~/.hazo-deploy/<app_name>.json */
5
+ export declare function getStatePath(appName: string): string;
6
+ /**
7
+ * Read the state file for `appName`. Returns `undefined` if it doesn't
8
+ * exist yet (e.g. before the first `deploy init`).
9
+ */
10
+ export declare function readState(appName: string): DeployState | undefined;
11
+ /** Overwrite the full state file for `appName`, creating ~/.hazo-deploy if needed. */
12
+ export declare function writeState(state: DeployState): void;
13
+ /**
14
+ * Merge `patch` into the existing state for `appName` and persist it.
15
+ * Throws if no state file exists yet — callers must `writeState` an initial
16
+ * state (e.g. during `deploy init`) before updating it.
17
+ */
18
+ export declare function updateState(appName: string, patch: Partial<DeployState>): DeployState;
19
+ //# sourceMappingURL=state.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"state.d.ts","sourceRoot":"","sources":["../../src/deploy/state.ts"],"names":[],"mappings":"AAUA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAI9C,4DAA4D;AAC5D,wBAAgB,WAAW,IAAI,MAAM,CAEpC;AAED,4EAA4E;AAC5E,wBAAgB,YAAY,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAEpD;AAED;;;GAGG;AACH,wBAAgB,SAAS,CAAC,OAAO,EAAE,MAAM,GAAG,WAAW,GAAG,SAAS,CAKlE;AAED,sFAAsF;AACtF,wBAAgB,UAAU,CAAC,KAAK,EAAE,WAAW,GAAG,IAAI,CAOnD;AAED;;;;GAIG;AACH,wBAAgB,WAAW,CAAC,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,CAAC,WAAW,CAAC,GAAG,WAAW,CAQrF"}
@@ -0,0 +1,52 @@
1
+ // hazo_env/src/deploy/state.ts — Deploy state file CRUD
2
+ //
3
+ // Persisted at ~/.hazo-deploy/<app_name>.json, outside both project
4
+ // directories so it survives directory swaps/renames and is readable from
5
+ // either the live or standby dir. The directory is created lazily on first
6
+ // write.
7
+ import fs from 'node:fs';
8
+ import os from 'node:os';
9
+ import path from 'node:path';
10
+ const STATE_DIR_NAME = '.hazo-deploy';
11
+ /** Directory holding all app state files: ~/.hazo-deploy */
12
+ export function getStateDir() {
13
+ return path.join(os.homedir(), STATE_DIR_NAME);
14
+ }
15
+ /** Full path to a given app's state file: ~/.hazo-deploy/<app_name>.json */
16
+ export function getStatePath(appName) {
17
+ return path.join(getStateDir(), `${appName}.json`);
18
+ }
19
+ /**
20
+ * Read the state file for `appName`. Returns `undefined` if it doesn't
21
+ * exist yet (e.g. before the first `deploy init`).
22
+ */
23
+ export function readState(appName) {
24
+ const filePath = getStatePath(appName);
25
+ if (!fs.existsSync(filePath))
26
+ return undefined;
27
+ const raw = fs.readFileSync(filePath, 'utf-8');
28
+ return JSON.parse(raw);
29
+ }
30
+ /** Overwrite the full state file for `appName`, creating ~/.hazo-deploy if needed. */
31
+ export function writeState(state) {
32
+ const dir = getStateDir();
33
+ if (!fs.existsSync(dir)) {
34
+ fs.mkdirSync(dir, { recursive: true });
35
+ }
36
+ const filePath = getStatePath(state.app_name);
37
+ fs.writeFileSync(filePath, JSON.stringify(state, null, 2) + '\n', 'utf-8');
38
+ }
39
+ /**
40
+ * Merge `patch` into the existing state for `appName` and persist it.
41
+ * Throws if no state file exists yet — callers must `writeState` an initial
42
+ * state (e.g. during `deploy init`) before updating it.
43
+ */
44
+ export function updateState(appName, patch) {
45
+ const existing = readState(appName);
46
+ if (!existing) {
47
+ throw new Error(`No deploy state found for "${appName}" at ${getStatePath(appName)}. Run "deploy init" first.`);
48
+ }
49
+ const next = { ...existing, ...patch };
50
+ writeState(next);
51
+ return next;
52
+ }
@@ -0,0 +1,54 @@
1
+ import type { CommandRunner, DeployConfig } from './types.js';
2
+ /** Snapshot of one directory's role in the blue/green pair. */
3
+ export interface DeployDirStatus {
4
+ role: 'live' | 'standby';
5
+ dir: string;
6
+ port: number;
7
+ /** Whether a PM2 process with a matching cwd is currently online. */
8
+ running: boolean;
9
+ pid?: number;
10
+ pm2Status?: string;
11
+ }
12
+ export interface DeployStatusResult {
13
+ appName: string;
14
+ /** False when no state file exists yet (fresh setup, before `deploy init`). */
15
+ stateFound: boolean;
16
+ live?: DeployDirStatus;
17
+ standby?: DeployDirStatus;
18
+ diskFreeMb?: number;
19
+ memoryFreeMb?: number;
20
+ minMemoryMb: number;
21
+ memoryLow: boolean;
22
+ lastSwitch?: string;
23
+ lastBuild?: string;
24
+ lastBuildStatus?: 'success' | 'failed';
25
+ /** Non-fatal problems encountered while gathering status (pm2 unavailable, unparsable df output, ...). */
26
+ warnings: string[];
27
+ }
28
+ /**
29
+ * Exported so `deploy clean` (src/deploy/clean.ts) can reuse the same
30
+ * free-memory probe for its swap-suggestion trigger instead of duplicating
31
+ * this platform-specific (/proc/meminfo vs vm_stat) parsing logic.
32
+ */
33
+ export declare function queryMemoryFreeMb(runner: CommandRunner, warnings: string[]): number | undefined;
34
+ /**
35
+ * Exported so `deploy build` (src/deploy/build.ts) can reuse the same
36
+ * `df`-based free-disk probe for its post-cleanup threshold check instead of
37
+ * duplicating this parsing logic — mirrors `queryMemoryFreeMb`'s export.
38
+ */
39
+ export declare function queryDiskFreeMb(runner: CommandRunner, dir: string, warnings: string[]): number | undefined;
40
+ export interface RunStatusOptions {
41
+ /** Directory to check disk free space on. Defaults to process.cwd(). */
42
+ cwd?: string;
43
+ }
44
+ /**
45
+ * Gather structured deploy status: which dir is live/standby, their ports
46
+ * and PM2 running state, disk/memory free, and the last build/switch info
47
+ * from the state file. Returns data only — src/cli.ts formats and prints it.
48
+ *
49
+ * Gracefully handles a missing state file (fresh setup, before `deploy
50
+ * init`): `stateFound` is false and `live`/`standby` are omitted, but
51
+ * disk/memory are still reported.
52
+ */
53
+ export declare function runStatus(config: DeployConfig, runner: CommandRunner, opts?: RunStatusOptions): DeployStatusResult;
54
+ //# sourceMappingURL=status.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"status.d.ts","sourceRoot":"","sources":["../../src/deploy/status.ts"],"names":[],"mappings":"AAWA,OAAO,KAAK,EAAE,aAAa,EAAE,YAAY,EAAe,MAAM,YAAY,CAAC;AAE3E,+DAA+D;AAC/D,MAAM,WAAW,eAAe;IAC9B,IAAI,EAAE,MAAM,GAAG,SAAS,CAAC;IACzB,GAAG,EAAE,MAAM,CAAC;IACZ,IAAI,EAAE,MAAM,CAAC;IACb,qEAAqE;IACrE,OAAO,EAAE,OAAO,CAAC;IACjB,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,kBAAkB;IACjC,OAAO,EAAE,MAAM,CAAC;IAChB,+EAA+E;IAC/E,UAAU,EAAE,OAAO,CAAC;IACpB,IAAI,CAAC,EAAE,eAAe,CAAC;IACvB,OAAO,CAAC,EAAE,eAAe,CAAC;IAC1B,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,WAAW,EAAE,MAAM,CAAC;IACpB,SAAS,EAAE,OAAO,CAAC;IACnB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,eAAe,CAAC,EAAE,SAAS,GAAG,QAAQ,CAAC;IACvC,0GAA0G;IAC1G,QAAQ,EAAE,MAAM,EAAE,CAAC;CACpB;AAsHD;;;;GAIG;AACH,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,aAAa,EAAE,QAAQ,EAAE,MAAM,EAAE,GAAG,MAAM,GAAG,SAAS,CAe/F;AAED;;;;GAIG;AACH,wBAAgB,eAAe,CAAC,MAAM,EAAE,aAAa,EAAE,GAAG,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,GAAG,MAAM,GAAG,SAAS,CAO1G;AAED,MAAM,WAAW,gBAAgB;IAC/B,wEAAwE;IACxE,GAAG,CAAC,EAAE,MAAM,CAAC;CACd;AAED;;;;;;;;GAQG;AACH,wBAAgB,SAAS,CACvB,MAAM,EAAE,YAAY,EACpB,MAAM,EAAE,aAAa,EACrB,IAAI,GAAE,gBAAqB,GAC1B,kBAAkB,CAoCpB"}
@@ -0,0 +1,182 @@
1
+ // hazo_env/src/deploy/status.ts — `deploy status` data gathering
2
+ //
3
+ // The first end-to-end deploy subcommand: resolves config, reads the state
4
+ // file, and queries PM2/disk/memory — all through the injected CommandRunner
5
+ // (the ONLY touchpoint for child_process is src/deploy/runner.ts; this file
6
+ // must never import node:child_process directly). Mirrors envsync/engine.ts's
7
+ // split of "compute structured data" from "format for console" — src/cli.ts
8
+ // does the printing, this file only returns data.
9
+ import path from 'node:path';
10
+ import { readState } from './state.js';
11
+ /**
12
+ * Query `pm2 jlist` and parse the JSON process list. Returns an empty list
13
+ * (plus a warning) rather than throwing when pm2 isn't installed/running or
14
+ * emits unparsable output — status should degrade gracefully, not crash.
15
+ */
16
+ function queryPm2Processes(runner, warnings) {
17
+ const result = runner.spawn('pm2 jlist');
18
+ if (result.code !== 0) {
19
+ warnings.push(`pm2 jlist failed (exit ${result.code}): ${result.stderr.trim() || 'no stderr'}`);
20
+ return [];
21
+ }
22
+ try {
23
+ const parsed = JSON.parse(result.stdout);
24
+ return Array.isArray(parsed) ? parsed : [];
25
+ }
26
+ catch {
27
+ warnings.push('pm2 jlist returned unparsable JSON');
28
+ return [];
29
+ }
30
+ }
31
+ /**
32
+ * Find the PM2 process whose cwd matches `dir`, if any.
33
+ *
34
+ * This depends on `pm2_env.pm_cwd` being set, which PM2 only does when
35
+ * `cwd` is passed explicitly to `pm2 start` (see the contract noted next
36
+ * to `DeployState['pm2_process']` in types.ts). If a later task's
37
+ * `pm2 start` invocation omits `cwd`, `pm_cwd` defaults to wherever
38
+ * `pm2 start` itself ran from and this match silently fails (reports
39
+ * "not running" with no error).
40
+ */
41
+ function findPm2ProcessForDir(processes, dir) {
42
+ const target = path.resolve(dir);
43
+ return processes.find((p) => p.pm2_env?.pm_cwd && path.resolve(p.pm2_env.pm_cwd) === target);
44
+ }
45
+ function dirStatus(role, dir, port, processes) {
46
+ const proc = findPm2ProcessForDir(processes, dir);
47
+ const status = proc?.pm2_env?.status;
48
+ return {
49
+ role,
50
+ dir,
51
+ port,
52
+ running: status === 'online',
53
+ pid: proc?.pid,
54
+ pm2Status: status,
55
+ };
56
+ }
57
+ /**
58
+ * Parse `df -k <dir>` output into free MB. Expects the standard two-line
59
+ * form (header + one data line) with "Available" as the 4th column.
60
+ */
61
+ function parseDiskFreeMb(dfOutput, warnings) {
62
+ const lines = dfOutput.trim().split('\n').filter((l) => l.trim().length > 0);
63
+ if (lines.length < 2) {
64
+ warnings.push('df output had no data line to parse');
65
+ return undefined;
66
+ }
67
+ const columns = lines[1].trim().split(/\s+/);
68
+ const availableKb = Number(columns[3]);
69
+ if (!Number.isFinite(availableKb)) {
70
+ warnings.push(`df output's Available column was not numeric: "${lines[1]}"`);
71
+ return undefined;
72
+ }
73
+ return Math.round(availableKb / 1024);
74
+ }
75
+ /** Parse `/proc/meminfo` output into free MB, preferring MemAvailable over MemFree. */
76
+ function parseMeminfoFreeMb(meminfo, warnings) {
77
+ const available = meminfo.match(/^MemAvailable:\s+(\d+)\s*kB/m);
78
+ const free = meminfo.match(/^MemFree:\s+(\d+)\s*kB/m);
79
+ const match = available ?? free;
80
+ if (!match) {
81
+ warnings.push('/proc/meminfo did not contain MemAvailable or MemFree');
82
+ return undefined;
83
+ }
84
+ return Math.round(Number(match[1]) / 1024);
85
+ }
86
+ /**
87
+ * Parse macOS `vm_stat` output into free MB: (free pages) * page size.
88
+ * vm_stat reports in pages, with the page size given in its header line,
89
+ * e.g. "Mach Virtual Memory Statistics: (page size of 4096 bytes)".
90
+ */
91
+ function parseVmStatFreeMb(vmStat, warnings) {
92
+ const pageSizeMatch = vmStat.match(/page size of (\d+) bytes/);
93
+ const freePagesMatch = vmStat.match(/^Pages free:\s+(\d+)\.?/m);
94
+ if (!pageSizeMatch || !freePagesMatch) {
95
+ warnings.push('vm_stat output was missing page size or "Pages free" line');
96
+ return undefined;
97
+ }
98
+ const pageSize = Number(pageSizeMatch[1]);
99
+ const freePages = Number(freePagesMatch[1]);
100
+ if (!Number.isFinite(pageSize) || !Number.isFinite(freePages)) {
101
+ warnings.push('vm_stat output had non-numeric page size or free page count');
102
+ return undefined;
103
+ }
104
+ return Math.round((freePages * pageSize) / (1024 * 1024));
105
+ }
106
+ /**
107
+ * Exported so `deploy clean` (src/deploy/clean.ts) can reuse the same
108
+ * free-memory probe for its swap-suggestion trigger instead of duplicating
109
+ * this platform-specific (/proc/meminfo vs vm_stat) parsing logic.
110
+ */
111
+ export function queryMemoryFreeMb(runner, warnings) {
112
+ if (process.platform === 'darwin') {
113
+ const result = runner.spawn('vm_stat');
114
+ if (result.code !== 0) {
115
+ warnings.push(`vm_stat failed (exit ${result.code}): ${result.stderr.trim() || 'no stderr'}`);
116
+ return undefined;
117
+ }
118
+ return parseVmStatFreeMb(result.stdout, warnings);
119
+ }
120
+ const result = runner.spawn('cat /proc/meminfo');
121
+ if (result.code !== 0) {
122
+ warnings.push(`reading /proc/meminfo failed (exit ${result.code}): ${result.stderr.trim() || 'no stderr'}`);
123
+ return undefined;
124
+ }
125
+ return parseMeminfoFreeMb(result.stdout, warnings);
126
+ }
127
+ /**
128
+ * Exported so `deploy build` (src/deploy/build.ts) can reuse the same
129
+ * `df`-based free-disk probe for its post-cleanup threshold check instead of
130
+ * duplicating this parsing logic — mirrors `queryMemoryFreeMb`'s export.
131
+ */
132
+ export function queryDiskFreeMb(runner, dir, warnings) {
133
+ const result = runner.spawn(`df -k ${JSON.stringify(dir)}`);
134
+ if (result.code !== 0) {
135
+ warnings.push(`df failed (exit ${result.code}): ${result.stderr.trim() || 'no stderr'}`);
136
+ return undefined;
137
+ }
138
+ return parseDiskFreeMb(result.stdout, warnings);
139
+ }
140
+ /**
141
+ * Gather structured deploy status: which dir is live/standby, their ports
142
+ * and PM2 running state, disk/memory free, and the last build/switch info
143
+ * from the state file. Returns data only — src/cli.ts formats and prints it.
144
+ *
145
+ * Gracefully handles a missing state file (fresh setup, before `deploy
146
+ * init`): `stateFound` is false and `live`/`standby` are omitted, but
147
+ * disk/memory are still reported.
148
+ */
149
+ export function runStatus(config, runner, opts = {}) {
150
+ const warnings = [];
151
+ const state = readState(config.app_name);
152
+ const processes = queryPm2Processes(runner, warnings);
153
+ const cwd = opts.cwd ?? process.cwd();
154
+ const diskFreeMb = queryDiskFreeMb(runner, cwd, warnings);
155
+ const memoryFreeMb = queryMemoryFreeMb(runner, warnings);
156
+ const memoryLow = memoryFreeMb !== undefined && memoryFreeMb < config.min_memory_mb;
157
+ if (!state) {
158
+ return {
159
+ appName: config.app_name,
160
+ stateFound: false,
161
+ diskFreeMb,
162
+ memoryFreeMb,
163
+ minMemoryMb: config.min_memory_mb,
164
+ memoryLow,
165
+ warnings,
166
+ };
167
+ }
168
+ return {
169
+ appName: config.app_name,
170
+ stateFound: true,
171
+ live: dirStatus('live', state.live_dir, state.live_port, processes),
172
+ standby: dirStatus('standby', state.standby_dir, state.staging_port, processes),
173
+ diskFreeMb,
174
+ memoryFreeMb,
175
+ minMemoryMb: config.min_memory_mb,
176
+ memoryLow,
177
+ lastSwitch: state.last_switch,
178
+ lastBuild: state.last_build,
179
+ lastBuildStatus: state.last_build_status,
180
+ warnings,
181
+ };
182
+ }
@@ -0,0 +1,40 @@
1
+ import type { CommandRunner, DeployConfig, DeployState } from './types.js';
2
+ export interface PostSwitchHookResult {
3
+ cmd: string;
4
+ status: 'pass' | 'fail';
5
+ detail: string;
6
+ }
7
+ export interface RunSwitchResult {
8
+ previousLiveDir: string;
9
+ newLiveDir: string;
10
+ newStandbyDir: string;
11
+ prodPort: number;
12
+ stagingPort: number;
13
+ /** True iff a staging PM2 process was found and stopped (false if it was already stopped/absent). */
14
+ stagingStopped: boolean;
15
+ /** Set when the staging-delete step (above) failed for a reason other than "not found". */
16
+ stagingDeleteWarning?: string;
17
+ /** Set when `pm2 save` failed after a successful switch (non-fatal — the switch itself already succeeded). */
18
+ pm2SaveWarning?: string;
19
+ postSwitchHooks: PostSwitchHookResult[];
20
+ state: DeployState;
21
+ }
22
+ /** Thrown when there's nothing to switch (no state file yet) or a fatal step fails. */
23
+ export declare class SwitchAbortError extends Error {
24
+ constructor(message: string);
25
+ }
26
+ export interface RunSwitchOptions {
27
+ /**
28
+ * Fix 2: bypass the "standby must have a successful, post-last-switch
29
+ * build" check below. Use only when the operator has independently
30
+ * verified the standby dir is safe to promote (e.g. it was built/verified
31
+ * through some means outside this state file's tracking).
32
+ */
33
+ force?: boolean;
34
+ }
35
+ /**
36
+ * Promote the standby directory to live. See this file's header for the
37
+ * full step-by-step rationale.
38
+ */
39
+ export declare function runSwitch(config: DeployConfig, runner: CommandRunner, opts?: RunSwitchOptions): RunSwitchResult;
40
+ //# sourceMappingURL=switch.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"switch.d.ts","sourceRoot":"","sources":["../../src/deploy/switch.ts"],"names":[],"mappings":"AA8DA,OAAO,KAAK,EAAE,aAAa,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAE3E,MAAM,WAAW,oBAAoB;IACnC,GAAG,EAAE,MAAM,CAAC;IACZ,MAAM,EAAE,MAAM,GAAG,MAAM,CAAC;IACxB,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,eAAe;IAC9B,eAAe,EAAE,MAAM,CAAC;IACxB,UAAU,EAAE,MAAM,CAAC;IACnB,aAAa,EAAE,MAAM,CAAC;IACtB,QAAQ,EAAE,MAAM,CAAC;IACjB,WAAW,EAAE,MAAM,CAAC;IACpB,qGAAqG;IACrG,cAAc,EAAE,OAAO,CAAC;IACxB,2FAA2F;IAC3F,oBAAoB,CAAC,EAAE,MAAM,CAAC;IAC9B,8GAA8G;IAC9G,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,eAAe,EAAE,oBAAoB,EAAE,CAAC;IACxC,KAAK,EAAE,WAAW,CAAC;CACpB;AAED,uFAAuF;AACvF,qBAAa,gBAAiB,SAAQ,KAAK;gBAC7B,OAAO,EAAE,MAAM;CAI5B;AAED,MAAM,WAAW,gBAAgB;IAC/B;;;;;OAKG;IACH,KAAK,CAAC,EAAE,OAAO,CAAC;CACjB;AAED;;;GAGG;AACH,wBAAgB,SAAS,CAAC,MAAM,EAAE,YAAY,EAAE,MAAM,EAAE,aAAa,EAAE,IAAI,GAAE,gBAAqB,GAAG,eAAe,CA0HnH"}