@rizom/ops 0.2.0-alpha.732 → 0.2.0-alpha.733
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/brains-ops.js
CHANGED
|
@@ -737,7 +737,7 @@ printf 'REMOTE_ARTIFACT_DIR=%s\\n' "$remote_dir"
|
|
|
737
737
|
`).replace(/\\n/g,`
|
|
738
738
|
`).trimEnd()}
|
|
739
739
|
`}var B8,rge;var eO=v(async()=>{pe();z8();gn();rf();Ys();await P8();B8=c.object({HCLOUD_TOKEN:c.string().min(1),KAMAL_SSH_PRIVATE_KEY:c.string().min(1)}),rge=c.object({servers:c.array(c.object({status:c.string(),public_net:c.object({ipv4:c.object({ip:c.string().min(1)})})}))})});import{parseArgs as IK}from"util";function nt(e){return e}class cf extends Error{constructor(e){super(e);this.name="CliUsageError"}}function AK(e,t){let r={...t};for(let o of e)for(let[n,i]of Object.entries(o.flags??{})){let s=r[n];if(s===void 0){r[n]=i;continue}if(s.type!==i.type||s.short!==i.short||s.default!==i.default)throw Error(`Conflicting definitions for flag --${n}: commands must agree on type, short, and default`)}return r}function RK(e){let t={};for(let[r,o]of Object.entries(e))t[r]={type:o.type,...o.short!==void 0?{short:o.short}:{},...o.default!==void 0?{default:o.default}:{}};return t}function TK(e){if(!(e instanceof Error)||!("code"in e))return!1;return e.code==="ERR_PARSE_ARGS_UNKNOWN_OPTION"||e.code==="ERR_PARSE_ARGS_INVALID_OPTION_VALUE"}function nO(e,t){let r=AK(t.commands,t.globalFlags??{}),o,n;try{({values:o,positionals:n}=IK({args:e,options:RK(r),allowPositionals:!0,strict:t.strict??!0}))}catch(s){if(TK(s))throw new cf(s.message.split(". ")[0]??s.message);throw s}if("help"in r&&o.help===!0)return{command:"help",args:[],flags:{help:!0}};if("version"in r&&o.version===!0)return{command:"version",args:[],flags:{version:!0}};let i={};for(let[s,a]of Object.entries(r)){let l=o[s];if(typeof l==="string"&&a.type==="string")i[s]=l;else if(typeof l==="boolean"&&a.type==="boolean")i[s]=l}return{command:n[0]??"help",args:n.slice(1),flags:i}}function oO(e){let t=e.reduce((r,o)=>Math.max(r,o.label.length),0);return e.map((r)=>` ${r.label.padEnd(t)} ${r.description}`)}function $K(e){return oO(e.map((t)=>({label:t.usage?`${t.name} ${t.usage}`:t.name,description:t.description})))}function OK(e,t){let r=t.type==="string"?` ${t.placeholder??"<value>"}`:"",o=t.short!==void 0?`, -${t.short}`:"";return`--${e}${r}${o}`}function iO(e){return oO(Object.entries(e).map(([t,r])=>({label:OK(t,r),description:r.description})))}function sO(e,t){return`Usage: ${e} ${t.name}${t.usage?` ${t.usage}`:""}`}function CK(e){return JSON.stringify(Object.entries(e).map(([t,r])=>[t,r.type,r.short??"",r.description,r.placeholder??"",r.default??""]).sort((t,r)=>String(t[0]).localeCompare(String(r[0]))))}function PK(e){let t=[],r=new Map;for(let n of e){let i=n.flags??{};if(Object.keys(i).length===0)continue;let s=CK(i),a=r.get(s);if(a){a.names.push(n.name);continue}let l={names:[n.name],flags:i};r.set(s,l),t.push(l)}let o=[];for(let n of t)o.push("",`${n.names.join(" / ")} options:`),o.push(...iO(n.flags));return o}function aO(e){let t=[e.intro,"",`Usage: ${e.cliName} ${e.usage??"<command> [args]"}`,"","Commands:",...$K(e.commands)];if(e.globalFlags&&Object.keys(e.globalFlags).length>0)t.push("","Options:",...iO(e.globalFlags));return t.push(...PK(e.commands)),t.join(`
|
|
740
|
-
`)}function cO(e){let t=new Map;for(let r of e){if(t.has(r.name))throw Error(`Duplicate command name: ${r.name}`);t.set(r.name,r)}return t}function ot(e,t){let r=e[t];return typeof r==="string"?r:void 0}function ps(e,t){let r=e[t];return typeof r==="boolean"?r:void 0}var lf={name:"@rizom/ops",version:"0.2.0-alpha.
|
|
740
|
+
`)}function cO(e){let t=new Map;for(let r of e){if(t.has(r.name))throw Error(`Duplicate command name: ${r.name}`);t.set(r.name,r)}return t}function ot(e,t){let r=e[t];return typeof r==="string"?r:void 0}function ps(e,t){let r=e[t];return typeof r==="boolean"?r:void 0}var lf={name:"@rizom/ops",version:"0.2.0-alpha.733",description:"Operator CLI for managing private brain fleet registry repos",keywords:["brains","ops","cli","deploy","fleet","operator"],license:"AGPL-3.0-only",author:"Yeehaa <yeehaa@rizom.ai> (https://rizom.ai)",bin:{"brains-ops":"./dist/brains-ops.js"},bugs:"https://github.com/rizom-ai/brains/issues",dependencies:{"@libsql/client":"^0.17.4","age-encryption":"^0.3.0",yaml:"^2.9.0"},devDependencies:{"@brains/contracts":"workspace:*","@brains/deploy-support":"workspace:*","@brains/eslint-config":"workspace:*","@brains/job-queue":"workspace:*","@brains/profile":"workspace:*","@brains/site-composition":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@brains/utils":"workspace:*","@types/bun":"^1.4.0",typescript:"^7.0.2"},engines:{bun:">=1.3.3"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./deploy":{types:"./dist/deploy.d.ts",import:"./dist/deploy.js",bun:"./dist/deploy.js"}},files:["dist","templates"],homepage:"https://github.com/rizom-ai/brains/tree/main/packages/brains-ops#readme",main:"./dist/index.js",publishConfig:{access:"public"},repository:{type:"git",url:"https://github.com/rizom-ai/brains.git",directory:"packages/brains-ops"},scripts:{build:"bun scripts/build.ts",lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",prepublishOnly:"bun scripts/build.ts",test:"bun test --timeout 20000","test:smoke":"bun run build && RUN_SMOKE_TESTS=1 bun test --timeout 60000",typecheck:"tsc --noEmit"},type:"module",types:"./dist/index.d.ts"};Ov();vi();import{writeFile as KY}from"fs/promises";import{join as mj}from"path";import{createSign as wW,generateKeyPairSync as xW}from"crypto";import{mkdir as _W,writeFile as cD}from"fs/promises";import{join as lD}from"path";async function OV(e){let t=await e.text();if(!t.trim())return;try{return JSON.parse(t)}catch{return t}}async function Qa(e,t,r){let o=await OV(e),n=t.safeParse(o);if(!e.ok||!n.success){let i=r.formatError??CV;throw Error(`${r.label}${i(e,o)}`)}return n.data}function CV(e,t){let r=t===void 0?"":`: ${typeof t==="string"?t:JSON.stringify(t)}`;return` (${e.status} ${e.statusText}${r})`}pe();var EW="2.5.4.3",kW="1.2.840.113549.1.1.11",pD="https://api.cloudflare.com/client/v4",IW="origin-rsa",AW=5475,fD=15000;function mD(e){return{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}var uD=c.looseObject({message:c.string().optional()}),RW=c.looseObject({errors:c.array(uD).optional(),messages:c.array(uD).optional()}),TW=c.looseObject({certificate:c.string().min(1),expires_on:c.string().optional()}),$W=c.looseObject({success:c.literal(!0),result:TW}),OW=c.looseObject({success:c.literal(!0)});function CW(){let{privateKey:e,publicKey:t}=xW("rsa",{modulusLength:2048,privateKeyEncoding:{type:"pkcs8",format:"pem"},publicKeyEncoding:{type:"spki",format:"der"}});return{privateKeyPem:e,publicKeyDer:Buffer.from(t)}}function PW(e,t){let r=wd(ZW(wd(dD(EW),LW(e)))),o=wd(DW(0),r,Buffer.from(t.publicKeyDer),UW(0,Buffer.alloc(0))),n=wW("sha256").update(o).sign(t.privateKeyPem),i=wd(o,wd(dD(kW),jW()),BW(n));return{csrPem:NW("CERTIFICATE REQUEST",i),certificationRequestInfoDer:o,signature:n}}async function zW(e,t,r,o){let n=await e(`${pD}/certificates`,{method:"POST",headers:mD(t),body:JSON.stringify({hostnames:[o,`*.${o}`],requested_validity:AW,request_type:IW,csr:r}),signal:AbortSignal.timeout(fD)}),i=await Qa(n,$W,{label:"Cloudflare Origin CA request failed",formatError:gD}),a={certificatePem:`${i.result.certificate.trim()}
|
|
741
741
|
`};if(i.result.expires_on)a.expiresOn=i.result.expires_on;return a}async function hD(e,t,r){let o=await e(`${pD}/zones/${r}/settings/ssl`,{method:"PATCH",headers:mD(t),body:JSON.stringify({value:"strict"}),signal:AbortSignal.timeout(fD)});await Qa(o,OW,{label:"Cloudflare zone SSL update failed",formatError:gD})}function NW(e,t){let o=t.toString("base64").match(/.{1,64}/g)??[];return[`-----BEGIN ${e}-----`,...o,`-----END ${e}-----`,""].join(`
|
|
742
742
|
`)}function DW(e){if(e!==0)throw Error("Only zero-valued INTEGER encoding is currently supported");return Buffer.from([2,1,0])}function dD(e){let t=e.split(".").map((s)=>Number(s));if(t.length<2||t.some((s)=>Number.isNaN(s)))throw Error(`Invalid OID: ${e}`);let r=t[0],o=t[1];if(r===void 0||o===void 0)throw Error(`Invalid OID: ${e}`);let i=[r*40+o];for(let s of t.slice(2)){let a=qW(s);i.push(...a)}return Tc(6,Buffer.from(i))}function LW(e){return Tc(12,Buffer.from(e,"utf8"))}function BW(e){return Tc(3,Buffer.concat([Buffer.from([0]),e]))}function jW(){return Buffer.from([5,0])}function wd(...e){return Tc(48,Buffer.concat(e))}function ZW(...e){return Tc(49,Buffer.concat(e))}function UW(e,t){return Tc(160+e,t)}function Tc(e,t){return Buffer.concat([Buffer.from([e]),MW(t.length),t])}function MW(e){if(e<128)return Buffer.from([e]);let t=[],r=e;while(r>0)t.unshift(r&255),r>>=8;return Buffer.from([128|t.length,...t])}function qW(e){if(!Number.isInteger(e)||e<0)throw Error(`Invalid OID component: ${e}`);if(e===0)return[0];let t=[],r=e;while(r>0)t.unshift(r&127),r>>=7;for(let o=0;o<t.length-1;o+=1)t[o]=(t[o]??0)|128;return t}function gD(e,t){let r=FW(t),o=r.length>0?`: ${r.join("; ")}`:"";return` (${e.status} ${e.statusText}${o})`}function FW(e){let t=RW.safeParse(e);if(!t.success)return[];return[...t.data.errors??[],...t.data.messages??[]].map((r)=>r.message).filter((r)=>typeof r==="string"&&r.length>0)}async function yD(e,t,r){let o=CW(),{csrPem:n}=PW(r,o),i=await zW(e,t,n,r);return{certificatePem:i.certificatePem,privateKeyPem:o.privateKeyPem,...i.expiresOn!==void 0&&{expiresOn:i.expiresOn}}}async function bD(e,t){let r=lD(e,"origin.pem"),o=lD(e,"origin.key");return await _W(e,{recursive:!0}),await Promise.all([cD(r,t.certificatePem,"utf-8"),cD(o,t.privateKeyPem,{encoding:"utf-8",mode:384})]),{certificatePath:r,privateKeyPath:o}}gn();Cu();Mn();async function gj(e,t={}){try{return await JY(e,t),{success:!0}}catch(r){return{success:!1,message:Ve(r,"Certificate bootstrap failed")}}}async function JY(e,t={}){let r=await wt(e),o=VY(r,t.handle),n=o.domain,i=t.env??process.env,s=Lr(e),a=t.cfApiToken??jt("CF_API_TOKEN",i,s),l=t.cfZoneId??o.cloudflareZoneId??jt("CF_ZONE_ID",i,s);if(!a)throw Error("Missing CF_API_TOKEN");if(!l)throw Error("Missing CF_ZONE_ID");let u=t.fetchImpl??fetch,d=t.logger??console.log,p=await yD(u,a,n),m=mj(e,".brains-ops","certs",o.id),{certificatePath:h,privateKeyPath:b}=await bD(m,p),y=mj(m,"secrets.yaml");await KY(y,HY(p.certificatePem,p.privateKeyPem),"utf-8"),await hD(u,a,l);let S=Wa(t.pushTo);if(S)await bi([["CERTIFICATE_PEM",p.certificatePem],["PRIVATE_KEY_PEM",p.privateKeyPem]],{logger:d,runCommand:t.runCommand??tr});if(d(`Issued ${o.id} Origin CA cert for ${n} and *.${n}`),d(`Wrote ${h}`),d(`Wrote ${b}`),d(`Wrote ${y}`),p.expiresOn)d(`Expires on ${p.expiresOn}`);if(d("Cloudflare zone SSL mode set to Full (strict)"),S)d(`Pushed CERTIFICATE_PEM and PRIVATE_KEY_PEM to ${S}`);return{domain:n,certificatePath:h,privateKeyPath:b,certificatePem:p.certificatePem,secretsSnippetPath:y}}function HY(e,t){return[`certificatePem: ${hj(e)}`,`privateKeyPem: ${hj(t)}`,""].join(`
|
|
743
743
|
`)}function hj(e){return`"${e.replace(/"/g,"\\\"").replace(/\n/g,"\\n")}"`}function VY(e,t){if(!t)return{id:"shared",domain:WY(e.pilot.domainSuffix)};let r=e.users.find((o)=>o.handle===t);if(!r)throw Error(`Unknown user handle: ${t}`);return{id:t,domain:r.domain,...r.cloudflareZoneId?{cloudflareZoneId:r.cloudflareZoneId}:{}}}function WY(e){let t=e.trim().replace(/^\./,"").replace(/\.$/,"");if(!t||t.includes("*"))throw Error(`Invalid pilot domainSuffix: ${e}`);return t}import{chmod as UI,mkdir as cg,readFile as Sj,writeFile as bj}from"fs/promises";import{dirname as eX,join as jc}from"path";import{fileURLToPath as tX}from"url";vi();Od();Ys();var rX=["pilot.yaml","package.json",".env.schema",".gitignore","cohorts/cohort-1.yaml","users/alice.yaml",".github/actions/varlock-env/action.yml",".github/workflows/build.yml",".github/workflows/deploy.yml",".github/workflows/directory-sync-stress.yml",".github/workflows/health-watchdog-smoke.yml",".github/workflows/offboard.yml",".github/workflows/reconcile.yml",".github/workflows/upgrade.yml","deploy/Dockerfile","deploy/kamal/deploy.yml","deploy/scripts/helpers.ts","deploy/scripts/create-predeploy-backup.ts","deploy/scripts/install-health-watchdog.ts","deploy/scripts/provision-server.ts","deploy/scripts/pull-local-models.ts","deploy/scripts/update-dns.ts","deploy/scripts/write-ssh-key.ts","deploy/scripts/decrypt-user-secrets.ts","deploy/scripts/validate-secrets.ts","deploy/scripts/write-kamal-secrets.ts","deploy/scripts/resolve-user-config.ts","deploy/scripts/resolve-missing-images.ts","deploy/scripts/verify-runtime-image.ts","deploy/scripts/resolve-deploy-handles.ts","deploy/scripts/sync-content-repo.ts",".kamal/hooks/pre-deploy","docs/onboarding-checklist.md","docs/canonical-crossover-record.md","docs/operator-playbook.md","docs/user-onboarding.md","README.md"],MI=new Set([".kamal/hooks/pre-deploy"]),nX=new Set(["cohorts/cohort-1.yaml","users/alice.yaml","docs/canonical-crossover-record.md"]),oX=tX(new URL("../templates/rover-pilot/",import.meta.url));function Ro(e){return(t)=>t.includes(e)}function iX(e){return GP.find((t)=>e===`deploy/scripts/${t}`)}function qI(e){return e.replace(/\n {2}secret:\n(?: {4}- .*\n)+\nvolumes:\n/,`
|
package/dist/index.js
CHANGED
|
@@ -747,7 +747,7 @@ printf 'REMOTE_ARTIFACT_DIR=%s\\n' "$remote_dir"
|
|
|
747
747
|
`),i}async function Q8(e,t){let r=await ut(e),o=r.users.find((n)=>n.handle===t);if(!o)throw Error(`Unknown pilot user: ${t}`);return{pilot:r.pilot,user:o}}async function Y8(e){let t=await nge(ao(oge(),"brains-ops-watchdog-smoke-")),r=ao(t,"id_ed25519"),o=ao(t,"known_hosts");try{let n=encodeURIComponent(`brain=${e.target.pilot.contentRepoPrefix}${e.target.user.handle}`),i=await e.fetchImpl(`https://api.hetzner.cloud/v1/servers?label_selector=${n}`,{headers:{Authorization:`Bearer ${e.environment.HCLOUD_TOKEN}`}});if(!i.ok)throw Error(`Hetzner server lookup failed with ${i.status}`);let s=ige.parse(await i.json());if(s.servers.length!==1)throw Error(`Expected one smoke server, found ${s.servers.length}`);let a=s.servers[0];if(a?.status!=="running")throw Error("Smoke server is not running");await Fl(r,age(e.environment.KAMAL_SSH_PRIVATE_KEY),{mode:384}),await rge(r,384);let l=await e.commandRunner("ssh-keyscan",["-T","10","-t","ed25519",a.public_net.ipv4.ip]);if(l.exitCode!==0||!l.stdout.trim())throw Error("Unable to resolve watchdog smoke SSH host key");return await Fl(o,l.stdout,{mode:384}),{temporaryRoot:t,sshKeyPath:r,knownHostsPath:o,serverIp:a.public_net.ipv4.ip,commandRunner:e.commandRunner}}catch(n){throw await gO(t,{recursive:!0,force:!0}),n}}async function hO(e,t,r){return e.commandRunner("ssh",[...X8(e),`root@${e.serverIp}`,"bash","-s","--",t,r],{stdin:yO()})}async function sge(e,t,r){return e.commandRunner("scp",[...X8(e),"-r",`root@${e.serverIp}:${t}/.`,r])}function X8(e){return["-i",e.sshKeyPath,"-o","BatchMode=yes","-o","IdentitiesOnly=yes","-o","ConnectTimeout=10","-o","StrictHostKeyChecking=yes","-o",`UserKnownHostsFile=${e.knownHostsPath}`]}async function Ub(e,t,r){await Promise.all([Fl(ao(e,`${t}.stdout.log`),r.stdout),Fl(ao(e,`${t}.stderr.log`),r.stderr)])}function age(e){return`${e.replace(/\r\n/g,`
|
|
748
748
|
`).replace(/\\n/g,`
|
|
749
749
|
`).trimEnd()}
|
|
750
|
-
`}var V8,ige;var qb=v(async()=>{pe();F8();Hr();cf();Rs();await q8();V8=c.object({HCLOUD_TOKEN:c.string().min(1),KAMAL_SSH_PRIVATE_KEY:c.string().min(1)}),ige=c.object({servers:c.array(c.object({status:c.string(),public_net:c.object({ipv4:c.object({ip:c.string().min(1)})})}))})});import{chmod as tk,mkdir as fh,readFile as N2,writeFile as z2}from"fs/promises";import{dirname as KW,join as mc}from"path";import{fileURLToPath as JW}from"url";var ff={name:"@rizom/ops",version:"0.2.0-alpha.
|
|
750
|
+
`}var V8,ige;var qb=v(async()=>{pe();F8();Hr();cf();Rs();await q8();V8=c.object({HCLOUD_TOKEN:c.string().min(1),KAMAL_SSH_PRIVATE_KEY:c.string().min(1)}),ige=c.object({servers:c.array(c.object({status:c.string(),public_net:c.object({ipv4:c.object({ip:c.string().min(1)})})}))})});import{chmod as tk,mkdir as fh,readFile as N2,writeFile as z2}from"fs/promises";import{dirname as KW,join as mc}from"path";import{fileURLToPath as JW}from"url";var ff={name:"@rizom/ops",version:"0.2.0-alpha.733",description:"Operator CLI for managing private brain fleet registry repos",keywords:["brains","ops","cli","deploy","fleet","operator"],license:"AGPL-3.0-only",author:"Yeehaa <yeehaa@rizom.ai> (https://rizom.ai)",bin:{"brains-ops":"./dist/brains-ops.js"},bugs:"https://github.com/rizom-ai/brains/issues",dependencies:{"@libsql/client":"^0.17.4","age-encryption":"^0.3.0",yaml:"^2.9.0"},devDependencies:{"@brains/contracts":"workspace:*","@brains/deploy-support":"workspace:*","@brains/eslint-config":"workspace:*","@brains/job-queue":"workspace:*","@brains/profile":"workspace:*","@brains/site-composition":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@brains/utils":"workspace:*","@types/bun":"^1.4.0",typescript:"^7.0.2"},engines:{bun:">=1.3.3"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./deploy":{types:"./dist/deploy.d.ts",import:"./dist/deploy.js",bun:"./dist/deploy.js"}},files:["dist","templates"],homepage:"https://github.com/rizom-ai/brains/tree/main/packages/brains-ops#readme",main:"./dist/index.js",publishConfig:{access:"public"},repository:{type:"git",url:"https://github.com/rizom-ai/brains.git",directory:"packages/brains-ops"},scripts:{build:"bun scripts/build.ts",lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",prepublishOnly:"bun scripts/build.ts",test:"bun test --timeout 20000","test:smoke":"bun run build && RUN_SMOKE_TESTS=1 bun test --timeout 60000",typecheck:"tsc --noEmit"},type:"module",types:"./dist/index.d.ts"};Xo();fc();Rs();var HW=["pilot.yaml","package.json",".env.schema",".gitignore","cohorts/cohort-1.yaml","users/alice.yaml",".github/actions/varlock-env/action.yml",".github/workflows/build.yml",".github/workflows/deploy.yml",".github/workflows/directory-sync-stress.yml",".github/workflows/health-watchdog-smoke.yml",".github/workflows/offboard.yml",".github/workflows/reconcile.yml",".github/workflows/upgrade.yml","deploy/Dockerfile","deploy/kamal/deploy.yml","deploy/scripts/helpers.ts","deploy/scripts/create-predeploy-backup.ts","deploy/scripts/install-health-watchdog.ts","deploy/scripts/provision-server.ts","deploy/scripts/pull-local-models.ts","deploy/scripts/update-dns.ts","deploy/scripts/write-ssh-key.ts","deploy/scripts/decrypt-user-secrets.ts","deploy/scripts/validate-secrets.ts","deploy/scripts/write-kamal-secrets.ts","deploy/scripts/resolve-user-config.ts","deploy/scripts/resolve-missing-images.ts","deploy/scripts/verify-runtime-image.ts","deploy/scripts/resolve-deploy-handles.ts","deploy/scripts/sync-content-repo.ts",".kamal/hooks/pre-deploy","docs/onboarding-checklist.md","docs/canonical-crossover-record.md","docs/operator-playbook.md","docs/user-onboarding.md","README.md"],rk=new Set([".kamal/hooks/pre-deploy"]),VW=new Set(["cohorts/cohort-1.yaml","users/alice.yaml","docs/canonical-crossover-record.md"]),WW=JW(new URL("../templates/rover-pilot/",import.meta.url));function ho(e){return(t)=>t.includes(e)}function GW(e){return IO.find((t)=>e===`deploy/scripts/${t}`)}function nk(e){return e.replace(/\n {2}secret:\n(?: {4}- .*\n)+\nvolumes:\n/,`
|
|
751
751
|
secret:
|
|
752
752
|
- __DYNAMIC_SECRETS__
|
|
753
753
|
|
package/package.json
CHANGED
|
@@ -44,7 +44,15 @@ export interface PredeployDatabaseSource {
|
|
|
44
44
|
assets?: boolean | undefined;
|
|
45
45
|
}
|
|
46
46
|
|
|
47
|
-
/**
|
|
47
|
+
/** A referenced asset whose stored bytes do not verify. */
|
|
48
|
+
interface AssetFailure {
|
|
49
|
+
digest: string;
|
|
50
|
+
/** The entities referencing it, as `type/id`. */
|
|
51
|
+
entities: string[];
|
|
52
|
+
reason: string;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** The asset inventory a snapshot holds, and what of it verified. */
|
|
48
56
|
interface AssetSnapshotReport {
|
|
49
57
|
/** Entity rows referencing an asset. */
|
|
50
58
|
references: number;
|
|
@@ -53,9 +61,30 @@ interface AssetSnapshotReport {
|
|
|
53
61
|
totalBytes: number;
|
|
54
62
|
/** Staged uploads no asset publishes; harmless, reported only. */
|
|
55
63
|
orphanUploads: number;
|
|
64
|
+
verified: number;
|
|
65
|
+
failed: number;
|
|
66
|
+
failures: AssetFailure[];
|
|
56
67
|
digests: string[];
|
|
57
68
|
}
|
|
58
69
|
|
|
70
|
+
/** Where the capture program writes what the deploy log shows. */
|
|
71
|
+
export interface PredeployCaptureOutput {
|
|
72
|
+
stdout(line: string): void;
|
|
73
|
+
stderr(line: string): void;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const consoleOutput: PredeployCaptureOutput = {
|
|
77
|
+
stdout: (line) => console.log(line),
|
|
78
|
+
stderr: (line) => console.error(line),
|
|
79
|
+
};
|
|
80
|
+
|
|
81
|
+
/** The asset counts a backup reports, read back from its output. */
|
|
82
|
+
export interface PredeployAssetSummary {
|
|
83
|
+
referenced: number;
|
|
84
|
+
verified: number;
|
|
85
|
+
failed: number;
|
|
86
|
+
}
|
|
87
|
+
|
|
59
88
|
export interface PredeployBackupMetadata {
|
|
60
89
|
snapshotId: string;
|
|
61
90
|
targetHandle: string;
|
|
@@ -87,6 +116,8 @@ export type PredeployBackupResult =
|
|
|
87
116
|
totalBytes: number;
|
|
88
117
|
durationSeconds: number;
|
|
89
118
|
verification: "passed";
|
|
119
|
+
/** Absent when the backup reported no asset counts. */
|
|
120
|
+
assets?: PredeployAssetSummary;
|
|
90
121
|
};
|
|
91
122
|
|
|
92
123
|
interface CommandResult {
|
|
@@ -106,7 +137,7 @@ interface DatabaseCaptureRecord extends Omit<
|
|
|
106
137
|
sha256: string;
|
|
107
138
|
quickCheckDriver: QuickCheckDriver;
|
|
108
139
|
quickCheck: string;
|
|
109
|
-
assetVerification?: Omit<AssetSnapshotReport, "digests">;
|
|
140
|
+
assetVerification?: Omit<AssetSnapshotReport, "digests" | "failures">;
|
|
110
141
|
}
|
|
111
142
|
|
|
112
143
|
interface GitCaptureRecord {
|
|
@@ -278,6 +309,8 @@ function vectorDigestDatabase(database: Database): {
|
|
|
278
309
|
}
|
|
279
310
|
|
|
280
311
|
const ASSET_REF_PREFIX = "asset://sha256/";
|
|
312
|
+
/** How the capture names a failed asset on stderr, for the deploy log. */
|
|
313
|
+
const ASSET_FAILURE_PREFIX = "pre-deploy snapshot: asset failed: ";
|
|
281
314
|
|
|
282
315
|
/**
|
|
283
316
|
* Check every asset the snapshot's entities reference: a published header
|
|
@@ -285,7 +318,12 @@ const ASSET_REF_PREFIX = "asset://sha256/";
|
|
|
285
318
|
* Any failure blocks the backup. A database from before staged asset
|
|
286
319
|
* storage references none.
|
|
287
320
|
*/
|
|
288
|
-
|
|
321
|
+
/**
|
|
322
|
+
* Re-hash every asset the snapshot's entities reference. Each asset is
|
|
323
|
+
* checked on its own, so one bad asset does not hide the others: the report
|
|
324
|
+
* names every failure and the entities that reference it.
|
|
325
|
+
*/
|
|
326
|
+
function verifySnapshotAssets(path: string): AssetSnapshotReport {
|
|
289
327
|
const database = new Database(path, { readonly: true });
|
|
290
328
|
try {
|
|
291
329
|
const tables = new Set(
|
|
@@ -301,74 +339,109 @@ function verifySnapshotAssets(path: string, name: string): AssetSnapshotReport {
|
|
|
301
339
|
assets: 0,
|
|
302
340
|
totalBytes: 0,
|
|
303
341
|
orphanUploads: 0,
|
|
342
|
+
verified: 0,
|
|
343
|
+
failed: 0,
|
|
344
|
+
failures: [],
|
|
304
345
|
digests: [],
|
|
305
346
|
};
|
|
306
347
|
}
|
|
307
|
-
const
|
|
308
|
-
|
|
309
|
-
};
|
|
310
|
-
const referenced = database
|
|
348
|
+
const referencing = new Map<string, string[]>();
|
|
349
|
+
database
|
|
311
350
|
.query(
|
|
312
|
-
"SELECT content,
|
|
351
|
+
"SELECT content, entityType, id FROM entities WHERE content LIKE ? ORDER BY content, entityType, id",
|
|
313
352
|
)
|
|
314
353
|
.all(`${ASSET_REF_PREFIX}%`)
|
|
315
354
|
.filter(isPlainRecord)
|
|
316
|
-
.
|
|
317
|
-
digest
|
|
318
|
-
|
|
319
|
-
|
|
355
|
+
.forEach((row) => {
|
|
356
|
+
const digest = String(row["content"]).slice(ASSET_REF_PREFIX.length);
|
|
357
|
+
const entity = `${String(row["entityType"])}/${String(row["id"])}`;
|
|
358
|
+
referencing.set(digest, [...(referencing.get(digest) ?? []), entity]);
|
|
359
|
+
});
|
|
320
360
|
const header = database.query(
|
|
321
361
|
"SELECT upload_id, size_bytes, chunk_count FROM assets WHERE digest = ?",
|
|
322
362
|
);
|
|
323
363
|
const chunks = database.query(
|
|
324
364
|
"SELECT ordinal, bytes FROM asset_chunks WHERE upload_id = ? ORDER BY ordinal",
|
|
325
365
|
);
|
|
326
|
-
|
|
366
|
+
/** The asset's size when its chunks verify, else why they do not. */
|
|
367
|
+
const verify = (digest: string): { size: number } | { reason: string } => {
|
|
327
368
|
const row = header.get(digest);
|
|
328
|
-
if (!isPlainRecord(row)) return
|
|
369
|
+
if (!isPlainRecord(row)) return { reason: "has no published asset" };
|
|
329
370
|
const sizeBytes = Number(row["size_bytes"]);
|
|
330
371
|
const chunkCount = Number(row["chunk_count"]);
|
|
331
372
|
const hasher = new Bun.CryptoHasher("sha256");
|
|
332
373
|
const read = { chunks: 0, bytes: 0 };
|
|
333
374
|
for (const chunk of chunks.iterate(String(row["upload_id"]))) {
|
|
334
375
|
if (!isPlainRecord(chunk) || Number(chunk["ordinal"]) !== read.chunks) {
|
|
335
|
-
return
|
|
376
|
+
return { reason: `is missing chunk ${read.chunks}` };
|
|
336
377
|
}
|
|
337
378
|
const bytes = chunk["bytes"];
|
|
338
379
|
if (!(bytes instanceof Uint8Array)) {
|
|
339
|
-
return
|
|
380
|
+
return { reason: `chunk ${read.chunks} is not binary` };
|
|
340
381
|
}
|
|
341
382
|
hasher.update(bytes);
|
|
342
383
|
read.chunks += 1;
|
|
343
384
|
read.bytes += bytes.byteLength;
|
|
344
385
|
}
|
|
345
386
|
if (read.chunks !== chunkCount || read.bytes !== sizeBytes) {
|
|
346
|
-
return
|
|
347
|
-
|
|
348
|
-
|
|
387
|
+
return {
|
|
388
|
+
reason: `holds ${read.chunks} chunks and ${read.bytes} bytes; expected ${chunkCount} and ${sizeBytes}`,
|
|
389
|
+
};
|
|
349
390
|
}
|
|
350
391
|
if (hasher.digest("hex") !== digest) {
|
|
351
|
-
return
|
|
392
|
+
return { reason: "chunks hash to a different digest" };
|
|
352
393
|
}
|
|
353
|
-
return sizeBytes;
|
|
354
|
-
}
|
|
394
|
+
return { size: sizeBytes };
|
|
395
|
+
};
|
|
396
|
+
const results = [...referencing].map(([digest, entities]) => ({
|
|
397
|
+
digest,
|
|
398
|
+
entities,
|
|
399
|
+
outcome: verify(digest),
|
|
400
|
+
}));
|
|
401
|
+
const failures = results.flatMap(({ digest, entities, outcome }) =>
|
|
402
|
+
"reason" in outcome ? [{ digest, entities, reason: outcome.reason }] : [],
|
|
403
|
+
);
|
|
355
404
|
const orphans = database
|
|
356
405
|
.query(
|
|
357
406
|
"SELECT COUNT(*) AS count FROM asset_uploads WHERE upload_id NOT IN (SELECT upload_id FROM assets)",
|
|
358
407
|
)
|
|
359
408
|
.get();
|
|
360
409
|
return {
|
|
361
|
-
references:
|
|
362
|
-
|
|
363
|
-
|
|
410
|
+
references: results.reduce(
|
|
411
|
+
(sum, { entities }) => sum + entities.length,
|
|
412
|
+
0,
|
|
413
|
+
),
|
|
414
|
+
assets: results.length,
|
|
415
|
+
totalBytes: results.reduce(
|
|
416
|
+
(sum, { outcome }) => sum + ("size" in outcome ? outcome.size : 0),
|
|
417
|
+
0,
|
|
418
|
+
),
|
|
364
419
|
orphanUploads: isPlainRecord(orphans) ? Number(orphans["count"]) : 0,
|
|
365
|
-
|
|
420
|
+
verified: results.length - failures.length,
|
|
421
|
+
failed: failures.length,
|
|
422
|
+
failures,
|
|
423
|
+
digests: results.map(({ digest }) => digest),
|
|
366
424
|
};
|
|
367
425
|
} finally {
|
|
368
426
|
database.close(false);
|
|
369
427
|
}
|
|
370
428
|
}
|
|
371
429
|
|
|
430
|
+
/** The counts and failures the deploy log shows, as the capture prints them. */
|
|
431
|
+
function reportAssetVerification(
|
|
432
|
+
report: AssetSnapshotReport,
|
|
433
|
+
output: PredeployCaptureOutput,
|
|
434
|
+
): void {
|
|
435
|
+
output.stdout(`ASSETS_REFERENCED=${report.assets}`);
|
|
436
|
+
output.stdout(`ASSETS_VERIFIED=${report.verified}`);
|
|
437
|
+
output.stdout(`ASSETS_FAILED=${report.failed}`);
|
|
438
|
+
report.failures.forEach(({ digest, entities, reason }) =>
|
|
439
|
+
output.stderr(
|
|
440
|
+
`${ASSET_FAILURE_PREFIX}${digest} (${entities.join(", ")}): ${reason}`,
|
|
441
|
+
),
|
|
442
|
+
);
|
|
443
|
+
}
|
|
444
|
+
|
|
372
445
|
function vectorDigest(path: string): {
|
|
373
446
|
counts: Record<string, number>;
|
|
374
447
|
sha256: string;
|
|
@@ -383,6 +456,7 @@ function vectorDigest(path: string): {
|
|
|
383
456
|
|
|
384
457
|
async function captureDatabases(
|
|
385
458
|
config: PredeployCaptureConfig,
|
|
459
|
+
output: PredeployCaptureOutput,
|
|
386
460
|
): Promise<DatabaseCaptureRecord[]> {
|
|
387
461
|
const captures: DatabaseCaptureRecord[] = [];
|
|
388
462
|
|
|
@@ -437,13 +511,19 @@ async function captureDatabases(
|
|
|
437
511
|
}
|
|
438
512
|
|
|
439
513
|
const assetReport = source.assets
|
|
440
|
-
? verifySnapshotAssets(destination
|
|
514
|
+
? verifySnapshotAssets(destination)
|
|
441
515
|
: undefined;
|
|
442
516
|
if (assetReport) {
|
|
443
517
|
await Bun.write(
|
|
444
518
|
`${config.backupDir}/${source.name}.asset-verify.json`,
|
|
445
519
|
`${JSON.stringify(assetReport, null, 2)}\n`,
|
|
446
520
|
);
|
|
521
|
+
reportAssetVerification(assetReport, output);
|
|
522
|
+
if (assetReport.failed > 0) {
|
|
523
|
+
throw new Error(
|
|
524
|
+
`${source.name}: asset verification failed: ${assetReport.failed} of ${assetReport.assets} referenced assets`,
|
|
525
|
+
);
|
|
526
|
+
}
|
|
447
527
|
}
|
|
448
528
|
|
|
449
529
|
const file = Bun.file(destination);
|
|
@@ -464,6 +544,8 @@ async function captureDatabases(
|
|
|
464
544
|
assets: assetReport.assets,
|
|
465
545
|
totalBytes: assetReport.totalBytes,
|
|
466
546
|
orphanUploads: assetReport.orphanUploads,
|
|
547
|
+
verified: assetReport.verified,
|
|
548
|
+
failed: assetReport.failed,
|
|
467
549
|
},
|
|
468
550
|
}),
|
|
469
551
|
});
|
|
@@ -629,8 +711,9 @@ async function captureGitCheckout(
|
|
|
629
711
|
|
|
630
712
|
export async function capturePredeployBackup(
|
|
631
713
|
config: PredeployCaptureConfig,
|
|
714
|
+
output: PredeployCaptureOutput = consoleOutput,
|
|
632
715
|
): Promise<void> {
|
|
633
|
-
const databases = await captureDatabases(config);
|
|
716
|
+
const databases = await captureDatabases(config, output);
|
|
634
717
|
const git = await captureGitCheckout(config.contentRoot, config.backupDir);
|
|
635
718
|
const manifest = {
|
|
636
719
|
schemaVersion: 1,
|
|
@@ -757,6 +840,60 @@ if (health.operationalStatus !== "operational") {
|
|
|
757
840
|
|
|
758
841
|
/** The runtime's own notices from a successful capture, as workflow warnings;
|
|
759
842
|
* other remote output (ssh host notes) stays out of the log. */
|
|
843
|
+
/** The asset counts the capture printed, when it printed them. */
|
|
844
|
+
function parseAssetSummary(output: string): PredeployAssetSummary | undefined {
|
|
845
|
+
const count = (name: string): number | undefined => {
|
|
846
|
+
const match = new RegExp(`^${name}=(\\d+)$`, "m").exec(output);
|
|
847
|
+
return match?.[1] === undefined ? undefined : Number(match[1]);
|
|
848
|
+
};
|
|
849
|
+
const referenced = count("ASSETS_REFERENCED");
|
|
850
|
+
const verified = count("ASSETS_VERIFIED");
|
|
851
|
+
const failed = count("ASSETS_FAILED");
|
|
852
|
+
return referenced === undefined ||
|
|
853
|
+
verified === undefined ||
|
|
854
|
+
failed === undefined
|
|
855
|
+
? undefined
|
|
856
|
+
: { referenced, verified, failed };
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
function assetSummaryLine(assets: PredeployAssetSummary): string {
|
|
860
|
+
return `pre-deploy snapshot assets: ${assets.referenced} referenced, ${assets.verified} verified, ${assets.failed} failed`;
|
|
861
|
+
}
|
|
862
|
+
|
|
863
|
+
/** What the deploy log shows for a backup that completed. */
|
|
864
|
+
export function predeployBackupLogLines(
|
|
865
|
+
result: PredeployBackupResult,
|
|
866
|
+
): string[] {
|
|
867
|
+
if (!result.applicable) {
|
|
868
|
+
return ["pre-deploy snapshot: not applicable (new server)"];
|
|
869
|
+
}
|
|
870
|
+
return [
|
|
871
|
+
`pre-deploy snapshot verified: ${result.snapshotId}`,
|
|
872
|
+
...(result.assets ? [assetSummaryLine(result.assets)] : []),
|
|
873
|
+
];
|
|
874
|
+
}
|
|
875
|
+
|
|
876
|
+
/**
|
|
877
|
+
* What the deploy log shows for a backup that failed: the asset counts the
|
|
878
|
+
* capture reached, and each failed asset with the entities referencing it.
|
|
879
|
+
*/
|
|
880
|
+
export function predeployBackupFailureLines(
|
|
881
|
+
stdout: string,
|
|
882
|
+
stderr: string,
|
|
883
|
+
): string[] {
|
|
884
|
+
const assets = parseAssetSummary(stdout);
|
|
885
|
+
return [
|
|
886
|
+
...(assets ? [assetSummaryLine(assets)] : []),
|
|
887
|
+
...stderr
|
|
888
|
+
.split("\n")
|
|
889
|
+
.filter((line) => line.startsWith(ASSET_FAILURE_PREFIX))
|
|
890
|
+
.map(
|
|
891
|
+
(line) =>
|
|
892
|
+
`::error title=Pre-deploy backup::${line.slice("pre-deploy snapshot: ".length).trim()}`,
|
|
893
|
+
),
|
|
894
|
+
];
|
|
895
|
+
}
|
|
896
|
+
|
|
760
897
|
export function predeployBackupNotices(stderr: string): string[] {
|
|
761
898
|
const prefix = "pre-deploy snapshot: ";
|
|
762
899
|
return stderr
|
|
@@ -979,6 +1116,7 @@ export function parsePredeployBackupOutput(
|
|
|
979
1116
|
) {
|
|
980
1117
|
throw new Error("Incomplete predeploy backup result");
|
|
981
1118
|
}
|
|
1119
|
+
const assets = parseAssetSummary(output);
|
|
982
1120
|
return {
|
|
983
1121
|
applicable: true,
|
|
984
1122
|
snapshotId,
|
|
@@ -988,6 +1126,7 @@ export function parsePredeployBackupOutput(
|
|
|
988
1126
|
totalBytes,
|
|
989
1127
|
durationSeconds,
|
|
990
1128
|
verification: "passed",
|
|
1129
|
+
...(assets && { assets }),
|
|
991
1130
|
};
|
|
992
1131
|
}
|
|
993
1132
|
|
|
@@ -1006,7 +1145,7 @@ function appendWorkflowResult(result: PredeployBackupResult): void {
|
|
|
1006
1145
|
appendFileSync(
|
|
1007
1146
|
summaryPath,
|
|
1008
1147
|
result.applicable
|
|
1009
|
-
? `### Verified pre-deploy snapshot\n- Snapshot: \`${result.snapshotId}\`\n- Path: \`${result.backupPath}\`\n- Bytes: \`${result.totalBytes}\`\n- Duration: \`${result.durationSeconds}s\`\n- Verification: passed\n`
|
|
1148
|
+
? `### Verified pre-deploy snapshot\n- Snapshot: \`${result.snapshotId}\`\n- Path: \`${result.backupPath}\`\n- Bytes: \`${result.totalBytes}\`\n- Duration: \`${result.durationSeconds}s\`\n- Verification: passed\n${result.assets ? `- Assets: ${result.assets.referenced} referenced, ${result.assets.verified} verified, ${result.assets.failed} failed\n` : ""}`
|
|
1010
1149
|
: "### Pre-deploy snapshot\nNot applicable: new server with no persistent state.\n",
|
|
1011
1150
|
);
|
|
1012
1151
|
}
|
|
@@ -1063,6 +1202,9 @@ export async function runPredeployBackup(): Promise<PredeployBackupResult> {
|
|
|
1063
1202
|
new Response(child.stderr).text(),
|
|
1064
1203
|
]);
|
|
1065
1204
|
if (exitCode !== 0) {
|
|
1205
|
+
for (const line of predeployBackupFailureLines(stdout, stderr)) {
|
|
1206
|
+
console.log(line);
|
|
1207
|
+
}
|
|
1066
1208
|
const diagnostic = stderr.trim().slice(0, 1000);
|
|
1067
1209
|
throw new Error(
|
|
1068
1210
|
`Predeploy backup failed${diagnostic ? `: ${diagnostic}` : ""}`,
|
|
@@ -1071,11 +1213,7 @@ export async function runPredeployBackup(): Promise<PredeployBackupResult> {
|
|
|
1071
1213
|
for (const notice of predeployBackupNotices(stderr)) console.log(notice);
|
|
1072
1214
|
const result = parsePredeployBackupOutput(stdout);
|
|
1073
1215
|
appendWorkflowResult(result);
|
|
1074
|
-
console.log(
|
|
1075
|
-
result.applicable
|
|
1076
|
-
? `pre-deploy snapshot verified: ${result.snapshotId}`
|
|
1077
|
-
: "pre-deploy snapshot: not applicable (new server)",
|
|
1078
|
-
);
|
|
1216
|
+
for (const line of predeployBackupLogLines(result)) console.log(line);
|
|
1079
1217
|
return result;
|
|
1080
1218
|
}
|
|
1081
1219
|
|