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.
- package/CHANGE_LOG.md +79 -0
- package/config/hazo_env_config.ini.sample +61 -0
- package/dist/cli.js +329 -0
- package/dist/deploy/build.d.ts +91 -0
- package/dist/deploy/build.d.ts.map +1 -0
- package/dist/deploy/build.js +389 -0
- package/dist/deploy/clean.d.ts +63 -0
- package/dist/deploy/clean.d.ts.map +1 -0
- package/dist/deploy/clean.js +135 -0
- package/dist/deploy/index.d.ts +13 -0
- package/dist/deploy/index.d.ts.map +1 -0
- package/dist/deploy/index.js +22 -0
- package/dist/deploy/init.d.ts +20 -0
- package/dist/deploy/init.d.ts.map +1 -0
- package/dist/deploy/init.js +131 -0
- package/dist/deploy/peer.d.ts +18 -0
- package/dist/deploy/peer.d.ts.map +1 -0
- package/dist/deploy/peer.js +48 -0
- package/dist/deploy/pm2-start.d.ts +100 -0
- package/dist/deploy/pm2-start.d.ts.map +1 -0
- package/dist/deploy/pm2-start.js +228 -0
- package/dist/deploy/rollback.d.ts +22 -0
- package/dist/deploy/rollback.d.ts.map +1 -0
- package/dist/deploy/rollback.js +196 -0
- package/dist/deploy/runner.d.ts +8 -0
- package/dist/deploy/runner.d.ts.map +1 -0
- package/dist/deploy/runner.js +35 -0
- package/dist/deploy/state.d.ts +19 -0
- package/dist/deploy/state.d.ts.map +1 -0
- package/dist/deploy/state.js +52 -0
- package/dist/deploy/status.d.ts +54 -0
- package/dist/deploy/status.d.ts.map +1 -0
- package/dist/deploy/status.js +182 -0
- package/dist/deploy/switch.d.ts +40 -0
- package/dist/deploy/switch.d.ts.map +1 -0
- package/dist/deploy/switch.js +183 -0
- package/dist/deploy/types.d.ts +96 -0
- package/dist/deploy/types.d.ts.map +1 -0
- package/dist/deploy/types.js +16 -0
- package/dist/deploy/verify.d.ts +41 -0
- package/dist/deploy/verify.d.ts.map +1 -0
- package/dist/deploy/verify.js +214 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -0
- package/dist/resolve/connect.d.ts.map +1 -1
- package/dist/resolve/connect.js +15 -1
- package/dist/resolve/deploy.d.ts +8 -0
- package/dist/resolve/deploy.d.ts.map +1 -0
- package/dist/resolve/deploy.js +140 -0
- package/dist/types/index.d.ts +10 -0
- package/dist/types/index.d.ts.map +1 -1
- package/package.json +12 -12
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"init.d.ts","sourceRoot":"","sources":["../../src/deploy/init.ts"],"names":[],"mappings":"AAqBA,OAAO,KAAK,EAAE,aAAa,EAAE,YAAY,EAAe,MAAM,YAAY,CAAC;AAgD3E,MAAM,WAAW,cAAc;IAC7B,iFAAiF;IACjF,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,oEAAoE;IACpE,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,WAAW,aAAa;IAC5B,UAAU,EAAE,MAAM,CAAC;IACnB,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,EAAE,MAAM,CAAC;CACnB;AA0CD;;;;;GAKG;AACH,wBAAgB,OAAO,CAAC,MAAM,EAAE,YAAY,EAAE,MAAM,EAAE,aAAa,EAAE,IAAI,GAAE,cAAmB,GAAG,aAAa,CAgC7G"}
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
// hazo_env/src/deploy/init.ts — `deploy init`: create peer dir, clone, copy config, write state
|
|
2
|
+
//
|
|
3
|
+
// The first step of the blue-green lifecycle: resolves the peer (standby)
|
|
4
|
+
// directory as a sibling of the current (live) directory, clones the repo
|
|
5
|
+
// into it from the same git remote, copies hazo_env_config.ini across with
|
|
6
|
+
// `dir_suffix` flipped, and writes the initial state file. After this,
|
|
7
|
+
// the operator cds into the peer dir and runs `deploy build`.
|
|
8
|
+
//
|
|
9
|
+
// All external commands (git remote/clone) flow through the injected
|
|
10
|
+
// CommandRunner — see types.ts's CommandRunner doc comment and runner.ts's
|
|
11
|
+
// header. Reading/writing the INI and the state file is plain fs/node:fs,
|
|
12
|
+
// matching how state.ts does its own JSON read/write directly rather than
|
|
13
|
+
// routing through CommandRunner: CommandRunner is for *external commands*,
|
|
14
|
+
// not hazo_env's own file I/O.
|
|
15
|
+
import fs from 'node:fs';
|
|
16
|
+
import path from 'node:path';
|
|
17
|
+
import { HazoConfig } from 'hazo_config/server';
|
|
18
|
+
import { resolvePeerDir } from './peer.js';
|
|
19
|
+
import { writeState } from './state.js';
|
|
20
|
+
import { getEnv } from '../index.client.js';
|
|
21
|
+
const CONFIG_RELATIVE_PATH = path.join('config', 'hazo_env_config.ini');
|
|
22
|
+
// Matches resolve/files.ts's DEFAULT_DATA_ROOT — kept as a local literal
|
|
23
|
+
// rather than importing that module, since resolveFilesConfig()/
|
|
24
|
+
// resolveFilesRoot() are both hard-coded to resolve against
|
|
25
|
+
// `process.cwd()`, which during `deploy init` is the CURRENT (live) dir,
|
|
26
|
+
// not the freshly-cloned peer dir this function needs to resolve the data
|
|
27
|
+
// root *for*. Re-reading the peer's own just-copied INI directly (see
|
|
28
|
+
// `ensurePeerDataDir` below) keeps this correct regardless of what
|
|
29
|
+
// directory `deploy init` itself happens to be run from.
|
|
30
|
+
const DEFAULT_DATA_ROOT = 'app_data';
|
|
31
|
+
/**
|
|
32
|
+
* Blue<->green swap applied to the `dir_suffix = <value>` VALUE in the INI
|
|
33
|
+
* (as opposed to peer.ts's swapColorSuffix, which swaps a "-blue"/"-green"
|
|
34
|
+
* suffix on a directory *basename*). Kept identical to peer.ts's internal
|
|
35
|
+
* SUFFIX_SWAP map — update both together if the color vocabulary ever
|
|
36
|
+
* changes.
|
|
37
|
+
*/
|
|
38
|
+
const COLOR_SWAP = {
|
|
39
|
+
blue: 'green',
|
|
40
|
+
green: 'blue',
|
|
41
|
+
};
|
|
42
|
+
function swapDirSuffixValue(value) {
|
|
43
|
+
const swapped = COLOR_SWAP[value];
|
|
44
|
+
if (!swapped) {
|
|
45
|
+
throw new Error(`Cannot swap dir_suffix "${value}" in hazo_env_config.ini: expected "blue" or "green".`);
|
|
46
|
+
}
|
|
47
|
+
return swapped;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Swap the `dir_suffix = <value>` line in the INI's [deploy] section to its
|
|
51
|
+
* blue/green opposite, leaving every other byte of the file untouched.
|
|
52
|
+
*/
|
|
53
|
+
function swapDirSuffixInIni(iniContent) {
|
|
54
|
+
const pattern = /^(\s*dir_suffix\s*=\s*)(\S+)(\s*)$/m;
|
|
55
|
+
const match = iniContent.match(pattern);
|
|
56
|
+
if (!match) {
|
|
57
|
+
throw new Error('Could not find a "dir_suffix = ..." line in hazo_env_config.ini to swap.');
|
|
58
|
+
}
|
|
59
|
+
const swapped = swapDirSuffixValue(match[2]);
|
|
60
|
+
return iniContent.replace(pattern, `$1${swapped}$3`);
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Fix 9: `deploy build`'s FIRST run on a fresh peer dir aborts at the
|
|
64
|
+
* sqlite db-copy step with "destination directory does not exist" because
|
|
65
|
+
* the `[data] root` dir (typically gitignored, so a fresh `git clone`
|
|
66
|
+
* doesn't bring it along) was never created. Mirrors build.ts's own
|
|
67
|
+
* db_strategy detection (auto -> infer sqlite-ness from `[db.<env>]` type;
|
|
68
|
+
* copy -> always sqlite; shared -> never sqlite) so this only fires for
|
|
69
|
+
* sites that are actually sqlite-backed — a no-op for Postgres/"shared"
|
|
70
|
+
* sites, which have no per-dir data file to provision.
|
|
71
|
+
*
|
|
72
|
+
* Reads the PEER's own just-copied INI (not `resolveFilesConfig()`/
|
|
73
|
+
* `resolveConnectConfig()`, both of which resolve against `process.cwd()`
|
|
74
|
+
* — the CURRENT/live dir here, not the peer) so the `[data] root` and
|
|
75
|
+
* `[db.<env>] type` values reflect the peer's own config exactly.
|
|
76
|
+
*/
|
|
77
|
+
function ensurePeerDataDir(config, peerIniPath, peerDir) {
|
|
78
|
+
if (config.db_strategy === 'shared')
|
|
79
|
+
return; // never sqlite-backed by definition — nothing to provision.
|
|
80
|
+
let peerConfig;
|
|
81
|
+
try {
|
|
82
|
+
peerConfig = new HazoConfig({ filePath: peerIniPath });
|
|
83
|
+
}
|
|
84
|
+
catch {
|
|
85
|
+
// Can't read the INI we just wrote — nothing safe to infer or create.
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
let sqliteBacked = config.db_strategy === 'copy';
|
|
89
|
+
if (config.db_strategy === 'auto') {
|
|
90
|
+
const env = getEnv();
|
|
91
|
+
const dbSection = peerConfig.getSection(`db.${env}`);
|
|
92
|
+
sqliteBacked = dbSection?.['type'] === 'sqlite';
|
|
93
|
+
}
|
|
94
|
+
if (!sqliteBacked)
|
|
95
|
+
return;
|
|
96
|
+
const dataSection = peerConfig.getSection('data');
|
|
97
|
+
const root = dataSection?.['root'] ?? DEFAULT_DATA_ROOT;
|
|
98
|
+
const dataRoot = path.isAbsolute(root) ? root : path.join(peerDir, root);
|
|
99
|
+
fs.mkdirSync(dataRoot, { recursive: true });
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Create the peer (standby) directory: resolve its path, abort if it
|
|
103
|
+
* already exists, clone the repo into it, copy the INI config across with
|
|
104
|
+
* `dir_suffix` flipped, and write the initial state file marking the
|
|
105
|
+
* current directory as live.
|
|
106
|
+
*/
|
|
107
|
+
export function runInit(config, runner, opts = {}) {
|
|
108
|
+
const currentDir = path.resolve(opts.cwd ?? process.cwd());
|
|
109
|
+
const peerDir = resolvePeerDir(currentDir, opts.peerDir);
|
|
110
|
+
if (fs.existsSync(peerDir)) {
|
|
111
|
+
throw new Error(`Peer directory already exists: ${peerDir}. "deploy init" only creates it fresh — remove it first (or run "deploy clean") if you want to re-init.`);
|
|
112
|
+
}
|
|
113
|
+
const originUrl = runner.exec('git remote get-url origin', { cwd: currentDir });
|
|
114
|
+
runner.exec(`git clone ${JSON.stringify(originUrl)} ${JSON.stringify(peerDir)}`, { cwd: currentDir });
|
|
115
|
+
const currentIniPath = path.join(currentDir, CONFIG_RELATIVE_PATH);
|
|
116
|
+
const peerIniPath = path.join(peerDir, CONFIG_RELATIVE_PATH);
|
|
117
|
+
const iniContent = fs.readFileSync(currentIniPath, 'utf-8');
|
|
118
|
+
const swappedIni = swapDirSuffixInIni(iniContent);
|
|
119
|
+
fs.mkdirSync(path.dirname(peerIniPath), { recursive: true });
|
|
120
|
+
fs.writeFileSync(peerIniPath, swappedIni, 'utf-8');
|
|
121
|
+
ensurePeerDataDir(config, peerIniPath, peerDir);
|
|
122
|
+
const state = {
|
|
123
|
+
app_name: config.app_name,
|
|
124
|
+
live_dir: currentDir,
|
|
125
|
+
live_port: config.prod_port,
|
|
126
|
+
standby_dir: peerDir,
|
|
127
|
+
staging_port: config.staging_port,
|
|
128
|
+
};
|
|
129
|
+
writeState(state);
|
|
130
|
+
return { currentDir, peerDir, originUrl };
|
|
131
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Given a directory basename ending in "-blue" or "-green", return the
|
|
3
|
+
* basename with that suffix swapped. Returns `undefined` if the basename
|
|
4
|
+
* doesn't end in a recognized color suffix.
|
|
5
|
+
*/
|
|
6
|
+
export declare function swapColorSuffix(dirName: string): string | undefined;
|
|
7
|
+
/**
|
|
8
|
+
* Resolve the absolute path to the peer (standby) directory for `currentDir`.
|
|
9
|
+
*
|
|
10
|
+
* - If `override` is provided, it wins unconditionally (resolved relative to
|
|
11
|
+
* `currentDir`'s parent if not already absolute).
|
|
12
|
+
* - Otherwise, swap the blue/green suffix on `currentDir`'s basename and
|
|
13
|
+
* resolve it as a sibling (same parent directory).
|
|
14
|
+
*
|
|
15
|
+
* Throws if no override is given and the basename has no blue/green suffix.
|
|
16
|
+
*/
|
|
17
|
+
export declare function resolvePeerDir(currentDir: string, override?: string): string;
|
|
18
|
+
//# sourceMappingURL=peer.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"peer.d.ts","sourceRoot":"","sources":["../../src/deploy/peer.ts"],"names":[],"mappings":"AAcA;;;;GAIG;AACH,wBAAgB,eAAe,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAQnE;AAED;;;;;;;;;GASG;AACH,wBAAgB,cAAc,CAAC,UAAU,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,MAAM,GAAG,MAAM,CAiB5E"}
|
|
@@ -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,100 @@
|
|
|
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
|
+
* Set when the staging-delete step failed for a reason OTHER than
|
|
62
|
+
* "process not found" (a real failure, not simply "nothing to delete").
|
|
63
|
+
* Previously such a failure was silently swallowed into `stagingDeleted:
|
|
64
|
+
* false`, indistinguishable from the common "already stopped/absent"
|
|
65
|
+
* case — leaving a stale `<name>-staging` registration in place for the
|
|
66
|
+
* NEXT `deploy build` to collide with (see build.ts's own tolerant
|
|
67
|
+
* staging-delete, added as defense in depth for this exact bug class).
|
|
68
|
+
* Callers (switch.ts/rollback.ts) should surface this, not just the
|
|
69
|
+
* plain boolean.
|
|
70
|
+
*/
|
|
71
|
+
stagingDeleteWarning?: string;
|
|
72
|
+
}
|
|
73
|
+
/** Thrown when any step of promoteDirFresh fails fatally. Message already includes the restore-attempt outcome when the primary start fails. */
|
|
74
|
+
export declare class PromoteDirFreshError extends Error {
|
|
75
|
+
constructor(message: string);
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Delete the current `name` registration in `fromDir`, optionally clean up
|
|
79
|
+
* a stale `stagingName` registration in `toDir`, then fresh-start `toDir`
|
|
80
|
+
* under `name` on `port` via `startNamedPm2Process`.
|
|
81
|
+
*
|
|
82
|
+
* On a failed primary start, this does NOT simply retry `startNamedPm2Process`
|
|
83
|
+
* for `fromDir` as the restore — task-8 review caught a real bug in both
|
|
84
|
+
* switch.ts's and rollback.ts's independently-written versions of this:
|
|
85
|
+
* `pm2 start` can register `name` against `toDir` and THEN fail (e.g. the
|
|
86
|
+
* process registers but immediately crashes, or the start command's exit
|
|
87
|
+
* code is non-zero for an unrelated reason after pm2 already created the
|
|
88
|
+
* registration). If that happens, the "restore" call's own
|
|
89
|
+
* `startNamedPm2Process(..., dir: fromDir, name)` sees `name` ALREADY
|
|
90
|
+
* registered — pm2 only recomputes `cwd`/`pm_cwd` for a name it has never
|
|
91
|
+
* registered before (see startNamedPm2Process's own header) — so it just
|
|
92
|
+
* restarts THAT existing registration in place, still pointing at `toDir`,
|
|
93
|
+
* while this function reports "Production RESTORED". Nothing was actually
|
|
94
|
+
* restored. Fixed by tolerant-deleting `name` (cwd: `toDir`) BEFORE
|
|
95
|
+
* attempting the restore start, exactly as the primary delete step does,
|
|
96
|
+
* so the restore's `startNamedPm2Process` call is guaranteed to see a truly
|
|
97
|
+
* unregistered name and recompute `cwd` correctly against `fromDir`.
|
|
98
|
+
*/
|
|
99
|
+
export declare function promoteDirFresh(runner: CommandRunner, opts: PromoteDirFreshOptions): PromoteDirFreshResult;
|
|
100
|
+
//# 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,CAkEnG;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;IACxB;;;;;;;;;;OAUG;IACH,oBAAoB,CAAC,EAAE,MAAM,CAAC;CAC/B;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,CA4D1G"}
|
|
@@ -0,0 +1,228 @@
|
|
|
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
|
+
// mode: 0o600 (owner read/write only) — this file is a clone of the real
|
|
98
|
+
// app's ecosystem config, including its `env`/`env_production` block,
|
|
99
|
+
// which is routinely populated from `.env.local` i.e. real production
|
|
100
|
+
// secrets (DB credentials, API keys, ...). Written to world-readable
|
|
101
|
+
// os.tmpdir() by default would leak those secrets to any other local
|
|
102
|
+
// user; 0o600 keeps it readable only by the user running this process.
|
|
103
|
+
fs.writeFileSync(tempFile, `module.exports = ${JSON.stringify({ apps: [namedApp] }, null, 2)};\n`, {
|
|
104
|
+
encoding: 'utf-8',
|
|
105
|
+
mode: 0o600,
|
|
106
|
+
});
|
|
107
|
+
// Deleted in `finally`, right after `pm2 start` returns — not left behind
|
|
108
|
+
// "forever" as this helper used to document. `pm2 start <file>` parses the
|
|
109
|
+
// config file SYNCHRONOUSLY inside its own short-lived CLI process (before
|
|
110
|
+
// handing the already-parsed app definition off to the pm2 daemon), so by
|
|
111
|
+
// the time `runner.exec` returns the file has already been fully read;
|
|
112
|
+
// deleting it here is safe and closes the secret-leak window instead of
|
|
113
|
+
// leaving a world-readable (well, now 0o600, but still unnecessary) copy
|
|
114
|
+
// of production secrets sitting in /tmp indefinitely. The deletion itself
|
|
115
|
+
// is best-effort: a failure to unlink must never mask the real pm2 result
|
|
116
|
+
// (success or failure) from the `try` block above it.
|
|
117
|
+
try {
|
|
118
|
+
runner.exec(`pm2 start ${JSON.stringify(tempFile)} --env production`);
|
|
119
|
+
}
|
|
120
|
+
finally {
|
|
121
|
+
try {
|
|
122
|
+
fs.unlinkSync(tempFile);
|
|
123
|
+
}
|
|
124
|
+
catch {
|
|
125
|
+
// best-effort cleanup — ignore (e.g. already removed, permissions).
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
// ─── promoteDirFresh ─────────────────────────────────────────────────────
|
|
130
|
+
//
|
|
131
|
+
// Shared by `deploy switch` and `deploy rollback` — both need the exact
|
|
132
|
+
// same "delete whatever's currently registered under <name>, optionally
|
|
133
|
+
// clean up a stale staging registration too, then fresh-start a different
|
|
134
|
+
// dir under that same name" sequence, in opposite directions (switch:
|
|
135
|
+
// standby -> live; rollback: previous-live -> live). Extracted here after
|
|
136
|
+
// task-8 review found the SAME bug in both files' independently-written
|
|
137
|
+
// restore-on-failure paths (see below) — one fix, shared by both callers,
|
|
138
|
+
// so it can't drift out of sync again.
|
|
139
|
+
const PM2_NOT_FOUND_PATTERN = /not found/i;
|
|
140
|
+
/** True if a non-zero pm2 result looks like "process or namespace <name> not found" rather than a real failure. */
|
|
141
|
+
export function isPm2ProcessNotFound(result) {
|
|
142
|
+
return PM2_NOT_FOUND_PATTERN.test(result.stdout) || PM2_NOT_FOUND_PATTERN.test(result.stderr);
|
|
143
|
+
}
|
|
144
|
+
/** Thrown when any step of promoteDirFresh fails fatally. Message already includes the restore-attempt outcome when the primary start fails. */
|
|
145
|
+
export class PromoteDirFreshError extends Error {
|
|
146
|
+
constructor(message) {
|
|
147
|
+
super(message);
|
|
148
|
+
this.name = 'PromoteDirFreshError';
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* Delete the current `name` registration in `fromDir`, optionally clean up
|
|
153
|
+
* a stale `stagingName` registration in `toDir`, then fresh-start `toDir`
|
|
154
|
+
* under `name` on `port` via `startNamedPm2Process`.
|
|
155
|
+
*
|
|
156
|
+
* On a failed primary start, this does NOT simply retry `startNamedPm2Process`
|
|
157
|
+
* for `fromDir` as the restore — task-8 review caught a real bug in both
|
|
158
|
+
* switch.ts's and rollback.ts's independently-written versions of this:
|
|
159
|
+
* `pm2 start` can register `name` against `toDir` and THEN fail (e.g. the
|
|
160
|
+
* process registers but immediately crashes, or the start command's exit
|
|
161
|
+
* code is non-zero for an unrelated reason after pm2 already created the
|
|
162
|
+
* registration). If that happens, the "restore" call's own
|
|
163
|
+
* `startNamedPm2Process(..., dir: fromDir, name)` sees `name` ALREADY
|
|
164
|
+
* registered — pm2 only recomputes `cwd`/`pm_cwd` for a name it has never
|
|
165
|
+
* registered before (see startNamedPm2Process's own header) — so it just
|
|
166
|
+
* restarts THAT existing registration in place, still pointing at `toDir`,
|
|
167
|
+
* while this function reports "Production RESTORED". Nothing was actually
|
|
168
|
+
* restored. Fixed by tolerant-deleting `name` (cwd: `toDir`) BEFORE
|
|
169
|
+
* attempting the restore start, exactly as the primary delete step does,
|
|
170
|
+
* so the restore's `startNamedPm2Process` call is guaranteed to see a truly
|
|
171
|
+
* unregistered name and recompute `cwd` correctly against `fromDir`.
|
|
172
|
+
*/
|
|
173
|
+
export function promoteDirFresh(runner, opts) {
|
|
174
|
+
const deleteResult = runner.spawn(`pm2 delete ${opts.name}`, { cwd: opts.fromDir });
|
|
175
|
+
if (deleteResult.code !== 0 && !isPm2ProcessNotFound(deleteResult)) {
|
|
176
|
+
throw new PromoteDirFreshError(`Failed to delete the current PM2 process "${opts.name}" in ${opts.fromDir}: ` +
|
|
177
|
+
(deleteResult.stderr || deleteResult.stdout || `exit code ${deleteResult.code}`));
|
|
178
|
+
}
|
|
179
|
+
let stagingDeleted = false;
|
|
180
|
+
let stagingDeleteWarning;
|
|
181
|
+
if (opts.stagingName) {
|
|
182
|
+
try {
|
|
183
|
+
const result = runner.spawn(`pm2 delete ${opts.stagingName}`, { cwd: opts.toDir });
|
|
184
|
+
stagingDeleted = result.code === 0;
|
|
185
|
+
if (!stagingDeleted && !isPm2ProcessNotFound(result)) {
|
|
186
|
+
stagingDeleteWarning =
|
|
187
|
+
`Failed to delete stale PM2 registration "${opts.stagingName}" in ${opts.toDir}: ` +
|
|
188
|
+
(result.stderr || result.stdout || `exit code ${result.code}`);
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
catch (e) {
|
|
192
|
+
stagingDeleted = false;
|
|
193
|
+
stagingDeleteWarning =
|
|
194
|
+
`Failed to delete stale PM2 registration "${opts.stagingName}" in ${opts.toDir}: ` +
|
|
195
|
+
(e instanceof Error ? e.message : String(e));
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
try {
|
|
199
|
+
startNamedPm2Process(runner, { dir: opts.toDir, name: opts.name, port: opts.port });
|
|
200
|
+
}
|
|
201
|
+
catch (startErr) {
|
|
202
|
+
const startMsg = startErr instanceof Error ? startErr.message : String(startErr);
|
|
203
|
+
// Clear any registration the failed start may have partially created
|
|
204
|
+
// against `toDir` BEFORE attempting the restore — see this function's
|
|
205
|
+
// doc comment for the bug this prevents. Best-effort: we're already in
|
|
206
|
+
// the failure path, and the restore attempt below still proceeds
|
|
207
|
+
// regardless of whether this cleanup itself succeeds.
|
|
208
|
+
try {
|
|
209
|
+
runner.spawn(`pm2 delete ${opts.name}`, { cwd: opts.toDir });
|
|
210
|
+
}
|
|
211
|
+
catch {
|
|
212
|
+
// ignore — best-effort cleanup
|
|
213
|
+
}
|
|
214
|
+
let restoreMsg;
|
|
215
|
+
try {
|
|
216
|
+
startNamedPm2Process(runner, { dir: opts.fromDir, name: opts.name, port: opts.port });
|
|
217
|
+
restoreMsg = `Production RESTORED: ${opts.fromLabel} in ${opts.fromDir} was restarted on port ${opts.port}.`;
|
|
218
|
+
}
|
|
219
|
+
catch (restoreErr) {
|
|
220
|
+
const restoreMsgDetail = restoreErr instanceof Error ? restoreErr.message : String(restoreErr);
|
|
221
|
+
restoreMsg =
|
|
222
|
+
`PRODUCTION IS DOWN: failed to restore ${opts.fromLabel} in ${opts.fromDir} as well: ${restoreMsgDetail}. ` +
|
|
223
|
+
`Manual intervention required.`;
|
|
224
|
+
}
|
|
225
|
+
throw new PromoteDirFreshError(`Failed to start the ${opts.toLabel} (${opts.toDir}) on the production port: ${startMsg}\n${restoreMsg}`);
|
|
226
|
+
}
|
|
227
|
+
return { stagingDeleted, stagingDeleteWarning };
|
|
228
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
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
|
+
/** Set when the defense-in-depth staging cleanup (see header) failed for a reason other than "not found". */
|
|
8
|
+
stagingDeleteWarning?: string;
|
|
9
|
+
/** Set when `pm2 save` failed after a successful rollback (non-fatal — the rollback itself already succeeded). */
|
|
10
|
+
pm2SaveWarning?: string;
|
|
11
|
+
}
|
|
12
|
+
/** Thrown when there's nothing to roll back, or a fatal step fails. */
|
|
13
|
+
export declare class RollbackAbortError extends Error {
|
|
14
|
+
constructor(message: string);
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Reverse the last `deploy switch`: put the previously-live build back on
|
|
18
|
+
* the production port. See this file's header for the full step-by-step
|
|
19
|
+
* rationale.
|
|
20
|
+
*/
|
|
21
|
+
export declare function runRollback(config: DeployConfig, runner: CommandRunner): RunRollbackResult;
|
|
22
|
+
//# 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;IACnB,6GAA6G;IAC7G,oBAAoB,CAAC,EAAE,MAAM,CAAC;IAC9B,kHAAkH;IAClH,cAAc,CAAC,EAAE,MAAM,CAAC;CACzB;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,CAoH1F"}
|