hazo_env 0.10.2 → 0.11.0

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 (56) hide show
  1. package/CHANGE_LOG.md +102 -0
  2. package/config/hazo_env_config.ini.sample +61 -0
  3. package/dist/cli.js +315 -0
  4. package/dist/deploy/build.d.ts +90 -0
  5. package/dist/deploy/build.d.ts.map +1 -0
  6. package/dist/deploy/build.js +299 -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 +6 -0
  11. package/dist/deploy/index.d.ts.map +1 -0
  12. package/dist/deploy/index.js +6 -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 +80 -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 +88 -0
  20. package/dist/deploy/pm2-start.d.ts.map +1 -0
  21. package/dist/deploy/pm2-start.js +196 -0
  22. package/dist/deploy/rollback.d.ts +18 -0
  23. package/dist/deploy/rollback.d.ts.map +1 -0
  24. package/dist/deploy/rollback.js +167 -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 +27 -0
  35. package/dist/deploy/switch.d.ts.map +1 -0
  36. package/dist/deploy/switch.js +152 -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/doctor.d.ts.map +1 -1
  44. package/dist/doctor.js +6 -2
  45. package/dist/index.d.ts +2 -0
  46. package/dist/index.d.ts.map +1 -1
  47. package/dist/index.js +3 -0
  48. package/dist/locales/locales/en.json +1 -0
  49. package/dist/resolve/connect.d.ts.map +1 -1
  50. package/dist/resolve/connect.js +15 -1
  51. package/dist/resolve/deploy.d.ts +8 -0
  52. package/dist/resolve/deploy.d.ts.map +1 -0
  53. package/dist/resolve/deploy.js +121 -0
  54. package/dist/types/index.d.ts +10 -0
  55. package/dist/types/index.d.ts.map +1 -1
  56. package/package.json +10 -8
@@ -0,0 +1,48 @@
1
+ // hazo_env/src/deploy/peer.ts — Peer (standby) directory resolution
2
+ //
3
+ // Default convention: sibling directories differ only by a blue/green
4
+ // suffix (e.g. "gotimer-blue" and "gotimer-green" living side by side in
5
+ // the same parent directory). `resolvePeerDir` swaps the suffix to find the
6
+ // peer; an explicit override (later tasks' `--peer-dir` flag) always wins.
7
+ import path from 'node:path';
8
+ const SUFFIX_SWAP = {
9
+ blue: 'green',
10
+ green: 'blue',
11
+ };
12
+ /**
13
+ * Given a directory basename ending in "-blue" or "-green", return the
14
+ * basename with that suffix swapped. Returns `undefined` if the basename
15
+ * doesn't end in a recognized color suffix.
16
+ */
17
+ export function swapColorSuffix(dirName) {
18
+ for (const [from, to] of Object.entries(SUFFIX_SWAP)) {
19
+ const suffix = `-${from}`;
20
+ if (dirName.endsWith(suffix)) {
21
+ return dirName.slice(0, -suffix.length) + `-${to}`;
22
+ }
23
+ }
24
+ return undefined;
25
+ }
26
+ /**
27
+ * Resolve the absolute path to the peer (standby) directory for `currentDir`.
28
+ *
29
+ * - If `override` is provided, it wins unconditionally (resolved relative to
30
+ * `currentDir`'s parent if not already absolute).
31
+ * - Otherwise, swap the blue/green suffix on `currentDir`'s basename and
32
+ * resolve it as a sibling (same parent directory).
33
+ *
34
+ * Throws if no override is given and the basename has no blue/green suffix.
35
+ */
36
+ export function resolvePeerDir(currentDir, override) {
37
+ const absCurrent = path.resolve(currentDir);
38
+ const parent = path.dirname(absCurrent);
39
+ if (override) {
40
+ return path.isAbsolute(override) ? override : path.resolve(parent, override);
41
+ }
42
+ const basename = path.basename(absCurrent);
43
+ const peerBasename = swapColorSuffix(basename);
44
+ if (!peerBasename) {
45
+ throw new Error(`Cannot resolve peer directory for "${basename}": no "-blue" or "-green" suffix found. Pass an explicit peer dir override.`);
46
+ }
47
+ return path.join(parent, peerBasename);
48
+ }
@@ -0,0 +1,88 @@
1
+ import type { CommandResult, CommandRunner } from './types.js';
2
+ export interface StartNamedPm2ProcessOptions {
3
+ /** Directory whose ecosystem.config.js is the template to start from. */
4
+ dir: string;
5
+ /** PM2 process name to start the app under — must not collide with an existing registration. */
6
+ name: string;
7
+ /** Port to run the app on, merged into the cloned app config's env. */
8
+ port: number;
9
+ }
10
+ /**
11
+ * Start `opts.dir`'s app under PM2 as `opts.name`, running on `opts.port`,
12
+ * with `cwd` set to `opts.dir`.
13
+ *
14
+ * Assumes a single-app ecosystem file (one entry in `apps`) — this
15
+ * project's existing convention (see gotimer's own ecosystem.config.js) and
16
+ * explicitly in scope per the deploy-module spec, which excludes
17
+ * multi-instance/cluster mode; no evidence of a multi-app ecosystem file
18
+ * was found anywhere in this monorepo while building this helper. Throws if
19
+ * `apps` is empty or has more than one entry, rather than silently guessing
20
+ * which one to use.
21
+ *
22
+ * `PORT` is merged into BOTH `env` and `env_production` on the cloned
23
+ * config, since gotimer's own ecosystem.config.js (the one concrete example
24
+ * in this monorepo) puts the app's runtime env — PORT included — under
25
+ * `env_production` rather than the bare `env` block; setting both makes this
26
+ * helper work regardless of which block the target app's `--env` flag
27
+ * actually resolves against, without having to inspect the file at the call
28
+ * site. Every other key the template app sets (script, args, instances,
29
+ * exec_mode, etc.) is carried over unchanged — only name/cwd/env are
30
+ * overridden.
31
+ */
32
+ export declare function startNamedPm2Process(runner: CommandRunner, opts: StartNamedPm2ProcessOptions): void;
33
+ /** True if a non-zero pm2 result looks like "process or namespace <name> not found" rather than a real failure. */
34
+ export declare function isPm2ProcessNotFound(result: CommandResult): boolean;
35
+ export interface PromoteDirFreshOptions {
36
+ /** Directory whose PM2 registration under `name` is being replaced. */
37
+ fromDir: string;
38
+ /** Directory to fresh-start under `name` on `port`. */
39
+ toDir: string;
40
+ /** PM2 process name both directories share (there's only ever one registration under this name at a time). */
41
+ name: string;
42
+ /** Production port to start `toDir` on. */
43
+ port: number;
44
+ /**
45
+ * Optional staging registration to tolerant-delete (cwd: `toDir`) before
46
+ * starting `toDir` fresh — e.g. `<name>-staging`, left running by `deploy
47
+ * build`'s health check against the dir now being promoted. Omit when
48
+ * the dir being promoted was never a staging candidate (e.g. rollback
49
+ * restoring a dir that was simply live before the last switch).
50
+ */
51
+ stagingName?: string;
52
+ /** Describes `toDir` in the primary failure message, e.g. "standby app" or "previous live app". */
53
+ toLabel: string;
54
+ /** Describes `fromDir` in the restore-outcome messages, e.g. "the previous live build" or "the build that was live before this rollback attempt". */
55
+ fromLabel: string;
56
+ }
57
+ export interface PromoteDirFreshResult {
58
+ /** True iff a staging PM2 process was found and deleted (false if stagingName was omitted, or was already stopped/absent). */
59
+ stagingDeleted: boolean;
60
+ }
61
+ /** Thrown when any step of promoteDirFresh fails fatally. Message already includes the restore-attempt outcome when the primary start fails. */
62
+ export declare class PromoteDirFreshError extends Error {
63
+ constructor(message: string);
64
+ }
65
+ /**
66
+ * Delete the current `name` registration in `fromDir`, optionally clean up
67
+ * a stale `stagingName` registration in `toDir`, then fresh-start `toDir`
68
+ * under `name` on `port` via `startNamedPm2Process`.
69
+ *
70
+ * On a failed primary start, this does NOT simply retry `startNamedPm2Process`
71
+ * for `fromDir` as the restore — task-8 review caught a real bug in both
72
+ * switch.ts's and rollback.ts's independently-written versions of this:
73
+ * `pm2 start` can register `name` against `toDir` and THEN fail (e.g. the
74
+ * process registers but immediately crashes, or the start command's exit
75
+ * code is non-zero for an unrelated reason after pm2 already created the
76
+ * registration). If that happens, the "restore" call's own
77
+ * `startNamedPm2Process(..., dir: fromDir, name)` sees `name` ALREADY
78
+ * registered — pm2 only recomputes `cwd`/`pm_cwd` for a name it has never
79
+ * registered before (see startNamedPm2Process's own header) — so it just
80
+ * restarts THAT existing registration in place, still pointing at `toDir`,
81
+ * while this function reports "Production RESTORED". Nothing was actually
82
+ * restored. Fixed by tolerant-deleting `name` (cwd: `toDir`) BEFORE
83
+ * attempting the restore start, exactly as the primary delete step does,
84
+ * so the restore's `startNamedPm2Process` call is guaranteed to see a truly
85
+ * unregistered name and recompute `cwd` correctly against `fromDir`.
86
+ */
87
+ export declare function promoteDirFresh(runner: CommandRunner, opts: PromoteDirFreshOptions): PromoteDirFreshResult;
88
+ //# sourceMappingURL=pm2-start.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pm2-start.d.ts","sourceRoot":"","sources":["../../src/deploy/pm2-start.ts"],"names":[],"mappings":"AAiCA,OAAO,KAAK,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAe/D,MAAM,WAAW,2BAA2B;IAC1C,yEAAyE;IACzE,GAAG,EAAE,MAAM,CAAC;IACZ,gGAAgG;IAChG,IAAI,EAAE,MAAM,CAAC;IACb,uEAAuE;IACvE,IAAI,EAAE,MAAM,CAAC;CACd;AAeD;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,aAAa,EAAE,IAAI,EAAE,2BAA2B,GAAG,IAAI,CA4CnG;AAeD,mHAAmH;AACnH,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,aAAa,GAAG,OAAO,CAEnE;AAED,MAAM,WAAW,sBAAsB;IACrC,uEAAuE;IACvE,OAAO,EAAE,MAAM,CAAC;IAChB,uDAAuD;IACvD,KAAK,EAAE,MAAM,CAAC;IACd,8GAA8G;IAC9G,IAAI,EAAE,MAAM,CAAC;IACb,2CAA2C;IAC3C,IAAI,EAAE,MAAM,CAAC;IACb;;;;;;OAMG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,mGAAmG;IACnG,OAAO,EAAE,MAAM,CAAC;IAChB,qJAAqJ;IACrJ,SAAS,EAAE,MAAM,CAAC;CACnB;AAED,MAAM,WAAW,qBAAqB;IACpC,8HAA8H;IAC9H,cAAc,EAAE,OAAO,CAAC;CACzB;AAED,gJAAgJ;AAChJ,qBAAa,oBAAqB,SAAQ,KAAK;gBACjC,OAAO,EAAE,MAAM;CAI5B;AAED;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAgB,eAAe,CAAC,MAAM,EAAE,aAAa,EAAE,IAAI,EAAE,sBAAsB,GAAG,qBAAqB,CAmD1G"}
@@ -0,0 +1,196 @@
1
+ // hazo_env/src/deploy/pm2-start.ts — shared helper: start a pm2 process
2
+ // under an explicit, previously-unused name/cwd/port.
3
+ //
4
+ // Why this exists (bug this fixes, found during task-7/switch review):
5
+ // `pm2 start ecosystem.config.js --name X` does NOT make pm2 register a
6
+ // distinct process named X when starting FROM A CONFIG FILE. In that mode
7
+ // pm2's `_startJson` reads the process name from the `name` field baked
8
+ // into the ecosystem file's own app entry — it never consults the CLI
9
+ // `--name` override. So the previous `deploy build` staging-start command
10
+ // (`pm2 start ecosystem.config.js --name <app>-staging --env production`)
11
+ // silently restarted (or no-op'd against) whatever process was ALREADY
12
+ // registered under the ecosystem file's real app name, instead of creating
13
+ // a genuinely separate staging process.
14
+ //
15
+ // pm2 only recomputes a process's cwd/pm_cwd (via `resolveAppAttributes`)
16
+ // when it sees a name it has never registered before. The only reliable
17
+ // way to get a truly new, distinct-cwd/port process is to hand pm2 a config
18
+ // file whose `name` field IS already the new name — so this helper clones
19
+ // the target dir's ecosystem.config.js, overrides name/cwd/port on that
20
+ // clone, writes it to a per-call-unique temp file, and starts FROM that
21
+ // temp file (never the original).
22
+ //
23
+ // Shared by `deploy build` (starts `<app_name>-staging`) and `deploy
24
+ // switch` (task 7: starts `<app_name>` on the standby dir, after stopping/
25
+ // deleting the old live registration, to promote standby to live) — both
26
+ // need the exact same "start this dir's app under an explicit distinct
27
+ // name/cwd/port" primitive, which is why this lives in its own file rather
28
+ // than inside build.ts.
29
+ import fs from 'node:fs';
30
+ import os from 'node:os';
31
+ import path from 'node:path';
32
+ import { createRequire } from 'node:module';
33
+ // ecosystem.config.js is a plain CommonJS module (`module.exports = {...}`,
34
+ // per every ecosystem.config.js in this monorepo — see gotimer's own, which
35
+ // also uses `require`/`__dirname` inside it). This package builds to real
36
+ // ESM (`"type": "module"`), where a bare `require` isn't in scope;
37
+ // `createRequire` is the ESM-safe way to get one — matching verify.ts's
38
+ // existing convention for reading CommonJS config/modules at runtime (see
39
+ // its doc comment). No cache-busting here: each `hazo_env` CLI invocation
40
+ // (`deploy build` or `deploy switch`) is a separate, single process that
41
+ // calls `startNamedPm2Process` at most once against a given
42
+ // ecosystem.config.js — there's no in-process repeat-read of the same path
43
+ // in real usage, so `require()`'s ordinary module cache is simply correct.
44
+ const require = createRequire(import.meta.url);
45
+ /**
46
+ * Start `opts.dir`'s app under PM2 as `opts.name`, running on `opts.port`,
47
+ * with `cwd` set to `opts.dir`.
48
+ *
49
+ * Assumes a single-app ecosystem file (one entry in `apps`) — this
50
+ * project's existing convention (see gotimer's own ecosystem.config.js) and
51
+ * explicitly in scope per the deploy-module spec, which excludes
52
+ * multi-instance/cluster mode; no evidence of a multi-app ecosystem file
53
+ * was found anywhere in this monorepo while building this helper. Throws if
54
+ * `apps` is empty or has more than one entry, rather than silently guessing
55
+ * which one to use.
56
+ *
57
+ * `PORT` is merged into BOTH `env` and `env_production` on the cloned
58
+ * config, since gotimer's own ecosystem.config.js (the one concrete example
59
+ * in this monorepo) puts the app's runtime env — PORT included — under
60
+ * `env_production` rather than the bare `env` block; setting both makes this
61
+ * helper work regardless of which block the target app's `--env` flag
62
+ * actually resolves against, without having to inspect the file at the call
63
+ * site. Every other key the template app sets (script, args, instances,
64
+ * exec_mode, etc.) is carried over unchanged — only name/cwd/env are
65
+ * overridden.
66
+ */
67
+ export function startNamedPm2Process(runner, opts) {
68
+ const ecosystemPath = path.join(opts.dir, 'ecosystem.config.js');
69
+ if (!fs.existsSync(ecosystemPath)) {
70
+ throw new Error(`No ecosystem.config.js found at ${ecosystemPath}.`);
71
+ }
72
+ const ecosystem = require(ecosystemPath);
73
+ if (!Array.isArray(ecosystem.apps) || ecosystem.apps.length === 0) {
74
+ throw new Error(`${ecosystemPath} has no "apps" entries — cannot start a named pm2 process from it.`);
75
+ }
76
+ if (ecosystem.apps.length > 1) {
77
+ throw new Error(`${ecosystemPath} declares ${ecosystem.apps.length} apps — startNamedPm2Process only supports a ` +
78
+ `single-app ecosystem file (multi-instance/cluster mode is out of scope for this deploy module).`);
79
+ }
80
+ const template = ecosystem.apps[0];
81
+ const portStr = String(opts.port);
82
+ const namedApp = {
83
+ ...template,
84
+ name: opts.name,
85
+ cwd: opts.dir,
86
+ env: { ...(template.env ?? {}), PORT: portStr },
87
+ env_production: { ...(template.env_production ?? {}), PORT: portStr },
88
+ };
89
+ // Written to os.tmpdir(), not opts.dir: opts.dir's own ecosystem.config.js
90
+ // may be tracked/gitignored in ways that make a sibling temp file there
91
+ // awkward (and a fresh clone's dir is exactly the case build.ts's db-setup
92
+ // step already has to guard against for a different path). A unique
93
+ // filename per call keeps concurrent invocations (e.g. build and a
94
+ // separate verify run) from clobbering each other.
95
+ const uniqueSuffix = `${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`;
96
+ const tempFile = path.join(os.tmpdir(), `hazo-env-pm2-${opts.name}-${uniqueSuffix}.config.cjs`);
97
+ fs.writeFileSync(tempFile, `module.exports = ${JSON.stringify({ apps: [namedApp] }, null, 2)};\n`, 'utf-8');
98
+ // Deliberately NOT cleaned up here: pm2 start may read the file
99
+ // asynchronously (forking its own daemon process against it), and
100
+ // deleting it immediately after `runner.exec` returns risks a race with
101
+ // that read. It's an ephemeral, uniquely-named file in os.tmpdir() — the
102
+ // OS reclaims tmpdir over time, and the cost of leaving a few small JSON
103
+ // files behind is far lower than the cost of a flaky deploy.
104
+ runner.exec(`pm2 start ${JSON.stringify(tempFile)} --env production`);
105
+ }
106
+ // ─── promoteDirFresh ─────────────────────────────────────────────────────
107
+ //
108
+ // Shared by `deploy switch` and `deploy rollback` — both need the exact
109
+ // same "delete whatever's currently registered under <name>, optionally
110
+ // clean up a stale staging registration too, then fresh-start a different
111
+ // dir under that same name" sequence, in opposite directions (switch:
112
+ // standby -> live; rollback: previous-live -> live). Extracted here after
113
+ // task-8 review found the SAME bug in both files' independently-written
114
+ // restore-on-failure paths (see below) — one fix, shared by both callers,
115
+ // so it can't drift out of sync again.
116
+ const PM2_NOT_FOUND_PATTERN = /not found/i;
117
+ /** True if a non-zero pm2 result looks like "process or namespace <name> not found" rather than a real failure. */
118
+ export function isPm2ProcessNotFound(result) {
119
+ return PM2_NOT_FOUND_PATTERN.test(result.stdout) || PM2_NOT_FOUND_PATTERN.test(result.stderr);
120
+ }
121
+ /** Thrown when any step of promoteDirFresh fails fatally. Message already includes the restore-attempt outcome when the primary start fails. */
122
+ export class PromoteDirFreshError extends Error {
123
+ constructor(message) {
124
+ super(message);
125
+ this.name = 'PromoteDirFreshError';
126
+ }
127
+ }
128
+ /**
129
+ * Delete the current `name` registration in `fromDir`, optionally clean up
130
+ * a stale `stagingName` registration in `toDir`, then fresh-start `toDir`
131
+ * under `name` on `port` via `startNamedPm2Process`.
132
+ *
133
+ * On a failed primary start, this does NOT simply retry `startNamedPm2Process`
134
+ * for `fromDir` as the restore — task-8 review caught a real bug in both
135
+ * switch.ts's and rollback.ts's independently-written versions of this:
136
+ * `pm2 start` can register `name` against `toDir` and THEN fail (e.g. the
137
+ * process registers but immediately crashes, or the start command's exit
138
+ * code is non-zero for an unrelated reason after pm2 already created the
139
+ * registration). If that happens, the "restore" call's own
140
+ * `startNamedPm2Process(..., dir: fromDir, name)` sees `name` ALREADY
141
+ * registered — pm2 only recomputes `cwd`/`pm_cwd` for a name it has never
142
+ * registered before (see startNamedPm2Process's own header) — so it just
143
+ * restarts THAT existing registration in place, still pointing at `toDir`,
144
+ * while this function reports "Production RESTORED". Nothing was actually
145
+ * restored. Fixed by tolerant-deleting `name` (cwd: `toDir`) BEFORE
146
+ * attempting the restore start, exactly as the primary delete step does,
147
+ * so the restore's `startNamedPm2Process` call is guaranteed to see a truly
148
+ * unregistered name and recompute `cwd` correctly against `fromDir`.
149
+ */
150
+ export function promoteDirFresh(runner, opts) {
151
+ const deleteResult = runner.spawn(`pm2 delete ${opts.name}`, { cwd: opts.fromDir });
152
+ if (deleteResult.code !== 0 && !isPm2ProcessNotFound(deleteResult)) {
153
+ throw new PromoteDirFreshError(`Failed to delete the current PM2 process "${opts.name}" in ${opts.fromDir}: ` +
154
+ (deleteResult.stderr || deleteResult.stdout || `exit code ${deleteResult.code}`));
155
+ }
156
+ let stagingDeleted = false;
157
+ if (opts.stagingName) {
158
+ try {
159
+ const result = runner.spawn(`pm2 delete ${opts.stagingName}`, { cwd: opts.toDir });
160
+ stagingDeleted = result.code === 0;
161
+ }
162
+ catch {
163
+ stagingDeleted = false;
164
+ }
165
+ }
166
+ try {
167
+ startNamedPm2Process(runner, { dir: opts.toDir, name: opts.name, port: opts.port });
168
+ }
169
+ catch (startErr) {
170
+ const startMsg = startErr instanceof Error ? startErr.message : String(startErr);
171
+ // Clear any registration the failed start may have partially created
172
+ // against `toDir` BEFORE attempting the restore — see this function's
173
+ // doc comment for the bug this prevents. Best-effort: we're already in
174
+ // the failure path, and the restore attempt below still proceeds
175
+ // regardless of whether this cleanup itself succeeds.
176
+ try {
177
+ runner.spawn(`pm2 delete ${opts.name}`, { cwd: opts.toDir });
178
+ }
179
+ catch {
180
+ // ignore — best-effort cleanup
181
+ }
182
+ let restoreMsg;
183
+ try {
184
+ startNamedPm2Process(runner, { dir: opts.fromDir, name: opts.name, port: opts.port });
185
+ restoreMsg = `Production RESTORED: ${opts.fromLabel} in ${opts.fromDir} was restarted on port ${opts.port}.`;
186
+ }
187
+ catch (restoreErr) {
188
+ const restoreMsgDetail = restoreErr instanceof Error ? restoreErr.message : String(restoreErr);
189
+ restoreMsg =
190
+ `PRODUCTION IS DOWN: failed to restore ${opts.fromLabel} in ${opts.fromDir} as well: ${restoreMsgDetail}. ` +
191
+ `Manual intervention required.`;
192
+ }
193
+ throw new PromoteDirFreshError(`Failed to start the ${opts.toLabel} (${opts.toDir}) on the production port: ${startMsg}\n${restoreMsg}`);
194
+ }
195
+ return { stagingDeleted };
196
+ }
@@ -0,0 +1,18 @@
1
+ import type { CommandRunner, DeployConfig, DeployState } from './types.js';
2
+ export interface RunRollbackResult {
3
+ restoredLiveDir: string;
4
+ newStandbyDir: string;
5
+ prodPort: number;
6
+ state: DeployState;
7
+ }
8
+ /** Thrown when there's nothing to roll back, or a fatal step fails. */
9
+ export declare class RollbackAbortError extends Error {
10
+ constructor(message: string);
11
+ }
12
+ /**
13
+ * Reverse the last `deploy switch`: put the previously-live build back on
14
+ * the production port. See this file's header for the full step-by-step
15
+ * rationale.
16
+ */
17
+ export declare function runRollback(config: DeployConfig, runner: CommandRunner): RunRollbackResult;
18
+ //# sourceMappingURL=rollback.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rollback.d.ts","sourceRoot":"","sources":["../../src/deploy/rollback.ts"],"names":[],"mappings":"AAkFA,OAAO,KAAK,EAAE,aAAa,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAE3E,MAAM,WAAW,iBAAiB;IAChC,eAAe,EAAE,MAAM,CAAC;IACxB,aAAa,EAAE,MAAM,CAAC;IACtB,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,WAAW,CAAC;CACpB;AAED,uEAAuE;AACvE,qBAAa,kBAAmB,SAAQ,KAAK;gBAC/B,OAAO,EAAE,MAAM;CAI5B;AAED;;;;GAIG;AACH,wBAAgB,WAAW,CAAC,MAAM,EAAE,YAAY,EAAE,MAAM,EAAE,aAAa,GAAG,iBAAiB,CAqF1F"}
@@ -0,0 +1,167 @@
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
+ throw new RollbackAbortError(`Standby has been rebuilt since the last switch (last_build ${state.last_build} is newer than ` +
112
+ `last_switch ${state.last_switch}) — the previous live build no longer exists (it was rebuilt in ` +
113
+ `place by "deploy build"). Cannot safely roll back.`);
114
+ }
115
+ const currentLiveDir = path.resolve(state.live_dir);
116
+ const restoreDir = path.resolve(state.previous_live_dir);
117
+ // Step 4: read the restored dir's git ref FIRST, before anything is
118
+ // stopped/started — mirrors switch.ts step 2 (see header).
119
+ const gitRef = runner.exec('git rev-parse HEAD', { cwd: restoreDir }).trim();
120
+ // Step 5: delete the current live PM2 registration, tolerant-delete any
121
+ // stray `<app_name>-staging` registration (defense in depth — see
122
+ // header), then fresh-start the previous-live dir on the production
123
+ // port — all via the shared helper (see header). On failure,
124
+ // promoteDirFresh itself attempts to bring the build rollback was trying
125
+ // to replace back up so production isn't silently left down, and
126
+ // reports plainly whether that worked.
127
+ try {
128
+ // stagingDeleted isn't currently surfaced in RunRollbackResult — this is
129
+ // defense in depth (see header), not the normal path — so the return
130
+ // value is intentionally unused here.
131
+ promoteDirFresh(runner, {
132
+ fromDir: currentLiveDir,
133
+ toDir: restoreDir,
134
+ name: config.app_name,
135
+ port: config.prod_port,
136
+ stagingName: `${config.app_name}-staging`,
137
+ toLabel: 'previous live app',
138
+ fromLabel: 'the build that was live before this rollback attempt',
139
+ });
140
+ }
141
+ catch (e) {
142
+ if (e instanceof PromoteDirFreshError) {
143
+ throw new RollbackAbortError(e.message);
144
+ }
145
+ throw e;
146
+ }
147
+ // Step 6: update state atomically. The restored dir becomes live, the dir
148
+ // that was live becomes standby, previous_live_dir is cleared (see
149
+ // header — deliberately not repopulated). git_ref was already resolved
150
+ // in step 4, before anything was touched.
151
+ const newState = updateState(config.app_name, {
152
+ live_dir: restoreDir,
153
+ live_port: config.prod_port,
154
+ standby_dir: currentLiveDir,
155
+ staging_port: config.staging_port,
156
+ previous_live_dir: undefined,
157
+ last_switch: new Date().toISOString(),
158
+ git_ref: gitRef,
159
+ pm2_process: config.app_name,
160
+ });
161
+ return {
162
+ restoredLiveDir: restoreDir,
163
+ newStandbyDir: currentLiveDir,
164
+ prodPort: config.prod_port,
165
+ state: newState,
166
+ };
167
+ }
@@ -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
+ }