hazo_env 0.10.4 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/CHANGE_LOG.md +69 -0
  2. package/config/hazo_env_config.ini.sample +61 -0
  3. package/dist/cli.js +315 -0
  4. package/dist/deploy/build.d.ts +90 -0
  5. package/dist/deploy/build.d.ts.map +1 -0
  6. package/dist/deploy/build.js +299 -0
  7. package/dist/deploy/clean.d.ts +63 -0
  8. package/dist/deploy/clean.d.ts.map +1 -0
  9. package/dist/deploy/clean.js +135 -0
  10. package/dist/deploy/index.d.ts +6 -0
  11. package/dist/deploy/index.d.ts.map +1 -0
  12. package/dist/deploy/index.js +6 -0
  13. package/dist/deploy/init.d.ts +20 -0
  14. package/dist/deploy/init.d.ts.map +1 -0
  15. package/dist/deploy/init.js +80 -0
  16. package/dist/deploy/peer.d.ts +18 -0
  17. package/dist/deploy/peer.d.ts.map +1 -0
  18. package/dist/deploy/peer.js +48 -0
  19. package/dist/deploy/pm2-start.d.ts +88 -0
  20. package/dist/deploy/pm2-start.d.ts.map +1 -0
  21. package/dist/deploy/pm2-start.js +196 -0
  22. package/dist/deploy/rollback.d.ts +18 -0
  23. package/dist/deploy/rollback.d.ts.map +1 -0
  24. package/dist/deploy/rollback.js +167 -0
  25. package/dist/deploy/runner.d.ts +8 -0
  26. package/dist/deploy/runner.d.ts.map +1 -0
  27. package/dist/deploy/runner.js +35 -0
  28. package/dist/deploy/state.d.ts +19 -0
  29. package/dist/deploy/state.d.ts.map +1 -0
  30. package/dist/deploy/state.js +52 -0
  31. package/dist/deploy/status.d.ts +54 -0
  32. package/dist/deploy/status.d.ts.map +1 -0
  33. package/dist/deploy/status.js +182 -0
  34. package/dist/deploy/switch.d.ts +27 -0
  35. package/dist/deploy/switch.d.ts.map +1 -0
  36. package/dist/deploy/switch.js +152 -0
  37. package/dist/deploy/types.d.ts +96 -0
  38. package/dist/deploy/types.d.ts.map +1 -0
  39. package/dist/deploy/types.js +16 -0
  40. package/dist/deploy/verify.d.ts +41 -0
  41. package/dist/deploy/verify.d.ts.map +1 -0
  42. package/dist/deploy/verify.js +214 -0
  43. package/dist/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 +121 -0
  51. package/dist/types/index.d.ts +10 -0
  52. package/dist/types/index.d.ts.map +1 -1
  53. package/package.json +3 -3
@@ -0,0 +1,299 @@
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 always updated, win or lose.
16
+ import path from 'node:path';
17
+ import { autoClean } from './clean.js';
18
+ import { resolvePeerDir } from './peer.js';
19
+ import { queryDiskFreeMb, queryMemoryFreeMb } from './status.js';
20
+ import { readState, updateState } from './state.js';
21
+ import { SWAP_INCREASE_SUGGESTIONS } from './clean.js';
22
+ import { startNamedPm2Process } from './pm2-start.js';
23
+ import { resolveConnectConfig } from '../resolve/connect.js';
24
+ /** Thrown when any pipeline step fails. Carries the steps completed so far for reporting. */
25
+ export class BuildAbortError extends Error {
26
+ constructor(message, steps) {
27
+ super(message);
28
+ this.name = 'BuildAbortError';
29
+ this.steps = steps;
30
+ }
31
+ }
32
+ const DEFAULT_HEALTH_CHECK_ATTEMPTS = 8;
33
+ const DEFAULT_HEALTH_CHECK_DELAY_MS = 1500;
34
+ /**
35
+ * Re-root `targetPath` (known to live under `fromDir`) onto `toDir`: compute
36
+ * `targetPath`'s path relative to `fromDir` and rejoin it onto `toDir`.
37
+ *
38
+ * Falls back to `targetPath` unchanged when it isn't actually inside
39
+ * `fromDir` — e.g. an absolute `[data] root` (or an absolute db path)
40
+ * configured identically for both live and standby legitimately points at
41
+ * one shared location rather than a per-directory one, and in that case
42
+ * there's nothing to re-root; callers treat an unchanged result as "shared,
43
+ * skip the copy" rather than attempting a same-path no-op command.
44
+ *
45
+ * Exported so `deploy verify` (src/deploy/verify.ts) can re-root the standby
46
+ * sqlite db path onto the live dir for its migration-parity check, using the
47
+ * exact same live/standby path mapping this file's own db-setup step relies
48
+ * on, instead of duplicating it.
49
+ */
50
+ export function reroot(fromDir, toDir, targetPath) {
51
+ const rel = path.relative(fromDir, targetPath);
52
+ if (rel.startsWith('..') || path.isAbsolute(rel)) {
53
+ return targetPath;
54
+ }
55
+ return path.join(toDir, rel);
56
+ }
57
+ /**
58
+ * Resolve a possibly-relative path against `baseDir` without touching an
59
+ * already-absolute one. Exported for the same reason as `reroot` above.
60
+ */
61
+ export function toAbsolute(baseDir, maybePath) {
62
+ return path.isAbsolute(maybePath) ? maybePath : path.resolve(baseDir, maybePath);
63
+ }
64
+ function resolveDbConfig(opts) {
65
+ if (opts.db) {
66
+ return resolveConnectConfig({ env: opts.db, allowOtherEnv: true });
67
+ }
68
+ return resolveConnectConfig();
69
+ }
70
+ /** Synchronous sleep via Atomics.wait — no async plumbing needed in this otherwise-sync pipeline. */
71
+ function sleepSync(ms) {
72
+ if (ms <= 0)
73
+ return;
74
+ const buffer = new SharedArrayBuffer(4);
75
+ const view = new Int32Array(buffer);
76
+ Atomics.wait(view, 0, 0, ms);
77
+ }
78
+ /**
79
+ * Poll `url` with curl up to `attempts` times, `delayMs` apart, succeeding on
80
+ * the first 200. `pm2 start` returns before the app has actually finished
81
+ * booting, so a single immediate check would almost always see
82
+ * connection-refused on a real deploy. Deliberately omits curl's `-f` (which
83
+ * makes curl itself exit non-zero — and `exec` throw — on a non-2xx
84
+ * response): `-w '%{http_code}'` needs the real status code in stdout so
85
+ * this function can judge pass/fail itself rather than only ever seeing
86
+ * "did curl's own exit code say ok".
87
+ *
88
+ * Exported so `deploy verify` (src/deploy/verify.ts) can reuse the exact same
89
+ * poll/retry logic for its own health check against the already-running
90
+ * staging app, instead of reimplementing it with a second curl-parsing
91
+ * helper. `deploy verify` passes a smaller `attempts`/`delayMs` budget by
92
+ * default — see verify.ts's doc comment for why.
93
+ */
94
+ export function checkHealth(runner, url, attempts, delayMs) {
95
+ let lastCode = '';
96
+ for (let attempt = 1; attempt <= attempts; attempt++) {
97
+ lastCode = runner.exec(`curl -s -o /dev/null -w '%{http_code}' ${JSON.stringify(url)}`).trim();
98
+ if (lastCode === '200')
99
+ return { ok: true, lastCode, attempts: attempt };
100
+ if (attempt < attempts)
101
+ sleepSync(delayMs);
102
+ }
103
+ return { ok: false, lastCode, attempts };
104
+ }
105
+ /**
106
+ * Run the full build pipeline against `cwd` (the standby directory). Steps
107
+ * run in the order documented in the task-5 brief (with db-strategy
108
+ * resolution/validation moved earlier, before git pull, so a bad `--db`
109
+ * fails fast); any failure throws `BuildAbortError` immediately. The state
110
+ * file's `last_build`/`last_build_status` is updated regardless of outcome
111
+ * (success path included), via a `finally` so a thrown error is never
112
+ * swallowed.
113
+ */
114
+ export function runBuild(config, runner, opts = {}) {
115
+ const cwd = path.resolve(opts.cwd ?? process.cwd());
116
+ const branch = opts.branch ?? config.branch;
117
+ const healthCheckAttempts = opts.healthCheckAttempts ?? DEFAULT_HEALTH_CHECK_ATTEMPTS;
118
+ const healthCheckDelayMs = opts.healthCheckDelayMs ?? DEFAULT_HEALTH_CHECK_DELAY_MS;
119
+ const warnings = [];
120
+ const steps = [];
121
+ function pass(name, detail) {
122
+ steps.push({ name, status: 'pass', detail });
123
+ }
124
+ function abort(name, message) {
125
+ steps.push({ name, status: 'fail', detail: message });
126
+ throw new BuildAbortError(message, steps);
127
+ }
128
+ /**
129
+ * Run a risky operation (anything touching CommandRunner or an external
130
+ * resolver) and convert ANY throw into the same BuildAbortError path a
131
+ * threshold-check abort() takes — so a real git/npm/pm2/curl failure also
132
+ * gets a pushed `fail` step and a printed summary, not a bare Error that
133
+ * skips both. A BuildAbortError thrown from inside `run` (i.e. `abort()`
134
+ * was already called deeper in the same step) passes through unchanged
135
+ * rather than double-reporting.
136
+ */
137
+ function runStep(name, run) {
138
+ try {
139
+ return run();
140
+ }
141
+ catch (e) {
142
+ if (e instanceof BuildAbortError)
143
+ throw e;
144
+ const msg = e instanceof Error ? e.message : String(e);
145
+ return abort(name, msg);
146
+ }
147
+ }
148
+ let buildStatus = 'failed';
149
+ try {
150
+ // Guard: refuse to run anything at all if the (authoritative) state file
151
+ // says `cwd` isn't the standby dir. Running the pipeline against the
152
+ // live dir would git-pull/rebuild the running production tree and, for
153
+ // the sqlite "copy" strategy, overwrite the live DB with the standby's
154
+ // stale one. An explicit --peer-dir still only overrides which dir is
155
+ // treated as "live" for the copy/stop-prod target — it never overrides
156
+ // this check.
157
+ const state = readState(config.app_name);
158
+ if (state && path.resolve(state.standby_dir) !== cwd) {
159
+ abort('standby-dir-guard', `deploy build must be run from the standby directory (${state.standby_dir}), not ${cwd}. ` +
160
+ `Running it here would git pull / install / rebuild the live tree and, for a sqlite "copy" ` +
161
+ `db_strategy, overwrite the live database. cd into the standby dir and re-run.`);
162
+ }
163
+ const liveDir = opts.peerDir
164
+ ? resolvePeerDir(cwd, opts.peerDir)
165
+ : state
166
+ ? path.resolve(state.live_dir)
167
+ : resolvePeerDir(cwd, opts.peerDir);
168
+ // Step 1: auto-clean, then check disk free against min_disk_mb.
169
+ const cleanResult = autoClean(config, runner);
170
+ pass('clean', `reclaimed ${cleanResult.totalBytesReclaimed} bytes across ${cleanResult.targets.length} targets`);
171
+ warnings.push(...cleanResult.warnings);
172
+ const diskFreeMb = queryDiskFreeMb(runner, cwd, warnings);
173
+ if (diskFreeMb !== undefined && diskFreeMb < config.min_disk_mb) {
174
+ abort('disk-check', `Disk free (${diskFreeMb} MB) is still below min_disk_mb (${config.min_disk_mb}) after cleanup.`);
175
+ }
176
+ pass('disk-check', diskFreeMb !== undefined ? `${diskFreeMb} MB free` : 'unknown — skipping check');
177
+ // Step 2/3: memory check, optionally freed by stopping the live PM2 process.
178
+ let memoryFreeMb = queryMemoryFreeMb(runner, warnings);
179
+ let memoryLow = memoryFreeMb !== undefined && memoryFreeMb < config.min_memory_mb;
180
+ if (memoryLow) {
181
+ if (opts.stopProd) {
182
+ runStep('stop-prod', () => runner.exec(`pm2 stop ${config.app_name}`, { cwd: liveDir }));
183
+ pass('stop-prod', `stopped "${config.app_name}" in ${liveDir}`);
184
+ memoryFreeMb = queryMemoryFreeMb(runner, warnings);
185
+ memoryLow = memoryFreeMb !== undefined && memoryFreeMb < config.min_memory_mb;
186
+ }
187
+ if (memoryLow) {
188
+ const freeDesc = memoryFreeMb !== undefined ? `${memoryFreeMb} MB` : 'unknown';
189
+ const suggestionLines = SWAP_INCREASE_SUGGESTIONS.map((c) => ` ${c}`).join('\n');
190
+ const hint = opts.stopProd
191
+ ? 'Stopping the live process did not free enough memory.'
192
+ : 'Re-run with --stop-prod to free memory by stopping the live process, or increase swap:';
193
+ abort('memory-check', `Free memory (${freeDesc}) is below min_memory_mb (${config.min_memory_mb}). ${hint}\n${suggestionLines}`);
194
+ }
195
+ }
196
+ pass('memory-check', memoryFreeMb !== undefined ? `${memoryFreeMb} MB free` : 'unknown — skipping check');
197
+ // Step (moved earlier): resolve/validate the db target BEFORE paying for
198
+ // git pull/install/build (and before --stop-prod has taken production
199
+ // down) — a typo'd --db should fail loudly and immediately.
200
+ const dbConfig = runStep('db-resolve', () => resolveDbConfig(opts));
201
+ const dbStrategyResolved = config.db_strategy === 'auto' ? (dbConfig.type === 'sqlite' ? 'copy' : 'shared') : config.db_strategy;
202
+ if (dbStrategyResolved === 'copy' && (dbConfig.type !== 'sqlite' || !dbConfig.sqlite)) {
203
+ abort('db-resolve', `db_strategy resolved to "copy" but the resolved db config is type "${dbConfig.type}", not sqlite.`);
204
+ }
205
+ pass('db-resolve', `strategy=${dbStrategyResolved}${opts.db ? ` db=${opts.db}` : ''}`);
206
+ // Step 4: git pull
207
+ runStep('git-pull', () => runner.exec(`git pull origin ${branch}`, { cwd }));
208
+ pass('git-pull', `origin ${branch}`);
209
+ // Step 5: install
210
+ runStep('install', () => runner.exec(config.install_cmd, { cwd }));
211
+ pass('install', config.install_cmd);
212
+ // Step 6: pre-build
213
+ runStep('pre-build', () => runner.exec(config.pre_build_cmd, { cwd }));
214
+ pass('pre-build', config.pre_build_cmd);
215
+ // Step 7: build
216
+ runStep('build', () => runner.exec(config.build_cmd, { cwd }));
217
+ pass('build', config.build_cmd);
218
+ // Step 8: DB setup. `dbConfig`/`dbStrategyResolved` were already
219
+ // resolved and validated above.
220
+ if (dbStrategyResolved === 'copy') {
221
+ // sqlite!.database_path is guaranteed by the db-resolve validation above.
222
+ const standbyDbPath = toAbsolute(cwd, dbConfig.sqlite.database_path);
223
+ const liveDbPath = reroot(cwd, liveDir, standbyDbPath);
224
+ if (liveDbPath === standbyDbPath) {
225
+ // The db path isn't nested under the standby dir at all (e.g. an
226
+ // absolute [data] root shared by both live and standby) — there's
227
+ // no per-directory copy of it to re-root onto the live dir, so
228
+ // treat it as already-shared storage and skip the copy rather than
229
+ // running a same-path no-op command.
230
+ pass('db-setup', `sqlite db path is outside the live/standby split (shared) — skipping copy: ${standbyDbPath}`);
231
+ }
232
+ else {
233
+ runStep('db-setup', () => {
234
+ const sourceCheck = runner.spawn(`test -f ${JSON.stringify(liveDbPath)}`);
235
+ if (sourceCheck.code !== 0) {
236
+ throw new Error(`Source sqlite db not found at ${liveDbPath} (live dir) — cannot back it up.`);
237
+ }
238
+ const destDir = path.dirname(standbyDbPath);
239
+ const destDirCheck = runner.spawn(`test -d ${JSON.stringify(destDir)}`);
240
+ if (destDirCheck.code !== 0) {
241
+ throw new Error(`Destination directory ${destDir} does not exist in the standby dir (data/ is typically ` +
242
+ `gitignored on a fresh clone) — create it before running deploy build.`);
243
+ }
244
+ // sqlite3's ".backup" takes a consistent point-in-time snapshot
245
+ // regardless of WAL state — unlike a plain `cp`, which can tear a
246
+ // live WAL-mode database mid-write (the exact corruption class
247
+ // this project has already been burned by once for a different
248
+ // reason: never cp/scp a live WAL-mode sqlite file).
249
+ runner.exec(`sqlite3 ${JSON.stringify(liveDbPath)} ${JSON.stringify(`.backup ${standbyDbPath}`)}`);
250
+ });
251
+ pass('db-setup', `sqlite backup ${liveDbPath} -> ${standbyDbPath}`);
252
+ }
253
+ }
254
+ else {
255
+ pass('db-setup', `postgres: using resolved [db.${opts.db ?? '(current env)'}] config -> ${dbConfig.postgrest?.base_url ?? '(no base_url)'}`);
256
+ }
257
+ if (config.migrate_cmd) {
258
+ runStep('migrate', () => runner.exec(config.migrate_cmd, { cwd }));
259
+ pass('migrate', config.migrate_cmd);
260
+ }
261
+ else {
262
+ pass('migrate', 'no migrate_cmd configured — assuming schema bootstrap runs automatically at app startup');
263
+ }
264
+ // Step 9: start the app on the staging port, under a name distinct from
265
+ // the live process. `pm2 start ecosystem.config.js --name X` does NOT
266
+ // actually rename the process when starting from a config file — pm2
267
+ // reads the name from the file's own `apps[].name` field in that mode
268
+ // and ignores the CLI --name override, so that would have silently
269
+ // restarted (or no-op'd against) whatever's already registered under
270
+ // the ecosystem file's real name. startNamedPm2Process works around
271
+ // this by cloning the ecosystem config with the new name/cwd/port baked
272
+ // in and starting pm2 from THAT clone instead — see pm2-start.ts's
273
+ // header for the full why.
274
+ const stagingProcessName = `${config.app_name}-staging`;
275
+ runStep('start-staging', () => startNamedPm2Process(runner, { dir: cwd, name: stagingProcessName, port: config.staging_port }));
276
+ pass('start-staging', `name=${stagingProcessName} PORT=${config.staging_port}, cwd=${cwd}`);
277
+ // Step 10: health check, retried — pm2 start returns before the app has
278
+ // actually finished booting.
279
+ const stagingUrl = `http://localhost:${config.staging_port}`;
280
+ const healthUrl = `${stagingUrl}${config.health_url}`;
281
+ const healthResult = runStep('health-check', () => checkHealth(runner, healthUrl, healthCheckAttempts, healthCheckDelayMs));
282
+ if (!healthResult.ok) {
283
+ abort('health-check', `Health check at ${healthUrl} returned "${healthResult.lastCode}" (expected 200) after ${healthCheckAttempts} attempt(s).`);
284
+ }
285
+ pass('health-check', `${healthUrl} -> 200 (attempt ${healthResult.attempts}/${healthCheckAttempts})`);
286
+ buildStatus = 'success';
287
+ return { steps, stagingPort: config.staging_port, stagingUrl, dbStrategyResolved, warnings };
288
+ }
289
+ finally {
290
+ try {
291
+ updateState(config.app_name, { last_build: new Date().toISOString(), last_build_status: buildStatus });
292
+ }
293
+ catch {
294
+ // No state file yet (deploy init was never run) — build still ran;
295
+ // state bookkeeping is best-effort and must never mask the real
296
+ // pipeline error (or success) above.
297
+ }
298
+ }
299
+ }
@@ -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,6 @@
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
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/deploy/index.ts"],"names":[],"mappings":"AACA,cAAc,YAAY,CAAC;AAC3B,cAAc,YAAY,CAAC;AAC3B,cAAc,aAAa,CAAC;AAC5B,cAAc,WAAW,CAAC;AAC1B,cAAc,gBAAgB,CAAC"}
@@ -0,0 +1,6 @@
1
+ // hazo_env/src/deploy/index.ts — Deploy module barrel export
2
+ export * from './types.js';
3
+ export * from './state.js';
4
+ export * from './runner.js';
5
+ export * from './peer.js';
6
+ export * from './pm2-start.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
@@ -0,0 +1 @@
1
+ {"version":3,"file":"init.d.ts","sourceRoot":"","sources":["../../src/deploy/init.ts"],"names":[],"mappings":"AAmBA,OAAO,KAAK,EAAE,aAAa,EAAE,YAAY,EAAe,MAAM,YAAY,CAAC;AAsC3E,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;AAED;;;;;GAKG;AACH,wBAAgB,OAAO,CAAC,MAAM,EAAE,YAAY,EAAE,MAAM,EAAE,aAAa,EAAE,IAAI,GAAE,cAAmB,GAAG,aAAa,CA8B7G"}
@@ -0,0 +1,80 @@
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 { resolvePeerDir } from './peer.js';
18
+ import { writeState } from './state.js';
19
+ const CONFIG_RELATIVE_PATH = path.join('config', 'hazo_env_config.ini');
20
+ /**
21
+ * Blue<->green swap applied to the `dir_suffix = <value>` VALUE in the INI
22
+ * (as opposed to peer.ts's swapColorSuffix, which swaps a "-blue"/"-green"
23
+ * suffix on a directory *basename*). Kept identical to peer.ts's internal
24
+ * SUFFIX_SWAP map — update both together if the color vocabulary ever
25
+ * changes.
26
+ */
27
+ const COLOR_SWAP = {
28
+ blue: 'green',
29
+ green: 'blue',
30
+ };
31
+ function swapDirSuffixValue(value) {
32
+ const swapped = COLOR_SWAP[value];
33
+ if (!swapped) {
34
+ throw new Error(`Cannot swap dir_suffix "${value}" in hazo_env_config.ini: expected "blue" or "green".`);
35
+ }
36
+ return swapped;
37
+ }
38
+ /**
39
+ * Swap the `dir_suffix = <value>` line in the INI's [deploy] section to its
40
+ * blue/green opposite, leaving every other byte of the file untouched.
41
+ */
42
+ function swapDirSuffixInIni(iniContent) {
43
+ const pattern = /^(\s*dir_suffix\s*=\s*)(\S+)(\s*)$/m;
44
+ const match = iniContent.match(pattern);
45
+ if (!match) {
46
+ throw new Error('Could not find a "dir_suffix = ..." line in hazo_env_config.ini to swap.');
47
+ }
48
+ const swapped = swapDirSuffixValue(match[2]);
49
+ return iniContent.replace(pattern, `$1${swapped}$3`);
50
+ }
51
+ /**
52
+ * Create the peer (standby) directory: resolve its path, abort if it
53
+ * already exists, clone the repo into it, copy the INI config across with
54
+ * `dir_suffix` flipped, and write the initial state file marking the
55
+ * current directory as live.
56
+ */
57
+ export function runInit(config, runner, opts = {}) {
58
+ const currentDir = path.resolve(opts.cwd ?? process.cwd());
59
+ const peerDir = resolvePeerDir(currentDir, opts.peerDir);
60
+ if (fs.existsSync(peerDir)) {
61
+ 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.`);
62
+ }
63
+ const originUrl = runner.exec('git remote get-url origin', { cwd: currentDir });
64
+ runner.exec(`git clone ${JSON.stringify(originUrl)} ${JSON.stringify(peerDir)}`, { cwd: currentDir });
65
+ const currentIniPath = path.join(currentDir, CONFIG_RELATIVE_PATH);
66
+ const peerIniPath = path.join(peerDir, CONFIG_RELATIVE_PATH);
67
+ const iniContent = fs.readFileSync(currentIniPath, 'utf-8');
68
+ const swappedIni = swapDirSuffixInIni(iniContent);
69
+ fs.mkdirSync(path.dirname(peerIniPath), { recursive: true });
70
+ fs.writeFileSync(peerIniPath, swappedIni, 'utf-8');
71
+ const state = {
72
+ app_name: config.app_name,
73
+ live_dir: currentDir,
74
+ live_port: config.prod_port,
75
+ standby_dir: peerDir,
76
+ staging_port: config.staging_port,
77
+ };
78
+ writeState(state);
79
+ return { currentDir, peerDir, originUrl };
80
+ }
@@ -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"}