@stacksjs/cloud 0.75.652 → 0.75.654
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.
|
@@ -18,6 +18,7 @@ export declare interface BackupStatus {
|
|
|
18
18
|
declare interface BackupOptions {
|
|
19
19
|
profile?: 'project-rpo'
|
|
20
20
|
check?: boolean
|
|
21
|
+
checkProvider?: string
|
|
21
22
|
drill?: boolean
|
|
22
23
|
drillDirectory?: string
|
|
23
24
|
retryFailed?: boolean
|
|
@@ -26,5 +27,5 @@ declare interface BackupOptions {
|
|
|
26
27
|
onRecovered?: () => Promise<void>
|
|
27
28
|
}
|
|
28
29
|
declare type ProjectStatus = Record<string, RecoveryReceipt | string | undefined> & { error?: string }
|
|
29
|
-
declare type Archive = Pick<ResticArchive, 'run' | 'restore' | 'restoreVerifiedFile' | 'snapshots'>;
|
|
30
|
+
declare type Archive = Pick<ResticArchive, 'run' | 'restore' | 'restoreVerifiedFile' | 'snapshots' | 'checkPackPartition'>;
|
|
30
31
|
export {};
|
|
@@ -2,5 +2,5 @@ import{existsSync,lstatSync,mkdirSync,realpathSync,statSync,unlinkSync,writeFile
|
|
|
2
2
|
${settings.map(([key,value])=>`${key}=${JSON.stringify(value)}`).join(`
|
|
3
3
|
`)}
|
|
4
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,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
|
-
`).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.
|
|
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/dist/host-backup/io.d.ts
CHANGED
package/dist/host-backup/io.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
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")}
|
|
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:options.logErrorsToOutput&&output!==undefined?output:"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")}
|
|
@@ -9,6 +9,7 @@ export declare class ResticArchive {
|
|
|
9
9
|
constructor(config: string, provider: string, requireS3Credentials?: boolean, policy?: Record<string, unknown>);
|
|
10
10
|
run(...args: string[]): Promise<string>;
|
|
11
11
|
snapshots(...args: string[]): Promise<ResticSnapshot[]>;
|
|
12
|
+
checkPackPartition(partition: number, log: string): Promise<void>;
|
|
12
13
|
restore(snapshot: string, path: string, destination: string): Promise<void>;
|
|
13
14
|
restoreVerifiedFile(snapshot: string, path: string, destination: string): Promise<void>;
|
|
14
15
|
}
|
|
@@ -1 +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{policy;repository;env;constructor(config,provider,requireS3Credentials=false,policy={lock:"5m",timeoutMs:6*3600000}){this.policy=policy;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",this.policy.lock,...args],{env:this.env,timeoutMs:this.policy.timeoutMs,interruptOnTimeout:true})}async snapshots(...args){return JSON.parse(await this.run("snapshots","--json",...args))}async restore(snapshot,path,destination){await command(["restic","--retry-lock",this.policy.lock,"dump",snapshot,path],{env:this.env,output:destination,timeoutMs:this.policy.timeoutMs,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)})}}
|
|
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{policy;repository;env;constructor(config,provider,requireS3Credentials=false,policy={lock:"5m",timeoutMs:6*3600000}){this.policy=policy;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};if(provider==="hetzner")this.env.GODEBUG=[this.env.GODEBUG,"http2client=0"].filter(Boolean).join(",")}run(...args){return command(["restic","--retry-lock",this.policy.lock,...args],{env:this.env,timeoutMs:this.policy.timeoutMs,interruptOnTimeout:true})}async snapshots(...args){return JSON.parse(await this.run("snapshots","--json",...args))}async checkPackPartition(partition,log){await command(["restic","--retry-lock","5m","--verbose","check",`--read-data-subset=${partition}/7`],{env:this.env,output:log,logErrorsToOutput:true,timeoutMs:6*3600000,interruptOnTimeout:true})}async restore(snapshot,path,destination){await command(["restic","--retry-lock",this.policy.lock,"dump",snapshot,path],{env:this.env,output:destination,timeoutMs:this.policy.timeoutMs,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.654",
|
|
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.654",
|
|
63
|
+
"@stacksjs/error-handling": "0.75.654",
|
|
64
|
+
"@stacksjs/logging": "0.75.654",
|
|
65
|
+
"@stacksjs/path": "0.75.654",
|
|
66
|
+
"@stacksjs/strings": "0.75.654",
|
|
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.654",
|
|
72
|
+
"@stacksjs/dns": "0.75.654",
|
|
73
|
+
"@stacksjs/env": "0.75.654",
|
|
74
|
+
"@stacksjs/router": "0.75.654",
|
|
75
|
+
"@stacksjs/storage": "0.75.654",
|
|
76
|
+
"@stacksjs/utils": "0.75.654",
|
|
77
|
+
"@stacksjs/validation": "0.75.654",
|
|
78
78
|
"better-dx": "^0.2.39"
|
|
79
79
|
}
|
|
80
80
|
}
|