hazo_env 0.11.0 → 0.14.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.
@@ -4,31 +4,31 @@ export interface StartNamedPm2ProcessOptions {
4
4
  dir: string;
5
5
  /** PM2 process name to start the app under — must not collide with an existing registration. */
6
6
  name: string;
7
- /** Port to run the app on, merged into the cloned app config's env. */
8
- port: number;
7
+ /**
8
+ * Port to run the app on, merged into the cloned app config's env and
9
+ * env_production. Optional, added for sidecar.ts's benefit: a sidecar
10
+ * process (e.g. a cron/jobs worker) typically doesn't listen on a port at
11
+ * all, unlike the web app this helper was originally built for. When
12
+ * omitted, NO `PORT` override is injected into either block — whatever
13
+ * the template app's own ecosystem.config.js entry already sets (or
14
+ * doesn't) for `PORT` is carried over completely unchanged. Existing
15
+ * callers (build.ts, switch.ts, rollback.ts) all pass a port and are
16
+ * unaffected.
17
+ */
18
+ port?: number;
19
+ /**
20
+ * Added for multi-app ecosystem files (kinstripe's and blogsketch's own
21
+ * ecosystem.config.js/.cjs each declare one critical web app plus one or
22
+ * more sidecar processes — a cron/jobs worker, and in kinstripe's case
23
+ * also a websocket server and a PDF-render pool — in the SAME file). When
24
+ * set, the template app is selected from `ecosystem.apps` by exact `name`
25
+ * match instead of assuming/requiring a single-app file; throws a clear
26
+ * error if no entry has this name. Omitting this option keeps today's
27
+ * exact single-app behavior unchanged (see the guard below) — none of
28
+ * this module's existing callers pass it.
29
+ */
30
+ selectAppName?: string;
9
31
  }
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
32
  export declare function startNamedPm2Process(runner: CommandRunner, opts: StartNamedPm2ProcessOptions): void;
33
33
  /** True if a non-zero pm2 result looks like "process or namespace <name> not found" rather than a real failure. */
34
34
  export declare function isPm2ProcessNotFound(result: CommandResult): boolean;
@@ -57,6 +57,18 @@ export interface PromoteDirFreshOptions {
57
57
  export interface PromoteDirFreshResult {
58
58
  /** True iff a staging PM2 process was found and deleted (false if stagingName was omitted, or was already stopped/absent). */
59
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;
60
72
  }
61
73
  /** Thrown when any step of promoteDirFresh fails fatally. Message already includes the restore-attempt outcome when the primary start fails. */
62
74
  export declare class PromoteDirFreshError extends Error {
@@ -1 +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"}
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;;;;;;;;;;OAUG;IACH,IAAI,CAAC,EAAE,MAAM,CAAC;IACd;;;;;;;;;;OAUG;IACH,aAAa,CAAC,EAAE,MAAM,CAAC;CACxB;AA6ED,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,aAAa,EAAE,IAAI,EAAE,2BAA2B,GAAG,IAAI,CA+EnG;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"}
@@ -46,46 +46,94 @@ const require = createRequire(import.meta.url);
46
46
  * Start `opts.dir`'s app under PM2 as `opts.name`, running on `opts.port`,
47
47
  * with `cwd` set to `opts.dir`.
48
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.
49
+ * Template selection: when `opts.selectAppName` is omitted, this assumes a
50
+ * single-app ecosystem file (one entry in `apps`) — this project's existing
51
+ * convention (see gotimer's own ecosystem.config.js) and explicitly in scope
52
+ * per the deploy-module spec, which excludes multi-instance/cluster mode;
53
+ * no evidence of a multi-app ecosystem file was found anywhere in this
54
+ * monorepo while building this helper. Throws if `apps` is empty or has
55
+ * more than one entry, rather than silently guessing which one to use. When
56
+ * `opts.selectAppName` IS given (added for kinstripe's and blogsketch's own
57
+ * multi-app ecosystem files — see `StartNamedPm2ProcessOptions`), the
58
+ * template is instead the `apps` entry whose `name` matches it exactly,
59
+ * regardless of how many other entries the file declares; throws a clear
60
+ * error if none matches.
56
61
  *
57
62
  * `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.
63
+ * config when `opts.port` is given, since gotimer's own ecosystem.config.js
64
+ * (the one concrete example in this monorepo) puts the app's runtime env —
65
+ * PORT included — under `env_production` rather than the bare `env` block;
66
+ * setting both makes this helper work regardless of which block the target
67
+ * app's `--env` flag actually resolves against, without having to inspect
68
+ * the file at the call site. When `opts.port` is omitted (sidecars — see
69
+ * `StartNamedPm2ProcessOptions.port`), neither block is touched for `PORT`
70
+ * at all. Every other key the template app sets (script, args, instances,
71
+ * exec_mode, etc.) is carried over unchanged — only name/cwd/(optionally)
72
+ * env are overridden.
66
73
  */
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}.`);
74
+ /**
75
+ * Candidate ecosystem-config filenames, in lookup-preference order. `.cjs`
76
+ * comes first: both real multi-app consumers this helper's `selectAppName`
77
+ * option was built for (kinstripe) use `ecosystem.config.cjs` — a plain
78
+ * `.js` file would be interpreted as ESM and fail the `module.exports =`
79
+ * CommonJS pattern every ecosystem file in this monorepo (and kinstripe's)
80
+ * actually uses, under a package with `"type": "module"` (exactly
81
+ * kinstripe's own package.json) — so apps that need the explicit `.cjs`
82
+ * extension to stay CommonJS are the common case this list exists to serve,
83
+ * not an edge case. `.js` is still checked second for existing single-app
84
+ * consumers (e.g. gotimer/blogsketch) that don't set `"type": "module"` and
85
+ * have always used the plain `.js` name.
86
+ */
87
+ const ECOSYSTEM_CONFIG_FILENAMES = ['ecosystem.config.cjs', 'ecosystem.config.js'];
88
+ /**
89
+ * Resolve `dir`'s ecosystem config file, trying each of
90
+ * `ECOSYSTEM_CONFIG_FILENAMES` in order and returning the first that exists.
91
+ * Throws a clear error listing every candidate name when none is found,
92
+ * rather than hard-coding a single extension (the previous behavior, which
93
+ * silently broke any `.cjs`-named consumer with "No ecosystem.config.js
94
+ * found" even though one existed under a different, equally valid name).
95
+ */
96
+ function resolveEcosystemConfigPath(dir) {
97
+ for (const filename of ECOSYSTEM_CONFIG_FILENAMES) {
98
+ const candidate = path.join(dir, filename);
99
+ if (fs.existsSync(candidate))
100
+ return candidate;
71
101
  }
102
+ throw new Error(`No ecosystem config found at ${dir} (tried: ${ECOSYSTEM_CONFIG_FILENAMES.join(', ')}).`);
103
+ }
104
+ export function startNamedPm2Process(runner, opts) {
105
+ const ecosystemPath = resolveEcosystemConfigPath(opts.dir);
72
106
  const ecosystem = require(ecosystemPath);
73
107
  if (!Array.isArray(ecosystem.apps) || ecosystem.apps.length === 0) {
74
108
  throw new Error(`${ecosystemPath} has no "apps" entries — cannot start a named pm2 process from it.`);
75
109
  }
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).`);
110
+ let template;
111
+ if (opts.selectAppName !== undefined) {
112
+ const match = ecosystem.apps.find((a) => a.name === opts.selectAppName);
113
+ if (!match) {
114
+ const declaredNames = ecosystem.apps.map((a) => a.name ?? '(unnamed)').join(', ');
115
+ throw new Error(`${ecosystemPath} has no "apps" entry named "${opts.selectAppName}" (declared names: ${declaredNames}) — ` +
116
+ `cannot start a named pm2 process from it.`);
117
+ }
118
+ template = match;
119
+ }
120
+ else {
121
+ if (ecosystem.apps.length > 1) {
122
+ throw new Error(`${ecosystemPath} declares ${ecosystem.apps.length} apps — startNamedPm2Process only supports a ` +
123
+ `single-app ecosystem file (multi-instance/cluster mode is out of scope for this deploy module).`);
124
+ }
125
+ template = ecosystem.apps[0];
79
126
  }
80
- const template = ecosystem.apps[0];
81
- const portStr = String(opts.port);
82
127
  const namedApp = {
83
128
  ...template,
84
129
  name: opts.name,
85
130
  cwd: opts.dir,
86
- env: { ...(template.env ?? {}), PORT: portStr },
87
- env_production: { ...(template.env_production ?? {}), PORT: portStr },
88
131
  };
132
+ if (opts.port !== undefined) {
133
+ const portStr = String(opts.port);
134
+ namedApp.env = { ...(template.env ?? {}), PORT: portStr };
135
+ namedApp.env_production = { ...(template.env_production ?? {}), PORT: portStr };
136
+ }
89
137
  // Written to os.tmpdir(), not opts.dir: opts.dir's own ecosystem.config.js
90
138
  // may be tracked/gitignored in ways that make a sibling temp file there
91
139
  // awkward (and a fresh clone's dir is exactly the case build.ts's db-setup
@@ -94,14 +142,37 @@ export function startNamedPm2Process(runner, opts) {
94
142
  // separate verify run) from clobbering each other.
95
143
  const uniqueSuffix = `${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`;
96
144
  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`);
145
+ // mode: 0o600 (owner read/write only) — this file is a clone of the real
146
+ // app's ecosystem config, including its `env`/`env_production` block,
147
+ // which is routinely populated from `.env.local` i.e. real production
148
+ // secrets (DB credentials, API keys, ...). Written to world-readable
149
+ // os.tmpdir() by default would leak those secrets to any other local
150
+ // user; 0o600 keeps it readable only by the user running this process.
151
+ fs.writeFileSync(tempFile, `module.exports = ${JSON.stringify({ apps: [namedApp] }, null, 2)};\n`, {
152
+ encoding: 'utf-8',
153
+ mode: 0o600,
154
+ });
155
+ // Deleted in `finally`, right after `pm2 start` returns — not left behind
156
+ // "forever" as this helper used to document. `pm2 start <file>` parses the
157
+ // config file SYNCHRONOUSLY inside its own short-lived CLI process (before
158
+ // handing the already-parsed app definition off to the pm2 daemon), so by
159
+ // the time `runner.exec` returns the file has already been fully read;
160
+ // deleting it here is safe and closes the secret-leak window instead of
161
+ // leaving a world-readable (well, now 0o600, but still unnecessary) copy
162
+ // of production secrets sitting in /tmp indefinitely. The deletion itself
163
+ // is best-effort: a failure to unlink must never mask the real pm2 result
164
+ // (success or failure) from the `try` block above it.
165
+ try {
166
+ runner.exec(`pm2 start ${JSON.stringify(tempFile)} --env production`);
167
+ }
168
+ finally {
169
+ try {
170
+ fs.unlinkSync(tempFile);
171
+ }
172
+ catch {
173
+ // best-effort cleanup — ignore (e.g. already removed, permissions).
174
+ }
175
+ }
105
176
  }
106
177
  // ─── promoteDirFresh ─────────────────────────────────────────────────────
107
178
  //
@@ -154,13 +225,22 @@ export function promoteDirFresh(runner, opts) {
154
225
  (deleteResult.stderr || deleteResult.stdout || `exit code ${deleteResult.code}`));
155
226
  }
156
227
  let stagingDeleted = false;
228
+ let stagingDeleteWarning;
157
229
  if (opts.stagingName) {
158
230
  try {
159
231
  const result = runner.spawn(`pm2 delete ${opts.stagingName}`, { cwd: opts.toDir });
160
232
  stagingDeleted = result.code === 0;
233
+ if (!stagingDeleted && !isPm2ProcessNotFound(result)) {
234
+ stagingDeleteWarning =
235
+ `Failed to delete stale PM2 registration "${opts.stagingName}" in ${opts.toDir}: ` +
236
+ (result.stderr || result.stdout || `exit code ${result.code}`);
237
+ }
161
238
  }
162
- catch {
239
+ catch (e) {
163
240
  stagingDeleted = false;
241
+ stagingDeleteWarning =
242
+ `Failed to delete stale PM2 registration "${opts.stagingName}" in ${opts.toDir}: ` +
243
+ (e instanceof Error ? e.message : String(e));
164
244
  }
165
245
  }
166
246
  try {
@@ -192,5 +272,5 @@ export function promoteDirFresh(runner, opts) {
192
272
  }
193
273
  throw new PromoteDirFreshError(`Failed to start the ${opts.toLabel} (${opts.toDir}) on the production port: ${startMsg}\n${restoreMsg}`);
194
274
  }
195
- return { stagingDeleted };
275
+ return { stagingDeleted, stagingDeleteWarning };
196
276
  }
@@ -1,9 +1,20 @@
1
+ import { type SidecarSyncResult } from './sidecar.js';
1
2
  import type { CommandRunner, DeployConfig, DeployState } from './types.js';
2
3
  export interface RunRollbackResult {
3
4
  restoredLiveDir: string;
4
5
  newStandbyDir: string;
5
6
  prodPort: number;
6
7
  state: DeployState;
8
+ /** Set when the defense-in-depth staging cleanup (see header) failed for a reason other than "not found". */
9
+ stagingDeleteWarning?: string;
10
+ /** Set when `pm2 save` failed after a successful rollback (non-fatal — the rollback itself already succeeded). */
11
+ pm2SaveWarning?: string;
12
+ /**
13
+ * Reload-or-recreate results for `config.sidecar_apps` (see sidecar.ts),
14
+ * run unconditionally after the web-app restore above has already
15
+ * succeeded. A sidecar failure is reported here, never thrown.
16
+ */
17
+ sidecars: SidecarSyncResult[];
7
18
  }
8
19
  /** Thrown when there's nothing to roll back, or a fatal step fails. */
9
20
  export declare class RollbackAbortError extends Error {
@@ -1 +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"}
1
+ {"version":3,"file":"rollback.d.ts","sourceRoot":"","sources":["../../src/deploy/rollback.ts"],"names":[],"mappings":"AAkFA,OAAO,EAAgB,KAAK,iBAAiB,EAAE,MAAM,cAAc,CAAC;AACpE,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;IACxB;;;;OAIG;IACH,QAAQ,EAAE,iBAAiB,EAAE,CAAC;CAC/B;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,CA0H1F"}
@@ -79,6 +79,7 @@
79
79
  import path from 'node:path';
80
80
  import { readState, updateState } from './state.js';
81
81
  import { promoteDirFresh, PromoteDirFreshError } from './pm2-start.js';
82
+ import { syncSidecars } from './sidecar.js';
82
83
  /** Thrown when there's nothing to roll back, or a fatal step fails. */
83
84
  export class RollbackAbortError extends Error {
84
85
  constructor(message) {
@@ -108,9 +109,19 @@ export function runRollback(config, runner) {
108
109
  // stale-build guard" in the header). A missing last_build means no build
109
110
  // has ever run; that's trivially "no build since the switch".
110
111
  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.`);
112
+ // Wording note (fix round): `last_build` here does not necessarily mean
113
+ // a build actually SUCCEEDED since the last switch — since build.ts
114
+ // (Fix 3) now writes a provisional `last_build` the moment the pipeline
115
+ // reaches its first destructive step (git pull), this guard also trips
116
+ // for a build attempt that was interrupted (e.g. Ctrl+C after `rm -rf
117
+ // .next` already ran) or that failed partway through. Either way the
118
+ // standby dir may no longer hold the artifact that was actually live
119
+ // before the switch, so the wording below covers both "it succeeded and
120
+ // got promoted" and "an attempt merely ran" without claiming more than
121
+ // is known.
122
+ throw new RollbackAbortError(`A build has run on standby since the last switch (last_build ${state.last_build} is newer than ` +
123
+ `last_switch ${state.last_switch}) — the previous live build may no longer be intact (it may have been ` +
124
+ `rebuilt, or partially rebuilt, in place by "deploy build"). Cannot safely roll back.`);
114
125
  }
115
126
  const currentLiveDir = path.resolve(state.live_dir);
116
127
  const restoreDir = path.resolve(state.previous_live_dir);
@@ -124,11 +135,15 @@ export function runRollback(config, runner) {
124
135
  // promoteDirFresh itself attempts to bring the build rollback was trying
125
136
  // to replace back up so production isn't silently left down, and
126
137
  // reports plainly whether that worked.
138
+ let stagingDeleteWarning;
127
139
  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, {
140
+ // stagingDeleted (a plain boolean) isn't currently surfaced in
141
+ // RunRollbackResult — this is defense in depth (see header), not the
142
+ // normal path. stagingDeleteWarning IS surfaced (Fix 4b): a REAL
143
+ // deletion failure (not just "nothing to delete") would otherwise be
144
+ // silently swallowed, leaving a stale registration for the next
145
+ // `deploy build` to collide with.
146
+ const promoteResult = promoteDirFresh(runner, {
132
147
  fromDir: currentLiveDir,
133
148
  toDir: restoreDir,
134
149
  name: config.app_name,
@@ -137,6 +152,7 @@ export function runRollback(config, runner) {
137
152
  toLabel: 'previous live app',
138
153
  fromLabel: 'the build that was live before this rollback attempt',
139
154
  });
155
+ stagingDeleteWarning = promoteResult.stagingDeleteWarning;
140
156
  }
141
157
  catch (e) {
142
158
  if (e instanceof PromoteDirFreshError) {
@@ -158,10 +174,29 @@ export function runRollback(config, runner) {
158
174
  git_ref: gitRef,
159
175
  pm2_process: config.app_name,
160
176
  });
177
+ // Fix 7: persist the pm2 process list after a successful promotion. Without
178
+ // this, a server reboot's `pm2 resurrect` (if configured to run on boot)
179
+ // could bring back the OLD pm2 registration while the state file already
180
+ // claims the restored dir is live — a silent divergence. Non-fatal: the
181
+ // rollback itself already succeeded, so a failed `pm2 save` is only a
182
+ // warning, never a reason to report the rollback as failed.
183
+ const saveResult = runner.spawn('pm2 save');
184
+ const pm2SaveWarning = saveResult.code !== 0
185
+ ? `"pm2 save" failed after rollback (exit ${saveResult.code}): ${saveResult.stderr || saveResult.stdout || 'no output'} — ` +
186
+ `a server reboot's "pm2 resurrect" may restore the OLD pm2 process list even though this rollback ` +
187
+ `succeeded. Run "pm2 save" manually.`
188
+ : undefined;
189
+ // Sidecar sync: runs unconditionally after the web app's own restore has
190
+ // already succeeded — see switch.ts's identical wiring/rationale.
191
+ // `restoreDir` is the NEW live dir at this point in the function.
192
+ const sidecars = syncSidecars(runner, restoreDir, config.sidecar_apps);
161
193
  return {
162
194
  restoredLiveDir: restoreDir,
163
195
  newStandbyDir: currentLiveDir,
164
196
  prodPort: config.prod_port,
165
197
  state: newState,
198
+ stagingDeleteWarning,
199
+ pm2SaveWarning,
200
+ sidecars,
166
201
  };
167
202
  }
@@ -0,0 +1,74 @@
1
+ import type { CommandRunner } from './types.js';
2
+ interface Pm2ProcessEnv {
3
+ status?: string;
4
+ pm_cwd?: string;
5
+ }
6
+ interface Pm2Process {
7
+ pid?: number;
8
+ name?: string;
9
+ pm2_env?: Pm2ProcessEnv;
10
+ }
11
+ /**
12
+ * Find the PM2 process registered under the EXACT name `name` — unlike
13
+ * status.ts's `findPm2ProcessForDir`, which matches by `pm2_env.pm_cwd`.
14
+ * A sidecar's registered name is stable across every switch/rollback cycle
15
+ * (there is no `-staging` clone for a sidecar), so matching by name is the
16
+ * correct, cwd-independent way to find "the one registration for this
17
+ * sidecar, wherever it currently points".
18
+ */
19
+ export declare function findPm2ProcessByName(processes: Pm2Process[], name: string): Pm2Process | undefined;
20
+ /** Outcome of a single `syncSidecar` call. */
21
+ export interface SidecarSyncResult {
22
+ /** The sidecar's pm2 process name (same as the `name` passed in). */
23
+ name: string;
24
+ /**
25
+ * 'reloaded' — it was already online against the right dir; reloaded in place.
26
+ * 'recreated' — it was missing, offline, or pointing at the wrong (demoted) dir; deleted and freshly started.
27
+ * 'failed' — the recreate path itself failed; see `warning` for the caught error's message.
28
+ */
29
+ action: 'reloaded' | 'recreated' | 'failed';
30
+ /** Human-readable description of what happened, for CLI/log output. */
31
+ detail: string;
32
+ /** Set only when `action === 'failed'`: the caught error's message. */
33
+ warning?: string;
34
+ }
35
+ /**
36
+ * Reload-or-recreate ONE sidecar so it ends up running against `opts.dir`
37
+ * (the directory that just became live). NEVER throws — every failure path
38
+ * returns `action: 'failed'` instead, since a sidecar problem must never
39
+ * abort the caller's web-app promotion (see switch.ts's/rollback.ts's own
40
+ * wiring, which calls this unconditionally AFTER the web app's own
41
+ * promotion has already succeeded).
42
+ *
43
+ * Logic:
44
+ * - Query `pm2 jlist` and find the process registered under `opts.name`.
45
+ * - If it's found, `pm2_env.status === 'online'`, AND its `pm_cwd`
46
+ * resolves to `opts.dir`: reload it in place (`pm2 reload <name>
47
+ * --update-env`, tolerant of failure — a failed reload falls through to
48
+ * the recreate path below rather than being silently swallowed; only a
49
+ * reload command that itself exits 0 is reported as `'reloaded'`).
50
+ * - Otherwise (not found, not online, or `pm_cwd` points at the OTHER
51
+ * dir — i.e. it's still running against the directory that was just
52
+ * demoted, or the reload above failed): tolerant-delete any existing
53
+ * `opts.name` registration (ignoring "not found", exactly like
54
+ * pm2-start.ts's own `promoteDirFresh`), then fresh-start it against
55
+ * `opts.dir` via the shared `startNamedPm2Process` primitive — selecting
56
+ * the matching entry out of the (typically multi-app) ecosystem file by
57
+ * name (`selectAppName: opts.name`), and omitting `port` entirely, since
58
+ * a sidecar (cron/jobs worker, websocket server, PDF-render pool, ...)
59
+ * doesn't listen on a port the way the web app does.
60
+ */
61
+ export declare function syncSidecar(runner: CommandRunner, opts: {
62
+ dir: string;
63
+ name: string;
64
+ }): SidecarSyncResult;
65
+ /**
66
+ * Sync every sidecar in `sidecarNames` onto `dir` (the directory that just
67
+ * became live). Simple sequential loop — these are cheap, cwd-only pm2
68
+ * operations, no need for anything fancier (parallelism, batching, ...).
69
+ * Each entry is independent: one sidecar's `'failed'` result never stops
70
+ * the rest from being attempted.
71
+ */
72
+ export declare function syncSidecars(runner: CommandRunner, dir: string, sidecarNames: string[]): SidecarSyncResult[];
73
+ export {};
74
+ //# sourceMappingURL=sidecar.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sidecar.d.ts","sourceRoot":"","sources":["../../src/deploy/sidecar.ts"],"names":[],"mappings":"AA2CA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAEhD,UAAU,aAAa;IACrB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,UAAU,UAAU;IAClB,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,aAAa,CAAC;CACzB;AAqBD;;;;;;;GAOG;AACH,wBAAgB,oBAAoB,CAAC,SAAS,EAAE,UAAU,EAAE,EAAE,IAAI,EAAE,MAAM,GAAG,UAAU,GAAG,SAAS,CAElG;AAED,8CAA8C;AAC9C,MAAM,WAAW,iBAAiB;IAChC,qEAAqE;IACrE,IAAI,EAAE,MAAM,CAAC;IACb;;;;OAIG;IACH,MAAM,EAAE,UAAU,GAAG,WAAW,GAAG,QAAQ,CAAC;IAC5C,uEAAuE;IACvE,MAAM,EAAE,MAAM,CAAC;IACf,uEAAuE;IACvE,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,wBAAgB,WAAW,CAAC,MAAM,EAAE,aAAa,EAAE,IAAI,EAAE;IAAE,GAAG,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,GAAG,iBAAiB,CAiDzG;AAED;;;;;;GAMG;AACH,wBAAgB,YAAY,CAAC,MAAM,EAAE,aAAa,EAAE,GAAG,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,EAAE,GAAG,iBAAiB,EAAE,CAE5G"}
@@ -0,0 +1,156 @@
1
+ // hazo_env/src/deploy/sidecar.ts — reload-or-recreate a non-web-facing PM2
2
+ // process that moves with whichever directory is currently live, but is
3
+ // NEVER itself blue-green-swapped.
4
+ //
5
+ // Why this exists: two real consuming apps (kinstripe's own
6
+ // ecosystem.config.cjs, and this monorepo's own ecosystem.config.js for
7
+ // blogsketch) each declare one critical web app (cluster mode, blue-green
8
+ // swapped via switch.ts/rollback.ts's promoteDirFresh) PLUS one or more
9
+ // sidecar processes in the SAME ecosystem file — a cron/scheduler/jobs
10
+ // worker in both apps' cases, and in kinstripe's case also a websocket
11
+ // server and a PDF-render pool. A sidecar must NEVER be duplicated into a
12
+ // standby dir the way the web app is: duplicating a scheduler/jobs-worker
13
+ // would double-claim and double-execute background jobs against the same
14
+ // shared production DB — a real correctness bug, not just wasted work.
15
+ // Instead, a sidecar has exactly ONE registration at a time, and after
16
+ // every switch/rollback it simply needs to end up pointing at whichever
17
+ // directory just became live.
18
+ //
19
+ // This is a parallel, independent primitive to the live/standby pair
20
+ // state.ts tracks: no live/standby distinction, no state-file tracking, no
21
+ // `-staging` clone, no health check (sidecars aren't web-facing, so there's
22
+ // nothing HTTP-reachable to health-check). The contract is purely
23
+ // "reload-in-place if it's already healthy against the right dir, otherwise
24
+ // tolerant-delete and fresh-start it there" — see `syncSidecar` below.
25
+ //
26
+ // Deliberately does not reuse status.ts's `findPm2ProcessForDir`: that
27
+ // function matches by `pm2_env.pm_cwd`, which is exactly wrong here — right
28
+ // after a switch, the OLD (now-demoted) dir's cwd is still what's actually
29
+ // registered, and matching by cwd would just find "the sidecar, still
30
+ // pointing at the wrong dir" instead of "the sidecar, by its stable
31
+ // name". Sidecars are looked up by their exact registered pm2 `name`
32
+ // instead (see `findPm2ProcessByName`), which is stable across every
33
+ // switch/rollback cycle (unlike the web app's own single `<app_name>`
34
+ // registration, a sidecar's name never changes — there's no
35
+ // `<name>-staging` clone, ever).
36
+ //
37
+ // status.ts's `Pm2Process`/`Pm2ProcessEnv` types and its `queryPm2Processes`
38
+ // jlist-parsing helper are not exported from that module, so this file
39
+ // redefines a minimal, structurally-compatible subset here rather than
40
+ // reaching into status.ts's internals.
41
+ import path from 'node:path';
42
+ import { startNamedPm2Process, isPm2ProcessNotFound } from './pm2-start.js';
43
+ /**
44
+ * Query `pm2 jlist` and parse the JSON process list. Mirrors status.ts's
45
+ * own `queryPm2Processes`, minus its `warnings` accumulator — a jlist
46
+ * failure here is not surfaced as a separate warning; it's indistinguishable
47
+ * from "the sidecar isn't registered yet", which `syncSidecar` already
48
+ * handles correctly by falling through to the recreate path. Returns an
49
+ * empty list (never throws) on any failure to read/parse pm2's output.
50
+ */
51
+ function queryPm2Processes(runner) {
52
+ const result = runner.spawn('pm2 jlist');
53
+ if (result.code !== 0)
54
+ return [];
55
+ try {
56
+ const parsed = JSON.parse(result.stdout);
57
+ return Array.isArray(parsed) ? parsed : [];
58
+ }
59
+ catch {
60
+ return [];
61
+ }
62
+ }
63
+ /**
64
+ * Find the PM2 process registered under the EXACT name `name` — unlike
65
+ * status.ts's `findPm2ProcessForDir`, which matches by `pm2_env.pm_cwd`.
66
+ * A sidecar's registered name is stable across every switch/rollback cycle
67
+ * (there is no `-staging` clone for a sidecar), so matching by name is the
68
+ * correct, cwd-independent way to find "the one registration for this
69
+ * sidecar, wherever it currently points".
70
+ */
71
+ export function findPm2ProcessByName(processes, name) {
72
+ return processes.find((p) => p.name === name);
73
+ }
74
+ /**
75
+ * Reload-or-recreate ONE sidecar so it ends up running against `opts.dir`
76
+ * (the directory that just became live). NEVER throws — every failure path
77
+ * returns `action: 'failed'` instead, since a sidecar problem must never
78
+ * abort the caller's web-app promotion (see switch.ts's/rollback.ts's own
79
+ * wiring, which calls this unconditionally AFTER the web app's own
80
+ * promotion has already succeeded).
81
+ *
82
+ * Logic:
83
+ * - Query `pm2 jlist` and find the process registered under `opts.name`.
84
+ * - If it's found, `pm2_env.status === 'online'`, AND its `pm_cwd`
85
+ * resolves to `opts.dir`: reload it in place (`pm2 reload <name>
86
+ * --update-env`, tolerant of failure — a failed reload falls through to
87
+ * the recreate path below rather than being silently swallowed; only a
88
+ * reload command that itself exits 0 is reported as `'reloaded'`).
89
+ * - Otherwise (not found, not online, or `pm_cwd` points at the OTHER
90
+ * dir — i.e. it's still running against the directory that was just
91
+ * demoted, or the reload above failed): tolerant-delete any existing
92
+ * `opts.name` registration (ignoring "not found", exactly like
93
+ * pm2-start.ts's own `promoteDirFresh`), then fresh-start it against
94
+ * `opts.dir` via the shared `startNamedPm2Process` primitive — selecting
95
+ * the matching entry out of the (typically multi-app) ecosystem file by
96
+ * name (`selectAppName: opts.name`), and omitting `port` entirely, since
97
+ * a sidecar (cron/jobs worker, websocket server, PDF-render pool, ...)
98
+ * doesn't listen on a port the way the web app does.
99
+ */
100
+ export function syncSidecar(runner, opts) {
101
+ try {
102
+ const processes = queryPm2Processes(runner);
103
+ const proc = findPm2ProcessByName(processes, opts.name);
104
+ const targetDir = path.resolve(opts.dir);
105
+ const cwdMatchesTarget = proc?.pm2_env?.pm_cwd !== undefined && path.resolve(proc.pm2_env.pm_cwd) === targetDir;
106
+ if (proc && proc.pm2_env?.status === 'online' && cwdMatchesTarget) {
107
+ const reloadResult = runner.spawn(`pm2 reload ${opts.name} --update-env`);
108
+ if (reloadResult.code === 0) {
109
+ return {
110
+ name: opts.name,
111
+ action: 'reloaded',
112
+ detail: `"${opts.name}" was already online against ${opts.dir}; reloaded with --update-env.`,
113
+ };
114
+ }
115
+ // Reload command itself failed (non-zero exit) — fall through to the
116
+ // recreate path below instead of reporting failure outright; a
117
+ // reload failure doesn't necessarily mean the recreate path will also
118
+ // fail (e.g. a transient pm2 daemon hiccup).
119
+ }
120
+ // Recreate path: not found, not online, pointing at the OTHER
121
+ // (just-demoted) dir, or a failed reload above. Tolerant-delete
122
+ // whatever's currently registered under `opts.name` first — mirrors
123
+ // promoteDirFresh's own "pm2 delete, not stop" reasoning (pm2-start.ts's
124
+ // header): a stale registration pointing at the wrong dir must be fully
125
+ // deregistered before starting fresh, or pm2 would just restart IT in
126
+ // place instead of recomputing `cwd`/`pm_cwd` against `opts.dir`.
127
+ const deleteResult = runner.spawn(`pm2 delete ${opts.name}`);
128
+ const wasRegistered = deleteResult.code === 0 || !isPm2ProcessNotFound(deleteResult);
129
+ startNamedPm2Process(runner, { dir: opts.dir, name: opts.name, selectAppName: opts.name });
130
+ return {
131
+ name: opts.name,
132
+ action: 'recreated',
133
+ detail: wasRegistered
134
+ ? `"${opts.name}" was stale (not online, or pointing at a different dir); deleted and recreated against ${opts.dir}.`
135
+ : `"${opts.name}" was not registered; created fresh against ${opts.dir}.`,
136
+ };
137
+ }
138
+ catch (e) {
139
+ return {
140
+ name: opts.name,
141
+ action: 'failed',
142
+ detail: `Failed to sync sidecar "${opts.name}" against ${opts.dir}.`,
143
+ warning: e instanceof Error ? e.message : String(e),
144
+ };
145
+ }
146
+ }
147
+ /**
148
+ * Sync every sidecar in `sidecarNames` onto `dir` (the directory that just
149
+ * became live). Simple sequential loop — these are cheap, cwd-only pm2
150
+ * operations, no need for anything fancier (parallelism, batching, ...).
151
+ * Each entry is independent: one sidecar's `'failed'` result never stops
152
+ * the rest from being attempted.
153
+ */
154
+ export function syncSidecars(runner, dir, sidecarNames) {
155
+ return sidecarNames.map((name) => syncSidecar(runner, { dir, name }));
156
+ }