Files
evig/scripts/ops/r2-backup-upload.cjs
b9248b21e1 fix(ops): the systemd units follow the box to /opt/evig (#432)
`revampit-cron@timecard-reminders.service` failed at 08:01 UTC today with
status=203/EXEC: "Unable to locate executable /opt/revampit/ops/run-cron.sh".

#430 renamed the box directory /opt/revampit -> /opt/evig at 07:44 UTC and
deliberately left the revampit-cron@* and revampit-backup units for a separate
pass. But those units name their program as a literal path — systemd cannot
interpolate a variable into ExecStart — so from 07:44 they all pointed at a
directory that no longer exists. timecard-reminders was simply the first timer
to fire afterwards; wake-recurring-tasks had run at 07:01, before the rename,
which is why only one unit looks broken.

It is not one job:

  - all five revampit-cron@* timers are dead from their next fire onward
  - revampit-backup.service — the ONLY off-box copy of prod Postgres — dies at
    03:32 UTC, and a 203/EXEC failure leaves no dump behind to notice
  - revampit-transcription.service still has WorkingDirectory=/opt/revampit and
    survives only because it has not been restarted since

and fixing the units alone would not have been enough: run-cron.sh itself
defaults APP_ENV to /opt/revampit/app/.env, so it would have read no
CRON_SECRET and every call would have come back 401.

Repoints every /opt path under scripts/ops/ at /opt/evig. Unit *names* stay
revampit-* — renaming a live schedule is still the separate, deliberate step
#430 called it.

Also here, because the same drift hid them:

  - revampit-cron@timecard-reminders.timer existed on the box but not in this
    repo, which claims to be the source of truth for scripts/ops/. Added,
    byte-identical to the installed copy.
  - release-escrow is the reverse: in this repo, never enabled on the box, so
    /api/cron/release-escrow has never once run on a schedule. Documented as a
    money-side go/no-go rather than switched on by an install loop.

The automation that ends the class: scripts/ci/ops-box-paths.sh compares every
/opt/<name> literal under scripts/ops/ against NAME= in the deploy script — the
one place that decides where the app lives — and fails when they disagree. Wired
into verify as `lint:ops`. Verified it fails on the pre-fix tree. The next box
rename now breaks CI instead of breaking the backups at 03:32 UTC.

.prettierignore gains .venv: a local python virtualenv (services/transcription)
made `npm run verify` fail locally on vendored site-packages while CI, which
never has one, stayed green — the precise local/CI split verify exists to
prevent.


Claude-Session: https://claude.ai/code/session_01LmyE2aLaXKB2V7WA3XQprm

Co-authored-by: Mao Nakamoto <41178744+maonakamoto@users.noreply.github.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-02 09:41:31 +00:00

149 lines
4.7 KiB
JavaScript

#!/usr/bin/env node
/**
* Upload one file to the PRIVATE R2 backups bucket, verify it landed, then prune
* old objects. Hardened so a transient R2/network blip retries instead of losing
* a night's backup, and so a missing/short upload is caught (not silently "ok").
*
* SDK resolution order (first that loads wins) — the backup must not depend on
* the app's redeployable node_modules:
* 1. /opt/evig/ops/node_modules (pinned, installed once — primary)
* 2. $APP_DIR/node_modules (the live app — fallback)
*
* Usage: node r2-backup-upload.cjs <localFile> <objectKey>
* Env: S3_ENDPOINT, S3_REGION, S3_ACCESS_KEY_ID, S3_SECRET_ACCESS_KEY
* BACKUP_BUCKET (default: revampit-backups)
* RETENTION_DAYS (default: 30)
* APP_DIR (default: /opt/evig/app)
* SDK_DIR (optional explicit @aws-sdk/client-s3 path)
*/
const fs = require('fs');
function loadSdk() {
const candidates = [
process.env.SDK_DIR,
'/opt/evig/ops/node_modules/@aws-sdk/client-s3',
`${process.env.APP_DIR || '/opt/evig/app'}/node_modules/@aws-sdk/client-s3`,
].filter(Boolean);
for (const p of candidates) {
try {
return require(p);
} catch {
/* try next */
}
}
throw new Error(`@aws-sdk/client-s3 not found in: ${candidates.join(', ')}`);
}
const {
S3Client,
PutObjectCommand,
HeadObjectCommand,
ListObjectsV2Command,
DeleteObjectsCommand,
} = loadSdk();
const [, , localFile, objectKey] = process.argv;
if (!localFile || !objectKey) {
console.error('usage: r2-backup-upload.cjs <localFile> <objectKey>');
process.exit(2);
}
const bucket = process.env.BACKUP_BUCKET || 'revampit-backups';
const retentionDays = parseInt(process.env.RETENTION_DAYS || '30', 10);
for (const k of ['S3_ENDPOINT', 'S3_ACCESS_KEY_ID', 'S3_SECRET_ACCESS_KEY']) {
if (!process.env[k]) {
console.error(`missing required env ${k}`);
process.exit(2);
}
}
const s3 = new S3Client({
endpoint: process.env.S3_ENDPOINT,
region: process.env.S3_REGION || 'auto',
credentials: {
accessKeyId: process.env.S3_ACCESS_KEY_ID,
secretAccessKey: process.env.S3_SECRET_ACCESS_KEY,
},
maxAttempts: 5, // SDK-level retry on top of our own loop
});
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
async function withRetry(label, fn, tries = 4) {
let lastErr;
for (let i = 1; i <= tries; i++) {
try {
return await fn();
} catch (e) {
lastErr = e;
if (i < tries) {
const wait = Math.min(2 ** i * 500, 8000);
console.error(`${label}: attempt ${i}/${tries} failed (${e.message}) — retry in ${wait}ms`);
await sleep(wait);
}
}
}
throw new Error(`${label} failed after ${tries} attempts: ${lastErr && lastErr.message}`);
}
async function main() {
const body = fs.readFileSync(localFile);
if (body.length === 0) throw new Error(`${localFile} is empty — refusing to upload`);
await withRetry('put', () =>
s3.send(
new PutObjectCommand({
Bucket: bucket,
Key: objectKey,
Body: body,
ContentType: 'application/octet-stream',
}),
),
);
// Verify the object actually landed at the expected size — an upload that
// "succeeded" but stored 0/short bytes must fail loudly, not pass.
const head = await withRetry('verify', () =>
s3.send(new HeadObjectCommand({ Bucket: bucket, Key: objectKey })),
);
if (Number(head.ContentLength) !== body.length) {
throw new Error(
`verify mismatch for ${objectKey}: stored ${head.ContentLength}, expected ${body.length}`,
);
}
console.log(`uploaded+verified ${objectKey} (${body.length} bytes) → ${bucket}`);
// Retention is best-effort: a prune failure must NOT fail the backup, because
// the night's copy is already safely stored.
try {
const cutoff = Date.now() - retentionDays * 86400_000;
let removed = 0;
let ContinuationToken;
do {
const page = await s3.send(new ListObjectsV2Command({ Bucket: bucket, ContinuationToken }));
const old = (page.Contents || []).filter(
(o) => o.LastModified && o.LastModified.getTime() < cutoff,
);
if (old.length) {
await s3.send(
new DeleteObjectsCommand({
Bucket: bucket,
Delete: { Objects: old.map((o) => ({ Key: o.Key })) },
}),
);
removed += old.length;
}
ContinuationToken = page.IsTruncated ? page.NextContinuationToken : undefined;
} while (ContinuationToken);
if (removed) console.log(`pruned ${removed} object(s) older than ${retentionDays}d`);
} catch (e) {
console.error(`WARN: prune failed (backup is safe): ${e.message}`);
}
}
main().catch((e) => {
console.error('backup upload FAILED:', e.message);
process.exit(1);
});