@stacksjs/cloud 0.75.639 → 0.75.643
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.d.ts +23 -0
- package/dist/host-backup/backup.js +6 -0
- package/dist/host-backup/deploy-archives.d.ts +17 -0
- package/dist/host-backup/deploy-archives.js +5 -0
- package/dist/host-backup/inventory.d.ts +29 -0
- package/dist/host-backup/inventory.js +7 -0
- package/dist/host-backup/io.d.ts +23 -0
- package/dist/host-backup/io.js +2 -0
- package/dist/host-backup/maintenance.d.ts +10 -0
- package/dist/host-backup/maintenance.js +2 -0
- package/dist/host-backup/recovery.d.ts +2 -0
- package/dist/host-backup/recovery.js +1 -0
- package/dist/host-backup/restic.d.ts +13 -0
- package/dist/host-backup/restic.js +1 -0
- package/package.json +13 -13
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { ResticArchive } from './restic';
|
|
2
|
+
import type { BackupInventory } from './inventory';
|
|
3
|
+
export declare function projectBackupDue(status: ProjectStatus, repositories: Record<string, string>, now: number): boolean;
|
|
4
|
+
export declare function runHostBackup(inventory: BackupInventory, statePath: string, options: BackupOptions, archives?: Record<string, Archive>): Promise<void>;
|
|
5
|
+
export declare const stagingMarker: '.host-backup-managed';
|
|
6
|
+
declare interface RecoveryReceipt {
|
|
7
|
+
timestamp: number
|
|
8
|
+
snapshot: string
|
|
9
|
+
databases: number
|
|
10
|
+
restore_verified: boolean
|
|
11
|
+
}
|
|
12
|
+
declare interface BackupOptions {
|
|
13
|
+
check?: boolean
|
|
14
|
+
drill?: boolean
|
|
15
|
+
drillDirectory?: string
|
|
16
|
+
retryFailed?: boolean
|
|
17
|
+
preserveBackups?: boolean
|
|
18
|
+
hostSources?: (project: string, root: string) => Promise<string[]>
|
|
19
|
+
onRecovered?: () => Promise<void>
|
|
20
|
+
}
|
|
21
|
+
declare type ProjectStatus = Record<string, RecoveryReceipt | string | undefined> & { error?: string }
|
|
22
|
+
declare type Archive = Pick<ResticArchive, 'run' | 'restore' | 'restoreVerifiedFile' | 'snapshots'>;
|
|
23
|
+
export {};
|
|
@@ -0,0 +1,6 @@
|
|
|
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
|
+
${settings.map(([key,value])=>`${key}=${JSON.stringify(value)}`).join(`
|
|
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.isFinite(Number(bytes))||freeBytes(root)<Number(bytes)*4+2*GiB)throw new Error("Insufficient MySQL snapshot/recovery space");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){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(),databases:mapping,files:selection.files??[]});sources.push(manifest);const failures=[];for(const[provider,archive]of Object.entries(archives)){try{console.log(`${project}: ${provider} uploading persistent files and consistent databases`);const output=await archive.run("backup","--json","--tag","app-daily","--tag","production","--tag",`project:${project}`,...exclusions,"--",...sources);const summary=output.split(`
|
|
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.restore(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(),snapshot,databases:Object.keys(mapping).length,restore_verified:true};console.log(`${project}: ${provider} uploaded and restored (${Object.keys(mapping).length} databases)`)}catch(error){failures.push(`${provider}: ${error instanceof Error?error.message:error}`)}}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){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",`app-daily,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)})}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");return}if(options.check){const checks=state.checks??={};for(const[provider,archive]of Object.entries(archives)){const partition=(checks[provider]?.partition??0)%7+1;await archive.run("check",`--read-data-subset=${partition}/7`);checks[provider]={partition,timestamp:epoch()};saveJson(statePath,state);console.log(`${provider}: repository check ${partition}/7 passed`)}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
|
+
`,{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);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){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?.()}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export declare function cleanupStaging(directory: string, references: ReadonlySet<string>, apply: boolean, now?: ReturnType<typeof Date.now>): void;
|
|
2
|
+
export declare function cleanupRestoreChecks(directory: string, references: ReadonlySet<string>, apply: boolean, now?: ReturnType<typeof Date.now>): void;
|
|
3
|
+
export declare function deploymentBackups(directory: string, references: ReadonlySet<string>, now?: ReturnType<typeof Date.now>): { uploads: BackupFile[], removals: BackupFile[] };
|
|
4
|
+
export declare function alreadyArchived(plan: BackupPlan, manifest: string): boolean;
|
|
5
|
+
export declare function archiveDeploymentBackups(directory: string, project: string, plan: BackupPlan, archives: Record<string, DeployArchive>, receipts: string): Promise<void>;
|
|
6
|
+
declare interface BackupFile {
|
|
7
|
+
path: string
|
|
8
|
+
fingerprint: string
|
|
9
|
+
size: number
|
|
10
|
+
mtime: number
|
|
11
|
+
}
|
|
12
|
+
export declare interface DeployArchive {
|
|
13
|
+
run: (...args: string[]) => Promise<string>
|
|
14
|
+
restore: (snapshot: string, path: string, destination: string) => Promise<void>
|
|
15
|
+
}
|
|
16
|
+
declare type BackupPlan = ReturnType<typeof deploymentBackups>;
|
|
17
|
+
export {};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{closeSync,constants,fchmodSync,fsyncSync,lstatSync,mkdirSync,openSync,readFileSync,readdirSync,rmSync,unlinkSync,writeFileSync}from"node:fs";import{dirname,join}from"node:path";import{stagingMarker}from"./backup";import{digest,freeBytes,readJson,saveJson,withScratch}from"./io";import{day,isReferenced}from"./maintenance";const restoreMarker=".mail-host-restore-check";const restoreMarkerContent=`disposable off-host restore copy
|
|
2
|
+
`;const backupName=/^\d{4}-\d{2}-\d{2}T[\d-]+\.(sqlite|postgres|mysql)\.(sqlite|sql)$/;const appTag="app-deploy";const twoHours=7200000;function backupFile(path){const stats=lstatSync(path,{throwIfNoEntry:false,bigint:true});if(!stats?.isFile()||stats.size===0n)return;return{path,size:Number(stats.size),mtime:Number(stats.mtimeMs),fingerprint:[stats.dev,stats.ino,stats.size,stats.mtimeNs,stats.ctimeNs].map(String).join(":")}}export function cleanupStaging(directory,references,apply,now=Date.now()){const marker=join(directory,stagingMarker);if(!lstatSync(directory,{throwIfNoEntry:false})?.isDirectory()||!lstatSync(marker,{throwIfNoEntry:false})?.isFile()||readFileSync(marker,"utf8")!==`managed disposable database dump staging
|
|
3
|
+
`)return;for(const project of readdirSync(directory,{withFileTypes:true})){if(!project.isDirectory())continue;const databases=join(directory,project.name,"databases");if(!lstatSync(databases,{throwIfNoEntry:false})?.isDirectory())continue;for(const name of readdirSync(databases)){const path=join(databases,name);const stat=lstatSync(path,{throwIfNoEntry:false});if(!name.endsWith(".partial")||!stat?.isFile()||now-stat.mtimeMs<twoHours||isReferenced(path,references))continue;console.log(`${apply?"Remove":"Would remove"} abandoned partial dump: ${path}`);if(apply)unlinkSync(path)}}}export function cleanupRestoreChecks(directory,references,apply,now=Date.now()){for(const entry of readdirSync(directory,{withFileTypes:true})){if(!entry.name.startsWith(".restore-check-")||!entry.isDirectory())continue;const path=join(directory,entry.name);const marker=join(path,restoreMarker);const stats=lstatSync(marker,{throwIfNoEntry:false});if(!stats?.isFile()||now-stats.mtimeMs<twoHours||readFileSync(marker,"utf8")!==restoreMarkerContent||isReferenced(path,references))continue;console.log(`${apply?"Remove":"Would remove"} abandoned restore-check copy: ${path}`);if(apply)rmSync(path,{recursive:true})}}export function deploymentBackups(directory,references,now=Date.now()){const groups=new Map;for(const name of readdirSync(directory).sort().reverse()){const match=backupName.exec(name);const path=join(directory,name);if(!match||isReferenced(path,references))continue;const entry=backupFile(path);if(!entry)continue;const key=`${match[1]}.${match[2]}`;const group=groups.get(key)??[];group.push(entry);groups.set(key,group)}const uploads=[];const removals=[];for(const files of groups.values()){uploads.push(...files.filter((file)=>now-file.mtime>=600000));removals.push(...files.slice(2).filter((file)=>now-file.mtime>=day))}return{uploads,removals}}function appendReceipt(path,receipt){const flags=constants.O_APPEND|constants.O_CREAT|constants.O_WRONLY|constants.O_NOFOLLOW;const fd=openSync(path,flags,384);try{fchmodSync(fd,384);writeFileSync(fd,`${JSON.stringify(receipt)}
|
|
4
|
+
`);fsyncSync(fd)}finally{closeSync(fd)}const directory=openSync(dirname(path),constants.O_RDONLY|constants.O_DIRECTORY);try{fsyncSync(directory)}finally{closeSync(directory)}}export function alreadyArchived(plan,manifest){if(plan.removals.length||!lstatSync(manifest,{throwIfNoEntry:false})?.isFile())return false;const recorded=readJson(manifest);return Object.keys(recorded).length===plan.uploads.length&&plan.uploads.every((file)=>recorded[file.path]===file.fingerprint)}export async function archiveDeploymentBackups(directory,project,plan,archives,receipts){if(!/^[a-z0-9_-]+$/i.test(project))throw new Error("Invalid deployment backup project name");const providers=Object.entries(archives);if(providers.length<2||!providers.some(([provider])=>provider==="aws"))throw new Error("Deployment backup archival requires AWS and a second repository");const paths=plan.uploads.map((file)=>file.path);const checksums=new Map;for(const file of plan.uploads){const checksum=await digest(file.path);if(backupFile(file.path)?.fingerprint!==file.fingerprint)throw new Error(`Backup changed during hashing: ${file.path}`);checksums.set(file.path,checksum)}const snapshots=new Map;for(const[provider,archive]of providers){const stdout=await archive.run("backup","--json","--tag",appTag,"--tag","production","--tag",`project:${project}`,"--",...paths);const summary=stdout.split(`
|
|
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(`${provider}: no completed backup snapshot`);const metadata=JSON.parse(await archive.run("cat","snapshot",snapshot));const saved=new Set(metadata.paths);if(saved.size!==paths.length||!paths.every((path)=>saved.has(path)))throw new Error(`${provider}: snapshot path verification failed`);snapshots.set(provider,snapshot)}mkdirSync(receipts,{recursive:true,mode:448});for(const file of plan.removals){const checksum=checksums.get(file.path);if(!checksum)throw new Error("Refusing to remove a backup outside the upload plan");if(freeBytes(directory)<file.size+512*1024**2)throw new Error("Insufficient restore-check space. Local backups are retained.");await withScratch(join(directory,".restore-check-"),async(scratch)=>{writeFileSync(join(scratch,restoreMarker),restoreMarkerContent,{mode:384});const restored=join(scratch,"restored");for(const[provider,archive]of providers){await archive.restore(snapshots.get(provider),file.path,restored);if(lstatSync(restored).size!==file.size||await digest(restored)!==checksum)throw new Error(`${provider}: restore verification failed for ${file.path}`)}});if(backupFile(file.path)?.fingerprint!==file.fingerprint)throw new Error(`Backup changed during archival: ${file.path}`);appendReceipt(join(receipts,`${project}.jsonl`),{path:file.path,snapshot:snapshots.get("aws"),sha256:checksum,size:file.size,verified_at:Math.floor(Date.now()/1000),replicas:Object.fromEntries(snapshots)});unlinkSync(file.path);console.log(`Verified off-host restores and removed local duplicate: ${file.path}`)}const manifest=plan.uploads.filter((file)=>backupFile(file.path)?.fingerprint===file.fingerprint);saveJson(join(receipts,`${project}.uploaded.json`),Object.fromEntries(manifest.map((file)=>[file.path,file.fingerprint])));console.log(`Archived ${project}: ${paths.length} deployment backups in ${providers.length} repositories`)}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
export declare function databaseName(name: string): string;
|
|
2
|
+
export declare function discoverManagedProjects(webRoot: string, stateRoot?: string): Record<string, BackupSelection>;
|
|
3
|
+
export declare function discoverPostgresDatabases(): Promise<Array<{ name: string, disposable: boolean }>>;
|
|
4
|
+
export declare function retireMissingDatabase(inventory: BackupInventory, name: string, liveNames: ReadonlySet<string>): void;
|
|
5
|
+
/** @defaultValue `['runuser', '-u', 'postgres', '--']` */
|
|
6
|
+
export declare const postgresCommand: string[];
|
|
7
|
+
/** @defaultValue `[...postgresCommand, '/usr/local/bin/psql', '-v', 'ON_ERROR_STOP=1', '-Atc']` */
|
|
8
|
+
export declare const psql: ((typeof postgresCommand)[number] | string)[];
|
|
9
|
+
export declare interface MysqlSource {
|
|
10
|
+
binary: string
|
|
11
|
+
database: string
|
|
12
|
+
socket?: string
|
|
13
|
+
user?: string
|
|
14
|
+
env_file?: string
|
|
15
|
+
}
|
|
16
|
+
export declare interface BackupSelection {
|
|
17
|
+
files?: string[]
|
|
18
|
+
sqlite?: string[]
|
|
19
|
+
postgres?: string[]
|
|
20
|
+
mysql?: MysqlSource[]
|
|
21
|
+
}
|
|
22
|
+
export declare interface BackupInventory {
|
|
23
|
+
repositories: Record<string, string>
|
|
24
|
+
projects: Record<string, BackupSelection>
|
|
25
|
+
staging?: string
|
|
26
|
+
created_at?: number
|
|
27
|
+
retired_databases?: Array<{ name: string, specification: BackupSelection, retired_at: number }>
|
|
28
|
+
legacy_external_databases?: Array<{ project: string, env_file: string, reason: string }>
|
|
29
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import{lstatSync,readFileSync,readdirSync,realpathSync,statSync}from"node:fs";import{extname,isAbsolute,join}from"node:path";import{command,envValues}from"./io";export const postgresCommand=["runuser","-u","postgres","--"];export const psql=[...postgresCommand,"/usr/local/bin/psql","-v","ON_ERROR_STOP=1","-Atc"];export function databaseName(name){if(!/^[a-z0-9_]+$/i.test(name)||!/[a-z0-9]/i.test(name))throw new Error("Invalid configured database name");return name}function isSqlite(path){return[".sqlite",".db",".sqlite3"].includes(extname(path))}function isFile(path){return statSync(path,{throwIfNoEntry:false})?.isFile()??false}function isDirectory(path){return statSync(path,{throwIfNoEntry:false})?.isDirectory()??false}function*sqliteFiles(directory){for(const entry of readdirSync(directory,{withFileTypes:true})){const path=join(directory,entry.name);if(entry.isDirectory())yield*sqliteFiles(path);else if(isSqlite(path)&&isFile(path))yield realpathSync(path)}}export function discoverManagedProjects(webRoot,stateRoot="/var/lib"){const projects=new Map;for(const siteName of readdirSync(webRoot).sort()){const site=join(webRoot,siteName);const owner=join(site,".ts-cloud/owner");const current=join(site,"current");if(!lstatSync(site).isDirectory()||!isFile(owner)||!lstatSync(current,{throwIfNoEntry:false})?.isSymbolicLink())continue;const name=readFileSync(owner,"utf8").trim();if(!/^[a-z0-9_-]+$/i.test(name))continue;let project=projects.get(name);if(!project){project={sqlite:new Set,files:new Set};projects.set(name,project)}const shared=join(site,"shared");const env=join(shared,".env");const values=isFile(env)?envValues(env):{};for(const file of[env,join(shared,".env.keys")]){if(isFile(file))project.files.add(realpathSync(file))}for(const name of["public","stx-images","uploads","storage"]){const directory=join(shared,name);if(!isDirectory(directory))continue;const persistentDirectory=realpathSync(directory);project.files.add(persistentDirectory);for(const database of sqliteFiles(persistentDirectory))project.sqlite.add(database)}const sharedDatabase=join(webRoot,`${name}-shared/database`);if((values.DB_CONNECTION??"sqlite")==="sqlite"){const configured=values.DB_DATABASE_PATH??values.DB_DATABASE;const candidates=[sharedDatabase,join(stateRoot,name)];if(configured&&!configured.startsWith("encrypted:"))candidates.push(...isAbsolute(configured)?[configured]:[join(current,configured),join(shared,configured)]);for(const candidate of candidates){if(isSqlite(candidate)&&isFile(candidate))project.sqlite.add(realpathSync(candidate));else if(isDirectory(candidate)){for(const entry of readdirSync(candidate)){const path=join(candidate,entry);if(isSqlite(path)&&isFile(path))project.sqlite.add(realpathSync(path))}}}}const snapshots=join(sharedDatabase,"snapshots");if(isDirectory(snapshots))project.files.add(snapshots)}return Object.fromEntries([...projects].map(([name,project])=>[name,{sqlite:[...project.sqlite].sort(),files:[...project.files].sort(),postgres:[]}]))}export async function discoverPostgresDatabases(){const output=await command([...psql,`
|
|
2
|
+
SELECT json_build_object('name', d.datname, 'disposable',
|
|
3
|
+
coalesce(shobj_description(d.oid, 'pg_database') = 'stacks:disposable-verification'
|
|
4
|
+
AND r.rolvaliduntil <= now() + interval '24 hours', false))
|
|
5
|
+
FROM pg_database d JOIN pg_roles r ON r.oid = d.datdba
|
|
6
|
+
WHERE NOT d.datistemplate AND d.datname <> 'postgres'`]);return output.split(`
|
|
7
|
+
`).filter(Boolean).map((line)=>JSON.parse(line))}export function retireMissingDatabase(inventory,name,liveNames){if(liveNames.has(name))throw new Error("A live database cannot be retired from backup selection");const selection=Object.hasOwn(inventory.projects,name)?inventory.projects[name]:undefined;if(selection?.postgres?.length!==1||selection.postgres[0]!==name||selection.sqlite?.length||selection.files?.length||selection.mysql?.length)throw new Error("Only a missing database-only selection can be retired");const retired=inventory.retired_databases??=[];retired.push({name,specification:selection,retired_at:Math.floor(Date.now()/1000)});delete inventory.projects[name]}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
export declare function readJson<T>(path: string): T;
|
|
2
|
+
export declare function atomicWrite(path: string, content: string | Uint8Array, mode?: number): void;
|
|
3
|
+
export declare function saveJson(path: string, value: unknown): void;
|
|
4
|
+
export declare function envValues(path: string): Record<string, string | undefined>;
|
|
5
|
+
export declare function requirePrivateDirectory(path: string): void;
|
|
6
|
+
export declare function freeBytes(path: string): number;
|
|
7
|
+
export declare function digest(path: string): Promise<string>;
|
|
8
|
+
export declare function withScratch<T>(prefix: string, operation: (path: string) => Promise<T>): Promise<T>;
|
|
9
|
+
export declare function command(args: string[], options?: CommandOptions): Promise<string>;
|
|
10
|
+
export declare function atomicDump(target: string, args: string[], validate?: (file: string) => Promise<unknown>): Promise<void>;
|
|
11
|
+
export declare function validateSqlite(path: string): void;
|
|
12
|
+
export declare function sqliteSnapshot(source: string, target: string): Promise<void>;
|
|
13
|
+
export declare function requireRoot(): void;
|
|
14
|
+
export declare const GiB: number;
|
|
15
|
+
declare interface CommandOptions {
|
|
16
|
+
input?: string
|
|
17
|
+
output?: string
|
|
18
|
+
discardOutput?: boolean
|
|
19
|
+
timeoutMs?: number
|
|
20
|
+
interruptOnTimeout?: boolean
|
|
21
|
+
env?: Record<string, string | undefined>
|
|
22
|
+
}
|
|
23
|
+
export {};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{__callDispose as __callDispose_vyva085h,__using as __using_nccbhqtj}from"bun:wrap";import{Database}from"bun:sqlite";import{createHash}from"node:crypto";import{closeSync,createReadStream,fsyncSync,lstatSync,mkdirSync,mkdtempSync,openSync,readFileSync,renameSync,rmSync,statfsSync,writeFileSync}from"node:fs";import{basename,dirname,join}from"node:path";import process from"node:process";import{parseEnv}from"node:util";export const GiB=1024**3;export function readJson(path){return JSON.parse(readFileSync(path,"utf8"))}export function atomicWrite(path,content,mode=384){const scratch=mkdtempSync(join(dirname(path),".write-"));const temporary=join(scratch,"file");try{const descriptor=openSync(temporary,"wx",mode);try{writeFileSync(descriptor,content);fsyncSync(descriptor)}finally{closeSync(descriptor)}renameSync(temporary,path)}finally{rmSync(scratch,{recursive:true,force:true})}}export function saveJson(path,value){mkdirSync(dirname(path),{recursive:true,mode:448});atomicWrite(path,`${JSON.stringify(value,null,2)}
|
|
2
|
+
`)}export function envValues(path){return parseEnv(readFileSync(path,"utf8"))}export function requirePrivateDirectory(path){const stats=lstatSync(path);if(!stats.isDirectory()||stats.uid!==process.geteuid?.()||stats.mode&63)throw new Error("Staging must be a dedicated private directory owned by the operator")}export function freeBytes(path){const stats=statfsSync(path);return stats.bavail*stats.bsize}export async function digest(path){const hash=createHash("sha256");for await(const chunk of createReadStream(path))hash.update(chunk);return hash.digest("hex")}export async function withScratch(prefix,operation){const path=mkdtempSync(prefix);try{return await operation(path)}finally{rmSync(path,{recursive:true,force:true})}}export async function command(args,options={}){const output=options.output?openSync(options.output,"w",384):undefined;let deadline;let escalation;let timedOut=false;try{const timeout=options.timeoutMs??1200000;const child=Bun.spawn(args,{stdin:options.input?Bun.file(options.input):"ignore",stdout:output??(options.discardOutput?"ignore":"pipe"),stderr:"ignore",env:options.env,timeout:options.interruptOnTimeout?0:timeout,killSignal:"SIGKILL"});if(options.interruptOnTimeout&&timeout>0){deadline=setTimeout(()=>{timedOut=true;child.kill("SIGINT");escalation=setTimeout(()=>child.kill("SIGKILL"),30000)},timeout)}const[stdout,code]=await Promise.all([child.stdout&&typeof child.stdout!=="number"?new Response(child.stdout).text():"",child.exited]);if(timedOut)throw new Error(`${basename(args[0]??"command")} timed out`);if(code!==0||child.signalCode)throw new Error(`${basename(args[0]??"command")} failed (${child.signalCode||`exit ${code}`})`);return stdout}finally{clearTimeout(deadline);clearTimeout(escalation);if(output!==undefined)closeSync(output)}}export async function atomicDump(target,args,validate){await withScratch(join(dirname(target),".dump-"),async(scratch)=>{const partial=join(scratch,basename(target));const limit=freeBytes(scratch)-2*GiB;if(limit<=0)throw new Error("Insufficient free space for dump");const position=args[0]==="runuser"?args.indexOf("--")+1:0;const bounded=[...args.slice(0,position),"prlimit",`--fsize=${limit}:${limit}`,"--",...args.slice(position)];await command(bounded,{output:partial});if(Bun.file(partial).size===0)throw new Error("Empty database dump");await validate?.(partial);renameSync(partial,target)})}export function validateSqlite(path){let __bun_temp_ref_1$=[];try{const db=__using_nccbhqtj(__bun_temp_ref_1$,new Database(path,{readonly:true}),0);const result=db.query("PRAGMA quick_check").all();if(result.length!==1||result[0]?.quick_check!=="ok")throw new Error("SQLite recovery integrity check failed");db.query("SELECT count(*) FROM sqlite_schema").get()}catch(__bun_temp_ref_2$){var __bun_temp_ref_3$=__bun_temp_ref_2$,__bun_temp_ref_4$=1}finally{__callDispose_vyva085h(__bun_temp_ref_1$,__bun_temp_ref_3$,__bun_temp_ref_4$)}}export async function sqliteSnapshot(source,target){await withScratch(join(dirname(target),".sqlite-"),async(scratch)=>{const partial=join(scratch,basename(target));await command(["sqlite3","-readonly","-cmd",".timeout 30000",source,`.backup "${partial.replaceAll("\\","\\\\").replaceAll('"',"\\\"")}"`],{timeoutMs:600000});await command(["sqlite3",partial,"PRAGMA journal_mode = DELETE"]);validateSqlite(partial);renameSync(partial,target)})}export function requireRoot(){if(process.geteuid?.()!==0)throw new Error("Root is required")}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export declare function diskUsage(path: string): number;
|
|
2
|
+
export declare function isReferenced(path: string, references: ReadonlySet<string>): boolean;
|
|
3
|
+
export declare function processReferences(proc?: string): Set<string>;
|
|
4
|
+
export declare function tryFileLock(path: string, create?: boolean): Promise<FileLock | undefined>;
|
|
5
|
+
export declare function withSiteLocks(sites: string[], operation: () => Promise<void>): Promise<boolean>;
|
|
6
|
+
export declare function managedSites(webRoot: string): Array<{ site: string, project: string }>;
|
|
7
|
+
export declare function releaseCandidates(site: string, references: ReadonlySet<string>, now?: ReturnType<typeof Date.now>): string[];
|
|
8
|
+
export declare const day: 86400000;
|
|
9
|
+
declare type FileLock = () => void;
|
|
10
|
+
export {};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{closeSync,constants,lstatSync,openSync,readFileSync,readdirSync,readlinkSync,realpathSync,statfsSync}from"node:fs";import{dirname,join}from"node:path";const releaseId=/^[0-9a-f]{7,40}$/;export const day=86400000;export function diskUsage(path){const stats=statfsSync(path);const used=stats.blocks-stats.bfree;return Math.ceil(100*used/(used+stats.bavail))}export function isReferenced(path,references){for(const reference of references){if(reference===path||reference.startsWith(`${path}/`))return true}return false}function whenPresent(read){try{return read()}catch(error){const code=error.code;if(code!=="ENOENT"&&code!=="ESRCH")throw error}}export function processReferences(proc="/proc"){const references=new Set;for(const row of readFileSync(join(proc,"self/mountinfo"),"utf8").trimEnd().split(`
|
|
2
|
+
`)){const path=row.split(" ")[4];if(!path)throw new Error("Cannot read mounted paths for host maintenance");references.add(path.replace(/\\([0-7]{3})/g,(_,octal)=>String.fromCharCode(Number.parseInt(octal,8))))}for(const pid of readdirSync(proc)){if(!/^\d+$/.test(pid))continue;const process=join(proc,pid);const descriptors=whenPresent(()=>readdirSync(join(process,"fd")));if(!descriptors)continue;for(const entry of["cwd","exe",...descriptors.map((name)=>`fd/${name}`)]){const path=whenPresent(()=>readlinkSync(join(process,entry)));if(path?.startsWith("/"))references.add(path.replace(/ \(deleted\)$/,""))}const argv=whenPresent(()=>readFileSync(join(process,"cmdline"),"utf8"));for(const arg of argv?.split("\x00")??[]){if(arg.startsWith("/"))references.add(arg)}}return references}export async function tryFileLock(path,create=false){const flags=constants.O_RDWR|constants.O_NOFOLLOW|(create?constants.O_CREAT:0);const fd=whenPresent(()=>openSync(path,flags,384));if(fd===undefined)return;let held=false;try{const child=Bun.spawn(["flock","-n","-E","75","3"],{stdio:["ignore","ignore","ignore",fd]});const code=await child.exited;if(code===75)return;if(code!==0)throw new Error("Unable to acquire the host maintenance lock");held=true;return()=>closeSync(fd)}finally{if(!held)closeSync(fd)}}export async function withSiteLocks(sites,operation){const releases=[];try{for(const site of sites.sort()){const release=await tryFileLock(join(site,".ts-cloud/deploy.lock"));if(!release)return false;releases.push(release)}await operation();return true}finally{for(const release of releases.reverse())release()}}export function managedSites(webRoot){const sites=[];for(const entry of readdirSync(webRoot,{withFileTypes:true})){if(!entry.isDirectory())continue;const site=join(webRoot,entry.name);const owner=join(site,".ts-cloud/owner");if(!lstatSync(owner,{throwIfNoEntry:false})?.isFile())continue;const project=readFileSync(owner,"utf8").trim();if(/^[a-z0-9_-]+$/i.test(project))sites.push({site,project})}return sites.sort((a,b)=>a.site.localeCompare(b.site))}export function releaseCandidates(site,references,now=Date.now()){site=realpathSync(site);const releases=join(site,"releases");const current=join(site,"current");if(!lstatSync(releases,{throwIfNoEntry:false})?.isDirectory()||!lstatSync(current,{throwIfNoEntry:false})?.isSymbolicLink())return[];const active=whenPresent(()=>realpathSync(current));if(!active||dirname(active)!==releases||!lstatSync(active,{throwIfNoEntry:false})?.isDirectory())return[];const siteDev=lstatSync(site).dev;const candidates=readdirSync(releases).filter((name)=>releaseId.test(name)).map((name)=>({path:join(releases,name),stats:lstatSync(join(releases,name),{throwIfNoEntry:false})})).filter(({stats})=>stats?.isDirectory()&&stats.dev===siteDev).sort((a,b)=>b.stats.mtimeMs-a.stats.mtimeMs);const rollback=join(site,".ts-cloud/previous-release");const previous=lstatSync(rollback,{throwIfNoEntry:false})?.isFile()?readFileSync(rollback,"utf8").trim():"";const keep=new Set([active,...candidates.slice(0,2).map(({path})=>path)]);if(releaseId.test(previous))keep.add(join(releases,previous));return candidates.filter(({path,stats})=>!keep.has(path)&&now-stats.mtimeMs>=day&&!isReferenced(path,references)).map(({path})=>path)}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{chmodSync,copyFileSync,existsSync}from"node:fs";import{dirname,join}from"node:path";import{command,withScratch}from"./io";import{databaseName,postgresCommand}from"./inventory";export async function postgresRecovery(dump,workspace){await withScratch(join(workspace,"pg-drill-"),async(scratch)=>{const restored=join(scratch,"database.dump");copyFileSync(dump,restored);chmodSync(restored,384);await command(["chown","postgres",scratch,restored]);const data=join(scratch,"data");const pgCtl=[...postgresCommand,"/usr/local/bin/pg_ctl","-D",data];await command([...postgresCommand,"/usr/local/bin/initdb","-D",data,"-U","backupcheck","--auth=trust","--no-locale"]);await command([...pgCtl,"-l",join(scratch,"postgres.log"),"-o",`-F -c listen_addresses='' -c unix_socket_directories='${scratch}' -p 55432`,"-w","start"]);try{const connection=["--host",scratch,"--port","55432","--username","backupcheck","--dbname","postgres"];await command([...postgresCommand,"/usr/local/bin/pg_restore","--no-owner","--no-privileges","--exit-on-error",...connection,restored],{timeoutMs:3600000});await command([...postgresCommand,"/usr/local/bin/psql",...connection,"-v","ON_ERROR_STOP=1","-Atc","SELECT count(*) FROM pg_class WHERE relkind='r'"])}finally{await command([...pgCtl,"-m","immediate","-w","stop"])}})}export async function mysqlRecovery(dump,name,binary,workspace){const database=databaseName(name);const mysql=join(dirname(binary),"mysql");const server=join(dirname(binary),"mysqld");await withScratch(join(workspace,"mysql-drill-"),async(scratch)=>{const data=join(scratch,"data");const socket=join(scratch,"mysql.sock");await command([server,"--no-defaults","--initialize-insecure","--user=root",`--datadir=${data}`]);const child=Bun.spawn([server,"--no-defaults","--user=root",`--datadir=${data}`,`--socket=${socket}`,`--pid-file=${join(scratch,"mysql.pid")}`,"--skip-networking","--mysqlx=0","--skip-log-bin","--innodb-flush-log-at-trx-commit=2","--innodb-buffer-pool-size=256M"],{stdout:"ignore",stderr:"ignore"});try{const deadline=performance.now()+60000;while(!existsSync(socket)){if(child.exitCode!==null||performance.now()>deadline)throw new Error("Disposable MySQL did not start");await Bun.sleep(100)}const args=[mysql,"--no-defaults",`--socket=${socket}`,"--user=root","--binary-mode"];await command([...args,"--execute",`CREATE DATABASE \`${database}\``]);await command([...args,"--execute","ALTER INSTANCE DISABLE INNODB REDO_LOG"]);await command([...args,database],{input:dump,timeoutMs:7200000});await command([...args,"--execute","ALTER INSTANCE ENABLE INNODB REDO_LOG"]);await command([...args,"--execute",`SELECT COUNT(*) FROM information_schema.tables WHERE table_schema='${database}'`])}finally{if(child.exitCode===null&&child.signalCode===null){child.kill("SIGTERM");const escalation=setTimeout(()=>child.kill("SIGKILL"),30000);try{await child.exited}finally{clearTimeout(escalation)}}}})}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export declare interface ResticSnapshot {
|
|
2
|
+
id: string
|
|
3
|
+
time: string
|
|
4
|
+
}
|
|
5
|
+
export declare class ResticArchive {
|
|
6
|
+
readonly repository: string;
|
|
7
|
+
private env;
|
|
8
|
+
constructor(config: string, provider: string, requireS3Credentials?: boolean);
|
|
9
|
+
run(...args: string[]): Promise<string>;
|
|
10
|
+
snapshots(...args: string[]): Promise<ResticSnapshot[]>;
|
|
11
|
+
restore(snapshot: string, path: string, destination: string): Promise<void>;
|
|
12
|
+
restoreVerifiedFile(snapshot: string, path: string, destination: string): Promise<void>;
|
|
13
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{lstatSync,realpathSync,renameSync}from"node:fs";import{dirname,isAbsolute,join,normalize,sep}from"node:path";import process from"node:process";import{command,envValues,withScratch}from"./io";export class ResticArchive{repository;env;constructor(config,provider,requireS3Credentials=false){const env={...process.env};for(const key of Object.keys(env)){if(key.startsWith("RESTIC_")||key.startsWith("AWS_"))delete env[key]}const credentials=envValues(config);if(!credentials.RESTIC_REPOSITORY||!credentials.RESTIC_PASSWORD_FILE&&!credentials.RESTIC_PASSWORD)throw new Error(`Incomplete Restic repository configuration for ${provider}`);if(requireS3Credentials&&(!credentials.RESTIC_PASSWORD_FILE||!credentials.AWS_ACCESS_KEY_ID||!credentials.AWS_SECRET_ACCESS_KEY))throw new Error(`Missing explicit S3 credentials or Restic password file for ${provider}`);this.repository=credentials.RESTIC_REPOSITORY;this.env={...env,RESTIC_CACHE_DIR:`${dirname(config)}/cache-${provider}`,...credentials}}run(...args){return command(["restic","--retry-lock","5m",...args],{env:this.env,timeoutMs:6*3600000,interruptOnTimeout:true})}async snapshots(...args){return JSON.parse(await this.run("snapshots","--json",...args))}async restore(snapshot,path,destination){await command(["restic","--retry-lock","5m","dump",snapshot,path],{env:this.env,output:destination,timeoutMs:6*3600000,interruptOnTimeout:true})}async restoreVerifiedFile(snapshot,path,destination){if(!isAbsolute(path))throw new Error("The Restic file path must be absolute");const archivePath=normalize(path);const include=archivePath.replace(/[\\*?()[\]{}]/g,"\\$&");await withScratch(join(dirname(destination),".restic-"),async(scratch)=>{await this.run("restore",snapshot,"--include",include,"--target",scratch,"--verify");const restored=join(scratch,archivePath);if(!lstatSync(restored,{throwIfNoEntry:false})?.isFile()||!realpathSync(restored).startsWith(realpathSync(scratch)+sep))throw new Error("Restic did not restore the requested file");renameSync(restored,destination)})}}
|
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.643",
|
|
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.643",
|
|
63
|
+
"@stacksjs/error-handling": "0.75.643",
|
|
64
|
+
"@stacksjs/logging": "0.75.643",
|
|
65
|
+
"@stacksjs/path": "0.75.643",
|
|
66
|
+
"@stacksjs/strings": "0.75.643",
|
|
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.643",
|
|
72
|
+
"@stacksjs/dns": "0.75.643",
|
|
73
|
+
"@stacksjs/env": "0.75.643",
|
|
74
|
+
"@stacksjs/router": "0.75.643",
|
|
75
|
+
"@stacksjs/storage": "0.75.643",
|
|
76
|
+
"@stacksjs/utils": "0.75.643",
|
|
77
|
+
"@stacksjs/validation": "0.75.643",
|
|
78
78
|
"better-dx": "^0.2.39"
|
|
79
79
|
}
|
|
80
80
|
}
|