@selvajs/selva 4.21.0-beta.14 → 4.21.0-beta.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/adapter-node.js +1 -1
- package/build/client/_app/immutable/entry/{app.CTLPmTNX.js → app.B1zrk4oJ.js} +2 -2
- package/build/client/_app/immutable/entry/app.B1zrk4oJ.js.br +0 -0
- package/build/client/_app/immutable/entry/app.B1zrk4oJ.js.gz +0 -0
- package/build/client/_app/immutable/nodes/{15.CKO0EYPJ.js → 15.CEROqZ8B.js} +1 -1
- package/build/client/_app/immutable/nodes/15.CEROqZ8B.js.br +0 -0
- package/build/client/_app/immutable/nodes/15.CEROqZ8B.js.gz +0 -0
- package/build/client/_app/version.json +1 -1
- package/build/client/_app/version.json.br +0 -0
- package/build/client/_app/version.json.gz +0 -0
- package/build/server/chunks/instance.js +3 -3
- package/build/server/chunks/internal.js +1 -1
- package/build/server/chunks/package.js +1 -1
- package/build/server/chunks/package.js.map +1 -1
- package/build/server/chunks/update-outcome.js +24 -7
- package/build/server/chunks/update-outcome.js.map +1 -1
- package/build/server/entries/endpoints/api/admin/system/update/_server.ts.js +99 -25
- package/build/server/entries/endpoints/api/admin/system/update/_server.ts.js.map +1 -1
- package/build/server/manifest-full.js +1 -1
- package/build/server/manifest.js +1 -1
- package/build/server/nodes/15.js +1 -1
- package/build/server/server.js +1 -1
- package/package.json +7 -7
- package/templates/ecosystem.config.cjs +2 -0
- package/build/client/_app/immutable/entry/app.CTLPmTNX.js.br +0 -0
- package/build/client/_app/immutable/entry/app.CTLPmTNX.js.gz +0 -0
- package/build/client/_app/immutable/nodes/15.CKO0EYPJ.js.br +0 -0
- package/build/client/_app/immutable/nodes/15.CKO0EYPJ.js.gz +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"update-outcome.js","names":[],"sources":["../../../src/lib/update-outcome.ts"],"sourcesContent":["// ============================================================================\n// Update-outcome derivation\n// ============================================================================\n//\n// The update runner (admin/api/system/update/+server.ts) emits structured log\n// lines and a small set of meaningful exit codes; `deriveOutcome` turns those\n// into a severity an operator can act on without reading the log. Ranking:\n// anything that leaves the app DOWN is `critical`; a safe rollback is\n// `warning`, not an error, because the site is still serving.\n\nexport type OutcomeSeverity = 'success' | 'info' | 'warning' | 'critical' | 'pending';\n\n/**\n * Synthetic exit code for a run that never reported one — the SSE handler's\n * 15-minute group-kill, or the reconciler giving up on a missing [EXIT] marker.\n * Outside the 0-255 range a real process can produce, so it can't collide.\n */\nexport const TIMED_OUT = -2;\n\nexport interface UpdateOutcome {\n\tseverity: OutcomeSeverity;\n\t/** Must be unambiguous about app up/down state. */\n\ttitle: string;\n\t/** What to do next when something is off. */\n\tdetail?: string;\n\tfrom?: string;\n\tto?: string;\n}\n\nfunction firstMatch(logs: string, re: RegExp): string | undefined {\n\tconst m = re.exec(logs);\n\treturn m ? m[1] : undefined;\n}\n\nfunction parseVersions(logs: string): { from?: string; to?: string } {\n\t// Pre-flight transition line, printed before npm runs — the only source of a\n\t// target version when the update fails early or is a no-op, e.g.\n\t// \"[INFO] Target (beta): 4.2.0 → 4.2.1-beta.1\". `Available:` is the\n\t// pre-channel spelling, kept so logs from an older runner still parse.\n\tconst version = String.raw`\\d+\\.\\d+\\.\\d+[^\\s]*`;\n\tconst transition = new RegExp(\n\t\tString.raw`(?:Target \\([^)]*\\)|Available):\\s*(${version})\\s*(?:→|->)\\s*(${version})`\n\t);\n\tconst arrow = transition.exec(logs);\n\n\t// The post-install lines are authoritative for what actually landed — prefer\n\t// them over the pre-flight target, which is only ever an intent.\n\tconst from = firstMatch(logs, /Current @selvajs\\/selva:\\s*v?(\\d+\\.\\d+\\.\\d+[^\\s]*)/) ?? arrow?.[1];\n\tconst to = firstMatch(logs, /New @selvajs\\/selva:\\s*v?(\\d+\\.\\d+\\.\\d+[^\\s]*)/) ?? arrow?.[2];\n\treturn { from, to };\n}\n\nfunction has(logs: string, needle: string): boolean {\n\treturn logs.includes(needle);\n}\n\nexport function deriveOutcome(exitCode: number | null, logs: string): UpdateOutcome {\n\tconst { from, to } = parseVersions(logs);\n\n\tif (exitCode === null) {\n\t\treturn { severity: 'pending', title: 'Update in progress…' };\n\t}\n\n\t// --- Critical: app is or may be DOWN. Rank these first. -------------------\n\tif (\n\t\texitCode === 6 ||\n\t\thas(logs, 'Manual recovery required') ||\n\t\thas(logs, 'manual intervention required')\n\t) {\n\t\treturn {\n\t\t\tseverity: 'critical',\n\t\t\ttitle: 'Update failed AND rollback failed — the app may be OFFLINE',\n\t\t\tdetail:\n\t\t\t\t'Both the new version and the rollback failed their health check. ' +\n\t\t\t\t'SSH into the server and run: `pm2 logs selva-compute`, then ' +\n\t\t\t\t'`pm2 start ecosystem.config.cjs` from the deployment directory.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\t// The SSE handler's 15-minute group-kill, and the reconciler's own poll cap.\n\t// Neither is an exit code the runner chose, so they carry no [EXIT] marker.\n\tif (exitCode === TIMED_OUT) {\n\t\treturn {\n\t\t\tseverity: 'critical',\n\t\t\ttitle: 'App did not come back online within 15 minutes',\n\t\t\tdetail:\n\t\t\t\t'The update may still be finishing in the background, or the new ' +\n\t\t\t\t'process is crash-looping. Check `pm2 logs selva-compute`. Do not ' +\n\t\t\t\t're-run the update until you have confirmed the current state.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\t// Exit 4: the rollback's own npm install failed, so node_modules is\n\t// half-written and the EXIT trap's restart is the only thing that may have\n\t// brought the app back. Same urgency as a failed rollback restart.\n\tif (exitCode === 4) {\n\t\treturn {\n\t\t\tseverity: 'critical',\n\t\t\ttitle: 'Update failed and the rollback could not reinstall — the app may be OFFLINE',\n\t\t\tdetail:\n\t\t\t\t'The previous version could not be restored from npm. SSH into the ' +\n\t\t\t\t'server and run `pm2 logs selva-compute`; if the app is down, reinstall ' +\n\t\t\t\t'explicitly with `npm install --prefer-online @selvajs/cli@<version> ' +\n\t\t\t\t'@selvajs/selva@<version>` from the deployment directory.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\t// Exit 3: unhealthy with no recorded prior version, so no rollback was even\n\t// attempted. The EXIT trap tried to restart whatever is on disk.\n\tif (exitCode === 3) {\n\t\treturn {\n\t\t\tseverity: 'critical',\n\t\t\ttitle: 'Update failed its health check and could not be rolled back automatically',\n\t\t\tdetail:\n\t\t\t\t'No prior version was recorded, so the previous build could not be ' +\n\t\t\t\t'restored. Check `pm2 logs selva-compute` to confirm whether the app ' +\n\t\t\t\t'came back online.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\n\t// Killed mid-run (128+signal). Nothing was installed, and whether the app\n\t// came back depends on how far the EXIT trap got before it died too. Rank\n\t// with the criticals: an unattended half-update is worse than a clean\n\t// failure.\n\tif (exitCode === 143 || exitCode === 130 || exitCode === 129 || has(logs, 'KILLED')) {\n\t\treturn {\n\t\t\tseverity: 'critical',\n\t\t\ttitle: 'Update was killed before it finished — nothing was installed',\n\t\t\tdetail:\n\t\t\t\t'The runner was terminated mid-update, most often by a systemd-supervised ' +\n\t\t\t\t'PM2 restarting its whole control group. The version on disk is unchanged. ' +\n\t\t\t\t'Check `pm2 logs selva-compute` and confirm the app is online before retrying; ' +\n\t\t\t\t'if a global pm2 owns the daemon, reconcile that first.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\n\t// --- Warning: update did not fully succeed, but the app IS up. ------------\n\t// Aborted at the systemd guard, before `pm2 update` could recycle the\n\t// daemon and take this runner down with it.\n\tif (exitCode === 9 || has(logs, 'SYSTEMD_PM2')) {\n\t\treturn {\n\t\t\tseverity: 'warning',\n\t\t\ttitle:\n\t\t\t\t'Update cancelled — PM2 needs a resync that only a shell can do safely. The app is untouched.',\n\t\t\tdetail:\n\t\t\t\t\"This deployment's PM2 runs under systemd, where `pm2 update` restarts the \" +\n\t\t\t\t'unit and kills the update mid-run. Nothing was installed and the app is ' +\n\t\t\t\t'still serving. SSH in and run `./node_modules/.bin/pm2 update` from the ' +\n\t\t\t\t'deployment directory, then retry the update here.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\t// Aborted at the data format check, before anything was stopped.\n\tif (exitCode === 10 || has(logs, 'DATA_FORMAT:')) {\n\t\tconst target = firstMatch(logs, /reads data format (\\d+),/);\n\t\tconst installed = firstMatch(logs, /this deployment is on format (\\d+)\\./);\n\t\treturn {\n\t\t\tseverity: 'warning',\n\t\t\ttitle: `Update cancelled — ${to ?? 'the target version'} cannot read this deployment's data. The app is untouched.`,\n\t\t\tdetail:\n\t\t\t\t(target && installed\n\t\t\t\t\t? `It reads data format ${target}; this deployment is on format ${installed}. `\n\t\t\t\t\t: '') +\n\t\t\t\t'Installing it would leave stored data, such as Compute API keys, unreadable. ' +\n\t\t\t\t'Switch the release channel back to stay on the installed version. To go back ' +\n\t\t\t\t'anyway, follow \"Going back to an older release\" in the admin guide.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\t// Aborted at the pm2 skew check, before anything was stopped — nothing was\n\t// installed and the app never went down.\n\tif (exitCode === 8 || has(logs, 'PM2_SKEW')) {\n\t\tconst daemon = firstMatch(logs, /daemon \\(v(\\d+\\.\\d+\\.\\d+)\\)/);\n\t\tconst local = firstMatch(logs, /deployment's pm2 \\(v(\\d+\\.\\d+\\.\\d+)\\)/);\n\t\treturn {\n\t\t\tseverity: 'warning',\n\t\t\ttitle:\n\t\t\t\tdaemon && local\n\t\t\t\t\t? `Update cancelled — a global PM2 (v${daemon}) owns the daemon, not this deployment's (v${local}). The app is untouched.`\n\t\t\t\t\t: 'Update cancelled — a conflicting global PM2 owns the daemon. The app is untouched.',\n\t\t\tdetail:\n\t\t\t\t'Resyncing would have downgraded the daemon and dropped its process ' +\n\t\t\t\t'table, so the update stopped before taking the app down. On the server: ' +\n\t\t\t\t'`which -a pm2`, `pm2 -v`, `pm2 ping` — remove or align the global pm2, then retry.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\t// A rollback whose cause is the DATABASE, not the release. Ranked ahead of\n\t// the generic rollback case: \"review the log before retrying\" is actively\n\t// misleading here, because the log holds nothing about the new version —\n\t// it is fine, and retrying without touching the database repeats verbatim.\n\tif (has(logs, 'SCHEMA_SKEW')) {\n\t\tconst expected = firstMatch(logs, /expects database migration head (\\S+?),/);\n\t\tconst actual = firstMatch(logs, /this database is at (\\S+?)\\./);\n\t\tconst skew =\n\t\t\texpected && actual ? ` The database is at ${actual}; ${to ?? 'it'} needs ${expected}.` : '';\n\t\t// `latest` is the stable line, which ships none of a beta's migrations.\n\t\tconst providerTag =\n\t\t\tfirstMatch(logs, /@selvajs\\/supabase-provider@([\\w.-]+)/) ??\n\t\t\t(has(logs, 'channel: beta') ? 'beta' : 'latest');\n\t\treturn {\n\t\t\tseverity: 'warning',\n\t\t\ttitle: `Update rolled back — the database migrations for ${to ?? 'the new version'} have not been applied.${skew} The app is online${from ? ` on ${from}` : ''}.`,\n\t\t\tdetail:\n\t\t\t\t'Nothing is wrong with the new version. Selva does not apply migrations ' +\n\t\t\t\t'during an update, because they cannot be rolled back — auto-migrating ' +\n\t\t\t\t'and then rolling the code back would leave the app and database on ' +\n\t\t\t\t'different heads. Apply them on the server, then re-run this update: ' +\n\t\t\t\t`\\`npm install --prefer-online @selvajs/supabase-provider@${providerTag}\\`, then ` +\n\t\t\t\t'`npx selva-supabase`, then `npx supabase db push`. The provider install ' +\n\t\t\t\t'is not optional — the migration SQL ships inside that package, and the ' +\n\t\t\t\t'update only moves @selvajs/cli and @selvajs/selva, so a sync without it ' +\n\t\t\t\t'copies nothing and the push reports \"up to date\" having done nothing. ' +\n\t\t\t\t'Retrying without this will fail in exactly the same way.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\t// Same shape: the rollback was caused by host configuration, not the release.\n\tif (has(logs, 'AT_REST_SECRETS')) {\n\t\treturn {\n\t\t\tseverity: 'warning',\n\t\t\ttitle: `Update rolled back — stored compute server keys do not decrypt under this host's SELVA_AT_REST_KEY. The app is online${from ? ` on ${from}` : ''}.`,\n\t\t\tdetail:\n\t\t\t\t'This is a configuration problem on the server, not a fault in the new ' +\n\t\t\t\t'version, so retrying alone will fail identically. Re-enter the affected ' +\n\t\t\t\t'keys at /admin/compute, or restore the SELVA_AT_REST_KEY the values were ' +\n\t\t\t\t'encrypted with, then re-run the update.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\tif (exitCode === 5 || has(logs, 'Rolled back')) {\n\t\treturn {\n\t\t\tseverity: 'warning',\n\t\t\ttitle: `Update failed — safely rolled back${from ? ` to ${from}` : ''}. The app is online.`,\n\t\t\tdetail:\n\t\t\t\t'The new version failed its health check, so the previous version ' +\n\t\t\t\t'was restored and is serving normally. Review the log below for why ' +\n\t\t\t\t'the new version failed before retrying.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\t// The install completed and the app is up, but on a Node the release doesn't\n\t// support. The health probe passes (it exercises nothing version-specific),\n\t// so this would otherwise read as a clean success right up until a real\n\t// request hits a newer API and throws (issue #176).\n\tif (has(logs, 'ENGINE_MISMATCH') || has(logs, 'EBADENGINE')) {\n\t\tconst required = firstMatch(logs, /requires Node ([^\\s]+(?:\\s*[<>=]+\\s*[\\d.]+)*)/);\n\t\tconst running = firstMatch(logs, /this host runs v?(\\d+\\.\\d+\\.\\d+)/);\n\t\treturn {\n\t\t\tseverity: 'warning',\n\t\t\ttitle: running\n\t\t\t\t? `Updated${to ? ` to ${to}` : ''}, but this release needs Node ${required ?? '(newer)'} — the host runs v${running}. Expect runtime failures.`\n\t\t\t\t: `Updated${to ? ` to ${to}` : ''}, but this release requires a newer Node than the host provides. Expect runtime failures.`,\n\t\t\tdetail:\n\t\t\t\t'npm installed it anyway (engine-strict is off) and the health check ' +\n\t\t\t\t'passed, but it does not exercise the newer APIs — routes that do will ' +\n\t\t\t\t'throw at request time. Upgrade Node on the server, then re-run the update.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\t// The runner moved pm2 to the release's pin but could not swap the daemon\n\t// (refused under systemd, or `pm2 update` failed). The app runs; the next\n\t// pm2 command warns about the skew until someone runs the swap by hand.\n\tif (has(logs, 'PM2_RESYNC_NEEDED')) {\n\t\treturn {\n\t\t\tseverity: 'warning',\n\t\t\ttitle: `Updated${to ? ` to ${to}` : ''}, but the pm2 daemon still runs the old pm2.`,\n\t\t\tdetail:\n\t\t\t\t'The app is online. On the server, run `npx pm2 update` in the deployment ' +\n\t\t\t\t'directory, let it finish, then check `npx pm2 list` shows selva-compute online.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\tif (has(logs, 'PM2_PIN_FAILED')) {\n\t\treturn {\n\t\t\tseverity: 'warning',\n\t\t\ttitle: `Updated${to ? ` to ${to}` : ''}, but pm2 stayed on the previous version.`,\n\t\t\tdetail:\n\t\t\t\t'The app is online on the old pm2. On the server, run `npx selva migrate` in ' +\n\t\t\t\t'the deployment directory to move it to the pinned version.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\tif (has(logs, 'npm cache may be stale') || has(logs, 'No version change')) {\n\t\treturn {\n\t\t\tseverity: 'warning',\n\t\t\ttitle: 'No version change — npm installed the same version.',\n\t\t\tdetail:\n\t\t\t\t'Your npm cache may be stale. On the server: `npm cache clean --force`, ' +\n\t\t\t\t'remove node_modules + package-lock.json, then `npm install --prefer-online`.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\n\t// --- Success variants -----------------------------------------------------\n\tif (exitCode === 0) {\n\t\t// \"Already on the 'beta' channel version (4.2.0)\" — the channel name is\n\t\t// interpolated, so match the stable prefix rather than a whole line.\n\t\tif (has(logs, 'Already on the') || has(logs, 'Nothing to do')) {\n\t\t\treturn {\n\t\t\t\tseverity: 'info',\n\t\t\t\ttitle: `Already up to date${from ? ` (${from})` : ''} — nothing to install.`,\n\t\t\t\tdetail: 'No changes were made and the app was not restarted.',\n\t\t\t\tfrom,\n\t\t\t\tto\n\t\t\t};\n\t\t}\n\t\tif (from && to && from !== to) {\n\t\t\treturn {\n\t\t\t\tseverity: 'success',\n\t\t\t\ttitle: `Updated ${from} → ${to}. The app is back online.`,\n\t\t\t\tfrom,\n\t\t\t\tto\n\t\t\t};\n\t\t}\n\t\tif (to) {\n\t\t\treturn {\n\t\t\t\tseverity: 'success',\n\t\t\t\ttitle: `Update complete — now on ${to}. The app is back online.`,\n\t\t\t\tfrom,\n\t\t\t\tto\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\tseverity: 'success',\n\t\t\ttitle: 'Update completed and the app is back online.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\n\t// --- Anything else: a non-zero exit we don't have a named case for. -------\n\t// Be explicit that we couldn't classify it rather than implying success.\n\treturn {\n\t\tseverity: 'critical',\n\t\ttitle: `Update failed (exit code ${exitCode}).`,\n\t\tdetail:\n\t\t\t'The update did not complete cleanly. Review the log below, and check ' +\n\t\t\t'`pm2 logs selva-compute` to confirm whether the app is currently online.',\n\t\tfrom,\n\t\tto\n\t};\n}\n"],"mappings":"AA6BA,SAAS,WAAW,MAAc,IAAgC;CACjE,MAAM,IAAI,GAAG,KAAK,IAAI;CACtB,OAAO,IAAI,EAAE,KAAK,KAAA;AACnB;AAEA,SAAS,cAAc,MAA8C;CAKpE,MAAM,UAAU,OAAO,GAAG;CAI1B,MAAM,QAAQ,IAHS,OACtB,OAAO,GAAG,sCAAsC,QAAQ,kBAAkB,QAAQ,EAErE,CAAA,CAAW,KAAK,IAAI;CAMlC,OAAO;EAAE,MAFI,WAAW,MAAM,oDAAoD,KAAK,QAAQ;EAEhF,IADJ,WAAW,MAAM,gDAAgD,KAAK,QAAQ;CACvE;AACnB;AAEA,SAAS,IAAI,MAAc,QAAyB;CACnD,OAAO,KAAK,SAAS,MAAM;AAC5B;AAEA,SAAgB,cAAc,UAAyB,MAA6B;CACnF,MAAM,EAAE,MAAM,OAAO,cAAc,IAAI;CAEvC,IAAI,aAAa,MAChB,OAAO;EAA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A;CACD;CAID,IAAI,aAAa,GAAG;EAGnB,IAAI,IAAI,MAAM,gBAAgB,KAAK,IAAI,MAAM,eAAe,GAC3D,OAAO;GACN,UAAU;GACV,OAAO,qBAAqB,OAAO,KAAK,KAAK,KAAK,GAAG;GACrD,QAAQ;GACR;GACA;EACD;EAED,IAAI,QAAQ,MAAM,SAAS,IAC1B,OAAO;GACN,UAAU;GACV,OAAO,WAAW,KAAK,KAAK,GAAG;GAC/B;GACA;EACD;EAED,IAAI,IACH,OAAO;GACN,UAAU;GACV,OAAO,4BAA4B,GAAG;GACtC;GACA;EACD;EAED,OAAO;GACN,UAAU;GACV,OAAO;GACP;GACA;EACD;CACD;CAIA,OAAO;EACN,UAAU;EACV,OAAO,4BAA4B,SAAS;EAC5C,QACC;EAED;EACA;CACD;AACD"}
|
|
1
|
+
{"version":3,"file":"update-outcome.js","names":[],"sources":["../../../src/lib/update-outcome.ts"],"sourcesContent":["// ============================================================================\n// Update-outcome derivation\n// ============================================================================\n//\n// The update runner (admin/api/system/update/+server.ts) emits structured log\n// lines and a small set of meaningful exit codes; `deriveOutcome` turns those\n// into a severity an operator can act on without reading the log. Ranking:\n// anything that leaves the app DOWN is `critical`; a safe rollback is\n// `warning`, not an error, because the site is still serving.\n\nexport type OutcomeSeverity = 'success' | 'info' | 'warning' | 'critical' | 'pending';\n\n/**\n * Synthetic exit code for a run that never reported one — the SSE handler's\n * 15-minute group-kill, or the reconciler giving up on a missing [EXIT] marker.\n * Outside the 0-255 range a real process can produce, so it can't collide.\n */\nexport const TIMED_OUT = -2;\n\nexport interface UpdateOutcome {\n\tseverity: OutcomeSeverity;\n\t/** Must be unambiguous about app up/down state. */\n\ttitle: string;\n\t/** What to do next when something is off. */\n\tdetail?: string;\n\tfrom?: string;\n\tto?: string;\n}\n\nfunction firstMatch(logs: string, re: RegExp): string | undefined {\n\tconst m = re.exec(logs);\n\treturn m ? m[1] : undefined;\n}\n\nfunction parseVersions(logs: string): { from?: string; to?: string } {\n\t// Pre-flight transition line, printed before npm runs — the only source of a\n\t// target version when the update fails early or is a no-op, e.g.\n\t// \"[INFO] Target (beta): 4.2.0 → 4.2.1-beta.1\". `Available:` is the\n\t// pre-channel spelling, kept so logs from an older runner still parse.\n\tconst version = String.raw`\\d+\\.\\d+\\.\\d+[^\\s]*`;\n\tconst transition = new RegExp(\n\t\tString.raw`(?:Target \\([^)]*\\)|Available):\\s*(${version})\\s*(?:→|->)\\s*(${version})`\n\t);\n\tconst arrow = transition.exec(logs);\n\n\t// The post-install lines are authoritative for what actually landed — prefer\n\t// them over the pre-flight target, which is only ever an intent.\n\tconst from = firstMatch(logs, /Current @selvajs\\/selva:\\s*v?(\\d+\\.\\d+\\.\\d+[^\\s]*)/) ?? arrow?.[1];\n\tconst to = firstMatch(logs, /New @selvajs\\/selva:\\s*v?(\\d+\\.\\d+\\.\\d+[^\\s]*)/) ?? arrow?.[2];\n\treturn { from, to };\n}\n\nfunction has(logs: string, needle: string): boolean {\n\treturn logs.includes(needle);\n}\n\nexport function deriveOutcome(exitCode: number | null, logs: string): UpdateOutcome {\n\tconst { from, to } = parseVersions(logs);\n\n\tif (exitCode === null) {\n\t\treturn { severity: 'pending', title: 'Update in progress…' };\n\t}\n\n\t// --- Critical: app is or may be DOWN. Rank these first. -------------------\n\tif (\n\t\texitCode === 6 ||\n\t\thas(logs, 'Manual recovery required') ||\n\t\thas(logs, 'manual intervention required')\n\t) {\n\t\treturn {\n\t\t\tseverity: 'critical',\n\t\t\ttitle: 'Update failed AND rollback failed — the app may be OFFLINE',\n\t\t\tdetail:\n\t\t\t\t'Both the new version and the rollback failed their health check. ' +\n\t\t\t\t'SSH into the server and run: `npx selva logs`, then ' +\n\t\t\t\t'`pm2 start ecosystem.config.cjs` from the deployment directory.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\t// The SSE handler's 15-minute group-kill, and the reconciler's own poll cap.\n\t// Neither is an exit code the runner chose, so they carry no [EXIT] marker.\n\tif (exitCode === TIMED_OUT) {\n\t\treturn {\n\t\t\tseverity: 'critical',\n\t\t\ttitle: 'App did not come back online within 15 minutes',\n\t\t\tdetail:\n\t\t\t\t'The update may still be finishing in the background, or the new ' +\n\t\t\t\t'process is crash-looping. Check `npx selva logs`. Do not ' +\n\t\t\t\t're-run the update until you have confirmed the current state.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\t// Exit 4: the rollback's own npm install failed, so node_modules is\n\t// half-written and the EXIT trap's restart is the only thing that may have\n\t// brought the app back. Same urgency as a failed rollback restart.\n\tif (exitCode === 4) {\n\t\treturn {\n\t\t\tseverity: 'critical',\n\t\t\ttitle: 'Update failed and the rollback could not reinstall — the app may be OFFLINE',\n\t\t\tdetail:\n\t\t\t\t'The previous version could not be restored from npm. SSH into the ' +\n\t\t\t\t'server and run `npx selva logs`; if the app is down, reinstall ' +\n\t\t\t\t'explicitly with `npm install --prefer-online @selvajs/cli@<version> ' +\n\t\t\t\t'@selvajs/selva@<version>` from the deployment directory.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\t// Exit 3: unhealthy with no recorded prior version, so no rollback was even\n\t// attempted. The EXIT trap tried to restart whatever is on disk.\n\tif (exitCode === 3) {\n\t\treturn {\n\t\t\tseverity: 'critical',\n\t\t\ttitle: 'Update failed its health check and could not be rolled back automatically',\n\t\t\tdetail:\n\t\t\t\t'No prior version was recorded, so the previous build could not be ' +\n\t\t\t\t'restored. Check `npx selva logs` to confirm whether the app ' +\n\t\t\t\t'came back online.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\n\t// Killed mid-run (128+signal). Nothing was installed, and whether the app\n\t// came back depends on how far the EXIT trap got before it died too. Rank\n\t// with the criticals: an unattended half-update is worse than a clean\n\t// failure.\n\tif (exitCode === 143 || exitCode === 130 || exitCode === 129 || has(logs, 'KILLED')) {\n\t\treturn {\n\t\t\tseverity: 'critical',\n\t\t\ttitle: 'Update was killed before it finished — nothing was installed',\n\t\t\tdetail:\n\t\t\t\t'The runner was terminated mid-update, most often by a systemd-supervised ' +\n\t\t\t\t'PM2 restarting its whole control group. The version on disk is unchanged. ' +\n\t\t\t\t'Check `npx selva logs` and confirm the app is online before retrying; ' +\n\t\t\t\t'if a global pm2 owns the daemon, reconcile that first.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\n\t// --- Warning: update did not fully succeed, but the app IS up. ------------\n\t// Aborted at the systemd guard, before `pm2 update` could recycle the\n\t// daemon and take this runner down with it.\n\tif (exitCode === 9 || has(logs, 'SYSTEMD_PM2')) {\n\t\treturn {\n\t\t\tseverity: 'warning',\n\t\t\ttitle:\n\t\t\t\t'Update cancelled — PM2 needs a resync that only a shell can do safely. The app is untouched.',\n\t\t\tdetail:\n\t\t\t\t\"This deployment's PM2 runs under systemd, where `pm2 update` restarts the \" +\n\t\t\t\t'unit and kills the update mid-run. Nothing was installed and the app is ' +\n\t\t\t\t'still serving. SSH in and run `./node_modules/.bin/pm2 update` from the ' +\n\t\t\t\t'deployment directory, then retry the update here.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\t// Aborted at the ownership check, before anything was stopped: pm2's app of this\n\t// name belongs to another install on the same machine.\n\tif (exitCode === 11 || has(logs, 'PM2_NAME_TAKEN')) {\n\t\tconst owner = firstMatch(logs, /PM2_NAME_TAKEN: pm2's '[^']*' runs from (\\S+),/);\n\t\treturn {\n\t\t\tseverity: 'warning',\n\t\t\ttitle: `Update cancelled — another Selva install${owner ? ` (${owner})` : ''} uses this install's PM2 app name. The app is untouched.`,\n\t\t\tdetail:\n\t\t\t\t'PM2 finds an app by name, so this update would have stopped the other install ' +\n\t\t\t\t'and left this one running on replaced files. Nothing was installed. On the ' +\n\t\t\t\t'server, give this install its own `name` in its ecosystem.config.cjs, run ' +\n\t\t\t\t'`npx selva start` from its directory, then retry the update here.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\t// Aborted after the stop, before npm ran: something still answered this\n\t// install's port, so the update could not have replaced it.\n\tif (exitCode === 12 || has(logs, 'NOT_STOPPED')) {\n\t\treturn {\n\t\t\tseverity: 'warning',\n\t\t\ttitle:\n\t\t\t\t'Update cancelled — the app kept answering after PM2 stopped it. Nothing was installed.',\n\t\t\tdetail:\n\t\t\t\t\"Either this install's PM2 does not run the process that is serving (another \" +\n\t\t\t\t'PM2 daemon, a systemd unit or a shell started it), or it did not exit. Updating ' +\n\t\t\t\t'would have replaced its files without restarting it. On the server, find what ' +\n\t\t\t\t'holds the port (`ss -ltnp`), stop it there, run `npx selva start` from the ' +\n\t\t\t\t'deployment directory, then retry.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\t// Aborted at the data format check, before anything was stopped.\n\tif (exitCode === 10 || has(logs, 'DATA_FORMAT:')) {\n\t\tconst target = firstMatch(logs, /reads data format (\\d+),/);\n\t\tconst installed = firstMatch(logs, /this deployment is on format (\\d+)\\./);\n\t\treturn {\n\t\t\tseverity: 'warning',\n\t\t\ttitle: `Update cancelled — ${to ?? 'the target version'} cannot read this deployment's data. The app is untouched.`,\n\t\t\tdetail:\n\t\t\t\t(target && installed\n\t\t\t\t\t? `It reads data format ${target}; this deployment is on format ${installed}. `\n\t\t\t\t\t: '') +\n\t\t\t\t'Installing it would leave stored data, such as Compute API keys, unreadable. ' +\n\t\t\t\t'Switch the release channel back to stay on the installed version. To go back ' +\n\t\t\t\t'anyway, follow \"Going back to an older release\" in the admin guide.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\t// Aborted at the pm2 skew check, before anything was stopped — nothing was\n\t// installed and the app never went down.\n\tif (exitCode === 8 || has(logs, 'PM2_SKEW')) {\n\t\tconst daemon = firstMatch(logs, /daemon \\(v(\\d+\\.\\d+\\.\\d+)\\)/);\n\t\tconst local = firstMatch(logs, /deployment's pm2 \\(v(\\d+\\.\\d+\\.\\d+)\\)/);\n\t\treturn {\n\t\t\tseverity: 'warning',\n\t\t\ttitle:\n\t\t\t\tdaemon && local\n\t\t\t\t\t? `Update cancelled — a global PM2 (v${daemon}) owns the daemon, not this deployment's (v${local}). The app is untouched.`\n\t\t\t\t\t: 'Update cancelled — a conflicting global PM2 owns the daemon. The app is untouched.',\n\t\t\tdetail:\n\t\t\t\t'Resyncing would have downgraded the daemon and dropped its process ' +\n\t\t\t\t'table, so the update stopped before taking the app down. On the server: ' +\n\t\t\t\t'`which -a pm2`, `pm2 -v`, `pm2 ping` — remove or align the global pm2, then retry.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\t// A rollback whose cause is the DATABASE, not the release. Ranked ahead of\n\t// the generic rollback case: \"review the log before retrying\" is actively\n\t// misleading here, because the log holds nothing about the new version —\n\t// it is fine, and retrying without touching the database repeats verbatim.\n\tif (has(logs, 'SCHEMA_SKEW')) {\n\t\tconst expected = firstMatch(logs, /expects database migration head (\\S+?),/);\n\t\tconst actual = firstMatch(logs, /this database is at (\\S+?)\\./);\n\t\tconst skew =\n\t\t\texpected && actual ? ` The database is at ${actual}; ${to ?? 'it'} needs ${expected}.` : '';\n\t\t// `latest` is the stable line, which ships none of a beta's migrations.\n\t\tconst providerTag =\n\t\t\tfirstMatch(logs, /@selvajs\\/supabase-provider@([\\w.-]+)/) ??\n\t\t\t(has(logs, 'channel: beta') ? 'beta' : 'latest');\n\t\treturn {\n\t\t\tseverity: 'warning',\n\t\t\ttitle: `Update rolled back — the database migrations for ${to ?? 'the new version'} have not been applied.${skew} The app is online${from ? ` on ${from}` : ''}.`,\n\t\t\tdetail:\n\t\t\t\t'Nothing is wrong with the new version. Selva does not apply migrations ' +\n\t\t\t\t'during an update, because they cannot be rolled back — auto-migrating ' +\n\t\t\t\t'and then rolling the code back would leave the app and database on ' +\n\t\t\t\t'different heads. Apply them on the server, then re-run this update: ' +\n\t\t\t\t`\\`npm install --prefer-online @selvajs/supabase-provider@${providerTag}\\`, then ` +\n\t\t\t\t'`npx selva-supabase`, then `npx supabase db push`. The provider install ' +\n\t\t\t\t'is not optional — the migration SQL ships inside that package, and the ' +\n\t\t\t\t'update only moves @selvajs/cli and @selvajs/selva, so a sync without it ' +\n\t\t\t\t'copies nothing and the push reports \"up to date\" having done nothing. ' +\n\t\t\t\t'Retrying without this will fail in exactly the same way.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\t// Same shape: the rollback was caused by host configuration, not the release.\n\tif (has(logs, 'AT_REST_SECRETS')) {\n\t\treturn {\n\t\t\tseverity: 'warning',\n\t\t\ttitle: `Update rolled back — stored compute server keys do not decrypt under this host's SELVA_AT_REST_KEY. The app is online${from ? ` on ${from}` : ''}.`,\n\t\t\tdetail:\n\t\t\t\t'This is a configuration problem on the server, not a fault in the new ' +\n\t\t\t\t'version, so retrying alone will fail identically. Re-enter the affected ' +\n\t\t\t\t'keys at /admin/compute, or restore the SELVA_AT_REST_KEY the values were ' +\n\t\t\t\t'encrypted with, then re-run the update.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\tif (exitCode === 5 || has(logs, 'Rolled back')) {\n\t\treturn {\n\t\t\tseverity: 'warning',\n\t\t\ttitle: `Update failed — safely rolled back${from ? ` to ${from}` : ''}. The app is online.`,\n\t\t\tdetail:\n\t\t\t\t'The new version failed its health check, so the previous version ' +\n\t\t\t\t'was restored and is serving normally. Review the log below for why ' +\n\t\t\t\t'the new version failed before retrying.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\t// The install completed and the app is up, but on a Node the release doesn't\n\t// support. The health probe passes (it exercises nothing version-specific),\n\t// so this would otherwise read as a clean success right up until a real\n\t// request hits a newer API and throws (issue #176).\n\tif (has(logs, 'ENGINE_MISMATCH') || has(logs, 'EBADENGINE')) {\n\t\tconst required = firstMatch(logs, /requires Node ([^\\s]+(?:\\s*[<>=]+\\s*[\\d.]+)*)/);\n\t\tconst running = firstMatch(logs, /this host runs v?(\\d+\\.\\d+\\.\\d+)/);\n\t\treturn {\n\t\t\tseverity: 'warning',\n\t\t\ttitle: running\n\t\t\t\t? `Updated${to ? ` to ${to}` : ''}, but this release needs Node ${required ?? '(newer)'} — the host runs v${running}. Expect runtime failures.`\n\t\t\t\t: `Updated${to ? ` to ${to}` : ''}, but this release requires a newer Node than the host provides. Expect runtime failures.`,\n\t\t\tdetail:\n\t\t\t\t'npm installed it anyway (engine-strict is off) and the health check ' +\n\t\t\t\t'passed, but it does not exercise the newer APIs — routes that do will ' +\n\t\t\t\t'throw at request time. Upgrade Node on the server, then re-run the update.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\t// The runner moved pm2 to the release's pin but could not swap the daemon\n\t// (refused under systemd, or `pm2 update` failed). The app runs; the next\n\t// pm2 command warns about the skew until someone runs the swap by hand.\n\tif (has(logs, 'PM2_RESYNC_NEEDED')) {\n\t\treturn {\n\t\t\tseverity: 'warning',\n\t\t\ttitle: `Updated${to ? ` to ${to}` : ''}, but the pm2 daemon still runs the old pm2.`,\n\t\t\tdetail:\n\t\t\t\t'The app is online. On the server, run `npx pm2 update` in the deployment ' +\n\t\t\t\t'directory, let it finish, then check `npx pm2 list` shows the app online.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\tif (has(logs, 'PM2_PIN_FAILED')) {\n\t\treturn {\n\t\t\tseverity: 'warning',\n\t\t\ttitle: `Updated${to ? ` to ${to}` : ''}, but pm2 stayed on the previous version.`,\n\t\t\tdetail:\n\t\t\t\t'The app is online on the old pm2. On the server, run `npx selva migrate` in ' +\n\t\t\t\t'the deployment directory to move it to the pinned version.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\tif (has(logs, 'npm cache may be stale') || has(logs, 'No version change')) {\n\t\treturn {\n\t\t\tseverity: 'warning',\n\t\t\ttitle: 'No version change — npm installed the same version.',\n\t\t\tdetail:\n\t\t\t\t'Your npm cache may be stale. On the server: `npm cache clean --force`, ' +\n\t\t\t\t'remove node_modules + package-lock.json, then `npm install --prefer-online`.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\n\t// --- Success variants -----------------------------------------------------\n\tif (exitCode === 0) {\n\t\t// \"Already on the 'beta' channel version (4.2.0)\" — the channel name is\n\t\t// interpolated, so match the stable prefix rather than a whole line.\n\t\tif (has(logs, 'Already on the') || has(logs, 'Nothing to do')) {\n\t\t\treturn {\n\t\t\t\tseverity: 'info',\n\t\t\t\ttitle: `Already up to date${from ? ` (${from})` : ''} — nothing to install.`,\n\t\t\t\tdetail: 'No changes were made and the app was not restarted.',\n\t\t\t\tfrom,\n\t\t\t\tto\n\t\t\t};\n\t\t}\n\t\tif (from && to && from !== to) {\n\t\t\treturn {\n\t\t\t\tseverity: 'success',\n\t\t\t\ttitle: `Updated ${from} → ${to}. The app is back online.`,\n\t\t\t\tfrom,\n\t\t\t\tto\n\t\t\t};\n\t\t}\n\t\tif (to) {\n\t\t\treturn {\n\t\t\t\tseverity: 'success',\n\t\t\t\ttitle: `Update complete — now on ${to}. The app is back online.`,\n\t\t\t\tfrom,\n\t\t\t\tto\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\tseverity: 'success',\n\t\t\ttitle: 'Update completed and the app is back online.',\n\t\t\tfrom,\n\t\t\tto\n\t\t};\n\t}\n\n\t// --- Anything else: a non-zero exit we don't have a named case for. -------\n\t// Be explicit that we couldn't classify it rather than implying success.\n\treturn {\n\t\tseverity: 'critical',\n\t\ttitle: `Update failed (exit code ${exitCode}).`,\n\t\tdetail:\n\t\t\t'The update did not complete cleanly. Review the log below, and check ' +\n\t\t\t'`npx selva logs` to confirm whether the app is currently online.',\n\t\tfrom,\n\t\tto\n\t};\n}\n"],"mappings":"AA6BA,SAAS,WAAW,MAAc,IAAgC;CACjE,MAAM,IAAI,GAAG,KAAK,IAAI;CACtB,OAAO,IAAI,EAAE,KAAK,KAAA;AACnB;AAEA,SAAS,cAAc,MAA8C;CAKpE,MAAM,UAAU,OAAO,GAAG;CAI1B,MAAM,QAAQ,IAHS,OACtB,OAAO,GAAG,sCAAsC,QAAQ,kBAAkB,QAAQ,EAErE,CAAA,CAAW,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] || PM2=pm2
|
|
91
91
|
|
|
92
|
+
# pm2 finds an app by name alone, and the name is whatever this install's
|
|
93
|
+
# ecosystem file declares. Two installs under one pm2 daemon need different ones.
|
|
94
|
+
APP=$(node -p "require(process.argv[1]).apps[0].name" "$ECOSYSTEM" 2>/dev/null)
|
|
95
|
+
case "$APP" in ''|undefined|null) APP=selva-compute ;; esac
|
|
96
|
+
HERE=$(cd "$(dirname "$ECOSYSTEM")" 2>/dev/null && pwd -P)
|
|
97
|
+
|
|
98
|
+
# Read PORT from .env the same way scripts/update.sh does, so non-default
|
|
99
|
+
# ports are respected.
|
|
100
|
+
PORT=$(grep "^PORT=" .env 2>/dev/null \\
|
|
101
|
+
| head -1 \\
|
|
102
|
+
| cut -d'=' -f2 \\
|
|
103
|
+
| sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//' -e 's/^["'"'"']//' -e 's/["'"'"']$//' -e 's/[[:space:]]*#.*//')
|
|
104
|
+
PORT=\${PORT:-3000}
|
|
105
|
+
|
|
106
|
+
# Prints one string field of the /api/health body on stdin.
|
|
107
|
+
json_field() {
|
|
108
|
+
grep -o '"'"$1"'":"[^"]*"' | head -1 | cut -d'"' -f4
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
# Prints the instanceId of whatever answers this install's port, or nothing while
|
|
112
|
+
# the port is silent.
|
|
113
|
+
serving_instance() {
|
|
114
|
+
curl -sS --max-time 5 "http://localhost:$PORT/api/health" 2>/dev/null | json_field instanceId
|
|
115
|
+
}
|
|
116
|
+
|
|
92
117
|
# Under systemd, \`pm2 update\` kills and respawns the daemon. systemd sees its
|
|
93
118
|
# unit's main process die and, with the default KillMode=control-group,
|
|
94
119
|
# SIGTERMs everything in the cgroup — including this runner. setsid escapes
|
|
@@ -118,25 +143,37 @@ pm2_under_systemd() {
|
|
|
118
143
|
# single failure path; fd 0 rather than /dev/stdin because the latter isn't a
|
|
119
144
|
# readable pipe everywhere.
|
|
120
145
|
app_status() {
|
|
121
|
-
"$PM2" jlist 2>/dev/null | node -e "
|
|
146
|
+
"$PM2" jlist 2>/dev/null | SELVA_APP="$APP" node -e "
|
|
122
147
|
try {
|
|
123
148
|
const list = JSON.parse(require('fs').readFileSync(0,'utf8'));
|
|
124
|
-
const app = list.find(p => p.name ===
|
|
149
|
+
const app = list.find(p => p.name === process.env.SELVA_APP);
|
|
125
150
|
process.stdout.write(app ? app.pm2_env.status : 'missing');
|
|
126
151
|
} catch { process.stdout.write('error'); }
|
|
127
152
|
" 2>/dev/null
|
|
128
153
|
}
|
|
129
154
|
|
|
155
|
+
# Prints the directory pm2 runs this app from, or nothing when pm2 has no app of
|
|
156
|
+
# that name.
|
|
157
|
+
app_dir() {
|
|
158
|
+
"$PM2" jlist 2>/dev/null | SELVA_APP="$APP" node -e "
|
|
159
|
+
try {
|
|
160
|
+
const list = JSON.parse(require('fs').readFileSync(0,'utf8'));
|
|
161
|
+
const app = list.find(p => p.name === process.env.SELVA_APP);
|
|
162
|
+
process.stdout.write((app && app.pm2_env.pm_cwd) || '');
|
|
163
|
+
} catch {}
|
|
164
|
+
" 2>/dev/null
|
|
165
|
+
}
|
|
166
|
+
|
|
130
167
|
wait_until_stopped() {
|
|
131
168
|
for i in $(seq 1 20); do
|
|
132
169
|
STATUS=$(app_status)
|
|
133
170
|
if [ "$STATUS" != "stopping" ]; then
|
|
134
171
|
return 0
|
|
135
172
|
fi
|
|
136
|
-
echo "[INFO]
|
|
173
|
+
echo "[INFO] $APP still draining (attempt $i/20) — waiting for SIGKILL escalation"
|
|
137
174
|
sleep 1
|
|
138
175
|
done
|
|
139
|
-
echo "[WARN]
|
|
176
|
+
echo "[WARN] $APP stuck in 'stopping' after 20s — continuing anyway"
|
|
140
177
|
return 1
|
|
141
178
|
}
|
|
142
179
|
|
|
@@ -150,7 +187,7 @@ start_app() {
|
|
|
150
187
|
return 0
|
|
151
188
|
fi
|
|
152
189
|
echo "[WARN] pm2 start failed — dropping the stale process entry and retrying"
|
|
153
|
-
"$PM2" delete
|
|
190
|
+
"$PM2" delete "$APP" >/dev/null 2>&1 || true
|
|
154
191
|
"$PM2" start "$ECOSYSTEM" --update-env
|
|
155
192
|
}
|
|
156
193
|
|
|
@@ -168,9 +205,9 @@ on_exit() {
|
|
|
168
205
|
STATUS=$(app_status)
|
|
169
206
|
fi
|
|
170
207
|
if [ "$STATUS" != "online" ]; then
|
|
171
|
-
echo "[RECOVER]
|
|
208
|
+
echo "[RECOVER] $APP is '$STATUS' — starting from ecosystem.config.cjs"
|
|
172
209
|
start_app >/dev/null 2>&1 || \\
|
|
173
|
-
echo "[RECOVER] pm2 start failed — manual intervention required: cd $(dirname "$ECOSYSTEM") && ./node_modules/.bin/pm2 delete
|
|
210
|
+
echo "[RECOVER] pm2 start failed — manual intervention required: cd $(dirname "$ECOSYSTEM") && ./node_modules/.bin/pm2 delete $APP; ./node_modules/.bin/pm2 start ecosystem.config.cjs"
|
|
174
211
|
fi
|
|
175
212
|
# Terminal marker: the restarted app's outcome reconciler greps this to turn
|
|
176
213
|
# the run into an audit event (selfUpdate.server.ts). Keep the format stable.
|
|
@@ -313,7 +350,27 @@ if echo "$PING_OUT" | grep -q "out-of-date"; then
|
|
|
313
350
|
fi
|
|
314
351
|
|
|
315
352
|
# ---------------------------------------------------------------------------
|
|
316
|
-
#
|
|
353
|
+
# 2b. This install must own the pm2 app it is about to stop.
|
|
354
|
+
# ---------------------------------------------------------------------------
|
|
355
|
+
# With two installs under one daemon and one name, the stop below takes the
|
|
356
|
+
# OTHER install down while this one keeps serving, and npm then rewrites build/
|
|
357
|
+
# under it.
|
|
358
|
+
OWNER=$(app_dir)
|
|
359
|
+
OWNER_REAL=
|
|
360
|
+
if [ -n "$OWNER" ]; then
|
|
361
|
+
OWNER_REAL=$(cd "$OWNER" 2>/dev/null && pwd -P)
|
|
362
|
+
fi
|
|
363
|
+
if [ -n "$OWNER" ] && [ -n "$HERE" ] && [ "\${OWNER_REAL:-$OWNER}" != "$HERE" ]; then
|
|
364
|
+
echo "[FATAL] PM2_NAME_TAKEN: pm2's '$APP' runs from $OWNER, not from this install ($HERE)."
|
|
365
|
+
echo "[FATAL] Two installs share one pm2 app name, so this update would have stopped the other one."
|
|
366
|
+
echo "[FATAL] Give this install its own name: change 'name' in $ECOSYSTEM, then from a shell:"
|
|
367
|
+
echo "[FATAL] cd $HERE && npx selva start"
|
|
368
|
+
echo "[FATAL] Aborting WITHOUT stopping the app — it is still running."
|
|
369
|
+
exit 11
|
|
370
|
+
fi
|
|
371
|
+
|
|
372
|
+
# ---------------------------------------------------------------------------
|
|
373
|
+
# 3. Stop the app BEFORE npm rewrites build/.
|
|
317
374
|
# ---------------------------------------------------------------------------
|
|
318
375
|
# SvelteKit's node adapter lazy-imports chunks from build/server/chunks/ on
|
|
319
376
|
# every request. Letting npm rewrite build/ while the old process still
|
|
@@ -325,15 +382,40 @@ fi
|
|
|
325
382
|
# This is also where the SSE connection to the frontend dies — selva-compute
|
|
326
383
|
# IS the SSE server. From here on, the user sees output via the log-file
|
|
327
384
|
# polling fallback in the admin UI, not over SSE.
|
|
328
|
-
echo "[STEP] Stopping
|
|
329
|
-
if ! "$PM2" stop
|
|
330
|
-
echo "[WARN] pm2 stop failed —
|
|
385
|
+
echo "[STEP] Stopping $APP"
|
|
386
|
+
if ! "$PM2" stop "$APP"; then
|
|
387
|
+
echo "[WARN] pm2 stop failed — $APP may not be running yet. Continuing."
|
|
331
388
|
fi
|
|
332
389
|
|
|
333
390
|
# pm2 stop returns before the process is actually gone. Everything below —
|
|
334
391
|
# npm rewriting build/, then the restart — must happen outside the drain window.
|
|
335
392
|
wait_until_stopped
|
|
336
393
|
|
|
394
|
+
# ---------------------------------------------------------------------------
|
|
395
|
+
# 3b. Nothing may answer the port once the app is stopped.
|
|
396
|
+
# ---------------------------------------------------------------------------
|
|
397
|
+
# A process this pm2 does not run (another pm2 daemon, a systemd unit, a shell)
|
|
398
|
+
# survives the stop above, and so does one that outlived its kill timeout. Either
|
|
399
|
+
# would keep rendering pages that name the old build's files after npm has
|
|
400
|
+
# replaced them, and would answer the health probe below, so the update would
|
|
401
|
+
# report success with nothing restarted.
|
|
402
|
+
SURVIVOR=
|
|
403
|
+
for i in $(seq 1 5); do
|
|
404
|
+
SURVIVOR=$(serving_instance)
|
|
405
|
+
if [ -z "$SURVIVOR" ]; then
|
|
406
|
+
break
|
|
407
|
+
fi
|
|
408
|
+
sleep 1
|
|
409
|
+
done
|
|
410
|
+
if [ -n "$SURVIVOR" ]; then
|
|
411
|
+
echo "[FATAL] NOT_STOPPED: something still answers on port $PORT after 'pm2 stop $APP'."
|
|
412
|
+
echo "[FATAL] Either this install's pm2 does not run that process, or it did not exit."
|
|
413
|
+
echo "[FATAL] Nothing was installed. Find what holds the port, stop it there, then start the app from this install:"
|
|
414
|
+
echo "[FATAL] ss -ltnp | grep ':$PORT '"
|
|
415
|
+
echo "[FATAL] cd $HERE && npx selva start"
|
|
416
|
+
exit 12
|
|
417
|
+
fi
|
|
418
|
+
|
|
337
419
|
# ---------------------------------------------------------------------------
|
|
338
420
|
# 4. Run npm update.
|
|
339
421
|
# ---------------------------------------------------------------------------
|
|
@@ -373,7 +455,7 @@ if [ -n "$PM2_PIN" ] && [ "$PM2_PIN" != "$PM2_DECLARED" ]; then
|
|
|
373
455
|
echo "[WARN] PM2_RESYNC_NEEDED: pm2 is now $PM2_PIN, but its daemon still runs the old version."
|
|
374
456
|
echo "[WARN] Swapping it here would restart the systemd unit and kill this runner. From a shell:"
|
|
375
457
|
echo "[WARN] cd $(dirname "$ECOSYSTEM") && npx pm2 update && npx pm2 list"
|
|
376
|
-
echo "[WARN] Let it finish: interrupting it leaves
|
|
458
|
+
echo "[WARN] Let it finish: interrupting it leaves $APP unregistered."
|
|
377
459
|
elif ! "$PM2" update; then
|
|
378
460
|
echo "[WARN] PM2_RESYNC_NEEDED: 'pm2 update' failed — the daemon still runs the old pm2."
|
|
379
461
|
echo "[WARN] cd $(dirname "$ECOSYSTEM") && npx pm2 update && npx pm2 list"
|
|
@@ -390,23 +472,15 @@ fi
|
|
|
390
472
|
# Start from ecosystem.config.cjs, NOT \`pm2 start selva-compute\` — the latter
|
|
391
473
|
# requires selva-compute to already be in pm2's in-memory process list, which
|
|
392
474
|
# a \`pm2 update\` (step 2) isn't guaranteed to preserve.
|
|
393
|
-
echo "[STEP] Starting
|
|
475
|
+
echo "[STEP] Starting $APP with new build"
|
|
394
476
|
if ! start_app; then
|
|
395
|
-
echo "[FATAL] pm2 start failed — investigate with \\\`pm2 logs
|
|
477
|
+
echo "[FATAL] pm2 start failed — investigate with \\\`pm2 logs $APP\\\`"
|
|
396
478
|
exit 2
|
|
397
479
|
fi
|
|
398
480
|
|
|
399
481
|
# ---------------------------------------------------------------------------
|
|
400
482
|
# 6. Health probe the new process.
|
|
401
483
|
# ---------------------------------------------------------------------------
|
|
402
|
-
# Read PORT from .env the same way scripts/update.sh does, so non-default
|
|
403
|
-
# ports are respected.
|
|
404
|
-
PORT=$(grep "^PORT=" .env 2>/dev/null \\
|
|
405
|
-
| head -1 \\
|
|
406
|
-
| cut -d'=' -f2 \\
|
|
407
|
-
| sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//' -e 's/^["'"'"']//' -e 's/["'"'"']$//' -e 's/[[:space:]]*#.*//')
|
|
408
|
-
PORT=\${PORT:-3000}
|
|
409
|
-
|
|
410
484
|
echo "[STEP] Health-probing the new process on port $PORT"
|
|
411
485
|
# mktemp for the same reason as the runner itself: /tmp is shared. Without one
|
|
412
486
|
# the probe still runs; only the rollback loses the body it names the cause from.
|
|
@@ -474,7 +548,7 @@ if [ -s "$HEALTH_BODY" ]; then
|
|
|
474
548
|
echo "[FATAL] SELVA_AT_REST_KEY, then re-run the update."
|
|
475
549
|
else
|
|
476
550
|
echo "[FATAL] The health endpoint did not report a known cause. Inspect the body above and"
|
|
477
|
-
echo "[FATAL] \\\`pm2 logs
|
|
551
|
+
echo "[FATAL] \\\`pm2 logs $APP\\\` for what the new version failed on."
|
|
478
552
|
fi
|
|
479
553
|
|
|
480
554
|
rm -f "$HEALTH_BODY"
|
|
@@ -496,7 +570,7 @@ if [ "$AFTER_FORMAT" -gt "$INSTALLED_FORMAT" ]; then
|
|
|
496
570
|
fi
|
|
497
571
|
|
|
498
572
|
echo "[STEP] Rolling back @selvajs/selva to $BEFORE"
|
|
499
|
-
"$PM2" stop
|
|
573
|
+
"$PM2" stop "$APP" >/dev/null 2>&1 || true
|
|
500
574
|
wait_until_stopped >/dev/null 2>&1
|
|
501
575
|
# Restore @selvajs/cli alongside the runtime: the forward step installs both at
|
|
502
576
|
# the channel tag, so reverting only the runtime leaves a version pair that was
|
|
@@ -515,7 +589,7 @@ if [ "$ROLLBACK_CODE" = "200" ]; then
|
|
|
515
589
|
fi
|
|
516
590
|
|
|
517
591
|
echo "[FATAL] Rollback restart also failed health check (HTTP $ROLLBACK_CODE)"
|
|
518
|
-
echo "[FATAL] Manual recovery required. Check: pm2 logs
|
|
592
|
+
echo "[FATAL] Manual recovery required. Check: pm2 logs $APP"
|
|
519
593
|
exit 6
|
|
520
594
|
`;
|
|
521
595
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"_server.ts.js","names":["join","readFileSync"],"sources":["../../../../../../../../src/lib/server/updateRunner.server.ts","../../../../../../../../src/routes/api/admin/system/update/+server.ts"],"sourcesContent":["/**\n * Generates the bash the self-update POST route spawns: a tiny daemonizing\n * launcher plus the runner script that actually stops/updates/starts/health-\n * checks the deployment. Split out of the route file because SvelteKit's\n * route-file validator only allows HTTP-verb exports (and `_`-prefixed ones) —\n * these are plain functions the runner-script contract tests import directly.\n */\n\nimport { readFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { findDeploymentDir } from './selfUpdate.server.js';\nimport { channelTag, type ReleaseChannel } from './releaseChannel.server.js';\n\nexport function readRuntimeVersion(dir: string): string | undefined {\n\ttry {\n\t\tconst pkg = JSON.parse(\n\t\t\treadFileSync(join(dir, 'node_modules', '@selvajs', 'selva', 'package.json'), 'utf8')\n\t\t);\n\t\treturn typeof pkg.version === 'string' ? pkg.version : undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n// No caller currently passes untrusted input (plan.cwd is from\n// process.cwd(), npm package names are hardcoded), but defensive quoting is\n// cheap.\nexport function shellQuote(s: string): string {\n\treturn `'${s.replace(/'/g, `'\\\\''`)}'`;\n}\n\n// Wraps the actual update commands in a tiny \"launcher\" that daemonizes them.\n//\n// THE PROBLEM: `pm2 stop selva-compute` (which the runner has to call) uses\n// tree-kill, which walks /proc parent-child relationships from\n// selva-compute's PID and SIGKILLs every descendant. Node's\n// `{ detached: true }` + `child.unref()` puts the spawned bash in a new\n// session/process group but does NOT change the parent-child relationship —\n// so tree-kill still finds and kills it, and the app never restarts.\n//\n// THE FIX: write the update commands to a tempfile and launch them via\n// `setsid bash ... &`, then have the launcher exit. The runner's PPID becomes\n// 1 (init) the moment the launcher exits, so it's no longer a descendant of\n// selva-compute and tree-kill can't reach it.\n//\n// Output: the launcher's prelude lines are echoed via tee into\n// UPDATE_LOG_PATH and through stdout (visible to SSE while the connection is\n// still up); the runner appends its output to the same log file; the\n// frontend tolerates the SSE blackout by polling the log file.\nexport function buildLauncher(\n\trunnerScript: string,\n\tlogPath: string,\n\tprelude: string[] = []\n): string {\n\tconst echoes = prelude.map((line) => `echo ${shellQuote(line)}`).join('\\n');\n\t// Note: runner script is embedded via a QUOTED heredoc so no variable\n\t// expansion happens — the runner text is written verbatim.\n\treturn `\nLOGFILE=${shellQuote(logPath)}\nmkdir -p \"$(dirname \"$LOGFILE\")\"\n: > \"$LOGFILE\"\n\n# mktemp, never a fixed name: /tmp is shared, and a file another account left at\n# a known path survives the write below and would run as the app user.\nRUNNER=$(mktemp \"\\${TMPDIR:-/tmp}/selva-update-runner.XXXXXXXX\") || {\n\techo \"[ERROR] Could not create the update runner in \\${TMPDIR:-/tmp}\"\n\texit 1\n}\ncat > \"$RUNNER\" <<'__SELVA_RUNNER_EOF__' || { echo \"[ERROR] Could not write the update runner\"; exit 1; }\nrm -f \"$0\"\nfor _ in $(seq 1 50); do\n kill -0 \"$SELVA_RUNNER_SPAWNER\" 2>/dev/null || break\n sleep 0.1\ndone\n${runnerScript}\n__SELVA_RUNNER_EOF__\n\ntrap '' PIPE\nexec > >(tee --output-error=warn-nopipe -a \"$LOGFILE\" 2>/dev/null) 2>&1\n${echoes}\n\n# Daemonize the runner so PM2's tree-kill of selva-compute can't reach it.\n# When the runner calls pm2 stop, pm2 lists the app's descendants and SIGKILLs\n# whatever on that list outlives its kill timeout. A runner still parented to this\n# launcher is on the list: it died mid-update and left the app stopped whenever the\n# registry answered inside the pause below. So it is orphaned before it runs a\n# line: the subshell forks it and exits, and the runner waits for that exit.\n# setsid gives it its own session; its stdio is detached from selva-compute's pipes.\nRUNNER_PID=$( (SELVA_RUNNER_SPAWNER=$BASHPID setsid bash \"$RUNNER\" </dev/null >>\"$LOGFILE\" 2>&1 & echo $!) )\necho \"[INFO] Update runner started (PID $RUNNER_PID, log: $LOGFILE)\"\n\n# Small pause so the runner has time to print its first line before SSE\n# closes — otherwise the frontend's first poll might see no progress.\nsleep 1\nexit 0\n`;\n}\n\n// Bash script the daemonized runner executes. Flow:\n//\n// 1. pre-flight — query the registry; if already on latest, exit clean\n// WITHOUT touching the running app. Refuse a target\n// that cannot read this deployment's data.\n// 2. pm2 sync — `pm2 update` if the daemon and CLI versions drifted.\n// 3. pm2 stop — stop selva-compute before npm overwrites build/, so\n// in-flight requests can't hit ERR_MODULE_NOT_FOUND\n// from chunk-hash churn under their feet.\n// 4. npm update — refresh @selvajs/* (--prefer-online bypasses the\n// packument cache, already baked into npmArgs).\n// 5. pm2 start — from ecosystem.config.cjs (not `pm2 start name`,\n// which requires the process to already be in pm2's\n// in-memory list — fragile after `pm2 update`).\n// 6. health probe — poll /api/health for up to 30s.\n// 7. rollback — on failure: npm install the prior version, restart.\n// 8. EXIT trap — last-resort: if anything above leaves the app\n// offline (crash, kill, network blip), unconditionally\n// try `pm2 start ecosystem.config.cjs` before exiting\n// so the customer's site doesn't stay dark.\n//\n// Embedded into the launcher via a quoted heredoc, so this whole string is\n// written verbatim — interpolated values must be shell-quoted at JS time.\nexport function buildNpmRunnerScript(\n\tnpmArgs: string[],\n\tversionBefore: string | undefined,\n\tecosystemPath: string,\n\ttag: string\n): string {\n\tconst npmCommand = ['npm', ...npmArgs].map(shellQuote).join(' ');\n\t// Empty string when versionBefore is undefined — bash sees `BEFORE=\"\"`\n\t// and skips the rollback path (you can't roll back to nothing).\n\tconst before = shellQuote(versionBefore ?? '');\n\tconst ecosystem = shellQuote(ecosystemPath);\n\t// The npm dist-tag the chosen channel resolves to (`latest` / `beta`). The\n\t// pre-flight and no-change warning query this tag, so they don't misfire on\n\t// a beta channel (where the channel's published version is a pre-release the\n\t// default `latest` query would never see) or on a revert (where the target\n\t// stable version is OLDER than the installed beta).\n\tconst distTag = shellQuote(tag);\n\n\treturn `#!/bin/bash\nset -o pipefail\nBEFORE=${before}\nECOSYSTEM=${ecosystem}\nTAG=${distTag}\n\n# Resolve the deployment-local pm2 explicitly instead of trusting PATH.\n# The runner is re-launched via \\`setsid bash\\` from a tempfile, so it inherits\n# whatever environment the spawning process had. When the update is triggered\n# from the admin UI that happens to include node_modules/.bin; from cron or a\n# bare shell it does not, and every pm2 call below — including the EXIT trap's\n# last-resort restart — fails with \"command not found\" and the app stays dark.\nPM2=\"$(dirname \"$ECOSYSTEM\")/node_modules/.bin/pm2\"\n[ -x \"$PM2\" ] || PM2=pm2\n\n# Under systemd, \\`pm2 update\\` kills and respawns the daemon. systemd sees its\n# unit's main process die and, with the default KillMode=control-group,\n# SIGTERMs everything in the cgroup — including this runner. setsid escapes\n# PM2's tree-kill but NOT the cgroup, so the runner never runs \\`pm2 update\\`\n# when this is true.\npm2_under_systemd() {\n grep -qs 'pm2.*\\\\.service' /proc/self/cgroup 2>/dev/null\n}\n\n# Waits for selva-compute to leave the transitional 'stopping' state.\n#\n# \\`pm2 stop\\` sends SIGINT and returns without waiting for the process to die.\n# The SvelteKit node adapter then drains in-flight requests before exiting, and\n# PM2 only escalates to SIGKILL after kill_timeout (10s in the scaffolded\n# ecosystem). For that whole window the process table entry has a name and an\n# id but no live pid — \\`pm2 start\\` resolves the name, converts to a restart,\n# finds nothing to restart, and pm2's own table printer crashes on\n# \\`undefined.pm2_env\\`. Polling here keeps the rest of the script out of that\n# window entirely.\n#\n# The drain reliably takes the full timeout when the update was triggered from\n# the admin UI: that page is fed by an SSE stream this very process serves, and\n# an open SSE stream never completes on its own.\n# Prints exactly one word. Callers compare it against 'online' / 'stopping', so\n# a probe that emits two tokens on failure (the inline catch AND a shell\n# fallback both firing) would silently never match either. Node's catch is the\n# single failure path; fd 0 rather than /dev/stdin because the latter isn't a\n# readable pipe everywhere.\napp_status() {\n \"$PM2\" jlist 2>/dev/null | node -e \"\n try {\n const list = JSON.parse(require('fs').readFileSync(0,'utf8'));\n const app = list.find(p => p.name === 'selva-compute');\n process.stdout.write(app ? app.pm2_env.status : 'missing');\n } catch { process.stdout.write('error'); }\n \" 2>/dev/null\n}\n\nwait_until_stopped() {\n for i in $(seq 1 20); do\n STATUS=$(app_status)\n if [ \"$STATUS\" != \"stopping\" ]; then\n return 0\n fi\n echo \"[INFO] selva-compute still draining (attempt $i/20) — waiting for SIGKILL escalation\"\n sleep 1\n done\n echo \"[WARN] selva-compute stuck in 'stopping' after 20s — continuing anyway\"\n return 1\n}\n\n# \\`pm2 start <ecosystem>\\` converts to a restart-by-id when an entry of the same\n# name is already in the table. If that entry is stale the restart fails and no\n# amount of retrying the same command helps — the name has to be dropped first\n# so the start registers a fresh process. Deleting a stopped entry is safe: the\n# ecosystem file is the source of truth for how to bring it back.\nstart_app() {\n if \"$PM2\" start \"$ECOSYSTEM\" --update-env; then\n return 0\n fi\n echo \"[WARN] pm2 start failed — dropping the stale process entry and retrying\"\n \"$PM2\" delete selva-compute >/dev/null 2>&1 || true\n \"$PM2\" start \"$ECOSYSTEM\" --update-env\n}\n\n# Last-resort safety net. If the script exits with the app NOT online for\n# any reason (crash, kill -9, network blip, npm hang past timeout), try to\n# bring it back from ecosystem.config.cjs before exiting. Leaving the app\n# down is the worst possible outcome of an update.\non_exit() {\n CODE=$?\n STATUS=$(app_status)\n # A 'stopping' entry is mid-drain, not down. Restarting it now hits the same\n # dead-id window that brought us here; wait for the entry to settle first.\n if [ \"$STATUS\" = \"stopping\" ]; then\n wait_until_stopped\n STATUS=$(app_status)\n fi\n if [ \"$STATUS\" != \"online\" ]; then\n echo \"[RECOVER] selva-compute is '$STATUS' — starting from ecosystem.config.cjs\"\n start_app >/dev/null 2>&1 || \\\\\n echo \"[RECOVER] pm2 start failed — manual intervention required: cd $(dirname \"$ECOSYSTEM\") && ./node_modules/.bin/pm2 delete selva-compute; ./node_modules/.bin/pm2 start ecosystem.config.cjs\"\n fi\n # Terminal marker: the restarted app's outcome reconciler greps this to turn\n # the run into an audit event (selfUpdate.server.ts). Keep the format stable.\n echo \"[EXIT] code=$CODE\"\n}\ntrap on_exit EXIT\n\n# A killed runner must not look like a finished one.\n#\n# \\`$?\\` inside an EXIT trap reports the last completed command, NOT the signal.\n# When systemd SIGTERMs the whole cgroup, the EXIT trap still runs and records\n# \\`code=0\\` — so deriveOutcome takes the exit-0 success branch and tells the\n# operator \"Updated X → Y. The app is back online.\" while npm never ran and\n# the deployment is unchanged. Catching the signal makes the recorded code\n# truthful; 143/130 are the conventional 128+signal values.\non_signal() {\n SIG=$1\n echo \"[FATAL] KILLED: runner received SIG$SIG before finishing.\"\n echo \"[FATAL] Nothing was installed by this run. If the app is down, recover with:\"\n echo \"[FATAL] cd $(dirname \"$ECOSYSTEM\") && pm2 start ecosystem.config.cjs --update-env\"\n echo \"[FATAL] A systemd-supervised pm2 can do this when 'pm2 update' recycles the daemon.\"\n exit $2\n}\ntrap 'on_signal TERM 143' TERM\ntrap 'on_signal INT 130' INT\ntrap 'on_signal HUP 129' HUP\n\n# ---------------------------------------------------------------------------\n# 1. Pre-flight: skip the whole cycle if there's nothing to install.\n# ---------------------------------------------------------------------------\n# Without this, clicking \"Update\" on an already-current instance triggers a\n# full stop/install/start cycle and a downtime window for no reason.\necho \"[STEP] Checking npm registry for the '$TAG' channel version\"\nLATEST=$(npm view \"@selvajs/selva@$TAG\" version --silent 2>/dev/null || echo \"\")\nif [ -z \"$LATEST\" ]; then\n echo \"[WARN] Could not query npm registry — proceeding with update attempt anyway\"\nelif [ -n \"$BEFORE\" ] && [ \"$LATEST\" = \"$BEFORE\" ]; then\n echo \"[INFO] Already on the '$TAG' channel version ($BEFORE)\"\n echo \"[DONE] Nothing to do\"\n exit 0\nelse\n # May be a forward update OR a revert (target older than installed) — either\n # way the installed version differs from what this channel publishes.\n echo \"[INFO] Target ($TAG): $BEFORE → $LATEST\"\nfi\n\n# ---------------------------------------------------------------------------\n# 1b. Node engine pre-flight — BEFORE any downtime.\n# ---------------------------------------------------------------------------\n# npm only treats an engine mismatch as fatal under engine-strict=true, which\n# no deployment sets. So a release requiring a newer Node installs\n# \"successfully\", pm2 starts, and /api/health returns 200 (it touches nothing\n# Node-version specific) — a false green that skips rollback entirely. Warn\n# here so a CLI-driven run sees it too; the admin UI blocks earlier.\nREQUIRED_NODE=$(npm view \"@selvajs/selva@$TAG\" engines.node --silent 2>/dev/null | tr -d '\"' | tr -d \"'\")\nRUNNING_NODE=$(node -p 'process.versions.node' 2>/dev/null)\nif [ -n \"$REQUIRED_NODE\" ] && [ -n \"$RUNNING_NODE\" ]; then\n # Compare majors only — the ranges we publish are all \\`>=X\\` forms.\n REQ_MAJOR=$(echo \"$REQUIRED_NODE\" | grep -o '[0-9]\\\\+' | head -1)\n RUN_MAJOR=$(echo \"$RUNNING_NODE\" | cut -d. -f1)\n if [ -n \"$REQ_MAJOR\" ] && [ \"$RUN_MAJOR\" -lt \"$REQ_MAJOR\" ] 2>/dev/null; then\n echo \"[WARN] ENGINE_MISMATCH: @selvajs/selva@$LATEST requires Node $REQUIRED_NODE but this host runs v$RUNNING_NODE\"\n echo \"[WARN] npm will install it anyway (engine-strict is off) and the health probe will pass,\"\n echo \"[WARN] but routes using newer Node APIs will fail at request time. Upgrade Node on this host.\"\n fi\nfi\n\n# ---------------------------------------------------------------------------\n# 1c. Data format pre-flight — BEFORE any downtime.\n# ---------------------------------------------------------------------------\n# A release with a lower data format than the installed one cannot read what\n# this deployment has already stored (dataFormat.server.ts). It would boot, fail\n# its health check and roll back: two outages for nothing. Installed by hand it\n# leaves stored Compute API keys unreadable. A release that declares no format\n# is format 1. Skipped when the registry gave no answer: the target is unknown.\nINSTALLED_FORMAT=$(node -p \"require('./node_modules/@selvajs/selva/package.json').selva?.dataFormat ?? 1\" 2>/dev/null)\ncase \"$INSTALLED_FORMAT\" in ''|*[!0-9]*) INSTALLED_FORMAT=1 ;; esac\nif [ -n \"$LATEST\" ] && TARGET_FORMAT=$(npm view \"@selvajs/selva@$TAG\" selva.dataFormat --silent 2>/dev/null); then\n TARGET_FORMAT=$(echo \"$TARGET_FORMAT\" | tr -d '\"' | tr -d \"'\" | tr -d '[:space:]')\n case \"$TARGET_FORMAT\" in ''|*[!0-9]*) TARGET_FORMAT=1 ;; esac\n if [ \"$TARGET_FORMAT\" -lt \"$INSTALLED_FORMAT\" ]; then\n echo \"[FATAL] DATA_FORMAT: @selvajs/selva@$LATEST reads data format $TARGET_FORMAT, but this deployment is on format $INSTALLED_FORMAT.\"\n echo \"[FATAL] It could not read what the installed version has stored, such as Compute API keys.\"\n echo \"[FATAL] Aborting WITHOUT stopping the app — it is still running.\"\n echo \"[FATAL] To go back anyway: docs/self-hosting/deployment/admin.md, 'Going back to an older release'.\"\n exit 10\n fi\nfi\n\n# ---------------------------------------------------------------------------\n# 2. Resync PM2 daemon if its in-memory version drifted from the CLI on disk.\n# ---------------------------------------------------------------------------\n# After a global pm2 upgrade the daemon keeps running its original version\n# while the CLI moves forward. Process commands then talk to a stale daemon\n# and the symptom is \"stop works, start never lands\". \\`pm2 update\\` dumps\n# processes, kills the daemon, respawns on the current CLI, restores the\n# dump. Doing it before we touch anything keeps the rest of the script\n# talking to a coherent daemon.\necho \"[STEP] Checking PM2 daemon/CLI version sync\"\nPING_OUT=$(\"$PM2\" ping 2>&1)\nif echo \"$PING_OUT\" | grep -q \"out-of-date\"; then\n # pm2 prints both versions alongside the warning. Which is newer decides\n # whether \\`pm2 update\\` can help — see the direction check below.\n DAEMON_V=$(echo \"$PING_OUT\" | sed -e 's/\\\\x1b\\\\[[0-9;]*m//g' \\\\\n | grep -i \"In memory PM2 version\" | grep -o '[0-9]\\\\+\\\\.[0-9]\\\\+\\\\.[0-9]\\\\+' | head -1)\n LOCAL_V=$(echo \"$PING_OUT\" | sed -e 's/\\\\x1b\\\\[[0-9;]*m//g' \\\\\n | grep -i \"Local PM2 version\" | grep -o '[0-9]\\\\+\\\\.[0-9]\\\\+\\\\.[0-9]\\\\+' | head -1)\n DAEMON_MAJOR=\\${DAEMON_V%%.*}\n LOCAL_MAJOR=\\${LOCAL_V%%.*}\n\n # A daemon NEWER than the deployment-local CLI means a foreign global pm2 owns\n # it. \\`pm2 update\\` would DOWNGRADE the daemon and feed it a dump it can't read,\n # losing the process table — selva-compute never gets re-registered. That is an\n # operator problem, not something this script can repair, so stop before we\n # take the app down.\n if [ -n \"$DAEMON_MAJOR\" ] && [ -n \"$LOCAL_MAJOR\" ] && [ \"$DAEMON_MAJOR\" -gt \"$LOCAL_MAJOR\" ] 2>/dev/null; then\n echo \"[FATAL] PM2_SKEW: the running daemon (v$DAEMON_V) is NEWER than this deployment's pm2 (v$LOCAL_V).\"\n echo \"[FATAL] A global pm2 owns the daemon. Running 'pm2 update' would downgrade it and drop\"\n echo \"[FATAL] the process table. Resolve manually before updating:\"\n echo \"[FATAL] which -a pm2 && pm2 -v && pm2 ping\"\n echo \"[FATAL] Aborting WITHOUT stopping the app — it is still running.\"\n exit 8\n fi\n\n if pm2_under_systemd; then\n echo \"[FATAL] SYSTEMD_PM2: this deployment's PM2 is supervised by systemd, and the daemon\"\n echo \"[FATAL] needs a resync. Running 'pm2 update' here would restart the systemd unit and\"\n echo \"[FATAL] kill this runner mid-update. Resync manually from a shell, then retry:\"\n echo \"[FATAL] cd $(dirname \"$ECOSYSTEM\") && ./node_modules/.bin/pm2 update\"\n echo \"[FATAL] Aborting WITHOUT stopping the app — it is still running.\"\n exit 9\n fi\n\n echo \"[STEP] PM2 daemon is out-of-date — running 'pm2 update' to resync\"\n if ! \"$PM2\" update; then\n echo \"[FATAL] pm2 update failed — aborting before stopping the running app\"\n exit 1\n fi\n echo \"[INFO] PM2 daemon resynced\"\nfi\n\n# ---------------------------------------------------------------------------\n# 3. Stop selva-compute BEFORE npm rewrites build/.\n# ---------------------------------------------------------------------------\n# SvelteKit's node adapter lazy-imports chunks from build/server/chunks/ on\n# every request. Letting npm rewrite build/ while the old process still\n# serves traffic means in-flight requests hit ERR_MODULE_NOT_FOUND for chunks\n# whose hash just changed under their feet. Stopping first is a brief\n# downtime window (~1-2s longer than restart-in-place) for a much smaller\n# blast radius.\n#\n# This is also where the SSE connection to the frontend dies — selva-compute\n# IS the SSE server. From here on, the user sees output via the log-file\n# polling fallback in the admin UI, not over SSE.\necho \"[STEP] Stopping selva-compute\"\nif ! \"$PM2\" stop selva-compute; then\n echo \"[WARN] pm2 stop failed — selva-compute may not be running yet. Continuing.\"\nfi\n\n# pm2 stop returns before the process is actually gone. Everything below —\n# npm rewriting build/, then the restart — must happen outside the drain window.\nwait_until_stopped\n\n# ---------------------------------------------------------------------------\n# 4. Run npm update.\n# ---------------------------------------------------------------------------\necho \"[STEP] Updating @selvajs/* packages\"\nif ! ${npmCommand}; then\n echo \"[FATAL] npm update failed — EXIT trap will restart the previous build\"\n exit 1\nfi\n\nAFTER=$(node -e \"try{console.log(require('./node_modules/@selvajs/selva/package.json').version)}catch(e){}\" 2>/dev/null)\necho \"[INFO] New @selvajs/selva: \\${AFTER:-unknown}\"\n\nif [ -n \"$BEFORE\" ] && [ \"$BEFORE\" = \"$AFTER\" ]; then\n echo \"[WARN] No version change ($BEFORE). Your npm cache may be stale.\"\n echo \"[WARN] Recover with:\"\n echo \"[WARN] npm cache clean --force\"\n echo \"[WARN] rm -rf node_modules package-lock.json\"\n echo \"[WARN] npm install --prefer-online\"\nfi\n\n# ---------------------------------------------------------------------------\n# 4b. Move pm2 onto the version the new CLI pins.\n# ---------------------------------------------------------------------------\n# Only \\`selva migrate\\` rewrites package.json, so without this a release that\n# bumps pm2 needs a manual migrate on every host. The pin is read from the CLI\n# just installed: its devDependencies.pm2 is what a fresh scaffold gets. The\n# app is stopped, so swapping the daemon here adds no downtime. A failure\n# leaves the old pm2 running the app: warn, never abort. A rollback below\n# keeps the new pm2: reinstalling the old one would leave the daemon newer\n# than the CLI, the one skew \\`pm2 update\\` cannot repair.\nPM2_DECLARED=$(node -p \"require('./package.json').dependencies?.pm2 ?? ''\" 2>/dev/null)\nPM2_PIN=$(node -p \"require('./node_modules/@selvajs/cli/package.json').devDependencies?.pm2 ?? ''\" 2>/dev/null)\nif [ -n \"$PM2_PIN\" ] && [ \"$PM2_PIN\" != \"$PM2_DECLARED\" ]; then\n echo \"[STEP] Moving pm2 \\${PM2_DECLARED:-(none)} → $PM2_PIN, the version this release pins\"\n if npm install --save --save-exact --prefer-online \"pm2@$PM2_PIN\"; then\n if pm2_under_systemd; then\n echo \"[WARN] PM2_RESYNC_NEEDED: pm2 is now $PM2_PIN, but its daemon still runs the old version.\"\n echo \"[WARN] Swapping it here would restart the systemd unit and kill this runner. From a shell:\"\n echo \"[WARN] cd $(dirname \"$ECOSYSTEM\") && npx pm2 update && npx pm2 list\"\n echo \"[WARN] Let it finish: interrupting it leaves selva-compute unregistered.\"\n elif ! \"$PM2\" update; then\n echo \"[WARN] PM2_RESYNC_NEEDED: 'pm2 update' failed — the daemon still runs the old pm2.\"\n echo \"[WARN] cd $(dirname \"$ECOSYSTEM\") && npx pm2 update && npx pm2 list\"\n fi\n else\n echo \"[WARN] PM2_PIN_FAILED: could not install pm2@$PM2_PIN — the previous pm2 still runs the app.\"\n echo \"[WARN] Retry from a shell: cd $(dirname \"$ECOSYSTEM\") && npx selva migrate\"\n fi\nfi\n\n# ---------------------------------------------------------------------------\n# 5. Start selva-compute with the new build.\n# ---------------------------------------------------------------------------\n# Start from ecosystem.config.cjs, NOT \\`pm2 start selva-compute\\` — the latter\n# requires selva-compute to already be in pm2's in-memory process list, which\n# a \\`pm2 update\\` (step 2) isn't guaranteed to preserve.\necho \"[STEP] Starting selva-compute with new build\"\nif ! start_app; then\n echo \"[FATAL] pm2 start failed — investigate with \\\\\\`pm2 logs selva-compute\\\\\\`\"\n exit 2\nfi\n\n# ---------------------------------------------------------------------------\n# 6. Health probe the new process.\n# ---------------------------------------------------------------------------\n# Read PORT from .env the same way scripts/update.sh does, so non-default\n# ports are respected.\nPORT=$(grep \"^PORT=\" .env 2>/dev/null \\\\\n | head -1 \\\\\n | cut -d'=' -f2 \\\\\n | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//' -e 's/^[\"'\"'\"']//' -e 's/[\"'\"'\"']$//' -e 's/[[:space:]]*#.*//')\nPORT=\\${PORT:-3000}\n\necho \"[STEP] Health-probing the new process on port $PORT\"\n# mktemp for the same reason as the runner itself: /tmp is shared. Without one\n# the probe still runs; only the rollback loses the body it names the cause from.\nHEALTH_BODY=$(mktemp \"\\${TMPDIR:-/tmp}/selva-health.XXXXXXXX\") || HEALTH_BODY=\nHEALTHY=0\nfor i in $(seq 1 15); do\n sleep 2\n CODE=$(curl -sS -o \"\\${HEALTH_BODY:-/dev/null}\" -w \"%{http_code}\" --max-time 5 \"http://localhost:$PORT/api/health\" 2>/dev/null || echo \"000\")\n if [ \"$CODE\" = \"200\" ]; then\n HEALTHY=1\n echo \"[INFO] Health probe passed after \\${i} attempt(s)\"\n [ -n \"$HEALTH_BODY\" ] && rm -f \"$HEALTH_BODY\"\n break\n fi\n echo \"[INFO] Probe attempt $i/15: HTTP $CODE — retrying\"\ndone\n\nif [ \"$HEALTHY\" = \"1\" ]; then\n echo \"[DONE] Update complete\"\n exit 0\nfi\n\n# ---------------------------------------------------------------------------\n# 7. Rollback path.\n# ---------------------------------------------------------------------------\necho \"[FATAL] New process failed health check after 30s\"\nif [ -s \"$HEALTH_BODY\" ]; then\n BODY=$(cat \"$HEALTH_BODY\")\n echo \"[FATAL] Last response body:\"\n echo \"$BODY\"\n\n # Name the cause before rolling back. /api/health reports WHY it is degraded\n # in a structured body, but a rollback that only prints raw JSON reads to an\n # operator as \"the update just failed\" — they retry, hit the identical\n # failure, and never learn the database is the thing that needs attention.\n # Each branch below emits a stable marker deriveOutcome keys on.\n # Match on the keys unique to each report rather than a bare \\`\"ok\":false\\`,\n # which appears in whichever sub-report failed and would misattribute one\n # cause to the other. \\`expected\\` only ever appears in schemaVersion;\n # \\`plaintextFound\\`/\\`failures\\` only in atRestSecrets.\n if echo \"$BODY\" | grep -q '\"expected\":'; then\n EXPECTED=$(echo \"$BODY\" | grep -o '\"expected\":\"[^\"]*\"' | head -1 | cut -d'\"' -f4)\n ACTUAL=$(echo \"$BODY\" | grep -o '\"actual\":\"[^\"]*\"' | head -1 | cut -d'\"' -f4)\n echo \"[FATAL] SCHEMA_SKEW: @selvajs/selva@\\${AFTER:-$LATEST} expects database migration head \\${EXPECTED:-(unknown)},\"\n echo \"[FATAL] but this database is at \\${ACTUAL:-(unavailable)}. The new version is fine — its migrations\"\n echo \"[FATAL] were never applied. Retrying the update WILL fail again in exactly the same way.\"\n echo \"[FATAL] The update does not apply migrations itself: they are not reversible, so an\"\n echo \"[FATAL] auto-migrate followed by a rollback would leave code and database on different heads.\"\n echo \"[FATAL] Apply them yourself, then re-run the update:\"\n echo \"[FATAL] cd $(dirname \"$ECOSYSTEM\")\"\n echo \"[FATAL] npm install --prefer-online @selvajs/supabase-provider@$TAG\"\n echo \"[FATAL] npx selva-supabase\"\n echo \"[FATAL] npx supabase db push\"\n echo \"[FATAL] The provider install is not optional: the migration SQL ships inside that\"\n echo \"[FATAL] package, and the update only moves @selvajs/cli and @selvajs/selva — so a sync\"\n echo \"[FATAL] without it copies 0 files and the push reports 'up to date' having done nothing.\"\n echo \"[FATAL] If db push asks for credentials, see docs/self-hosting/providers/supabase.md\"\n echo \"[FATAL] — it needs a Supabase ACCOUNT credential (supabase login, or SUPABASE_ACCESS_TOKEN),\"\n echo \"[FATAL] which is not any of the three keys in .env.\"\n elif echo \"$BODY\" | grep -qE '\"plaintextFound\":true|\"failures\":\\\\[[^]]'; then\n echo \"[FATAL] AT_REST_SECRETS: stored compute server API keys could not be decrypted under the\"\n echo \"[FATAL] current SELVA_AT_REST_KEY. This is a configuration problem on this host, not a\"\n echo \"[FATAL] fault in the new version — retrying the update will fail the same way.\"\n echo \"[FATAL] Re-enter the affected keys at /admin/compute, or restore the original\"\n echo \"[FATAL] SELVA_AT_REST_KEY, then re-run the update.\"\n else\n echo \"[FATAL] The health endpoint did not report a known cause. Inspect the body above and\"\n echo \"[FATAL] \\\\\\`pm2 logs selva-compute\\\\\\` for what the new version failed on.\"\n fi\n\n rm -f \"$HEALTH_BODY\"\nfi\n\nif [ -z \"$BEFORE\" ]; then\n echo \"[FATAL] No prior version recorded — cannot roll back automatically.\"\n echo \"[FATAL] EXIT trap will attempt to restart the current build anyway.\"\n exit 3\nfi\n\n# The failed version has already booted, so it may have rewritten stored data in\n# a format $BEFORE cannot read. Rolling back is still the better outcome; say so.\nAFTER_FORMAT=$(node -p \"require('./node_modules/@selvajs/selva/package.json').selva?.dataFormat ?? 1\" 2>/dev/null)\ncase \"$AFTER_FORMAT\" in ''|*[!0-9]*) AFTER_FORMAT=1 ;; esac\nif [ \"$AFTER_FORMAT\" -gt \"$INSTALLED_FORMAT\" ]; then\n echo \"[WARN] DATA_FORMAT_ROLLBACK: the failed version stores data format $AFTER_FORMAT; $BEFORE reads format $INSTALLED_FORMAT.\"\n echo \"[WARN] If Compute API keys fail to load after this rollback, re-enter them at /admin/compute.\"\nfi\n\necho \"[STEP] Rolling back @selvajs/selva to $BEFORE\"\n\"$PM2\" stop selva-compute >/dev/null 2>&1 || true\nwait_until_stopped >/dev/null 2>&1\n# Restore @selvajs/cli alongside the runtime: the forward step installs both at\n# the channel tag, so reverting only the runtime leaves a version pair that was\n# never released together.\nif ! npm install --save \"@selvajs/cli@$BEFORE\" \"@selvajs/selva@$BEFORE\"; then\n echo \"[FATAL] Rollback npm install failed — EXIT trap will retry restart.\"\n exit 4\nfi\n\nstart_app || true\nsleep 3\nROLLBACK_CODE=$(curl -sS -o /dev/null -w \"%{http_code}\" --max-time 5 \"http://localhost:$PORT/api/health\" 2>/dev/null || echo \"000\")\nif [ \"$ROLLBACK_CODE\" = \"200\" ]; then\n echo \"[DONE] Rolled back to $BEFORE — previous version is online\"\n exit 5\nfi\n\necho \"[FATAL] Rollback restart also failed health check (HTTP $ROLLBACK_CODE)\"\necho \"[FATAL] Manual recovery required. Check: pm2 logs selva-compute\"\nexit 6\n`;\n}\n\n// Selva self-updates as a CLI-scaffolded npm deployment: the deployment dir\n// holds a package.json that depends on @selvajs/selva, and update means\n// `npm install @selvajs/*@<tag>` + pm2 restart. Deployment-dir detection\n// (cwd-upward probe, `INSTALL_DIR` override) lives in `selfUpdate.server.ts`,\n// shared with the outcome reconciler and the log path.\nexport type UpdatePlan = { cwd: string; args: string[] };\n\n// Only the CLI and the runtime move. Provider code is bundled into\n// @selvajs/selva; @selvajs/supabase-provider carries just the migration SQL,\n// which the operator installs and pushes before updating.\n//\n// `npm install` pins to the channel's dist-tag rather than using `npm\n// update`, because `update` only ever moves FORWARD within the installed\n// semver range — it can't switch dist-tags or DOWNGRADE. Pinning to @latest /\n// @beta makes one command serve every transition: forward stable bumps,\n// beta→newer-beta, and the revert case (beta→stable lands on an older version).\n//\n// --save persists the resolved version into package.json so the next plain\n// install is reproducible; --prefer-online forces npm to revalidate cached\n// packuments against the registry — without it, npm's packument cache (5+\n// min TTL) can silently no-op right after publish.\nexport function npmInstallArgs(channel: ReleaseChannel): string[] {\n\tconst tag = channelTag(channel);\n\treturn ['install', '--save', '--prefer-online', `@selvajs/cli@${tag}`, `@selvajs/selva@${tag}`];\n}\n\nexport function detectUpdatePlan(\n\tenv: Record<string, string | undefined>,\n\tchannel: ReleaseChannel\n): UpdatePlan | null {\n\tconst dir = findDeploymentDir(env);\n\treturn dir ? { cwd: dir, args: npmInstallArgs(channel) } : null;\n}\n","import { spawn } from 'child_process';\nimport { join } from 'path';\nimport { readFileSync, writeFileSync } from 'fs';\nimport { env } from '#lib/server/env.js';\nimport { json } from '@sveltejs/kit';\nimport { actorFrom } from '@selvajs/platform';\nimport type { RequestHandler } from './$types';\nimport { requirePermission } from '#lib/server/access.server.js';\nimport { renderThrown } from '@selvajs/server/logging';\nimport { checkForUpdate } from '#lib/server/updateCheck.server.js';\nimport { readChannel, channelTag } from '#lib/server/releaseChannel.server.js';\nimport { getEventSink, getErrorReporter } from '#lib/server/providers.server.js';\nimport {\n\tfindDeploymentDir,\n\tstartUpdateOutcomeReconciler,\n\tupdateLogPath,\n\tupdateStatePath,\n\ttype PendingUpdateState\n} from '#lib/server/selfUpdate.server.js';\nimport {\n\treadRuntimeVersion,\n\tbuildLauncher,\n\tbuildNpmRunnerScript,\n\tdetectUpdatePlan\n} from '#lib/server/updateRunner.server.js';\n\n// Where the bash wrapper mirrors all script output (`updateLogPath` — in the\n// deployment dir so it survives reboots, audit O2). The SSE stream dies the\n// moment `pm2 stop selva-compute` succeeds (selva-compute IS the SSE server),\n// so the frontend loses visibility into everything that happens after — npm\n// update output, pm2 start result, health-probe results, rollback decisions.\n// The script keeps writing to this file regardless. Once the new selva-compute\n// process is back up, the frontend polls GET on this same route to fetch the\n// full log and reveal what happened during the blackout. One log per update —\n// the wrapper truncates at start, so we never carry stale content forward.\n// The runner's `[EXIT] code=N` marker in the same log also drives the\n// post-restart audit-event reconciliation (`selfUpdate.server.ts`).\n\n// Strip ANSI escape codes from terminal output\nfunction stripAnsi(str: string): string {\n\t// eslint-disable-next-line no-control-regex\n\treturn str.replace(/\\x1B\\[[0-9;]*[mGKHF]/g, '');\n}\n\n// POST - Run update and stream output via Server-Sent Events.\n//\n// Runs `npm update @selvajs/*` then restarts via ecosystem.config.cjs. The\n// runner script handles stop / update / start / health-probe / rollback with\n// an EXIT trap that keeps the app online no matter how it exits.\nexport const POST: RequestHandler = async ({ locals }) => {\n\trequirePermission(locals, 'instance_admin');\n\n\tconst channel = readChannel();\n\tconst plan = detectUpdatePlan(env, channel);\n\tif (!plan) {\n\t\treturn new Response(\n\t\t\tJSON.stringify({\n\t\t\t\terror:\n\t\t\t\t\t\"Couldn't determine how to update this deployment. \" +\n\t\t\t\t\t'Expected node_modules/@selvajs/selva (CLI scaffold) in the cwd ' +\n\t\t\t\t\t'or a parent directory.'\n\t\t\t}),\n\t\t\t{ status: 500, headers: { 'Content-Type': 'application/json' } }\n\t\t);\n\t}\n\n\t// Capture the runtime version BEFORE we touch anything, so we can:\n\t// (a) detect a no-op update and warn, (b) roll back to the prior version\n\t// if the new process fails to come up healthy.\n\tconst versionBefore = readRuntimeVersion(plan.cwd);\n\tconst actorId = locals.ctx ? actorFrom(locals.ctx) : 'system';\n\n\t// Audit trail (O2): `started` now; the terminal event is emitted by the\n\t// outcome reconciler after the app restarts (this process is killed\n\t// mid-update). The state file is the reconciler's emission token.\n\tconst pending: PendingUpdateState = {\n\t\tstartedAt: new Date().toISOString(),\n\t\tactorId,\n\t\tchannel,\n\t\tfromVersion: versionBefore\n\t};\n\ttry {\n\t\twriteFileSync(updateStatePath(plan.cwd), JSON.stringify(pending, null, '\\t'));\n\t} catch (err) {\n\t\tlocals.log.error('Could not persist pending-update state', {\n\t\t\tcomponent: 'selfUpdate',\n\t\t\terr: renderThrown(err)\n\t\t});\n\t}\n\tawait getEventSink().emit({\n\t\ttype: 'system.update.started',\n\t\tchannel,\n\t\tfromVersion: versionBefore,\n\t\tactorId\n\t});\n\n\tconst stream = new ReadableStream({\n\t\tstart(controller) {\n\t\t\tconst encoder = new TextEncoder();\n\n\t\t\tfunction sendEvent(type: string, data: Record<string, unknown>) {\n\t\t\t\tconst message = `data: ${JSON.stringify({ type, ...data })}\\n\\n`;\n\t\t\t\tcontroller.enqueue(encoder.encode(message));\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\t// Prelude lines are passed to the bash wrapper rather than\n\t\t\t\t// sendEvent'd directly so they end up in both the SSE stream\n\t\t\t\t// (via bash stdout) AND the log file (via tee). Without this,\n\t\t\t\t// the frontend's blackout-recovery file fetch would clobber\n\t\t\t\t// these lines when it replaces its buffer with the file content.\n\t\t\t\tconst prelude = [\n\t\t\t\t\t`[INFO] Updating deployment (cwd: ${plan.cwd}, channel: ${channel})`,\n\t\t\t\t\t...(versionBefore ? [`[INFO] Current @selvajs/selva: ${versionBefore}`] : [])\n\t\t\t\t];\n\n\t\t\t\t// Spawn the launcher detached. The launcher writes the actual\n\t\t\t\t// runner script to disk, daemonizes it (setsid + & + exit),\n\t\t\t\t// and quits — leaving the runner with PPID=1 so PM2's tree-kill\n\t\t\t\t// of selva-compute can't reach it. See buildLauncher for the\n\t\t\t\t// full rationale.\n\t\t\t\t//\n\t\t\t\t// The runner is buildNpmRunnerScript — pre-flights the version\n\t\t\t\t// check, then stop / npm update / start / health probe /\n\t\t\t\t// rollback, with an EXIT trap that ensures the app is online no\n\t\t\t\t// matter how the script exits.\n\t\t\t\tconst runnerScript = buildNpmRunnerScript(\n\t\t\t\t\tplan.args,\n\t\t\t\t\tversionBefore,\n\t\t\t\t\tjoin(plan.cwd, 'ecosystem.config.cjs'),\n\t\t\t\t\tchannelTag(channel)\n\t\t\t\t);\n\t\t\t\tconst cmd = 'bash';\n\t\t\t\tconst args = ['-c', buildLauncher(runnerScript, updateLogPath(plan.cwd), prelude)];\n\n\t\t\t\t// Prepend the deployment's node_modules/.bin to PATH so the bash\n\t\t\t\t// script finds the project-local pm2 (and any other tooling\n\t\t\t\t// installed as a deployment dependency). Without this the script\n\t\t\t\t// inherits the SvelteKit process's PATH, which on most servers\n\t\t\t\t// doesn't include node_modules/.bin — so `pm2` resolves to\n\t\t\t\t// whatever's globally installed, or fails outright if no global\n\t\t\t\t// pm2 exists. Both are wrong: we want the project-local pm2 so\n\t\t\t\t// daemon and CLI stay aligned. Mirrors the local-only resolution\n\t\t\t\t// in @selvajs/cli's pm2Bin().\n\t\t\t\tconst localBin = join(plan.cwd, 'node_modules', '.bin');\n\t\t\t\tconst child = spawn(cmd, args, {\n\t\t\t\t\tcwd: plan.cwd,\n\t\t\t\t\tenv: {\n\t\t\t\t\t\tPATH: `${localBin}:${process.env.PATH ?? ''}`,\n\n\t\t\t\t\t\tHOME: process.env.HOME,\n\t\t\t\t\t\tINSTALL_DIR: plan.cwd\n\t\t\t\t\t},\n\t\t\t\t\tdetached: true,\n\t\t\t\t\tstdio: ['ignore', 'pipe', 'pipe']\n\t\t\t\t});\n\t\t\t\tchild.unref();\n\n\t\t\t\t// Covers the outcomes that DON'T restart this process (pre-flight\n\t\t\t\t// \"already up to date\", early failures): this process is still\n\t\t\t\t// alive to reconcile them. A real update kills this process; the\n\t\t\t\t// restarted one re-arms the reconciler from hooks.server.ts.\n\t\t\t\tstartUpdateOutcomeReconciler({\n\t\t\t\t\tdeploymentDir: plan.cwd,\n\t\t\t\t\temit: (e) => getEventSink().emit(e),\n\t\t\t\t\treport: (err) => getErrorReporter().capture(err, { tags: { origin: 'selfUpdate' } })\n\t\t\t\t});\n\n\t\t\t\t// Kill the process if it runs longer than 15 minutes.\n\t\t\t\t// The child is detached (its own process group), so signal the\n\t\t\t\t// whole group via negative pid — otherwise descendants (pnpm,\n\t\t\t\t// node, pm2) outlive the bash wrapper.\n\t\t\t\tconst timeout = setTimeout(\n\t\t\t\t\t() => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tif (child.pid) process.kill(-child.pid, 'SIGTERM');\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t// group already gone — nothing to do\n\t\t\t\t\t\t}\n\t\t\t\t\t\tsendEvent('log', { data: '[FATAL] Update timed out after 15 minutes' });\n\t\t\t\t\t\tsendEvent('exit', { code: -1 });\n\t\t\t\t\t\tcontroller.close();\n\t\t\t\t\t},\n\t\t\t\t\t15 * 60 * 1000\n\t\t\t\t);\n\n\t\t\t\t// Stream stdout\n\t\t\t\tlet restarting = false;\n\t\t\t\tchild.stdout.on('data', (data) => {\n\t\t\t\t\tconst lines = data.toString().split('\\n');\n\t\t\t\t\tfor (const line of lines) {\n\t\t\t\t\t\tconst clean = stripAnsi(line).trim();\n\t\t\t\t\t\tif (clean) {\n\t\t\t\t\t\t\t// Detect both stopProcessId (pm2 restart) and restartProcessId (pm2 reload)\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t!restarting &&\n\t\t\t\t\t\t\t\t(clean.includes('Applying action stopProcessId') ||\n\t\t\t\t\t\t\t\t\tclean.includes('Applying action restartProcessId'))\n\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\trestarting = true;\n\t\t\t\t\t\t\t\tsendEvent('restarting', { data: clean });\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tsendEvent('log', { data: clean });\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\t// Stream stderr\n\t\t\t\tchild.stderr.on('data', (data) => {\n\t\t\t\t\tconst lines = data.toString().split('\\n');\n\t\t\t\t\tfor (const line of lines) {\n\t\t\t\t\t\tconst clean = stripAnsi(line).trim();\n\t\t\t\t\t\tif (clean) {\n\t\t\t\t\t\t\tsendEvent('log', { data: `[ERROR] ${clean}` });\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\t// Handle process exit\n\t\t\t\tchild.on('close', (code) => {\n\t\t\t\t\tclearTimeout(timeout);\n\t\t\t\t\tsendEvent('exit', { code: code ?? -1 });\n\t\t\t\t\tcontroller.close();\n\t\t\t\t});\n\n\t\t\t\t// Handle errors\n\t\t\t\tchild.on('error', (err) => {\n\t\t\t\t\tclearTimeout(timeout);\n\t\t\t\t\tsendEvent('log', { data: `[FATAL] ${err.message}` });\n\t\t\t\t\tsendEvent('exit', { code: -1 });\n\t\t\t\t\tcontroller.close();\n\t\t\t\t});\n\t\t\t} catch (err) {\n\t\t\t\tsendEvent('log', { data: `[FATAL] Failed to spawn process: ${err}` });\n\t\t\t\tsendEvent('exit', { code: -1 });\n\t\t\t\tcontroller.close();\n\t\t\t}\n\t\t}\n\t});\n\n\treturn new Response(stream, {\n\t\theaders: {\n\t\t\t'Content-Type': 'text/event-stream',\n\t\t\t'Cache-Control': 'no-cache',\n\t\t\tConnection: 'keep-alive'\n\t\t}\n\t});\n};\n\n// GET — two jobs, selected by query param:\n//\n// ?check=1 → query the npm registry and report whether a newer\n// @selvajs/selva is published. JSON: { current, latest,\n// updateAvailable }. The admin page calls this on load to show\n// an \"update available\" badge. Degrades gracefully: if the\n// registry is unreachable, latest is null and updateAvailable\n// is false (we never block the page on npm).\n//\n// (default) → read the tee'd update log so the frontend can recover the\n// chunk of output that happened during the SSE blackout (between\n// `pm2 stop` killing this process and the new selva-compute\n// coming back online). Empty body if no update has run yet.\n// Polled by the admin UI during the post-restart wait.\nexport const GET: RequestHandler = async ({ locals, url, fetch }) => {\n\trequirePermission(locals, 'instance_admin');\n\n\tif (url.searchParams.get('check') !== null) {\n\t\treturn json(await checkForUpdate(fetch, readChannel()), {\n\t\t\theaders: { 'Cache-Control': 'no-store' }\n\t\t});\n\t}\n\n\tlet body = '';\n\ttry {\n\t\tbody = readFileSync(updateLogPath(findDeploymentDir(env)), 'utf8');\n\t} catch {\n\t\t// Log doesn't exist (no update has run yet). Empty body is correct —\n\t\t// the frontend treats no content as \"nothing to show yet\".\n\t}\n\treturn new Response(body, {\n\t\theaders: {\n\t\t\t'Content-Type': 'text/plain; charset=utf-8',\n\t\t\t'Cache-Control': 'no-store'\n\t\t}\n\t});\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAaA,SAAgB,mBAAmB,KAAiC;CACnE,IAAI;EACH,MAAM,MAAM,KAAK,MAChB,a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,MAAM,MACrC,OAAO,KAAK,MAAM,eAAe,OAAO,YAAY,CAAC,GAAG,EACvD,SAAS,EAAE,iBAAiB,WAAW,EACxC,CAAC;CAGF,IAAI,OAAO;CACX,IAAI;EACH,OAAOC,eAAa,cAAc,kBAAkB,GAAG,CAAC,GAAG,MAAM;CAClE,QAAQ,CAGR;CACA,OAAO,IAAI,SAAS,MAAM,EACzB,SAAS;EACR,gBAAgB;EAChB,iBAAiB;CAClB,EACD,CAAC;AACF"}
|
|
1
|
+
{"version":3,"file":"_server.ts.js","names":["join","readFileSync"],"sources":["../../../../../../../../src/lib/server/updateRunner.server.ts","../../../../../../../../src/routes/api/admin/system/update/+server.ts"],"sourcesContent":["/**\n * Generates the bash the self-update POST route spawns: a tiny daemonizing\n * launcher plus the runner script that actually stops/updates/starts/health-\n * checks the deployment. Split out of the route file because SvelteKit's\n * route-file validator only allows HTTP-verb exports (and `_`-prefixed ones) —\n * these are plain functions the runner-script contract tests import directly.\n */\n\nimport { readFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { findDeploymentDir } from './selfUpdate.server.js';\nimport { channelTag, type ReleaseChannel } from './releaseChannel.server.js';\n\nexport function readRuntimeVersion(dir: string): string | undefined {\n\ttry {\n\t\tconst pkg = JSON.parse(\n\t\t\treadFileSync(join(dir, 'node_modules', '@selvajs', 'selva', 'package.json'), 'utf8')\n\t\t);\n\t\treturn typeof pkg.version === 'string' ? pkg.version : undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n// No caller currently passes untrusted input (plan.cwd is from\n// process.cwd(), npm package names are hardcoded), but defensive quoting is\n// cheap.\nexport function shellQuote(s: string): string {\n\treturn `'${s.replace(/'/g, `'\\\\''`)}'`;\n}\n\n// Wraps the actual update commands in a tiny \"launcher\" that daemonizes them.\n//\n// THE PROBLEM: `pm2 stop selva-compute` (which the runner has to call) uses\n// tree-kill, which walks /proc parent-child relationships from\n// selva-compute's PID and SIGKILLs every descendant. Node's\n// `{ detached: true }` + `child.unref()` puts the spawned bash in a new\n// session/process group but does NOT change the parent-child relationship —\n// so tree-kill still finds and kills it, and the app never restarts.\n//\n// THE FIX: write the update commands to a tempfile and launch them via\n// `setsid bash ... &`, then have the launcher exit. The runner's PPID becomes\n// 1 (init) the moment the launcher exits, so it's no longer a descendant of\n// selva-compute and tree-kill can't reach it.\n//\n// Output: the launcher's prelude lines are echoed via tee into\n// UPDATE_LOG_PATH and through stdout (visible to SSE while the connection is\n// still up); the runner appends its output to the same log file; the\n// frontend tolerates the SSE blackout by polling the log file.\nexport function buildLauncher(\n\trunnerScript: string,\n\tlogPath: string,\n\tprelude: string[] = []\n): string {\n\tconst echoes = prelude.map((line) => `echo ${shellQuote(line)}`).join('\\n');\n\t// Note: runner script is embedded via a QUOTED heredoc so no variable\n\t// expansion happens — the runner text is written verbatim.\n\treturn `\nLOGFILE=${shellQuote(logPath)}\nmkdir -p \"$(dirname \"$LOGFILE\")\"\n: > \"$LOGFILE\"\n\n# mktemp, never a fixed name: /tmp is shared, and a file another account left at\n# a known path survives the write below and would run as the app user.\nRUNNER=$(mktemp \"\\${TMPDIR:-/tmp}/selva-update-runner.XXXXXXXX\") || {\n\techo \"[ERROR] Could not create the update runner in \\${TMPDIR:-/tmp}\"\n\texit 1\n}\ncat > \"$RUNNER\" <<'__SELVA_RUNNER_EOF__' || { echo \"[ERROR] Could not write the update runner\"; exit 1; }\nrm -f \"$0\"\nfor _ in $(seq 1 50); do\n kill -0 \"$SELVA_RUNNER_SPAWNER\" 2>/dev/null || break\n sleep 0.1\ndone\n${runnerScript}\n__SELVA_RUNNER_EOF__\n\ntrap '' PIPE\nexec > >(tee --output-error=warn-nopipe -a \"$LOGFILE\" 2>/dev/null) 2>&1\n${echoes}\n\n# Daemonize the runner so PM2's tree-kill of selva-compute can't reach it.\n# When the runner calls pm2 stop, pm2 lists the app's descendants and SIGKILLs\n# whatever on that list outlives its kill timeout. A runner still parented to this\n# launcher is on the list: it died mid-update and left the app stopped whenever the\n# registry answered inside the pause below. So it is orphaned before it runs a\n# line: the subshell forks it and exits, and the runner waits for that exit.\n# setsid gives it its own session; its stdio is detached from selva-compute's pipes.\nRUNNER_PID=$( (SELVA_RUNNER_SPAWNER=$BASHPID setsid bash \"$RUNNER\" </dev/null >>\"$LOGFILE\" 2>&1 & echo $!) )\necho \"[INFO] Update runner started (PID $RUNNER_PID, log: $LOGFILE)\"\n\n# Small pause so the runner has time to print its first line before SSE\n# closes — otherwise the frontend's first poll might see no progress.\nsleep 1\nexit 0\n`;\n}\n\n// Bash script the daemonized runner executes. Flow:\n//\n// 1. pre-flight — query the registry; if already on latest, exit clean\n// WITHOUT touching the running app. Refuse a target\n// that cannot read this deployment's data.\n// 2. pm2 sync — `pm2 update` if the daemon and CLI versions drifted.\n// 2b. ownership — refuse when pm2's app of this name belongs to another\n// install: the stop would take THAT one down.\n// 3. pm2 stop — stop the app before npm overwrites build/, so\n// in-flight requests can't hit ERR_MODULE_NOT_FOUND\n// from chunk-hash churn under their feet.\n// 3b. gone? — refuse when the old process still answers the port:\n// this pm2 does not run it, so it cannot replace it.\n// 4. npm update — refresh @selvajs/* (--prefer-online bypasses the\n// packument cache, already baked into npmArgs).\n// 5. pm2 start — from ecosystem.config.cjs (not `pm2 start name`,\n// which requires the process to already be in pm2's\n// in-memory list — fragile after `pm2 update`).\n// 6. health probe — poll /api/health for up to 30s.\n// 7. rollback — on failure: npm install the prior version, restart.\n// 8. EXIT trap — last-resort: if anything above leaves the app\n// offline (crash, kill, network blip), unconditionally\n// try `pm2 start ecosystem.config.cjs` before exiting\n// so the customer's site doesn't stay dark.\n//\n// Embedded into the launcher via a quoted heredoc, so this whole string is\n// written verbatim — interpolated values must be shell-quoted at JS time.\nexport function buildNpmRunnerScript(\n\tnpmArgs: string[],\n\tversionBefore: string | undefined,\n\tecosystemPath: string,\n\ttag: string\n): string {\n\tconst npmCommand = ['npm', ...npmArgs].map(shellQuote).join(' ');\n\t// Empty string when versionBefore is undefined — bash sees `BEFORE=\"\"`\n\t// and skips the rollback path (you can't roll back to nothing).\n\tconst before = shellQuote(versionBefore ?? '');\n\tconst ecosystem = shellQuote(ecosystemPath);\n\t// The npm dist-tag the chosen channel resolves to (`latest` / `beta`). The\n\t// pre-flight and no-change warning query this tag, so they don't misfire on\n\t// a beta channel (where the channel's published version is a pre-release the\n\t// default `latest` query would never see) or on a revert (where the target\n\t// stable version is OLDER than the installed beta).\n\tconst distTag = shellQuote(tag);\n\n\treturn `#!/bin/bash\nset -o pipefail\nBEFORE=${before}\nECOSYSTEM=${ecosystem}\nTAG=${distTag}\n\n# Resolve the deployment-local pm2 explicitly instead of trusting PATH.\n# The runner is re-launched via \\`setsid bash\\` from a tempfile, so it inherits\n# whatever environment the spawning process had. When the update is triggered\n# from the admin UI that happens to include node_modules/.bin; from cron or a\n# bare shell it does not, and every pm2 call below — including the EXIT trap's\n# last-resort restart — fails with \"command not found\" and the app stays dark.\nPM2=\"$(dirname \"$ECOSYSTEM\")/node_modules/.bin/pm2\"\n[ -x \"$PM2\" ] || PM2=pm2\n\n# pm2 finds an app by name alone, and the name is whatever this install's\n# ecosystem file declares. Two installs under one pm2 daemon need different ones.\nAPP=$(node -p \"require(process.argv[1]).apps[0].name\" \"$ECOSYSTEM\" 2>/dev/null)\ncase \"$APP\" in ''|undefined|null) APP=selva-compute ;; esac\nHERE=$(cd \"$(dirname \"$ECOSYSTEM\")\" 2>/dev/null && pwd -P)\n\n# Read PORT from .env the same way scripts/update.sh does, so non-default\n# ports are respected.\nPORT=$(grep \"^PORT=\" .env 2>/dev/null \\\\\n | head -1 \\\\\n | cut -d'=' -f2 \\\\\n | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//' -e 's/^[\"'\"'\"']//' -e 's/[\"'\"'\"']$//' -e 's/[[:space:]]*#.*//')\nPORT=\\${PORT:-3000}\n\n# Prints one string field of the /api/health body on stdin.\njson_field() {\n grep -o '\"'\"$1\"'\":\"[^\"]*\"' | head -1 | cut -d'\"' -f4\n}\n\n# Prints the instanceId of whatever answers this install's port, or nothing while\n# the port is silent.\nserving_instance() {\n curl -sS --max-time 5 \"http://localhost:$PORT/api/health\" 2>/dev/null | json_field instanceId\n}\n\n# Under systemd, \\`pm2 update\\` kills and respawns the daemon. systemd sees its\n# unit's main process die and, with the default KillMode=control-group,\n# SIGTERMs everything in the cgroup — including this runner. setsid escapes\n# PM2's tree-kill but NOT the cgroup, so the runner never runs \\`pm2 update\\`\n# when this is true.\npm2_under_systemd() {\n grep -qs 'pm2.*\\\\.service' /proc/self/cgroup 2>/dev/null\n}\n\n# Waits for selva-compute to leave the transitional 'stopping' state.\n#\n# \\`pm2 stop\\` sends SIGINT and returns without waiting for the process to die.\n# The SvelteKit node adapter then drains in-flight requests before exiting, and\n# PM2 only escalates to SIGKILL after kill_timeout (10s in the scaffolded\n# ecosystem). For that whole window the process table entry has a name and an\n# id but no live pid — \\`pm2 start\\` resolves the name, converts to a restart,\n# finds nothing to restart, and pm2's own table printer crashes on\n# \\`undefined.pm2_env\\`. Polling here keeps the rest of the script out of that\n# window entirely.\n#\n# The drain reliably takes the full timeout when the update was triggered from\n# the admin UI: that page is fed by an SSE stream this very process serves, and\n# an open SSE stream never completes on its own.\n# Prints exactly one word. Callers compare it against 'online' / 'stopping', so\n# a probe that emits two tokens on failure (the inline catch AND a shell\n# fallback both firing) would silently never match either. Node's catch is the\n# single failure path; fd 0 rather than /dev/stdin because the latter isn't a\n# readable pipe everywhere.\napp_status() {\n \"$PM2\" jlist 2>/dev/null | SELVA_APP=\"$APP\" node -e \"\n try {\n const list = JSON.parse(require('fs').readFileSync(0,'utf8'));\n const app = list.find(p => p.name === process.env.SELVA_APP);\n process.stdout.write(app ? app.pm2_env.status : 'missing');\n } catch { process.stdout.write('error'); }\n \" 2>/dev/null\n}\n\n# Prints the directory pm2 runs this app from, or nothing when pm2 has no app of\n# that name.\napp_dir() {\n \"$PM2\" jlist 2>/dev/null | SELVA_APP=\"$APP\" node -e \"\n try {\n const list = JSON.parse(require('fs').readFileSync(0,'utf8'));\n const app = list.find(p => p.name === process.env.SELVA_APP);\n process.stdout.write((app && app.pm2_env.pm_cwd) || '');\n } catch {}\n \" 2>/dev/null\n}\n\nwait_until_stopped() {\n for i in $(seq 1 20); do\n STATUS=$(app_status)\n if [ \"$STATUS\" != \"stopping\" ]; then\n return 0\n fi\n echo \"[INFO] $APP still draining (attempt $i/20) — waiting for SIGKILL escalation\"\n sleep 1\n done\n echo \"[WARN] $APP stuck in 'stopping' after 20s — continuing anyway\"\n return 1\n}\n\n# \\`pm2 start <ecosystem>\\` converts to a restart-by-id when an entry of the same\n# name is already in the table. If that entry is stale the restart fails and no\n# amount of retrying the same command helps — the name has to be dropped first\n# so the start registers a fresh process. Deleting a stopped entry is safe: the\n# ecosystem file is the source of truth for how to bring it back.\nstart_app() {\n if \"$PM2\" start \"$ECOSYSTEM\" --update-env; then\n return 0\n fi\n echo \"[WARN] pm2 start failed — dropping the stale process entry and retrying\"\n \"$PM2\" delete \"$APP\" >/dev/null 2>&1 || true\n \"$PM2\" start \"$ECOSYSTEM\" --update-env\n}\n\n# Last-resort safety net. If the script exits with the app NOT online for\n# any reason (crash, kill -9, network blip, npm hang past timeout), try to\n# bring it back from ecosystem.config.cjs before exiting. Leaving the app\n# down is the worst possible outcome of an update.\non_exit() {\n CODE=$?\n STATUS=$(app_status)\n # A 'stopping' entry is mid-drain, not down. Restarting it now hits the same\n # dead-id window that brought us here; wait for the entry to settle first.\n if [ \"$STATUS\" = \"stopping\" ]; then\n wait_until_stopped\n STATUS=$(app_status)\n fi\n if [ \"$STATUS\" != \"online\" ]; then\n echo \"[RECOVER] $APP is '$STATUS' — starting from ecosystem.config.cjs\"\n start_app >/dev/null 2>&1 || \\\\\n echo \"[RECOVER] pm2 start failed — manual intervention required: cd $(dirname \"$ECOSYSTEM\") && ./node_modules/.bin/pm2 delete $APP; ./node_modules/.bin/pm2 start ecosystem.config.cjs\"\n fi\n # Terminal marker: the restarted app's outcome reconciler greps this to turn\n # the run into an audit event (selfUpdate.server.ts). Keep the format stable.\n echo \"[EXIT] code=$CODE\"\n}\ntrap on_exit EXIT\n\n# A killed runner must not look like a finished one.\n#\n# \\`$?\\` inside an EXIT trap reports the last completed command, NOT the signal.\n# When systemd SIGTERMs the whole cgroup, the EXIT trap still runs and records\n# \\`code=0\\` — so deriveOutcome takes the exit-0 success branch and tells the\n# operator \"Updated X → Y. The app is back online.\" while npm never ran and\n# the deployment is unchanged. Catching the signal makes the recorded code\n# truthful; 143/130 are the conventional 128+signal values.\non_signal() {\n SIG=$1\n echo \"[FATAL] KILLED: runner received SIG$SIG before finishing.\"\n echo \"[FATAL] Nothing was installed by this run. If the app is down, recover with:\"\n echo \"[FATAL] cd $(dirname \"$ECOSYSTEM\") && pm2 start ecosystem.config.cjs --update-env\"\n echo \"[FATAL] A systemd-supervised pm2 can do this when 'pm2 update' recycles the daemon.\"\n exit $2\n}\ntrap 'on_signal TERM 143' TERM\ntrap 'on_signal INT 130' INT\ntrap 'on_signal HUP 129' HUP\n\n# ---------------------------------------------------------------------------\n# 1. Pre-flight: skip the whole cycle if there's nothing to install.\n# ---------------------------------------------------------------------------\n# Without this, clicking \"Update\" on an already-current instance triggers a\n# full stop/install/start cycle and a downtime window for no reason.\necho \"[STEP] Checking npm registry for the '$TAG' channel version\"\nLATEST=$(npm view \"@selvajs/selva@$TAG\" version --silent 2>/dev/null || echo \"\")\nif [ -z \"$LATEST\" ]; then\n echo \"[WARN] Could not query npm registry — proceeding with update attempt anyway\"\nelif [ -n \"$BEFORE\" ] && [ \"$LATEST\" = \"$BEFORE\" ]; then\n echo \"[INFO] Already on the '$TAG' channel version ($BEFORE)\"\n echo \"[DONE] Nothing to do\"\n exit 0\nelse\n # May be a forward update OR a revert (target older than installed) — either\n # way the installed version differs from what this channel publishes.\n echo \"[INFO] Target ($TAG): $BEFORE → $LATEST\"\nfi\n\n# ---------------------------------------------------------------------------\n# 1b. Node engine pre-flight — BEFORE any downtime.\n# ---------------------------------------------------------------------------\n# npm only treats an engine mismatch as fatal under engine-strict=true, which\n# no deployment sets. So a release requiring a newer Node installs\n# \"successfully\", pm2 starts, and /api/health returns 200 (it touches nothing\n# Node-version specific) — a false green that skips rollback entirely. Warn\n# here so a CLI-driven run sees it too; the admin UI blocks earlier.\nREQUIRED_NODE=$(npm view \"@selvajs/selva@$TAG\" engines.node --silent 2>/dev/null | tr -d '\"' | tr -d \"'\")\nRUNNING_NODE=$(node -p 'process.versions.node' 2>/dev/null)\nif [ -n \"$REQUIRED_NODE\" ] && [ -n \"$RUNNING_NODE\" ]; then\n # Compare majors only — the ranges we publish are all \\`>=X\\` forms.\n REQ_MAJOR=$(echo \"$REQUIRED_NODE\" | grep -o '[0-9]\\\\+' | head -1)\n RUN_MAJOR=$(echo \"$RUNNING_NODE\" | cut -d. -f1)\n if [ -n \"$REQ_MAJOR\" ] && [ \"$RUN_MAJOR\" -lt \"$REQ_MAJOR\" ] 2>/dev/null; then\n echo \"[WARN] ENGINE_MISMATCH: @selvajs/selva@$LATEST requires Node $REQUIRED_NODE but this host runs v$RUNNING_NODE\"\n echo \"[WARN] npm will install it anyway (engine-strict is off) and the health probe will pass,\"\n echo \"[WARN] but routes using newer Node APIs will fail at request time. Upgrade Node on this host.\"\n fi\nfi\n\n# ---------------------------------------------------------------------------\n# 1c. Data format pre-flight — BEFORE any downtime.\n# ---------------------------------------------------------------------------\n# A release with a lower data format than the installed one cannot read what\n# this deployment has already stored (dataFormat.server.ts). It would boot, fail\n# its health check and roll back: two outages for nothing. Installed by hand it\n# leaves stored Compute API keys unreadable. A release that declares no format\n# is format 1. Skipped when the registry gave no answer: the target is unknown.\nINSTALLED_FORMAT=$(node -p \"require('./node_modules/@selvajs/selva/package.json').selva?.dataFormat ?? 1\" 2>/dev/null)\ncase \"$INSTALLED_FORMAT\" in ''|*[!0-9]*) INSTALLED_FORMAT=1 ;; esac\nif [ -n \"$LATEST\" ] && TARGET_FORMAT=$(npm view \"@selvajs/selva@$TAG\" selva.dataFormat --silent 2>/dev/null); then\n TARGET_FORMAT=$(echo \"$TARGET_FORMAT\" | tr -d '\"' | tr -d \"'\" | tr -d '[:space:]')\n case \"$TARGET_FORMAT\" in ''|*[!0-9]*) TARGET_FORMAT=1 ;; esac\n if [ \"$TARGET_FORMAT\" -lt \"$INSTALLED_FORMAT\" ]; then\n echo \"[FATAL] DATA_FORMAT: @selvajs/selva@$LATEST reads data format $TARGET_FORMAT, but this deployment is on format $INSTALLED_FORMAT.\"\n echo \"[FATAL] It could not read what the installed version has stored, such as Compute API keys.\"\n echo \"[FATAL] Aborting WITHOUT stopping the app — it is still running.\"\n echo \"[FATAL] To go back anyway: docs/self-hosting/deployment/admin.md, 'Going back to an older release'.\"\n exit 10\n fi\nfi\n\n# ---------------------------------------------------------------------------\n# 2. Resync PM2 daemon if its in-memory version drifted from the CLI on disk.\n# ---------------------------------------------------------------------------\n# After a global pm2 upgrade the daemon keeps running its original version\n# while the CLI moves forward. Process commands then talk to a stale daemon\n# and the symptom is \"stop works, start never lands\". \\`pm2 update\\` dumps\n# processes, kills the daemon, respawns on the current CLI, restores the\n# dump. Doing it before we touch anything keeps the rest of the script\n# talking to a coherent daemon.\necho \"[STEP] Checking PM2 daemon/CLI version sync\"\nPING_OUT=$(\"$PM2\" ping 2>&1)\nif echo \"$PING_OUT\" | grep -q \"out-of-date\"; then\n # pm2 prints both versions alongside the warning. Which is newer decides\n # whether \\`pm2 update\\` can help — see the direction check below.\n DAEMON_V=$(echo \"$PING_OUT\" | sed -e 's/\\\\x1b\\\\[[0-9;]*m//g' \\\\\n | grep -i \"In memory PM2 version\" | grep -o '[0-9]\\\\+\\\\.[0-9]\\\\+\\\\.[0-9]\\\\+' | head -1)\n LOCAL_V=$(echo \"$PING_OUT\" | sed -e 's/\\\\x1b\\\\[[0-9;]*m//g' \\\\\n | grep -i \"Local PM2 version\" | grep -o '[0-9]\\\\+\\\\.[0-9]\\\\+\\\\.[0-9]\\\\+' | head -1)\n DAEMON_MAJOR=\\${DAEMON_V%%.*}\n LOCAL_MAJOR=\\${LOCAL_V%%.*}\n\n # A daemon NEWER than the deployment-local CLI means a foreign global pm2 owns\n # it. \\`pm2 update\\` would DOWNGRADE the daemon and feed it a dump it can't read,\n # losing the process table — selva-compute never gets re-registered. That is an\n # operator problem, not something this script can repair, so stop before we\n # take the app down.\n if [ -n \"$DAEMON_MAJOR\" ] && [ -n \"$LOCAL_MAJOR\" ] && [ \"$DAEMON_MAJOR\" -gt \"$LOCAL_MAJOR\" ] 2>/dev/null; then\n echo \"[FATAL] PM2_SKEW: the running daemon (v$DAEMON_V) is NEWER than this deployment's pm2 (v$LOCAL_V).\"\n echo \"[FATAL] A global pm2 owns the daemon. Running 'pm2 update' would downgrade it and drop\"\n echo \"[FATAL] the process table. Resolve manually before updating:\"\n echo \"[FATAL] which -a pm2 && pm2 -v && pm2 ping\"\n echo \"[FATAL] Aborting WITHOUT stopping the app — it is still running.\"\n exit 8\n fi\n\n if pm2_under_systemd; then\n echo \"[FATAL] SYSTEMD_PM2: this deployment's PM2 is supervised by systemd, and the daemon\"\n echo \"[FATAL] needs a resync. Running 'pm2 update' here would restart the systemd unit and\"\n echo \"[FATAL] kill this runner mid-update. Resync manually from a shell, then retry:\"\n echo \"[FATAL] cd $(dirname \"$ECOSYSTEM\") && ./node_modules/.bin/pm2 update\"\n echo \"[FATAL] Aborting WITHOUT stopping the app — it is still running.\"\n exit 9\n fi\n\n echo \"[STEP] PM2 daemon is out-of-date — running 'pm2 update' to resync\"\n if ! \"$PM2\" update; then\n echo \"[FATAL] pm2 update failed — aborting before stopping the running app\"\n exit 1\n fi\n echo \"[INFO] PM2 daemon resynced\"\nfi\n\n# ---------------------------------------------------------------------------\n# 2b. This install must own the pm2 app it is about to stop.\n# ---------------------------------------------------------------------------\n# With two installs under one daemon and one name, the stop below takes the\n# OTHER install down while this one keeps serving, and npm then rewrites build/\n# under it.\nOWNER=$(app_dir)\nOWNER_REAL=\nif [ -n \"$OWNER\" ]; then\n OWNER_REAL=$(cd \"$OWNER\" 2>/dev/null && pwd -P)\nfi\nif [ -n \"$OWNER\" ] && [ -n \"$HERE\" ] && [ \"\\${OWNER_REAL:-$OWNER}\" != \"$HERE\" ]; then\n echo \"[FATAL] PM2_NAME_TAKEN: pm2's '$APP' runs from $OWNER, not from this install ($HERE).\"\n echo \"[FATAL] Two installs share one pm2 app name, so this update would have stopped the other one.\"\n echo \"[FATAL] Give this install its own name: change 'name' in $ECOSYSTEM, then from a shell:\"\n echo \"[FATAL] cd $HERE && npx selva start\"\n echo \"[FATAL] Aborting WITHOUT stopping the app — it is still running.\"\n exit 11\nfi\n\n# ---------------------------------------------------------------------------\n# 3. Stop the app BEFORE npm rewrites build/.\n# ---------------------------------------------------------------------------\n# SvelteKit's node adapter lazy-imports chunks from build/server/chunks/ on\n# every request. Letting npm rewrite build/ while the old process still\n# serves traffic means in-flight requests hit ERR_MODULE_NOT_FOUND for chunks\n# whose hash just changed under their feet. Stopping first is a brief\n# downtime window (~1-2s longer than restart-in-place) for a much smaller\n# blast radius.\n#\n# This is also where the SSE connection to the frontend dies — selva-compute\n# IS the SSE server. From here on, the user sees output via the log-file\n# polling fallback in the admin UI, not over SSE.\necho \"[STEP] Stopping $APP\"\nif ! \"$PM2\" stop \"$APP\"; then\n echo \"[WARN] pm2 stop failed — $APP may not be running yet. Continuing.\"\nfi\n\n# pm2 stop returns before the process is actually gone. Everything below —\n# npm rewriting build/, then the restart — must happen outside the drain window.\nwait_until_stopped\n\n# ---------------------------------------------------------------------------\n# 3b. Nothing may answer the port once the app is stopped.\n# ---------------------------------------------------------------------------\n# A process this pm2 does not run (another pm2 daemon, a systemd unit, a shell)\n# survives the stop above, and so does one that outlived its kill timeout. Either\n# would keep rendering pages that name the old build's files after npm has\n# replaced them, and would answer the health probe below, so the update would\n# report success with nothing restarted.\nSURVIVOR=\nfor i in $(seq 1 5); do\n SURVIVOR=$(serving_instance)\n if [ -z \"$SURVIVOR\" ]; then\n break\n fi\n sleep 1\ndone\nif [ -n \"$SURVIVOR\" ]; then\n echo \"[FATAL] NOT_STOPPED: something still answers on port $PORT after 'pm2 stop $APP'.\"\n echo \"[FATAL] Either this install's pm2 does not run that process, or it did not exit.\"\n echo \"[FATAL] Nothing was installed. Find what holds the port, stop it there, then start the app from this install:\"\n echo \"[FATAL] ss -ltnp | grep ':$PORT '\"\n echo \"[FATAL] cd $HERE && npx selva start\"\n exit 12\nfi\n\n# ---------------------------------------------------------------------------\n# 4. Run npm update.\n# ---------------------------------------------------------------------------\necho \"[STEP] Updating @selvajs/* packages\"\nif ! ${npmCommand}; then\n echo \"[FATAL] npm update failed — EXIT trap will restart the previous build\"\n exit 1\nfi\n\nAFTER=$(node -e \"try{console.log(require('./node_modules/@selvajs/selva/package.json').version)}catch(e){}\" 2>/dev/null)\necho \"[INFO] New @selvajs/selva: \\${AFTER:-unknown}\"\n\nif [ -n \"$BEFORE\" ] && [ \"$BEFORE\" = \"$AFTER\" ]; then\n echo \"[WARN] No version change ($BEFORE). Your npm cache may be stale.\"\n echo \"[WARN] Recover with:\"\n echo \"[WARN] npm cache clean --force\"\n echo \"[WARN] rm -rf node_modules package-lock.json\"\n echo \"[WARN] npm install --prefer-online\"\nfi\n\n# ---------------------------------------------------------------------------\n# 4b. Move pm2 onto the version the new CLI pins.\n# ---------------------------------------------------------------------------\n# Only \\`selva migrate\\` rewrites package.json, so without this a release that\n# bumps pm2 needs a manual migrate on every host. The pin is read from the CLI\n# just installed: its devDependencies.pm2 is what a fresh scaffold gets. The\n# app is stopped, so swapping the daemon here adds no downtime. A failure\n# leaves the old pm2 running the app: warn, never abort. A rollback below\n# keeps the new pm2: reinstalling the old one would leave the daemon newer\n# than the CLI, the one skew \\`pm2 update\\` cannot repair.\nPM2_DECLARED=$(node -p \"require('./package.json').dependencies?.pm2 ?? ''\" 2>/dev/null)\nPM2_PIN=$(node -p \"require('./node_modules/@selvajs/cli/package.json').devDependencies?.pm2 ?? ''\" 2>/dev/null)\nif [ -n \"$PM2_PIN\" ] && [ \"$PM2_PIN\" != \"$PM2_DECLARED\" ]; then\n echo \"[STEP] Moving pm2 \\${PM2_DECLARED:-(none)} → $PM2_PIN, the version this release pins\"\n if npm install --save --save-exact --prefer-online \"pm2@$PM2_PIN\"; then\n if pm2_under_systemd; then\n echo \"[WARN] PM2_RESYNC_NEEDED: pm2 is now $PM2_PIN, but its daemon still runs the old version.\"\n echo \"[WARN] Swapping it here would restart the systemd unit and kill this runner. From a shell:\"\n echo \"[WARN] cd $(dirname \"$ECOSYSTEM\") && npx pm2 update && npx pm2 list\"\n echo \"[WARN] Let it finish: interrupting it leaves $APP unregistered.\"\n elif ! \"$PM2\" update; then\n echo \"[WARN] PM2_RESYNC_NEEDED: 'pm2 update' failed — the daemon still runs the old pm2.\"\n echo \"[WARN] cd $(dirname \"$ECOSYSTEM\") && npx pm2 update && npx pm2 list\"\n fi\n else\n echo \"[WARN] PM2_PIN_FAILED: could not install pm2@$PM2_PIN — the previous pm2 still runs the app.\"\n echo \"[WARN] Retry from a shell: cd $(dirname \"$ECOSYSTEM\") && npx selva migrate\"\n fi\nfi\n\n# ---------------------------------------------------------------------------\n# 5. Start selva-compute with the new build.\n# ---------------------------------------------------------------------------\n# Start from ecosystem.config.cjs, NOT \\`pm2 start selva-compute\\` — the latter\n# requires selva-compute to already be in pm2's in-memory process list, which\n# a \\`pm2 update\\` (step 2) isn't guaranteed to preserve.\necho \"[STEP] Starting $APP with new build\"\nif ! start_app; then\n echo \"[FATAL] pm2 start failed — investigate with \\\\\\`pm2 logs $APP\\\\\\`\"\n exit 2\nfi\n\n# ---------------------------------------------------------------------------\n# 6. Health probe the new process.\n# ---------------------------------------------------------------------------\necho \"[STEP] Health-probing the new process on port $PORT\"\n# mktemp for the same reason as the runner itself: /tmp is shared. Without one\n# the probe still runs; only the rollback loses the body it names the cause from.\nHEALTH_BODY=$(mktemp \"\\${TMPDIR:-/tmp}/selva-health.XXXXXXXX\") || HEALTH_BODY=\nHEALTHY=0\nfor i in $(seq 1 15); do\n sleep 2\n CODE=$(curl -sS -o \"\\${HEALTH_BODY:-/dev/null}\" -w \"%{http_code}\" --max-time 5 \"http://localhost:$PORT/api/health\" 2>/dev/null || echo \"000\")\n if [ \"$CODE\" = \"200\" ]; then\n HEALTHY=1\n echo \"[INFO] Health probe passed after \\${i} attempt(s)\"\n [ -n \"$HEALTH_BODY\" ] && rm -f \"$HEALTH_BODY\"\n break\n fi\n echo \"[INFO] Probe attempt $i/15: HTTP $CODE — retrying\"\ndone\n\nif [ \"$HEALTHY\" = \"1\" ]; then\n echo \"[DONE] Update complete\"\n exit 0\nfi\n\n# ---------------------------------------------------------------------------\n# 7. Rollback path.\n# ---------------------------------------------------------------------------\necho \"[FATAL] New process failed health check after 30s\"\nif [ -s \"$HEALTH_BODY\" ]; then\n BODY=$(cat \"$HEALTH_BODY\")\n echo \"[FATAL] Last response body:\"\n echo \"$BODY\"\n\n # Name the cause before rolling back. /api/health reports WHY it is degraded\n # in a structured body, but a rollback that only prints raw JSON reads to an\n # operator as \"the update just failed\" — they retry, hit the identical\n # failure, and never learn the database is the thing that needs attention.\n # Each branch below emits a stable marker deriveOutcome keys on.\n # Match on the keys unique to each report rather than a bare \\`\"ok\":false\\`,\n # which appears in whichever sub-report failed and would misattribute one\n # cause to the other. \\`expected\\` only ever appears in schemaVersion;\n # \\`plaintextFound\\`/\\`failures\\` only in atRestSecrets.\n if echo \"$BODY\" | grep -q '\"expected\":'; then\n EXPECTED=$(echo \"$BODY\" | grep -o '\"expected\":\"[^\"]*\"' | head -1 | cut -d'\"' -f4)\n ACTUAL=$(echo \"$BODY\" | grep -o '\"actual\":\"[^\"]*\"' | head -1 | cut -d'\"' -f4)\n echo \"[FATAL] SCHEMA_SKEW: @selvajs/selva@\\${AFTER:-$LATEST} expects database migration head \\${EXPECTED:-(unknown)},\"\n echo \"[FATAL] but this database is at \\${ACTUAL:-(unavailable)}. The new version is fine — its migrations\"\n echo \"[FATAL] were never applied. Retrying the update WILL fail again in exactly the same way.\"\n echo \"[FATAL] The update does not apply migrations itself: they are not reversible, so an\"\n echo \"[FATAL] auto-migrate followed by a rollback would leave code and database on different heads.\"\n echo \"[FATAL] Apply them yourself, then re-run the update:\"\n echo \"[FATAL] cd $(dirname \"$ECOSYSTEM\")\"\n echo \"[FATAL] npm install --prefer-online @selvajs/supabase-provider@$TAG\"\n echo \"[FATAL] npx selva-supabase\"\n echo \"[FATAL] npx supabase db push\"\n echo \"[FATAL] The provider install is not optional: the migration SQL ships inside that\"\n echo \"[FATAL] package, and the update only moves @selvajs/cli and @selvajs/selva — so a sync\"\n echo \"[FATAL] without it copies 0 files and the push reports 'up to date' having done nothing.\"\n echo \"[FATAL] If db push asks for credentials, see docs/self-hosting/providers/supabase.md\"\n echo \"[FATAL] — it needs a Supabase ACCOUNT credential (supabase login, or SUPABASE_ACCESS_TOKEN),\"\n echo \"[FATAL] which is not any of the three keys in .env.\"\n elif echo \"$BODY\" | grep -qE '\"plaintextFound\":true|\"failures\":\\\\[[^]]'; then\n echo \"[FATAL] AT_REST_SECRETS: stored compute server API keys could not be decrypted under the\"\n echo \"[FATAL] current SELVA_AT_REST_KEY. This is a configuration problem on this host, not a\"\n echo \"[FATAL] fault in the new version — retrying the update will fail the same way.\"\n echo \"[FATAL] Re-enter the affected keys at /admin/compute, or restore the original\"\n echo \"[FATAL] SELVA_AT_REST_KEY, then re-run the update.\"\n else\n echo \"[FATAL] The health endpoint did not report a known cause. Inspect the body above and\"\n echo \"[FATAL] \\\\\\`pm2 logs $APP\\\\\\` for what the new version failed on.\"\n fi\n\n rm -f \"$HEALTH_BODY\"\nfi\n\nif [ -z \"$BEFORE\" ]; then\n echo \"[FATAL] No prior version recorded — cannot roll back automatically.\"\n echo \"[FATAL] EXIT trap will attempt to restart the current build anyway.\"\n exit 3\nfi\n\n# The failed version has already booted, so it may have rewritten stored data in\n# a format $BEFORE cannot read. Rolling back is still the better outcome; say so.\nAFTER_FORMAT=$(node -p \"require('./node_modules/@selvajs/selva/package.json').selva?.dataFormat ?? 1\" 2>/dev/null)\ncase \"$AFTER_FORMAT\" in ''|*[!0-9]*) AFTER_FORMAT=1 ;; esac\nif [ \"$AFTER_FORMAT\" -gt \"$INSTALLED_FORMAT\" ]; then\n echo \"[WARN] DATA_FORMAT_ROLLBACK: the failed version stores data format $AFTER_FORMAT; $BEFORE reads format $INSTALLED_FORMAT.\"\n echo \"[WARN] If Compute API keys fail to load after this rollback, re-enter them at /admin/compute.\"\nfi\n\necho \"[STEP] Rolling back @selvajs/selva to $BEFORE\"\n\"$PM2\" stop \"$APP\" >/dev/null 2>&1 || true\nwait_until_stopped >/dev/null 2>&1\n# Restore @selvajs/cli alongside the runtime: the forward step installs both at\n# the channel tag, so reverting only the runtime leaves a version pair that was\n# never released together.\nif ! npm install --save \"@selvajs/cli@$BEFORE\" \"@selvajs/selva@$BEFORE\"; then\n echo \"[FATAL] Rollback npm install failed — EXIT trap will retry restart.\"\n exit 4\nfi\n\nstart_app || true\nsleep 3\nROLLBACK_CODE=$(curl -sS -o /dev/null -w \"%{http_code}\" --max-time 5 \"http://localhost:$PORT/api/health\" 2>/dev/null || echo \"000\")\nif [ \"$ROLLBACK_CODE\" = \"200\" ]; then\n echo \"[DONE] Rolled back to $BEFORE — previous version is online\"\n exit 5\nfi\n\necho \"[FATAL] Rollback restart also failed health check (HTTP $ROLLBACK_CODE)\"\necho \"[FATAL] Manual recovery required. Check: pm2 logs $APP\"\nexit 6\n`;\n}\n\n// Selva self-updates as a CLI-scaffolded npm deployment: the deployment dir\n// holds a package.json that depends on @selvajs/selva, and update means\n// `npm install @selvajs/*@<tag>` + pm2 restart. Deployment-dir detection\n// (cwd-upward probe, `INSTALL_DIR` override) lives in `selfUpdate.server.ts`,\n// shared with the outcome reconciler and the log path.\nexport type UpdatePlan = { cwd: string; args: string[] };\n\n// Only the CLI and the runtime move. Provider code is bundled into\n// @selvajs/selva; @selvajs/supabase-provider carries just the migration SQL,\n// which the operator installs and pushes before updating.\n//\n// `npm install` pins to the channel's dist-tag rather than using `npm\n// update`, because `update` only ever moves FORWARD within the installed\n// semver range — it can't switch dist-tags or DOWNGRADE. Pinning to @latest /\n// @beta makes one command serve every transition: forward stable bumps,\n// beta→newer-beta, and the revert case (beta→stable lands on an older version).\n//\n// --save persists the resolved version into package.json so the next plain\n// install is reproducible; --prefer-online forces npm to revalidate cached\n// packuments against the registry — without it, npm's packument cache (5+\n// min TTL) can silently no-op right after publish.\nexport function npmInstallArgs(channel: ReleaseChannel): string[] {\n\tconst tag = channelTag(channel);\n\treturn ['install', '--save', '--prefer-online', `@selvajs/cli@${tag}`, `@selvajs/selva@${tag}`];\n}\n\nexport function detectUpdatePlan(\n\tenv: Record<string, string | undefined>,\n\tchannel: ReleaseChannel\n): UpdatePlan | null {\n\tconst dir = findDeploymentDir(env);\n\treturn dir ? { cwd: dir, args: npmInstallArgs(channel) } : null;\n}\n","import { spawn } from 'child_process';\nimport { join } from 'path';\nimport { readFileSync, writeFileSync } from 'fs';\nimport { env } from '#lib/server/env.js';\nimport { json } from '@sveltejs/kit';\nimport { actorFrom } from '@selvajs/platform';\nimport type { RequestHandler } from './$types';\nimport { requirePermission } from '#lib/server/access.server.js';\nimport { renderThrown } from '@selvajs/server/logging';\nimport { checkForUpdate } from '#lib/server/updateCheck.server.js';\nimport { readChannel, channelTag } from '#lib/server/releaseChannel.server.js';\nimport { getEventSink, getErrorReporter } from '#lib/server/providers.server.js';\nimport {\n\tfindDeploymentDir,\n\tstartUpdateOutcomeReconciler,\n\tupdateLogPath,\n\tupdateStatePath,\n\ttype PendingUpdateState\n} from '#lib/server/selfUpdate.server.js';\nimport {\n\treadRuntimeVersion,\n\tbuildLauncher,\n\tbuildNpmRunnerScript,\n\tdetectUpdatePlan\n} from '#lib/server/updateRunner.server.js';\n\n// Where the bash wrapper mirrors all script output (`updateLogPath` — in the\n// deployment dir so it survives reboots, audit O2). The SSE stream dies the\n// moment `pm2 stop selva-compute` succeeds (selva-compute IS the SSE server),\n// so the frontend loses visibility into everything that happens after — npm\n// update output, pm2 start result, health-probe results, rollback decisions.\n// The script keeps writing to this file regardless. Once the new selva-compute\n// process is back up, the frontend polls GET on this same route to fetch the\n// full log and reveal what happened during the blackout. One log per update —\n// the wrapper truncates at start, so we never carry stale content forward.\n// The runner's `[EXIT] code=N` marker in the same log also drives the\n// post-restart audit-event reconciliation (`selfUpdate.server.ts`).\n\n// Strip ANSI escape codes from terminal output\nfunction stripAnsi(str: string): string {\n\t// eslint-disable-next-line no-control-regex\n\treturn str.replace(/\\x1B\\[[0-9;]*[mGKHF]/g, '');\n}\n\n// POST - Run update and stream output via Server-Sent Events.\n//\n// Runs `npm update @selvajs/*` then restarts via ecosystem.config.cjs. The\n// runner script handles stop / update / start / health-probe / rollback with\n// an EXIT trap that keeps the app online no matter how it exits.\nexport const POST: RequestHandler = async ({ locals }) => {\n\trequirePermission(locals, 'instance_admin');\n\n\tconst channel = readChannel();\n\tconst plan = detectUpdatePlan(env, channel);\n\tif (!plan) {\n\t\treturn new Response(\n\t\t\tJSON.stringify({\n\t\t\t\terror:\n\t\t\t\t\t\"Couldn't determine how to update this deployment. \" +\n\t\t\t\t\t'Expected node_modules/@selvajs/selva (CLI scaffold) in the cwd ' +\n\t\t\t\t\t'or a parent directory.'\n\t\t\t}),\n\t\t\t{ status: 500, headers: { 'Content-Type': 'application/json' } }\n\t\t);\n\t}\n\n\t// Capture the runtime version BEFORE we touch anything, so we can:\n\t// (a) detect a no-op update and warn, (b) roll back to the prior version\n\t// if the new process fails to come up healthy.\n\tconst versionBefore = readRuntimeVersion(plan.cwd);\n\tconst actorId = locals.ctx ? actorFrom(locals.ctx) : 'system';\n\n\t// Audit trail (O2): `started` now; the terminal event is emitted by the\n\t// outcome reconciler after the app restarts (this process is killed\n\t// mid-update). The state file is the reconciler's emission token.\n\tconst pending: PendingUpdateState = {\n\t\tstartedAt: new Date().toISOString(),\n\t\tactorId,\n\t\tchannel,\n\t\tfromVersion: versionBefore\n\t};\n\ttry {\n\t\twriteFileSync(updateStatePath(plan.cwd), JSON.stringify(pending, null, '\\t'));\n\t} catch (err) {\n\t\tlocals.log.error('Could not persist pending-update state', {\n\t\t\tcomponent: 'selfUpdate',\n\t\t\terr: renderThrown(err)\n\t\t});\n\t}\n\tawait getEventSink().emit({\n\t\ttype: 'system.update.started',\n\t\tchannel,\n\t\tfromVersion: versionBefore,\n\t\tactorId\n\t});\n\n\tconst stream = new ReadableStream({\n\t\tstart(controller) {\n\t\t\tconst encoder = new TextEncoder();\n\n\t\t\tfunction sendEvent(type: string, data: Record<string, unknown>) {\n\t\t\t\tconst message = `data: ${JSON.stringify({ type, ...data })}\\n\\n`;\n\t\t\t\tcontroller.enqueue(encoder.encode(message));\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\t// Prelude lines are passed to the bash wrapper rather than\n\t\t\t\t// sendEvent'd directly so they end up in both the SSE stream\n\t\t\t\t// (via bash stdout) AND the log file (via tee). Without this,\n\t\t\t\t// the frontend's blackout-recovery file fetch would clobber\n\t\t\t\t// these lines when it replaces its buffer with the file content.\n\t\t\t\tconst prelude = [\n\t\t\t\t\t`[INFO] Updating deployment (cwd: ${plan.cwd}, channel: ${channel})`,\n\t\t\t\t\t...(versionBefore ? [`[INFO] Current @selvajs/selva: ${versionBefore}`] : [])\n\t\t\t\t];\n\n\t\t\t\t// Spawn the launcher detached. The launcher writes the actual\n\t\t\t\t// runner script to disk, daemonizes it (setsid + & + exit),\n\t\t\t\t// and quits — leaving the runner with PPID=1 so PM2's tree-kill\n\t\t\t\t// of selva-compute can't reach it. See buildLauncher for the\n\t\t\t\t// full rationale.\n\t\t\t\t//\n\t\t\t\t// The runner is buildNpmRunnerScript — pre-flights the version\n\t\t\t\t// check, then stop / npm update / start / health probe /\n\t\t\t\t// rollback, with an EXIT trap that ensures the app is online no\n\t\t\t\t// matter how the script exits.\n\t\t\t\tconst runnerScript = buildNpmRunnerScript(\n\t\t\t\t\tplan.args,\n\t\t\t\t\tversionBefore,\n\t\t\t\t\tjoin(plan.cwd, 'ecosystem.config.cjs'),\n\t\t\t\t\tchannelTag(channel)\n\t\t\t\t);\n\t\t\t\tconst cmd = 'bash';\n\t\t\t\tconst args = ['-c', buildLauncher(runnerScript, updateLogPath(plan.cwd), prelude)];\n\n\t\t\t\t// Prepend the deployment's node_modules/.bin to PATH so the bash\n\t\t\t\t// script finds the project-local pm2 (and any other tooling\n\t\t\t\t// installed as a deployment dependency). Without this the script\n\t\t\t\t// inherits the SvelteKit process's PATH, which on most servers\n\t\t\t\t// doesn't include node_modules/.bin — so `pm2` resolves to\n\t\t\t\t// whatever's globally installed, or fails outright if no global\n\t\t\t\t// pm2 exists. Both are wrong: we want the project-local pm2 so\n\t\t\t\t// daemon and CLI stay aligned. Mirrors the local-only resolution\n\t\t\t\t// in @selvajs/cli's pm2Bin().\n\t\t\t\tconst localBin = join(plan.cwd, 'node_modules', '.bin');\n\t\t\t\tconst child = spawn(cmd, args, {\n\t\t\t\t\tcwd: plan.cwd,\n\t\t\t\t\tenv: {\n\t\t\t\t\t\tPATH: `${localBin}:${process.env.PATH ?? ''}`,\n\n\t\t\t\t\t\tHOME: process.env.HOME,\n\t\t\t\t\t\tINSTALL_DIR: plan.cwd\n\t\t\t\t\t},\n\t\t\t\t\tdetached: true,\n\t\t\t\t\tstdio: ['ignore', 'pipe', 'pipe']\n\t\t\t\t});\n\t\t\t\tchild.unref();\n\n\t\t\t\t// Covers the outcomes that DON'T restart this process (pre-flight\n\t\t\t\t// \"already up to date\", early failures): this process is still\n\t\t\t\t// alive to reconcile them. A real update kills this process; the\n\t\t\t\t// restarted one re-arms the reconciler from hooks.server.ts.\n\t\t\t\tstartUpdateOutcomeReconciler({\n\t\t\t\t\tdeploymentDir: plan.cwd,\n\t\t\t\t\temit: (e) => getEventSink().emit(e),\n\t\t\t\t\treport: (err) => getErrorReporter().capture(err, { tags: { origin: 'selfUpdate' } })\n\t\t\t\t});\n\n\t\t\t\t// Kill the process if it runs longer than 15 minutes.\n\t\t\t\t// The child is detached (its own process group), so signal the\n\t\t\t\t// whole group via negative pid — otherwise descendants (pnpm,\n\t\t\t\t// node, pm2) outlive the bash wrapper.\n\t\t\t\tconst timeout = setTimeout(\n\t\t\t\t\t() => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tif (child.pid) process.kill(-child.pid, 'SIGTERM');\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t// group already gone — nothing to do\n\t\t\t\t\t\t}\n\t\t\t\t\t\tsendEvent('log', { data: '[FATAL] Update timed out after 15 minutes' });\n\t\t\t\t\t\tsendEvent('exit', { code: -1 });\n\t\t\t\t\t\tcontroller.close();\n\t\t\t\t\t},\n\t\t\t\t\t15 * 60 * 1000\n\t\t\t\t);\n\n\t\t\t\t// Stream stdout\n\t\t\t\tlet restarting = false;\n\t\t\t\tchild.stdout.on('data', (data) => {\n\t\t\t\t\tconst lines = data.toString().split('\\n');\n\t\t\t\t\tfor (const line of lines) {\n\t\t\t\t\t\tconst clean = stripAnsi(line).trim();\n\t\t\t\t\t\tif (clean) {\n\t\t\t\t\t\t\t// Detect both stopProcessId (pm2 restart) and restartProcessId (pm2 reload)\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t!restarting &&\n\t\t\t\t\t\t\t\t(clean.includes('Applying action stopProcessId') ||\n\t\t\t\t\t\t\t\t\tclean.includes('Applying action restartProcessId'))\n\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\trestarting = true;\n\t\t\t\t\t\t\t\tsendEvent('restarting', { data: clean });\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tsendEvent('log', { data: clean });\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\t// Stream stderr\n\t\t\t\tchild.stderr.on('data', (data) => {\n\t\t\t\t\tconst lines = data.toString().split('\\n');\n\t\t\t\t\tfor (const line of lines) {\n\t\t\t\t\t\tconst clean = stripAnsi(line).trim();\n\t\t\t\t\t\tif (clean) {\n\t\t\t\t\t\t\tsendEvent('log', { data: `[ERROR] ${clean}` });\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\t// Handle process exit\n\t\t\t\tchild.on('close', (code) => {\n\t\t\t\t\tclearTimeout(timeout);\n\t\t\t\t\tsendEvent('exit', { code: code ?? -1 });\n\t\t\t\t\tcontroller.close();\n\t\t\t\t});\n\n\t\t\t\t// Handle errors\n\t\t\t\tchild.on('error', (err) => {\n\t\t\t\t\tclearTimeout(timeout);\n\t\t\t\t\tsendEvent('log', { data: `[FATAL] ${err.message}` });\n\t\t\t\t\tsendEvent('exit', { code: -1 });\n\t\t\t\t\tcontroller.close();\n\t\t\t\t});\n\t\t\t} catch (err) {\n\t\t\t\tsendEvent('log', { data: `[FATAL] Failed to spawn process: ${err}` });\n\t\t\t\tsendEvent('exit', { code: -1 });\n\t\t\t\tcontroller.close();\n\t\t\t}\n\t\t}\n\t});\n\n\treturn new Response(stream, {\n\t\theaders: {\n\t\t\t'Content-Type': 'text/event-stream',\n\t\t\t'Cache-Control': 'no-cache',\n\t\t\tConnection: 'keep-alive'\n\t\t}\n\t});\n};\n\n// GET — two jobs, selected by query param:\n//\n// ?check=1 → query the npm registry and report whether a newer\n// @selvajs/selva is published. JSON: { current, latest,\n// updateAvailable }. The admin page calls this on load to show\n// an \"update available\" badge. Degrades gracefully: if the\n// registry is unreachable, latest is null and updateAvailable\n// is false (we never block the page on npm).\n//\n// (default) → read the tee'd update log so the frontend can recover the\n// chunk of output that happened during the SSE blackout (between\n// `pm2 stop` killing this process and the new selva-compute\n// coming back online). Empty body if no update has run yet.\n// Polled by the admin UI during the post-restart wait.\nexport const GET: RequestHandler = async ({ locals, url, fetch }) => {\n\trequirePermission(locals, 'instance_admin');\n\n\tif (url.searchParams.get('check') !== null) {\n\t\treturn json(await checkForUpdate(fetch, readChannel()), {\n\t\t\theaders: { 'Cache-Control': 'no-store' }\n\t\t});\n\t}\n\n\tlet body = '';\n\ttry {\n\t\tbody = readFileSync(updateLogPath(findDeploymentDir(env)), 'utf8');\n\t} catch {\n\t\t// Log doesn't exist (no update has run yet). Empty body is correct —\n\t\t// the frontend treats no content as \"nothing to show yet\".\n\t}\n\treturn new Response(body, {\n\t\theaders: {\n\t\t\t'Content-Type': 'text/plain; charset=utf-8',\n\t\t\t'Cache-Control': 'no-store'\n\t\t}\n\t});\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAaA,SAAgB,mBAAmB,KAAiC;CACnE,IAAI;EACH,MAAM,MAAM,KAAK,MAChB,aAAa,KAAK,KAAK,gBAAgB,YAAY,SAAS,cAAc,GAAG,MAAM,CACpF;EACA,OAAO,OAAO,IAAI,YAAY,WAAW,IAAI,UAAU,KAAA;CACxD,QAAQ;EACP;CACD;AACD;AAKA,SAAgB,WAAW,GAAmB;CAC7C,OAAO,IAAI,EAAE,QAAQ,MAAM,OAAO,EAAE;AACrC;AAoBA,SAAgB,cACf,cACA,SACA,UAAoB,CAAC,GACZ;CACT,MAAM,SAAS,QAAQ,KAAK,SAAS,QAAQ,WAAW,IAAI,GAAG,CAAC,CAAC,KAAK,IAAI;CAG1E,OAAO;UACE,WAAW,OAAO,EAAE;;;;;;;;;;;;;;;;EAgB5B,aAAa;;;;;EAKb,OAAO;;;;;;;;;;;;;;;;;AAiBT;AA6BA,SAAgB,qBACf,SACA,eACA,eACA,KACS;CACT,MAAM,aAAa,CAAC,OAAO,GAAG,OAAO,CAAC,CAAC,IAAI,UAAU,CAAC,CAAC,KAAK,GAAG;CAY/D,OAAO;;SATQ,WAAW,iBAAiB,EAWnC,EAAO;YAVG,WAAW,aAWlB,EAAU;MALL,WAAW,GAMtB,EAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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