openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
9 lines • 10.9 kB
JavaScript
import{n as containsAsciiControlCharacter}from"./string-normalization-D_oBUpO3.mjs";import{c as sha256File}from"./directory-durability-o_aQCRBZ.mjs";import{x as root}from"./fs-safe-Bxzu1j4h.mjs";import{n as ignoreMissingPath}from"./errno-DUBt6SQQ.mjs";import{n as normalizeAgentId,t as isValidAgentId}from"./agent-id-cOfqmfln.mjs";import"./session-key-BPgKfU2m.mjs";import{Et as _enum,Jn as string,Lt as boolean,Nt as array,Pn as number,Un as record,lr as uuid,qn as strictObject,xn as literal}from"./schemas-DuCQi-Qb.mjs";import{t as datetime}from"./iso-DI0cgeRE.mjs";import{a as sameFileMutationFingerprint,t as copyFileHandle}from"./file-descriptor-CRkf5tcV.mjs";import{a as resolveSqliteDatabaseFilePaths,t as SQLITE_SIDECAR_SUFFIXES}from"./sqlite-files-731tEtYd.mjs";import fs from"node:fs";import path from"node:path";import fs$1 from"node:fs/promises";import{sameFileIdentity}from"@openclaw/fs-safe/advanced";
//!src/snapshot/snapshot-provider.ts
const SNAPSHOT_MANIFEST_FILENAME=`manifest.json`;const SNAPSHOT_SQLITE_FILENAME=`database.sqlite`;
//!src/snapshot/manifest.ts
const MAX_MANIFEST_BYTES=1048576;const MAX_SQLITE_USER_VERSION=2147483647;const MIN_SQLITE_USER_VERSION=-2147483648;const SNAPSHOT_ID_PATTERN=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,254}$/;const SHA256_PATTERN=/^[a-f0-9]{64}$/;async function hashSnapshotArtifact(e){const t=await(await root(e)).open(SNAPSHOT_SQLITE_FILENAME,{hardlinks:`reject`,symlinks:`reject`});try{return{...await hashFileHandle(t.handle),identity:t.exactIdentity}}finally{await t.handle.close()}}async function copySnapshotArtifact(e,t){const n=await(await root(e)).open(SNAPSHOT_SQLITE_FILENAME,{hardlinks:`reject`,symlinks:`reject`});let r;let i;try{r=await fs$1.open(t,`wx+`,384);i=await r.stat({bigint:true});const e=await hashFileHandle(n.handle,r);await r.sync();const a=await r.stat({bigint:true});const o=await fs$1.lstat(t,{bigint:true});if(!sameFileIdentity(i,a)||!sameFileIdentity(i,o))throw new Error(`Snapshot restore staging file changed during copy: ${t}`);return{...e,identity:a}}catch(e){await r?.close().catch(()=>void 0);r=void 0;if(i){const e=await fs$1.lstat(t,{bigint:true}).catch(()=>void 0);if(e&&sameFileIdentity(i,e))await fs$1.unlink(t).catch(()=>void 0)}throw e}finally{await r?.close().catch(()=>void 0);await n.handle.close().catch(()=>void 0)}}async function hashFileHandle(e,t){const n=await e.stat({bigint:true});let r=0;if(t)r=await copyFileHandle(e,t);const i=await sha256File(t??e);const a=await e.stat({bigint:true});if(!sameFileMutationFingerprint(n,a)||t&&r!==i.bytes)throw new Error(`Snapshot artifact changed while being read.`);return{sha256:i.digest,sizeBytes:i.bytes}}async function writeSnapshotManifest(e,t){const n=path.join(e,SNAPSHOT_MANIFEST_FILENAME);const r=await fs$1.open(n,`wx+`,384);try{await r.writeFile(`${JSON.stringify(t,null,2)}\n`,`utf8`);await r.sync()}finally{await r.close()}}async function readSnapshotManifest(e){const t=await root(e);const n=path.join(e,SNAPSHOT_MANIFEST_FILENAME);const r=await t.read(SNAPSHOT_MANIFEST_FILENAME,{hardlinks:`reject`,maxBytes:MAX_MANIFEST_BYTES,symlinks:`reject`});let i;try{i=JSON.parse(r.buffer.toString(`utf8`))}catch(e){throw new Error(`Snapshot manifest is not valid JSON: ${n}`,{cause:e})}return parseSnapshotManifest(i,n,path.basename(e))}function parseSnapshotManifest(e,t,n){const r=requireRecord(e,`manifest`,t);requireExactKeys(r,[`schemaVersion`,`snapshotId`,`createdAt`,`database`,`artifact`]);if(r.schemaVersion!==1)throw new Error(`Unsupported snapshot manifest schemaVersion ${String(r.schemaVersion)}: ${t}`);const i=requireSnapshotId(r.snapshotId,t);if(i!==n)throw new Error(`Snapshot manifest id ${i} does not match directory ${n}: ${t}`);const a=requireCanonicalTimestamp(r.createdAt,t);const o=parseSnapshotDatabase(r.database,t);const s=requireRecord(r.artifact,`artifact`,t);requireExactKeys(s,[`path`,`sha256`,`sizeBytes`]);if(s.path!==`database.sqlite`)throw new Error(`Snapshot manifest artifact.path must be ${SNAPSHOT_SQLITE_FILENAME}: ${t}`);if(typeof s.sha256!==`string`||!SHA256_PATTERN.test(s.sha256))throw new Error(`Snapshot manifest artifact.sha256 is invalid: ${t}`);if(!Number.isSafeInteger(s.sizeBytes)||Number(s.sizeBytes)<=0)throw new Error(`Snapshot manifest artifact.sizeBytes is invalid: ${t}`);return{schemaVersion:1,snapshotId:i,createdAt:a,database:o,artifact:{path:SNAPSHOT_SQLITE_FILENAME,sha256:s.sha256,sizeBytes:Number(s.sizeBytes)}}}function parseSnapshotDatabase(e,t){const n=requireRecord(e,`database`,t);const r=n.role;const i=requireSafeText(n.basename,`database.basename`,t,255);if(path.basename(i)!==i||i===`.`||i===`..`)throw new Error(`Snapshot manifest database.basename is invalid: ${t}`);const a=requireSqliteUserVersion(n.userVersion,t);if(r===`global`){requireExactKeys(n,[`role`,`basename`,`userVersion`]);return{role:r,basename:i,userVersion:a}}if(r===`agent`){requireExactKeys(n,[`role`,`agentId`,`basename`,`userVersion`]);const e=requireSafeText(n.agentId,`database.agentId`,t,64);if(!isValidAgentId(e)||normalizeAgentId(e)!==e)throw new Error(`Snapshot manifest database.agentId is invalid: ${t}`);return{role:r,agentId:e,basename:i,userVersion:a}}if(r===`generic`){requireExactKeys(n,[`role`,`id`,`basename`,`userVersion`]);return{role:r,id:requireSafeText(n.id,`database.id`,t,256),basename:i,userVersion:a}}throw new Error(`Snapshot manifest database.role is invalid: ${t}`)}function requireRecord(e,t,n){if(!e||typeof e!==`object`||Array.isArray(e))throw new Error(`Snapshot manifest ${t} must be an object: ${n}`);return e}function requireExactKeys(e,t){const n=Object.keys(e).toSorted();const r=[...t].toSorted();if(n.length!==r.length||n.some((e,t)=>e!==r[t]))throw new Error(`Snapshot manifest fields must be exactly ${t.join(`, `)}; got ${n.join(`, `)}`)}function requireSnapshotId(e,t){if(typeof e!==`string`||!SNAPSHOT_ID_PATTERN.test(e))throw new Error(`Snapshot manifest snapshotId is invalid: ${t}`);return e}function requireCanonicalTimestamp(e,t){if(typeof e!==`string`)throw new Error(`Snapshot manifest createdAt is invalid: ${t}`);const n=new Date(e);if(!Number.isFinite(n.getTime())||n.toISOString()!==e)throw new Error(`Snapshot manifest createdAt is not canonical ISO 8601: ${t}`);return e}function requireSafeText(e,t,n,r){if(typeof e!==`string`||e.length===0||e.length>r||e.trim()!==e||containsAsciiControlCharacter(e))throw new Error(`Snapshot manifest ${t} is invalid: ${n}`);return e}function requireSqliteUserVersion(e,t){if(!Number.isSafeInteger(e)||Number(e)<MIN_SQLITE_USER_VERSION||Number(e)>MAX_SQLITE_USER_VERSION)throw new Error(`Snapshot manifest database.userVersion is invalid: ${t}`);return Number(e)}
//!src/snapshot/restore-paths.ts
async function assertFreshRestoreTarget(e){for(const t of resolveSqliteDatabaseFilePaths(e))if(await fs$1.lstat(t).catch(ignoreMissingPath))throw new Error(`Fresh SQLite restore path already exists: ${t}`)}function assertNoSqliteSidecarsSync(e,t){for(const n of SQLITE_SIDECAR_SUFFIXES){const r=`${e}${n}`;try{fs.lstatSync(r)}catch(e){ignoreMissingPath(e);continue}throw new Error(`${t}: ${r}`)}}
//!src/snapshot/export-envelope.ts
const identifier=string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,254}$/);const digest=string().regex(/^[a-f0-9]{64}$/);const version=number().int().nonnegative().max(2147483647);const artifact=strictObject({sha256:digest,sizeBytes:number().int().positive().safe()});const table=strictObject({rows:number().int().nonnegative().safe(),sha256:digest});const allocation=strictObject({value:string().regex(/^(0|[1-9][0-9]{0,18})$/).refine(e=>/^[0-9]{1,19}$/.test(e)&&BigInt(e)<=9223372036854775807n),called:boolean()});const postgresEnvelope=strictObject({schemaVersion:literal(2),snapshotId:identifier,createdAt:datetime({precision:3}),profile:_enum([`exact`,`user-backup`]),source:strictObject({engine:literal(`postgres`),storeId:uuid(),owner:identifier,namespace:identifier,schemaVersion:version}),exportSchemaVersion:version,activeFragments:array(identifier),verification:strictObject({tables:record(identifier,table),allocations:record(identifier,allocation)}),carrier:literal(`postgres-schema`).optional(),schema:string().regex(/^restore_[a-f0-9]{32}$/).optional(),artifacts:strictObject({"database.sqlite":artifact.optional(),"anchor.sqlite":artifact}),sanitizedDifferences:array(identifier)}).refine(e=>e.profile!==`exact`||e.sanitizedDifferences.length===0,{message:`Exact exports must not contain sanitization differences`}).refine(e=>e.carrier===`postgres-schema`?e.profile===`exact`&&Boolean(e.schema)&&!e.artifacts[`database.sqlite`]:!e.schema&&Boolean(e.artifacts[`database.sqlite`]),{message:`Export carrier does not match its artifacts`});function parsePostgresEnvelope(e,t){const n=postgresEnvelope.parse(e);if(n.snapshotId!==t)throw new Error(`Export manifest id does not match its directory`);return n}async function readSnapshotExportEnvelope(e,t=path.basename(e)){const n=await(await root(e)).read(SNAPSHOT_MANIFEST_FILENAME,{hardlinks:`reject`,symlinks:`reject`,maxBytes:1048576});const r=JSON.parse(n.buffer.toString(`utf8`));if(r&&typeof r===`object`&&`schemaVersion`in r&&r.schemaVersion===1)return{engine:`sqlite`,manifest:parseSnapshotManifest(r,e,t)};return{engine:`postgres`,manifest:parsePostgresEnvelope(r,t)}}async function writePostgresExportEnvelope(e,t){const n=parsePostgresEnvelope(t,path.basename(e));const r=await fs$1.open(path.join(e,SNAPSHOT_MANIFEST_FILENAME),`wx`,384);try{await r.writeFile(`${JSON.stringify(n,null,2)}\n`);await r.sync()}finally{await r.close()}}async function verifyPostgresExportEnvelope(e,t,n,r){const i=parsePostgresEnvelope(t,path.basename(e));if(i.profile!==r)throw new Error(`Export profile does not match the requested restore`);const a=await root(e);for(const t of[`database.sqlite`,`anchor.sqlite`]){const r=i.artifacts[t];if(!r)continue;assertNoSqliteSidecarsSync(path.join(e,t),`PostgreSQL export has unexpected SQLite sidecar`);const o=await a.open(t,{hardlinks:`reject`,symlinks:`reject`});try{const e=await o.handle.stat({bigint:true});const a=await sha256File(o.handle);if(a.digest!==r.sha256||a.bytes!==r.sizeBytes)throw new Error(`Export artifact verification failed: ${t}`);if(t===`anchor.sqlite`){const e=await n(o.handle);if(e.engine!==`postgres`||e.storeId!==i.source.storeId||e.namespace!==i.source.namespace)throw new Error(`Export anchor does not match the source store identity`)}if(!sameFileMutationFingerprint(e,await o.handle.stat({bigint:true})))throw new Error(`Export artifact changed during verification: ${t}`)}finally{await o.handle.close()}}}export{assertFreshRestoreTarget as a,hashSnapshotArtifact as c,SNAPSHOT_MANIFEST_FILENAME as d,SNAPSHOT_SQLITE_FILENAME as f,writePostgresExportEnvelope as i,readSnapshotManifest as l,readSnapshotExportEnvelope as n,assertNoSqliteSidecarsSync as o,verifyPostgresExportEnvelope as r,copySnapshotArtifact as s,parsePostgresEnvelope as t,writeSnapshotManifest as u};