@stacksjs/cloud 0.75.695 → 0.75.701
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/dist/host-backup/backup.js +1 -1
- package/package.json +13 -13
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import{existsSync,lstatSync,mkdirSync,realpathSync,statSync,unlinkSync,writeFileSync}from"node:fs";import{basename,dirname,join}from"node:path";import{databaseName,postgresCommand,psql}from"./inventory";import{atomicDump,command,digest,envValues,freeBytes,GiB,readJson,requirePrivateDirectory,saveJson,sqliteSnapshot,validateSqlite,withScratch}from"./io";import{mysqlRecovery,postgresRecovery}from"./recovery";import{ResticArchive}from"./restic";export const stagingMarker=".host-backup-managed";const defaultStage="/var/cache/host-backup";const maxBackupAge=36*3600;const epoch=()=>Math.floor(Date.now()/1000);export function projectBackupDue(status,repositories,now){return Boolean(status.error)||Object.keys(repositories).some((provider)=>{const receipt=status[provider];if(!receipt||typeof receipt==="string"||!receipt.restore_verified)return true;const age=now-receipt.timestamp;return!(age>=0&&age<=maxBackupAge)})}function allProjectsRecovered(inventory,state,now){return Object.keys(inventory.projects).every((project)=>{const status=state.projects&&Object.hasOwn(state.projects,project)?state.projects[project]:undefined;return!projectBackupDue(status??{},inventory.repositories,now)})}async function mysqlDump(root,target,source){const database=databaseName(source.database);await withScratch(join(root,"mysql-options-"),async(scratch)=>{const client=join(scratch,"client.cnf");const values=source.env_file?envValues(source.env_file):{};const connection=source.socket?{socket:source.socket}:{host:values.DB_HOST,port:values.DB_PORT??"3306",password:values.DB_PASSWORD??"","ssl-mode":"REQUIRED"};if(!source.socket&&!connection.host)throw new Error("MySQL backup has no configured host");const fields={user:source.user??values.DB_USERNAME??"root",...connection};const settings=Object.entries(fields).filter(([,value])=>value!==undefined);writeFileSync(client,`[client]
|
|
2
2
|
${settings.map(([key,value])=>`${key}=${JSON.stringify(value)}`).join(`
|
|
3
3
|
`)}
|
|
4
|
-
`,{mode:384});const optionFile=`--defaults-extra-file=${client}`;const bytes=await command([join(dirname(source.binary),"mysql"),optionFile,"--batch","--skip-column-names","--execute",`SELECT COALESCE(SUM(data_length+index_length),0) FROM information_schema.tables WHERE table_schema='${database}'`]);if(!Number.
|
|
4
|
+
`,{mode:384});const optionFile=`--defaults-extra-file=${client}`;const bytes=await command([join(dirname(source.binary),"mysql"),optionFile,"--batch","--skip-column-names","--execute",`SELECT COALESCE(SUM(data_length+index_length),0) FROM information_schema.tables WHERE table_schema='${database}'`]);const databaseBytes=Number(bytes);const requiredBytes=databaseBytes*4+2*GiB;if(!bytes||databaseBytes<0||!Number.isSafeInteger(databaseBytes)||!Number.isSafeInteger(requiredBytes))throw new Error(`Could not determine the MySQL snapshot/recovery space required in ${root}`);const availableBytes=freeBytes(root);if(availableBytes<requiredBytes)throw new Error(`Insufficient MySQL snapshot/recovery space in ${root} (requires ${requiredBytes} bytes with ${availableBytes} bytes available)`);await atomicDump(target,[source.binary,optionFile,"--single-transaction","--quick","--skip-lock-tables","--no-tablespaces","--set-gtid-purged=OFF","--hex-blob","--column-statistics=0",...source.socket?["--routines","--events","--triggers"]:[],database])})}async function backupProject(project,selection,archives,stage,status,options,persist){const sourceTimestamp=epoch();const root=join(stage,project);const databases=join(root,"databases");mkdirSync(databases,{recursive:true,mode:448});requirePrivateDirectory(root);requirePrivateDirectory(databases);const sources=await options.hostSources?.(project,root)??[];const mapping={};for(const[index,source]of(selection.sqlite??[]).entries()){const target=join(databases,`${index}-${basename(source)}`);if(freeBytes(root)<statSync(source).size*2+GiB)throw new Error("Insufficient space for SQLite snapshot and recovery");await sqliteSnapshot(source,target);sources.push(target);mapping[target]={source,engine:"sqlite",sha256:await digest(target)}}for(const name of selection.postgres??[]){const database=databaseName(name);const target=join(databases,`${database}.dump`);const bytes=await command([...psql,`SELECT pg_database_size('${database}')`]);if(!Number.isFinite(Number(bytes))||freeBytes(root)<Number(bytes)*2+2*GiB)throw new Error("Insufficient PostgreSQL snapshot/recovery space");await atomicDump(target,[...postgresCommand,"/usr/local/bin/pg_dump","--format=custom","--no-owner","--dbname",database],(path)=>command(["/usr/local/bin/pg_restore","--list",path]));sources.push(target);mapping[target]={source:database,engine:"postgres",sha256:await digest(target)}}for(const[index,source]of(selection.mysql??[]).entries()){const target=join(databases,`mysql-${index}-${databaseName(source.database)}.sql`);await mysqlDump(root,target,source);sources.push(target);mapping[target]={source:source.database,engine:"mysql",sha256:await digest(target)}}const exclusions=[];for(const path of selection.files??[]){const source=realpathSync(path);sources.push(source);if(statSync(source).isDirectory()&&basename(source)!=="snapshots"){for(const pattern of["**/*.sqlite","**/*.db","**/*.sqlite3","**/*-wal","**/*-shm","**/*-journal","**/logs/**","**/cache/**","**/framework/**"])exclusions.push("--exclude",join(source,pattern))}}const manifest=join(root,"recovery.json");saveJson(manifest,{project,created:epoch(),sourceTimestamp,databases:mapping,files:selection.files??[]});sources.push(manifest);const failures=[];const upload=async([provider,archive])=>{try{console.log(`${project}: ${provider} uploading persistent files and consistent databases`);const output=await archive.run("backup","--json","--tag",options.profile??"app-daily","--tag","production","--tag",`project:${project}`,...exclusions,"--",...sources);const summary=output.split(`
|
|
5
5
|
`).filter((line)=>line.startsWith("{")).map((line)=>JSON.parse(line)).find((record)=>record.message_type==="summary");const snapshot=summary?.snapshot_id;if(!snapshot)throw new Error("Backup returned no snapshot ID");await withScratch(join(root,"restore-"),async(scratch)=>{const restored=join(scratch,"recovered");for(const[file,record]of Object.entries(mapping)){await archive.restoreVerifiedFile(snapshot,file,restored);if(await digest(restored)!==record.sha256)throw new Error("Database recovery checksum mismatch");if(record.engine==="sqlite")validateSqlite(restored);else if(record.engine==="postgres")await command(["/usr/local/bin/pg_restore","--list",restored])}await archive.restore(snapshot,manifest,restored);if(await digest(restored)!==await digest(manifest))throw new Error("Recovery manifest checksum mismatch")});status[provider]={timestamp:epoch(),source_timestamp:sourceTimestamp,snapshot,databases:Object.keys(mapping).length,restore_verified:true};if(options.profile)persist();console.log(`${project}: ${provider} uploaded and restored (${Object.keys(mapping).length} databases)`)}catch(error){failures.push(`${provider}: ${error instanceof Error?error.message:error}`)}};if(options.profile)await Promise.all(Object.entries(archives).map(upload));else for(const archive of Object.entries(archives))await upload(archive);if(failures.length)throw new Error(failures.join(", "));for(const path of Object.keys(mapping)){if(lstatSync(path,{throwIfNoEntry:false})?.isFile())unlinkSync(path)}}async function recoveryDrill(inventory,archives,state,statePath,directory,profile="app-daily"){const drills=state.drills??={};for(const[project,selection]of Object.entries(inventory.projects)){const postgres=selection.postgres??[];const mysql=(selection.mysql??[]).map((source,index)=>({source,index})).filter((item)=>item.source.socket);if(postgres.length===0&&mysql.length===0)continue;const root=join(inventory.staging??defaultStage,project,"databases");for(const[provider,archive]of Object.entries(archives)){const snapshots=await archive.snapshots("--latest","1","--tag",`${profile},project:${project}`);const snapshot=snapshots.sort((a,b)=>Date.parse(b.time)-Date.parse(a.time))[0];if(!snapshot)throw new Error(`${project}: no ${provider} recovery snapshot`);console.log(`${project}: ${provider} starting restore drill (${postgres.length} PostgreSQL, ${mysql.length} Vitess)`);for(const database of postgres){await withScratch(join(directory,"host-drill-"),async(scratch)=>{const dump=join(scratch,"database.dump");await archive.restoreVerifiedFile(snapshot.id,join(root,`${databaseName(database)}.dump`),dump);await postgresRecovery(dump,directory)})}if(profile==="project-rpo"&&selection.files?.length){await withScratch(join(directory,"host-files-drill-"),async(scratch)=>{const paths=selection.files.map((path)=>realpathSync(path));const includes=paths.flatMap((path)=>["--include",path.replace(/[\\*?()[\]{}]/g,"\\$&")]);await archive.run("restore",snapshot.id,"--verify","--target",scratch,...includes);for(const path of paths)lstatSync(join(scratch,path))})}for(const{source,index}of mysql){await withScratch(join(directory,"host-drill-"),async(scratch)=>{const dump=join(scratch,"database.sql");await archive.restoreVerifiedFile(snapshot.id,join(root,`mysql-${index}-${databaseName(source.database)}.sql`),dump);await mysqlRecovery(dump,source.database,source.binary,directory)})}drills[`${project}:${provider}`]=epoch();saveJson(statePath,state);console.log(`${project}: ${provider} recovered into isolated database instances (${postgres.length} PostgreSQL, ${mysql.length} Vitess)`)}}}export async function runHostBackup(inventory,statePath,options,archives=Object.fromEntries(Object.entries(inventory.repositories).map(([provider,config])=>[provider,new ResticArchive(config,provider)]))){if(Object.keys(archives).length===0)throw new Error("No backup repositories configured");for(const project of Object.keys(inventory.projects)){if(!/^[a-z0-9_-]+$/i.test(project))throw new Error("Invalid backup project name")}const state=existsSync(statePath)?readJson(statePath):{};if(options.drill){await recoveryDrill(inventory,archives,state,statePath,options.drillDirectory??"/var/tmp",options.profile);return}if(options.check||options.checkProvider!==undefined){const providers=Object.entries(archives).filter(([provider])=>options.checkProvider===undefined||provider===options.checkProvider);if(!providers.length)throw new Error("Unknown Restic provider for pack integrity check");const checks=state.checks??={};const logDir=join(dirname(statePath),"pack-checks");mkdirSync(logDir,{recursive:true,mode:448});requirePrivateDirectory(logDir);const failed=[];for(const[provider,archive]of providers){if(!/^[a-z0-9_-]+$/i.test(provider))throw new Error("Invalid Restic provider name");const partition=(checks[provider]?.partition??0)%7+1;const log=join(logDir,`${provider}.log`);console.log(`${provider}: checking Restic pack partition ${partition}/7`);try{await archive.checkPackPartition(partition,log);checks[provider]={partition,timestamp:epoch()};saveJson(statePath,state);console.log(`${provider}: repository check ${partition}/7 passed`)}catch(error){failed.push(provider);console.error(`${provider}: repository check ${partition}/7 failed (${error instanceof Error?error.message:error}). See ${log}`)}}if(failed.length)throw new Error(`Restic pack checks failed for ${failed.join(", ")}`);return}const retryAt=epoch();if(options.retryFailed&&allProjectsRecovered(inventory,state,retryAt)){console.log("All app backups are fresh and recovery-verified");return}const stage=inventory.staging??defaultStage;mkdirSync(stage,{recursive:true,mode:448});requirePrivateDirectory(stage);writeFileSync(join(stage,stagingMarker),`managed disposable database dump staging
|
|
6
6
|
`,{mode:384});const failures=[];const projects=state.projects=Object.assign(Object.create(null),state.projects);for(const[project,selection]of Object.entries(inventory.projects)){const previous=projects[project]??={};if(options.retryFailed&&!projectBackupDue(previous,inventory.repositories,retryAt))continue;try{await backupProject(project,selection,archives,stage,previous,options,()=>saveJson(statePath,state));delete previous.error}catch(error){previous.error=error instanceof Error?error.message:String(error);failures.push(project);console.error(`${project}: backup failed: ${previous.error}`)}projects[project]=previous;saveJson(statePath,state)}if(failures.length)throw new Error(`Backup failures: ${failures.join(", ")}`);if(!options.preserveBackups&&!options.profile){for(const archive of Object.values(archives))await archive.run("forget","--tag","app-daily","--group-by","tags","--keep-daily","7","--keep-weekly","5","--keep-monthly","12","--prune")}if(options.retryFailed&&allProjectsRecovered(inventory,state,epoch()))await options.onRecovered?.()}
|
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"name": "@stacksjs/cloud",
|
|
3
3
|
"type": "module",
|
|
4
4
|
"sideEffects": false,
|
|
5
|
-
"version": "0.75.
|
|
5
|
+
"version": "0.75.701",
|
|
6
6
|
"description": "The Stacks cloud/serverless integration & implementation.",
|
|
7
7
|
"author": "Chris Breuer",
|
|
8
8
|
"contributors": [
|
|
@@ -59,22 +59,22 @@
|
|
|
59
59
|
"prepublishOnly": "bun run build"
|
|
60
60
|
},
|
|
61
61
|
"dependencies": {
|
|
62
|
-
"@stacksjs/config": "0.75.
|
|
63
|
-
"@stacksjs/error-handling": "0.75.
|
|
64
|
-
"@stacksjs/logging": "0.75.
|
|
65
|
-
"@stacksjs/path": "0.75.
|
|
66
|
-
"@stacksjs/strings": "0.75.
|
|
62
|
+
"@stacksjs/config": "0.75.701",
|
|
63
|
+
"@stacksjs/error-handling": "0.75.701",
|
|
64
|
+
"@stacksjs/logging": "0.75.701",
|
|
65
|
+
"@stacksjs/path": "0.75.701",
|
|
66
|
+
"@stacksjs/strings": "0.75.701",
|
|
67
67
|
"@stacksjs/ts-cloud": "0.16.148",
|
|
68
68
|
"@stacksjs/ts-xml": "^0.1.2"
|
|
69
69
|
},
|
|
70
70
|
"devDependencies": {
|
|
71
|
-
"@stacksjs/cli": "0.75.
|
|
72
|
-
"@stacksjs/dns": "0.75.
|
|
73
|
-
"@stacksjs/env": "0.75.
|
|
74
|
-
"@stacksjs/router": "0.75.
|
|
75
|
-
"@stacksjs/storage": "0.75.
|
|
76
|
-
"@stacksjs/utils": "0.75.
|
|
77
|
-
"@stacksjs/validation": "0.75.
|
|
71
|
+
"@stacksjs/cli": "0.75.701",
|
|
72
|
+
"@stacksjs/dns": "0.75.701",
|
|
73
|
+
"@stacksjs/env": "0.75.701",
|
|
74
|
+
"@stacksjs/router": "0.75.701",
|
|
75
|
+
"@stacksjs/storage": "0.75.701",
|
|
76
|
+
"@stacksjs/utils": "0.75.701",
|
|
77
|
+
"@stacksjs/validation": "0.75.701",
|
|
78
78
|
"better-dx": "^0.2.39"
|
|
79
79
|
}
|
|
80
80
|
}
|