hazo_env 0.10.4 → 0.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/CHANGE_LOG.md +79 -0
  2. package/config/hazo_env_config.ini.sample +61 -0
  3. package/dist/cli.js +329 -0
  4. package/dist/deploy/build.d.ts +91 -0
  5. package/dist/deploy/build.d.ts.map +1 -0
  6. package/dist/deploy/build.js +389 -0
  7. package/dist/deploy/clean.d.ts +63 -0
  8. package/dist/deploy/clean.d.ts.map +1 -0
  9. package/dist/deploy/clean.js +135 -0
  10. package/dist/deploy/index.d.ts +13 -0
  11. package/dist/deploy/index.d.ts.map +1 -0
  12. package/dist/deploy/index.js +22 -0
  13. package/dist/deploy/init.d.ts +20 -0
  14. package/dist/deploy/init.d.ts.map +1 -0
  15. package/dist/deploy/init.js +131 -0
  16. package/dist/deploy/peer.d.ts +18 -0
  17. package/dist/deploy/peer.d.ts.map +1 -0
  18. package/dist/deploy/peer.js +48 -0
  19. package/dist/deploy/pm2-start.d.ts +100 -0
  20. package/dist/deploy/pm2-start.d.ts.map +1 -0
  21. package/dist/deploy/pm2-start.js +228 -0
  22. package/dist/deploy/rollback.d.ts +22 -0
  23. package/dist/deploy/rollback.d.ts.map +1 -0
  24. package/dist/deploy/rollback.js +196 -0
  25. package/dist/deploy/runner.d.ts +8 -0
  26. package/dist/deploy/runner.d.ts.map +1 -0
  27. package/dist/deploy/runner.js +35 -0
  28. package/dist/deploy/state.d.ts +19 -0
  29. package/dist/deploy/state.d.ts.map +1 -0
  30. package/dist/deploy/state.js +52 -0
  31. package/dist/deploy/status.d.ts +54 -0
  32. package/dist/deploy/status.d.ts.map +1 -0
  33. package/dist/deploy/status.js +182 -0
  34. package/dist/deploy/switch.d.ts +40 -0
  35. package/dist/deploy/switch.d.ts.map +1 -0
  36. package/dist/deploy/switch.js +183 -0
  37. package/dist/deploy/types.d.ts +96 -0
  38. package/dist/deploy/types.d.ts.map +1 -0
  39. package/dist/deploy/types.js +16 -0
  40. package/dist/deploy/verify.d.ts +41 -0
  41. package/dist/deploy/verify.d.ts.map +1 -0
  42. package/dist/deploy/verify.js +214 -0
  43. package/dist/index.d.ts +2 -0
  44. package/dist/index.d.ts.map +1 -1
  45. package/dist/index.js +3 -0
  46. package/dist/resolve/connect.d.ts.map +1 -1
  47. package/dist/resolve/connect.js +15 -1
  48. package/dist/resolve/deploy.d.ts +8 -0
  49. package/dist/resolve/deploy.d.ts.map +1 -0
  50. package/dist/resolve/deploy.js +140 -0
  51. package/dist/types/index.d.ts +10 -0
  52. package/dist/types/index.d.ts.map +1 -1
  53. package/package.json +12 -12
@@ -0,0 +1,389 @@
1
+ // hazo_env/src/deploy/build.ts — `deploy build`: the full standby build pipeline
2
+ //
3
+ // Run from the standby directory. Orchestrates: guard against running from
4
+ // the live dir -> auto-clean + disk check -> memory check (optionally freed
5
+ // by stopping the live PM2 process) -> resolve/validate the db target ->
6
+ // git pull -> install -> pre-build -> build -> DB setup (sqlite backup or
7
+ // postgres resolve) + migrate -> start on a distinct staging PM2 process ->
8
+ // health check (retried) -> final summary. Every step after
9
+ // cleanup/resolution flows through the injected CommandRunner (see types.ts's
10
+ // doc comment) so this file never imports node:child_process directly.
11
+ //
12
+ // Any step failure aborts immediately (throws BuildAbortError) and leaves
13
+ // whatever partial work happened on disk as-is — re-running `deploy build`
14
+ // is the recovery path, not an automatic rollback. The state file's
15
+ // last_build/last_build_status is updated once the pipeline reaches its
16
+ // first DESTRUCTIVE step (git pull) — never before (an early abort, e.g.
17
+ // the standby-dir guard or a disk/memory/db-resolve failure, leaves
18
+ // last_build untouched, since nothing destructive happened) — and is
19
+ // overwritten again with the final outcome if the pipeline completes
20
+ // normally (success or a later failure). See the "Fix 3" comments inline
21
+ // around the git-pull step and the closing `finally` block for the full
22
+ // rationale (this two-write scheme fixes both a false "stale build" block
23
+ // on deploy rollback from an early abort, and a missed one from a Ctrl+C
24
+ // after `pre_build_cmd` has already run).
25
+ import path from 'node:path';
26
+ import { autoClean } from './clean.js';
27
+ import { resolvePeerDir } from './peer.js';
28
+ import { queryDiskFreeMb, queryMemoryFreeMb } from './status.js';
29
+ import { readState, updateState } from './state.js';
30
+ import { SWAP_INCREASE_SUGGESTIONS } from './clean.js';
31
+ import { startNamedPm2Process, isPm2ProcessNotFound } from './pm2-start.js';
32
+ import { resolveConnectConfig } from '../resolve/connect.js';
33
+ /** Thrown when any pipeline step fails. Carries the steps completed so far for reporting. */
34
+ export class BuildAbortError extends Error {
35
+ constructor(message, steps) {
36
+ super(message);
37
+ this.name = 'BuildAbortError';
38
+ this.steps = steps;
39
+ }
40
+ }
41
+ const DEFAULT_HEALTH_CHECK_ATTEMPTS = 8;
42
+ const DEFAULT_HEALTH_CHECK_DELAY_MS = 1500;
43
+ /**
44
+ * Re-root `targetPath` (known to live under `fromDir`) onto `toDir`: compute
45
+ * `targetPath`'s path relative to `fromDir` and rejoin it onto `toDir`.
46
+ *
47
+ * Falls back to `targetPath` unchanged when it isn't actually inside
48
+ * `fromDir` — e.g. an absolute `[data] root` (or an absolute db path)
49
+ * configured identically for both live and standby legitimately points at
50
+ * one shared location rather than a per-directory one, and in that case
51
+ * there's nothing to re-root; callers treat an unchanged result as "shared,
52
+ * skip the copy" rather than attempting a same-path no-op command.
53
+ *
54
+ * Exported so `deploy verify` (src/deploy/verify.ts) can re-root the standby
55
+ * sqlite db path onto the live dir for its migration-parity check, using the
56
+ * exact same live/standby path mapping this file's own db-setup step relies
57
+ * on, instead of duplicating it.
58
+ */
59
+ export function reroot(fromDir, toDir, targetPath) {
60
+ const rel = path.relative(fromDir, targetPath);
61
+ if (rel.startsWith('..') || path.isAbsolute(rel)) {
62
+ return targetPath;
63
+ }
64
+ return path.join(toDir, rel);
65
+ }
66
+ /**
67
+ * Resolve a possibly-relative path against `baseDir` without touching an
68
+ * already-absolute one. Exported for the same reason as `reroot` above.
69
+ */
70
+ export function toAbsolute(baseDir, maybePath) {
71
+ return path.isAbsolute(maybePath) ? maybePath : path.resolve(baseDir, maybePath);
72
+ }
73
+ function resolveDbConfig(opts) {
74
+ if (opts.db) {
75
+ return resolveConnectConfig({ env: opts.db, allowOtherEnv: true });
76
+ }
77
+ return resolveConnectConfig();
78
+ }
79
+ /** Synchronous sleep via Atomics.wait — no async plumbing needed in this otherwise-sync pipeline. */
80
+ function sleepSync(ms) {
81
+ if (ms <= 0)
82
+ return;
83
+ const buffer = new SharedArrayBuffer(4);
84
+ const view = new Int32Array(buffer);
85
+ Atomics.wait(view, 0, 0, ms);
86
+ }
87
+ /**
88
+ * Poll `url` with curl up to `attempts` times, `delayMs` apart, succeeding on
89
+ * the first 200. `pm2 start` returns before the app has actually finished
90
+ * booting, so a single immediate check would almost always see
91
+ * connection-refused on a real deploy. Deliberately omits curl's `-f` (which
92
+ * makes curl itself exit non-zero — and `exec` throw — on a non-2xx
93
+ * response): `-w '%{http_code}'` needs the real status code in stdout so
94
+ * this function can judge pass/fail itself rather than only ever seeing
95
+ * "did curl's own exit code say ok".
96
+ *
97
+ * Exported so `deploy verify` (src/deploy/verify.ts) can reuse the exact same
98
+ * poll/retry logic for its own health check against the already-running
99
+ * staging app, instead of reimplementing it with a second curl-parsing
100
+ * helper. `deploy verify` passes a smaller `attempts`/`delayMs` budget by
101
+ * default — see verify.ts's doc comment for why.
102
+ */
103
+ export function checkHealth(runner, url, attempts, delayMs) {
104
+ let lastCode = '';
105
+ for (let attempt = 1; attempt <= attempts; attempt++) {
106
+ const result = runner.spawn(`curl -s -o /dev/null -w '%{http_code}' ${JSON.stringify(url)}`);
107
+ lastCode = result.code === 0 ? result.stdout.trim() : `curl_exit_${result.code}`;
108
+ if (lastCode === '200')
109
+ return { ok: true, lastCode, attempts: attempt };
110
+ if (attempt < attempts)
111
+ sleepSync(delayMs);
112
+ }
113
+ return { ok: false, lastCode, attempts };
114
+ }
115
+ /**
116
+ * Run the full build pipeline against `cwd` (the standby directory). Steps
117
+ * run in the order documented in the task-5 brief (with db-strategy
118
+ * resolution/validation moved earlier, before git pull, so a bad `--db`
119
+ * fails fast); any failure throws `BuildAbortError` immediately. The state
120
+ * file's `last_build`/`last_build_status` is written once the pipeline
121
+ * reaches its first destructive step (git pull), and again with the final
122
+ * outcome if the pipeline completes (success or failure) — see this file's
123
+ * header (Fix 3) for the full rationale; an early abort never touches it.
124
+ */
125
+ export function runBuild(config, runner, opts = {}) {
126
+ const cwd = path.resolve(opts.cwd ?? process.cwd());
127
+ const branch = opts.branch ?? config.branch;
128
+ const healthCheckAttempts = opts.healthCheckAttempts ?? DEFAULT_HEALTH_CHECK_ATTEMPTS;
129
+ const healthCheckDelayMs = opts.healthCheckDelayMs ?? DEFAULT_HEALTH_CHECK_DELAY_MS;
130
+ const warnings = [];
131
+ const steps = [];
132
+ // Fix 3: whether the pipeline has reached its first DESTRUCTIVE step (git
133
+ // pull — see the `finally` block at the bottom of this function for the
134
+ // full rationale). Early aborts (standby-dir guard, disk/memory checks,
135
+ // db-resolve validation) never flip this, so they never touch
136
+ // last_build/last_build_status at all — nothing destructive happened, so
137
+ // there's nothing stale to warn rollback.ts about.
138
+ let destructiveStepReached = false;
139
+ // Fix 6: true once `--stop-prod` has actually stopped the live PM2
140
+ // process. If the build subsequently aborts for ANY reason, `abort()`
141
+ // below makes sure that fact — production is currently DOWN — is
142
+ // unmissable in the thrown error, rather than buried behind an unrelated
143
+ // "build failed" message.
144
+ let productionStopped = false;
145
+ let liveDirForAbortMessage = '';
146
+ function pass(name, detail) {
147
+ steps.push({ name, status: 'pass', detail });
148
+ }
149
+ function abort(name, message) {
150
+ const finalMessage = productionStopped
151
+ ? `${message}\n\n` +
152
+ `⚠ PRODUCTION IS DOWN: --stop-prod stopped "${config.app_name}" in ${liveDirForAbortMessage} to free ` +
153
+ `memory, and the build subsequently aborted — production was never restarted. Bring it back up with:\n` +
154
+ ` cd ${liveDirForAbortMessage} && pm2 start ecosystem.config.js --env production\n` +
155
+ `or run "deploy rollback" / investigate manually.`
156
+ : message;
157
+ steps.push({ name, status: 'fail', detail: finalMessage });
158
+ throw new BuildAbortError(finalMessage, steps);
159
+ }
160
+ /**
161
+ * Run a risky operation (anything touching CommandRunner or an external
162
+ * resolver) and convert ANY throw into the same BuildAbortError path a
163
+ * threshold-check abort() takes — so a real git/npm/pm2/curl failure also
164
+ * gets a pushed `fail` step and a printed summary, not a bare Error that
165
+ * skips both. A BuildAbortError thrown from inside `run` (i.e. `abort()`
166
+ * was already called deeper in the same step) passes through unchanged
167
+ * rather than double-reporting.
168
+ */
169
+ function runStep(name, run) {
170
+ try {
171
+ return run();
172
+ }
173
+ catch (e) {
174
+ if (e instanceof BuildAbortError)
175
+ throw e;
176
+ const msg = e instanceof Error ? e.message : String(e);
177
+ return abort(name, msg);
178
+ }
179
+ }
180
+ let buildStatus = 'failed';
181
+ try {
182
+ // Guard: refuse to run anything at all if the (authoritative) state file
183
+ // says `cwd` isn't the standby dir. Running the pipeline against the
184
+ // live dir would git-pull/rebuild the running production tree and, for
185
+ // the sqlite "copy" strategy, overwrite the live DB with the standby's
186
+ // stale one. An explicit --peer-dir still only overrides which dir is
187
+ // treated as "live" for the copy/stop-prod target — it never overrides
188
+ // this check.
189
+ const state = readState(config.app_name);
190
+ if (state && path.resolve(state.standby_dir) !== cwd) {
191
+ abort('standby-dir-guard', `deploy build must be run from the standby directory (${state.standby_dir}), not ${cwd}. ` +
192
+ `Running it here would git pull / install / rebuild the live tree and, for a sqlite "copy" ` +
193
+ `db_strategy, overwrite the live database. cd into the standby dir and re-run.`);
194
+ }
195
+ const liveDir = opts.peerDir
196
+ ? resolvePeerDir(cwd, opts.peerDir)
197
+ : state
198
+ ? path.resolve(state.live_dir)
199
+ : resolvePeerDir(cwd, opts.peerDir);
200
+ // Step 1: auto-clean, then check disk free against min_disk_mb.
201
+ const cleanResult = autoClean(config, runner);
202
+ pass('clean', `reclaimed ${cleanResult.totalBytesReclaimed} bytes across ${cleanResult.targets.length} targets`);
203
+ warnings.push(...cleanResult.warnings);
204
+ const diskFreeMb = queryDiskFreeMb(runner, cwd, warnings);
205
+ if (diskFreeMb !== undefined && diskFreeMb < config.min_disk_mb) {
206
+ abort('disk-check', `Disk free (${diskFreeMb} MB) is still below min_disk_mb (${config.min_disk_mb}) after cleanup.`);
207
+ }
208
+ pass('disk-check', diskFreeMb !== undefined ? `${diskFreeMb} MB free` : 'unknown — skipping check');
209
+ // Step 2/3: memory check, optionally freed by stopping the live PM2 process.
210
+ let memoryFreeMb = queryMemoryFreeMb(runner, warnings);
211
+ let memoryLow = memoryFreeMb !== undefined && memoryFreeMb < config.min_memory_mb;
212
+ if (memoryLow) {
213
+ if (opts.stopProd) {
214
+ runStep('stop-prod', () => runner.exec(`pm2 stop ${config.app_name}`, { cwd: liveDir }));
215
+ pass('stop-prod', `stopped "${config.app_name}" in ${liveDir}`);
216
+ productionStopped = true;
217
+ liveDirForAbortMessage = liveDir;
218
+ memoryFreeMb = queryMemoryFreeMb(runner, warnings);
219
+ memoryLow = memoryFreeMb !== undefined && memoryFreeMb < config.min_memory_mb;
220
+ }
221
+ if (memoryLow) {
222
+ const freeDesc = memoryFreeMb !== undefined ? `${memoryFreeMb} MB` : 'unknown';
223
+ const suggestionLines = SWAP_INCREASE_SUGGESTIONS.map((c) => ` ${c}`).join('\n');
224
+ const hint = opts.stopProd
225
+ ? 'Stopping the live process did not free enough memory.'
226
+ : 'Re-run with --stop-prod to free memory by stopping the live process, or increase swap:';
227
+ abort('memory-check', `Free memory (${freeDesc}) is below min_memory_mb (${config.min_memory_mb}). ${hint}\n${suggestionLines}`);
228
+ }
229
+ }
230
+ pass('memory-check', memoryFreeMb !== undefined ? `${memoryFreeMb} MB free` : 'unknown — skipping check');
231
+ // Step (moved earlier): resolve/validate the db target BEFORE paying for
232
+ // git pull/install/build (and before --stop-prod has taken production
233
+ // down) — a typo'd --db should fail loudly and immediately.
234
+ const dbConfig = runStep('db-resolve', () => resolveDbConfig(opts));
235
+ const dbStrategyResolved = config.db_strategy === 'auto' ? (dbConfig.type === 'sqlite' ? 'copy' : 'shared') : config.db_strategy;
236
+ if (dbStrategyResolved === 'copy' && (dbConfig.type !== 'sqlite' || !dbConfig.sqlite)) {
237
+ abort('db-resolve', `db_strategy resolved to "copy" but the resolved db config is type "${dbConfig.type}", not sqlite.`);
238
+ }
239
+ pass('db-resolve', `strategy=${dbStrategyResolved}${opts.db ? ` db=${opts.db}` : ''}`);
240
+ // Fix 3: write a provisional/pessimistic `last_build` marker right
241
+ // before the first DESTRUCTIVE step (git pull) — everything above this
242
+ // point (guard, disk/memory checks, db-resolve) is read-only, so an
243
+ // abort before here must NEVER touch last_build at all (an early abort
244
+ // leaves the previous live build fully intact; rollback.ts's
245
+ // stale-build guard must stay unblocked). From here on, the standby
246
+ // dir's on-disk state is no longer guaranteed clean: if the operator
247
+ // Ctrl+C's the process after `pre_build_cmd` (typically `rm -rf .next`)
248
+ // has already run, the `finally` block below never executes (process
249
+ // killed) — this provisional write is what's left behind for
250
+ // rollback.ts to see, correctly blocking it (the standby dir may now be
251
+ // a half-destroyed mess that is no longer safe to promote). A normal
252
+ // completion (success or a later, cleaner failure) overwrites this via
253
+ // the `finally` block's own write.
254
+ destructiveStepReached = true;
255
+ try {
256
+ updateState(config.app_name, { last_build: new Date().toISOString(), last_build_status: 'failed' });
257
+ }
258
+ catch {
259
+ // No state file yet — best-effort, same as the finally block below.
260
+ }
261
+ // Step 4: git pull
262
+ runStep('git-pull', () => runner.exec(`git pull origin ${branch}`, { cwd }));
263
+ pass('git-pull', `origin ${branch}`);
264
+ // Step 5: install
265
+ runStep('install', () => runner.exec(config.install_cmd, { cwd }));
266
+ pass('install', config.install_cmd);
267
+ // Step 6: pre-build
268
+ runStep('pre-build', () => runner.exec(config.pre_build_cmd, { cwd }));
269
+ pass('pre-build', config.pre_build_cmd);
270
+ // Step 7: build
271
+ runStep('build', () => runner.exec(config.build_cmd, { cwd }));
272
+ pass('build', config.build_cmd);
273
+ // Step 8: DB setup. `dbConfig`/`dbStrategyResolved` were already
274
+ // resolved and validated above.
275
+ if (dbStrategyResolved === 'copy') {
276
+ // sqlite!.database_path is guaranteed by the db-resolve validation above.
277
+ const standbyDbPath = toAbsolute(cwd, dbConfig.sqlite.database_path);
278
+ const liveDbPath = reroot(cwd, liveDir, standbyDbPath);
279
+ if (liveDbPath === standbyDbPath) {
280
+ // The db path isn't nested under the standby dir at all (e.g. an
281
+ // absolute [data] root shared by both live and standby) — there's
282
+ // no per-directory copy of it to re-root onto the live dir, so
283
+ // treat it as already-shared storage and skip the copy rather than
284
+ // running a same-path no-op command.
285
+ pass('db-setup', `sqlite db path is outside the live/standby split (shared) — skipping copy: ${standbyDbPath}`);
286
+ }
287
+ else {
288
+ runStep('db-setup', () => {
289
+ const sourceCheck = runner.spawn(`test -f ${JSON.stringify(liveDbPath)}`);
290
+ if (sourceCheck.code !== 0) {
291
+ throw new Error(`Source sqlite db not found at ${liveDbPath} (live dir) — cannot back it up.`);
292
+ }
293
+ const destDir = path.dirname(standbyDbPath);
294
+ const destDirCheck = runner.spawn(`test -d ${JSON.stringify(destDir)}`);
295
+ if (destDirCheck.code !== 0) {
296
+ throw new Error(`Destination directory ${destDir} does not exist in the standby dir (data/ is typically ` +
297
+ `gitignored on a fresh clone) — create it before running deploy build.`);
298
+ }
299
+ // sqlite3's ".backup" takes a consistent point-in-time snapshot
300
+ // regardless of WAL state — unlike a plain `cp`, which can tear a
301
+ // live WAL-mode database mid-write (the exact corruption class
302
+ // this project has already been burned by once for a different
303
+ // reason: never cp/scp a live WAL-mode sqlite file).
304
+ runner.exec(`sqlite3 ${JSON.stringify(liveDbPath)} ${JSON.stringify(`.backup ${standbyDbPath}`)}`);
305
+ });
306
+ pass('db-setup', `sqlite backup ${liveDbPath} -> ${standbyDbPath}`);
307
+ }
308
+ }
309
+ else {
310
+ pass('db-setup', `postgres: using resolved [db.${opts.db ?? '(current env)'}] config -> ${dbConfig.postgrest?.base_url ?? '(no base_url)'}`);
311
+ }
312
+ if (config.migrate_cmd) {
313
+ runStep('migrate', () => runner.exec(config.migrate_cmd, { cwd }));
314
+ pass('migrate', config.migrate_cmd);
315
+ }
316
+ else {
317
+ pass('migrate', 'no migrate_cmd configured — assuming schema bootstrap runs automatically at app startup');
318
+ }
319
+ // Step 9: start the app on the staging port, under a name distinct from
320
+ // the live process. `pm2 start ecosystem.config.js --name X` does NOT
321
+ // actually rename the process when starting from a config file — pm2
322
+ // reads the name from the file's own `apps[].name` field in that mode
323
+ // and ignores the CLI --name override, so that would have silently
324
+ // restarted (or no-op'd against) whatever's already registered under
325
+ // the ecosystem file's real name. startNamedPm2Process works around
326
+ // this by cloning the ecosystem config with the new name/cwd/port baked
327
+ // in and starting pm2 from THAT clone instead — see pm2-start.ts's
328
+ // header for the full why.
329
+ const stagingProcessName = `${config.app_name}-staging`;
330
+ // Fix 4a: tolerant-delete any stale "<app>-staging" registration before
331
+ // starting it fresh — defense in depth. `start-staging` normally finds
332
+ // nothing here because a prior `deploy switch`/`deploy rollback` already
333
+ // deleted it (via `promoteDirFresh`'s own staging-delete step). If that
334
+ // delete ever silently failed, the NEXT `deploy build` would otherwise
335
+ // hit the stale registration and `startNamedPm2Process` would restart
336
+ // IT IN PLACE (pm2 only recomputes cwd for a name it's never registered
337
+ // before — see pm2-start.ts's header) — meaning the health check below
338
+ // would test the OLD directory's code, not this build's, and a
339
+ // subsequent `deploy switch` would silently promote untested code. Never
340
+ // fatal: "process not found" is the expected common case, and any other
341
+ // failure here is only a warning — the fresh start below is what
342
+ // actually matters.
343
+ const stagingCleanupResult = runner.spawn(`pm2 delete ${stagingProcessName}`, { cwd });
344
+ if (stagingCleanupResult.code === 0) {
345
+ pass('clean-stale-staging', `deleted a stale "${stagingProcessName}" PM2 registration before starting fresh`);
346
+ }
347
+ else if (isPm2ProcessNotFound(stagingCleanupResult)) {
348
+ pass('clean-stale-staging', `no stale "${stagingProcessName}" registration found`);
349
+ }
350
+ else {
351
+ const detail = `failed to delete a stale "${stagingProcessName}" registration (continuing anyway): ` +
352
+ (stagingCleanupResult.stderr || stagingCleanupResult.stdout || `exit code ${stagingCleanupResult.code}`);
353
+ warnings.push(detail);
354
+ pass('clean-stale-staging', detail);
355
+ }
356
+ runStep('start-staging', () => startNamedPm2Process(runner, { dir: cwd, name: stagingProcessName, port: config.staging_port }));
357
+ pass('start-staging', `name=${stagingProcessName} PORT=${config.staging_port}, cwd=${cwd}`);
358
+ // Step 10: health check, retried — pm2 start returns before the app has
359
+ // actually finished booting.
360
+ const stagingUrl = `http://localhost:${config.staging_port}`;
361
+ const healthUrl = `${stagingUrl}${config.health_url}`;
362
+ const healthResult = runStep('health-check', () => checkHealth(runner, healthUrl, healthCheckAttempts, healthCheckDelayMs));
363
+ if (!healthResult.ok) {
364
+ abort('health-check', `Health check at ${healthUrl} returned "${healthResult.lastCode}" (expected 200) after ${healthCheckAttempts} attempt(s).`);
365
+ }
366
+ pass('health-check', `${healthUrl} -> 200 (attempt ${healthResult.attempts}/${healthCheckAttempts})`);
367
+ buildStatus = 'success';
368
+ return { steps, stagingPort: config.staging_port, stagingUrl, dbStrategyResolved, warnings };
369
+ }
370
+ finally {
371
+ // Fix 3: only overwrite last_build/last_build_status here if the
372
+ // pipeline actually reached the first destructive step (the provisional
373
+ // marker written just before git pull, above). An early abort (guard/
374
+ // disk/memory/db-resolve) never set that flag, so this block correctly
375
+ // no-ops for it — nothing destructive happened, so last_build should be
376
+ // left exactly as it was (possibly undefined) rather than stamped
377
+ // "failed" and falsely blocking deploy rollback's stale-build guard.
378
+ if (destructiveStepReached) {
379
+ try {
380
+ updateState(config.app_name, { last_build: new Date().toISOString(), last_build_status: buildStatus });
381
+ }
382
+ catch {
383
+ // No state file yet (deploy init was never run) — build still ran;
384
+ // state bookkeeping is best-effort and must never mask the real
385
+ // pipeline error (or success) above.
386
+ }
387
+ }
388
+ }
389
+ }
@@ -0,0 +1,63 @@
1
+ import type { CommandRunner, DeployConfig } from './types.js';
2
+ /** Result of cleaning a single target (a directory, or the npm cache). */
3
+ export interface CleanTargetResult {
4
+ /** Human-readable target name, e.g. ".next.rollback" or "npm-cache". */
5
+ target: string;
6
+ /** Absolute path cleaned (or the npm cache dir, or "(unknown)" if undetectable). */
7
+ path: string;
8
+ /** Bytes reclaimed. 0 if the target didn't exist or removal failed. */
9
+ bytesReclaimed: number;
10
+ /** True when the target didn't exist (nothing to clean — not an error). */
11
+ skipped: boolean;
12
+ /** Set when removal (or `npm cache clean --force`) failed. */
13
+ error?: string;
14
+ }
15
+ /** Result of the safe auto-clean pass — the shape Task 5's build pipeline reuses. */
16
+ export interface AutoCleanResult {
17
+ targets: CleanTargetResult[];
18
+ totalBytesReclaimed: number;
19
+ /** Non-fatal problems encountered while cleaning (a removal failed, etc.). */
20
+ warnings: string[];
21
+ }
22
+ export interface RunCleanOptions {
23
+ /** Also print (never execute) system-level cleanup + swap-increase commands. */
24
+ aggressive: boolean;
25
+ /** Directory the relative targets (.next.rollback, .next.staging, node_modules/.cache) are resolved against. Defaults to process.cwd(). */
26
+ cwd?: string;
27
+ }
28
+ /** Full result of `deploy clean`, including the CLI-only suggestion lists. */
29
+ export interface RunCleanResult extends AutoCleanResult {
30
+ memoryFreeMb?: number;
31
+ minMemoryMb: number;
32
+ /** True when memoryFreeMb is below config.min_memory_mb. */
33
+ memoryLow: boolean;
34
+ /**
35
+ * Swap-increase commands (fallocate/mkswap/swapon), suggested-not-executed.
36
+ * Populated whenever memoryLow is true — independent of --aggressive.
37
+ */
38
+ swapSuggestions: string[];
39
+ /**
40
+ * System-level cleanup commands (journalctl/apt/docker), suggested-not-executed.
41
+ * Populated only when opts.aggressive is true.
42
+ */
43
+ systemSuggestions: string[];
44
+ }
45
+ /** Printed (never run — all require sudo) only when `--aggressive` is passed. */
46
+ export declare const SYSTEM_CLEANUP_SUGGESTIONS: string[];
47
+ /** Printed (never run) whenever free memory is below config.min_memory_mb. */
48
+ export declare const SWAP_INCREASE_SUGGESTIONS: string[];
49
+ /**
50
+ * Safe-targets-only cleanup, for reuse by `deploy build`'s auto-clean step
51
+ * (Task 5). Stable 2-arg signature — do not add parameters here; use
52
+ * `runClean` for anything CLI-specific (--aggressive, swap suggestions).
53
+ */
54
+ export declare function autoClean(_config: DeployConfig, runner: CommandRunner): AutoCleanResult;
55
+ /**
56
+ * Full `deploy clean` behavior: runs the same safe-target cleanup as
57
+ * `autoClean`, then adds the memory-triggered swap suggestion (independent
58
+ * of --aggressive) and, when opts.aggressive is true, the system-level
59
+ * cleanup suggestions. Suggestions are returned as data for src/cli.ts to
60
+ * print — nothing in this module ever executes a sudo command.
61
+ */
62
+ export declare function runClean(config: DeployConfig, runner: CommandRunner, opts: RunCleanOptions): RunCleanResult;
63
+ //# sourceMappingURL=clean.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"clean.d.ts","sourceRoot":"","sources":["../../src/deploy/clean.ts"],"names":[],"mappings":"AAiCA,OAAO,KAAK,EAAE,aAAa,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAE9D,0EAA0E;AAC1E,MAAM,WAAW,iBAAiB;IAChC,wEAAwE;IACxE,MAAM,EAAE,MAAM,CAAC;IACf,oFAAoF;IACpF,IAAI,EAAE,MAAM,CAAC;IACb,uEAAuE;IACvE,cAAc,EAAE,MAAM,CAAC;IACvB,2EAA2E;IAC3E,OAAO,EAAE,OAAO,CAAC;IACjB,8DAA8D;IAC9D,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,qFAAqF;AACrF,MAAM,WAAW,eAAe;IAC9B,OAAO,EAAE,iBAAiB,EAAE,CAAC;IAC7B,mBAAmB,EAAE,MAAM,CAAC;IAC5B,8EAA8E;IAC9E,QAAQ,EAAE,MAAM,EAAE,CAAC;CACpB;AAED,MAAM,WAAW,eAAe;IAC9B,gFAAgF;IAChF,UAAU,EAAE,OAAO,CAAC;IACpB,2IAA2I;IAC3I,GAAG,CAAC,EAAE,MAAM,CAAC;CACd;AAED,8EAA8E;AAC9E,MAAM,WAAW,cAAe,SAAQ,eAAe;IACrD,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,WAAW,EAAE,MAAM,CAAC;IACpB,4DAA4D;IAC5D,SAAS,EAAE,OAAO,CAAC;IACnB;;;OAGG;IACH,eAAe,EAAE,MAAM,EAAE,CAAC;IAC1B;;;OAGG;IACH,iBAAiB,EAAE,MAAM,EAAE,CAAC;CAC7B;AAED,iFAAiF;AACjF,eAAO,MAAM,0BAA0B,UAItC,CAAC;AAEF,8EAA8E;AAC9E,eAAO,MAAM,yBAAyB,UAKrC,CAAC;AA8EF;;;;GAIG;AACH,wBAAgB,SAAS,CAAC,OAAO,EAAE,YAAY,EAAE,MAAM,EAAE,aAAa,GAAG,eAAe,CAEvF;AAED;;;;;;GAMG;AACH,wBAAgB,QAAQ,CAAC,MAAM,EAAE,YAAY,EAAE,MAAM,EAAE,aAAa,EAAE,IAAI,EAAE,eAAe,GAAG,cAAc,CAiB3G"}
@@ -0,0 +1,135 @@
1
+ // hazo_env/src/deploy/clean.ts — `deploy clean` disk-space reclamation
2
+ //
3
+ // Removes safe, deploy-owned targets only: the build pipeline's own
4
+ // `.next.rollback` / `.next.staging` staging dirs (NOT plain `.next` —
5
+ // that's the live app's current build, never ours to touch here),
6
+ // `node_modules/.cache`, and the global npm cache. Reports bytes reclaimed
7
+ // per target and in total.
8
+ //
9
+ // Every directory removal and the `npm cache clean --force` call goes
10
+ // through the injected CommandRunner (see types.ts's doc comment and
11
+ // runner.ts's header) — this file must never import node:child_process or
12
+ // call fs.rmSync directly. Sizes are measured the same way, by shelling out
13
+ // to `du -sk <path>` via runner.spawn — see the "Design decision" note
14
+ // below on why.
15
+ //
16
+ // `autoClean(config, runner)` is the stable, 2-arg entry point Task 5
17
+ // (`deploy build`'s auto-clean step) imports directly — its signature must
18
+ // not change. `runClean(config, runner, opts)` is the CLI-facing superset
19
+ // that adds `--aggressive` system-cleanup suggestions and the
20
+ // memory-triggered swap suggestion; it's never imported by Task 5.
21
+ //
22
+ // Design decision (size measurement): `du -sk <path>` via CommandRunner,
23
+ // not `fs.statSync`/a manual recursive walk. `du` already does the
24
+ // recursive-sum-in-KB that would otherwise need reimplementing, and routing
25
+ // it through `runner.spawn` keeps this file's only filesystem-adjacent
26
+ // touchpoint the same CommandRunner seam used for the actual removal —
27
+ // one injection point for tests to mock, matching this module's existing
28
+ // "measure via CommandRunner" discipline (see status.ts's df/vm_stat calls).
29
+ // The tradeoff: `du`'s output format varies by platform/locale, so
30
+ // `parseDuKb` is deliberately lenient (first whitespace-separated token).
31
+ import path from 'node:path';
32
+ import { queryMemoryFreeMb } from './status.js';
33
+ /** Printed (never run — all require sudo) only when `--aggressive` is passed. */
34
+ export const SYSTEM_CLEANUP_SUGGESTIONS = [
35
+ 'sudo journalctl --vacuum-size=100M',
36
+ 'sudo apt clean',
37
+ 'sudo docker system prune -f',
38
+ ];
39
+ /** Printed (never run) whenever free memory is below config.min_memory_mb. */
40
+ export const SWAP_INCREASE_SUGGESTIONS = [
41
+ 'sudo fallocate -l 2G /swapfile',
42
+ 'sudo chmod 600 /swapfile',
43
+ 'sudo mkswap /swapfile',
44
+ 'sudo swapon /swapfile',
45
+ ];
46
+ const DIR_TARGETS = [
47
+ { name: '.next.rollback', relativePath: '.next.rollback' },
48
+ { name: '.next.staging', relativePath: '.next.staging' },
49
+ { name: 'node_modules/.cache', relativePath: path.join('node_modules', '.cache') },
50
+ ];
51
+ /** Parse `du -sk <path>` output's leading KB column. Lenient to platform/locale variance. */
52
+ function parseDuKb(duOutput) {
53
+ const token = duOutput.trim().split(/\s+/)[0];
54
+ const kb = Number(token);
55
+ return Number.isFinite(kb) ? kb : undefined;
56
+ }
57
+ /** Measure a path's size in KB via `du -sk`, or undefined if it doesn't exist / du fails. */
58
+ function measureDirKb(runner, absPath) {
59
+ const result = runner.spawn(`du -sk ${JSON.stringify(absPath)}`);
60
+ if (result.code !== 0)
61
+ return undefined;
62
+ return parseDuKb(result.stdout);
63
+ }
64
+ function cleanDirTarget(runner, cwd, name, relativePath, warnings) {
65
+ const absPath = path.join(cwd, relativePath);
66
+ const beforeKb = measureDirKb(runner, absPath);
67
+ if (beforeKb === undefined) {
68
+ // Doesn't exist (or unreadable) — nothing to clean, not an error.
69
+ return { target: name, path: absPath, bytesReclaimed: 0, skipped: true };
70
+ }
71
+ const removeResult = runner.spawn(`rm -rf ${JSON.stringify(absPath)}`);
72
+ if (removeResult.code !== 0) {
73
+ const error = removeResult.stderr.trim() || `exit ${removeResult.code}`;
74
+ warnings.push(`failed to remove ${absPath}: ${error}`);
75
+ return { target: name, path: absPath, bytesReclaimed: 0, skipped: false, error };
76
+ }
77
+ return { target: name, path: absPath, bytesReclaimed: beforeKb * 1024, skipped: false };
78
+ }
79
+ /**
80
+ * Clean the global npm cache via `npm cache clean --force`. Bytes reclaimed
81
+ * is measured as the npm cache directory's size before minus after the
82
+ * clean (resolved via `npm config get cache`, both through CommandRunner).
83
+ */
84
+ function cleanNpmCacheTarget(runner, warnings) {
85
+ const cachePathResult = runner.spawn('npm config get cache');
86
+ const cachePath = cachePathResult.code === 0 ? cachePathResult.stdout.trim() : undefined;
87
+ const beforeKb = cachePath ? measureDirKb(runner, cachePath) ?? 0 : 0;
88
+ const cleanResult = runner.spawn('npm cache clean --force');
89
+ if (cleanResult.code !== 0) {
90
+ const error = cleanResult.stderr.trim() || `exit ${cleanResult.code}`;
91
+ warnings.push(`npm cache clean --force failed: ${error}`);
92
+ return { target: 'npm-cache', path: cachePath ?? '(unknown)', bytesReclaimed: 0, skipped: false, error };
93
+ }
94
+ const afterKb = cachePath ? measureDirKb(runner, cachePath) ?? 0 : 0;
95
+ const bytesReclaimed = Math.max(0, (beforeKb - afterKb) * 1024);
96
+ return { target: 'npm-cache', path: cachePath ?? '(unknown)', bytesReclaimed, skipped: false };
97
+ }
98
+ function cleanAllTargets(runner, cwd) {
99
+ const warnings = [];
100
+ const targets = DIR_TARGETS.map((t) => cleanDirTarget(runner, cwd, t.name, t.relativePath, warnings));
101
+ targets.push(cleanNpmCacheTarget(runner, warnings));
102
+ const totalBytesReclaimed = targets.reduce((sum, t) => sum + t.bytesReclaimed, 0);
103
+ return { targets, totalBytesReclaimed, warnings };
104
+ }
105
+ /**
106
+ * Safe-targets-only cleanup, for reuse by `deploy build`'s auto-clean step
107
+ * (Task 5). Stable 2-arg signature — do not add parameters here; use
108
+ * `runClean` for anything CLI-specific (--aggressive, swap suggestions).
109
+ */
110
+ export function autoClean(_config, runner) {
111
+ return cleanAllTargets(runner, process.cwd());
112
+ }
113
+ /**
114
+ * Full `deploy clean` behavior: runs the same safe-target cleanup as
115
+ * `autoClean`, then adds the memory-triggered swap suggestion (independent
116
+ * of --aggressive) and, when opts.aggressive is true, the system-level
117
+ * cleanup suggestions. Suggestions are returned as data for src/cli.ts to
118
+ * print — nothing in this module ever executes a sudo command.
119
+ */
120
+ export function runClean(config, runner, opts) {
121
+ const cwd = opts.cwd ?? process.cwd();
122
+ const auto = cleanAllTargets(runner, cwd);
123
+ const warnings = [...auto.warnings];
124
+ const memoryFreeMb = queryMemoryFreeMb(runner, warnings);
125
+ const memoryLow = memoryFreeMb !== undefined && memoryFreeMb < config.min_memory_mb;
126
+ return {
127
+ ...auto,
128
+ warnings,
129
+ memoryFreeMb,
130
+ minMemoryMb: config.min_memory_mb,
131
+ memoryLow,
132
+ swapSuggestions: memoryLow ? SWAP_INCREASE_SUGGESTIONS : [],
133
+ systemSuggestions: opts.aggressive ? SYSTEM_CLEANUP_SUGGESTIONS : [],
134
+ };
135
+ }
@@ -0,0 +1,13 @@
1
+ export * from './types.js';
2
+ export * from './state.js';
3
+ export * from './runner.js';
4
+ export * from './peer.js';
5
+ export * from './pm2-start.js';
6
+ export * from './clean.js';
7
+ export * from './status.js';
8
+ export * from './init.js';
9
+ export * from './build.js';
10
+ export * from './verify.js';
11
+ export * from './switch.js';
12
+ export * from './rollback.js';
13
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/deploy/index.ts"],"names":[],"mappings":"AAUA,cAAc,YAAY,CAAC;AAC3B,cAAc,YAAY,CAAC;AAC3B,cAAc,aAAa,CAAC;AAC5B,cAAc,WAAW,CAAC;AAC1B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,YAAY,CAAC;AAC3B,cAAc,aAAa,CAAC;AAC5B,cAAc,WAAW,CAAC;AAC1B,cAAc,YAAY,CAAC;AAC3B,cAAc,aAAa,CAAC;AAC5B,cAAc,aAAa,CAAC;AAC5B,cAAc,eAAe,CAAC"}
@@ -0,0 +1,22 @@
1
+ // hazo_env/src/deploy/index.ts — Deploy module barrel export
2
+ //
3
+ // Fix 5 (final review wave): the command functions (runInit/runBuild/
4
+ // runVerify/runSwitch/runRollback/runStatus/runClean) and their abort error
5
+ // classes were missing from this barrel — only the supporting
6
+ // types/state/runner/peer/pm2-start modules were exported, so programmatic
7
+ // callers of `hazo_env` (per the spec's "Package export" section) couldn't
8
+ // actually import the deploy commands themselves. `src/index.ts`'s own
9
+ // `export * from './deploy/index.js'` picks up everything added here
10
+ // automatically — no change needed there.
11
+ export * from './types.js';
12
+ export * from './state.js';
13
+ export * from './runner.js';
14
+ export * from './peer.js';
15
+ export * from './pm2-start.js';
16
+ export * from './clean.js';
17
+ export * from './status.js';
18
+ export * from './init.js';
19
+ export * from './build.js';
20
+ export * from './verify.js';
21
+ export * from './switch.js';
22
+ export * from './rollback.js';
@@ -0,0 +1,20 @@
1
+ import type { CommandRunner, DeployConfig } from './types.js';
2
+ export interface RunInitOptions {
3
+ /** Directory to treat as "current" (the live dir). Defaults to process.cwd(). */
4
+ cwd?: string;
5
+ /** Explicit peer dir override, passed through to resolvePeerDir. */
6
+ peerDir?: string;
7
+ }
8
+ export interface RunInitResult {
9
+ currentDir: string;
10
+ peerDir: string;
11
+ originUrl: string;
12
+ }
13
+ /**
14
+ * Create the peer (standby) directory: resolve its path, abort if it
15
+ * already exists, clone the repo into it, copy the INI config across with
16
+ * `dir_suffix` flipped, and write the initial state file marking the
17
+ * current directory as live.
18
+ */
19
+ export declare function runInit(config: DeployConfig, runner: CommandRunner, opts?: RunInitOptions): RunInitResult;
20
+ //# sourceMappingURL=init.d.ts.map