@north-light/cli 0.3.757 → 0.3.758

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.
Files changed (30) hide show
  1. package/dist/api/contract.d.ts +1 -1
  2. package/dist/api/contract.js +1 -1
  3. package/dist/commands/sys/import/move.d.ts +5 -0
  4. package/dist/commands/sys/import/move.js +7 -7
  5. package/dist/commands/sys/import/retry.d.ts +1 -0
  6. package/dist/commands/sys/import/retry.js +1 -0
  7. package/dist/commands/sys/import/start.js +1 -1
  8. package/dist/core/import/export/cloud.d.ts +1 -0
  9. package/dist/core/import/export/cloud.js +1 -1
  10. package/dist/core/import/load/bind.d.ts +5 -4
  11. package/dist/core/import/load/bind.js +16 -16
  12. package/dist/core/import/load/blobs.d.ts +6 -0
  13. package/dist/core/import/load/blobs.js +1 -1
  14. package/dist/core/import/load/prepare.js +8 -8
  15. package/dist/core/import/load/run.js +1 -1
  16. package/dist/daemon/api/handlers/imports.js +1 -1
  17. package/dist/daemon/api/operations.js +1 -1
  18. package/dist/daemon/reconcilers/storage-maintenance.js +1 -1
  19. package/package.json +3 -3
  20. package/packages/crouter-api/dist/api/contract.js +1 -1
  21. package/packages/crouter-api/dist/commands/sys/import/move.js +1 -1
  22. package/packages/crouter-api/dist/commands/sys/import/retry.js +38 -0
  23. package/packages/crouter-api/dist/commands/sys/import/start.js +2 -1
  24. package/packages/crouter-api/dist/core/import/export/cloud.js +1 -0
  25. package/packages/crouter-api/dist/core/import/load/prepare.js +2 -2
  26. package/packages/crouter-api/dist/daemon/api/operations.js +1 -0
  27. package/packages/crouter-api/package.json +1 -1
  28. package/packages/crouter-identity/package.json +1 -1
  29. package/packages/crouter-plugin/package.json +3 -3
  30. package/runtime.lock.json +14 -14
@@ -1,5 +1,5 @@
1
1
  /** The contract level this build serves and requires. Written by `scripts/contract.mjs release`; never edit by hand. */
2
- export declare const CONTRACT_LEVEL = "1.78";
2
+ export declare const CONTRACT_LEVEL = "1.79";
3
3
  /** Request header naming the one contract level the caller needs, e.g. `1.3`. Optional: absent means no check. */
4
4
  export declare const REQUIRED_CONTRACT_HEADER = "Crouter-Required-Contract";
5
5
  /** Response header listing the contract levels the server serves, comma-separated, one per major, e.g. `1.3`. */
@@ -1 +1 @@
1
- var c=Object.defineProperty;var e=(r,t)=>c(r,"name",{value:t,configurable:!0});const f="1.78",i="Crouter-Required-Contract",p="Crouter-Contract";function l(r){const t=/^(\d+)\.(\d+)$/.exec(r.trim());return t===null?null:{major:Number(t[1]),minor:Number(t[2])}}e(l,"parseContractLevel");function a(r){return r==null?[]:r.split(",").map(t=>l(t)).filter(t=>t!==null)}e(a,"parseServedContracts");function s(r,t){const n=l(r);return n===null?!1:(typeof t=="string"||t===null||t===void 0?a(t):t).some(u=>u.major===n.major&&u.minor>=n.minor)}e(s,"contractSatisfies");function C(r,t,n={}){if(r===void 0)return null;if(l(r)===null)return{status:400,code:"invalid_request",param:i,message:`${i} must be a contract level like 1.0.`};if(s(r,t))return null;const o=r.trim();return{status:426,code:"runtime_version_unsupported",message:t===null||a(t).length===0?`The runtime did not name its contract level; the caller requires contract ${o} or later. Roll the runtime forward.`:`The runtime serves contract ${t}; the caller requires contract ${o} or later within the same major. Roll the runtime forward, or pin an SDK whose crouterContract the runtime serves.`,details:{sdk_version:(n.legacyMinimum??"").trim(),runtime_version:n.runtimeVersion??null,required_contract:o,runtime_contract:t}}}e(C,"contractRefusal");export{p as CONTRACT_HEADER,f as CONTRACT_LEVEL,i as REQUIRED_CONTRACT_HEADER,C as contractRefusal,s as contractSatisfies,l as parseContractLevel,a as parseServedContracts};
1
+ var c=Object.defineProperty;var e=(r,t)=>c(r,"name",{value:t,configurable:!0});const f="1.79",i="Crouter-Required-Contract",p="Crouter-Contract";function l(r){const t=/^(\d+)\.(\d+)$/.exec(r.trim());return t===null?null:{major:Number(t[1]),minor:Number(t[2])}}e(l,"parseContractLevel");function a(r){return r==null?[]:r.split(",").map(t=>l(t)).filter(t=>t!==null)}e(a,"parseServedContracts");function s(r,t){const n=l(r);return n===null?!1:(typeof t=="string"||t===null||t===void 0?a(t):t).some(u=>u.major===n.major&&u.minor>=n.minor)}e(s,"contractSatisfies");function C(r,t,n={}){if(r===void 0)return null;if(l(r)===null)return{status:400,code:"invalid_request",param:i,message:`${i} must be a contract level like 1.0.`};if(s(r,t))return null;const o=r.trim();return{status:426,code:"runtime_version_unsupported",message:t===null||a(t).length===0?`The runtime did not name its contract level; the caller requires contract ${o} or later. Roll the runtime forward.`:`The runtime serves contract ${t}; the caller requires contract ${o} or later within the same major. Roll the runtime forward, or pin an SDK whose crouterContract the runtime serves.`,details:{sdk_version:(n.legacyMinimum??"").trim(),runtime_version:n.runtimeVersion??null,required_contract:o,runtime_contract:t}}}e(C,"contractRefusal");export{p as CONTRACT_HEADER,f as CONTRACT_LEVEL,i as REQUIRED_CONTRACT_HEADER,C as contractRefusal,s as contractSatisfies,l as parseContractLevel,a as parseServedContracts};
@@ -15,6 +15,11 @@ export declare function endDrainConfirmed(client: {
15
15
  export declare function settleDrainAtEnd(done: boolean, client: {
16
16
  endDaemonDrain(): Promise<unknown>;
17
17
  }): Promise<void>;
18
+ /** After `load` was sent the run's outcome is unknown until the control plane says it: wait for `done`, throw on `failed` / `rolled_back`, and keep asking
19
+ * while the control plane cannot be reached or answers an error (a lost answer must never read as a failure: the account may hold the records). Only a
20
+ * sign-in that no longer works, or an answer the control plane will repeat, ends the wait with `move_outcome_unknown`, because asking can never succeed again. A `load` that threw while the run
21
+ * never left `uploading` did not start, so its error stands. */
22
+ export declare function awaitRunOutcome(cloud: ImportCloud, runId: string, loadError: unknown): Promise<void>;
18
23
  export interface ExportStep {
19
24
  name: string;
20
25
  timings: string[];
@@ -1,10 +1,10 @@
1
- var W=Object.defineProperty;var d=(e,t)=>W(e,"name",{value:t,configurable:!0});import{mkdtempSync as X,readFileSync as L,readdirSync as T,rmSync as Q}from"node:fs";import{tmpdir as Z}from"node:os";import{join as g}from"node:path";import{CrtrError as s,general as tt}from"../../../core/errors.js";import{ExitCode as h}from"../../../types.js";import{cliClient as x}from"../../api-client.js";import{ImportCloud as A,STORE_FILE as et,STORE_ORDER as rt}from"../../../core/import/export/cloud.js";import{Uploader as nt,localObjects as F,reviewSourceObject as ot}from"../../../core/import/export/files.js";import{BODIES_TABLE as P,bundleKeys as M}from"../../../core/import/bundle/layout.js";import{crtrVersion as it}from"../../../shared/crtr-version.js";import{nodeArchive as at}from"../../../core/import/export/archive.js";import{buildSourceJson as st}from"../../../core/import/export/source.js";import{runDaemonBodiesDump as ct,runDaemonImportDump as dt,runDaemonInstallId as lt,spawnDaemon as ut,stopAllDaemons as ft}from"../../../daemon/manage.js";import{deleteMoveRecord as U,moveUnfinishedError as mt,readMachineConfig as wt,readMoveRecord as D,writeMachineConfig as pt,writeMachineCredential as ht,writeMoveRecord as b}from"../../../daemon/machine-link/config.js";import{notifyMoveFinished as gt}from"../../../daemon/machine-link/move-notify.js";import{registerSignedInMac as yt}from"../../../core/directory/join.js";import{controlPlaneUrl as _t,forgetSignIn as Et,personAccount as B,personBearer as I,readPersonCredential as $t,signIn as St,signOut as vt}from"../../../core/directory/person-credential.js";import{NORTHLIGHT_DIRECTORY_URL as Ut}from"../../../core/directory/issuer.js";import{isPidAlive as j}from"../../../core/canvas/pid.js";const y=d(e=>new Promise(t=>setTimeout(t,e)),"sleep");function ee(){return wt()?.directoryUrl??$t()?.directoryUrl??Ut}d(ee,"defaultDirectoryUrl");async function J(e){let t="the daemon still reports a drain";for(let r=1;r<=3;r++){try{if((await e.endDaemonDrain()).drained===!1)return}catch(n){t=n instanceof Error?n.message:String(n)}r<3&&await y(1e3)}throw new s("drain_not_ended",`the local daemon's pause could not be confirmed ended: ${t}`,h.GENERAL,{next:"Run `crtr sys import resume`."})}d(J,"endDrainConfirmed");async function It(e,t){e||await J(t)}d(It,"settleDrainAtEnd");const Nt=3e4;async function Rt(e,t,r){let n=2e3;for(;;){let i;try{i=await e.get(t)}catch(c){const l=c instanceof s?c.details?.status:void 0;if(c instanceof s&&(c.code==="not_signed_in"||typeof l=="number"&&l<500&&l!==408&&l!==429))throw new s("move_outcome_unknown",`could not confirm whether Northlight finished loading this computer's records: ${c.message}`,h.GENERAL,{next:"Run `crtr sys signin` to settle the move."});process.stderr.write(`waiting for Northlight: ${c instanceof Error?c.message:String(c)}
2
- `),await y(n),n=Math.min(n*2,Nt);continue}if(n=2e3,i.state==="done")return;if(i.state==="failed"||i.state==="rolled_back")throw tt(`the import failed at ${i.failure?.step??i.step??"an unknown step"}: ${i.failure?.message??i.state}`,{code:i.failure?.code??"import_failed"});if(i.state==="uploading"&&r!==void 0)throw r;await y(2e3)}}d(Rt,"awaitRunOutcome");async function Tt(e,t,r,n,i=()=>{},c=()=>{}){let l=Date.now();const o=d((f,m)=>{const p=Date.now(),v=`${f}=${((p-l)/1e3).toFixed(1)}s`;n.timings.push(v),process.stderr.write(`${f} ${((p-l)/1e3).toFixed(1)}s
3
- `),l=p,n.name=m},"next"),u=X(g(Z(),"crtr-import-")),S=x({local:!0});let _=!1,N=!1,E=!1,$;try{n.name="start";const{installId:f}=await lt(),m=r===void 0?await t.start({source_install_id:f,source_kind:e,release:it()}):{run_id:r};i(m.run_id),n.name="blobs";const p=new nt(t,m.run_id,a=>process.stderr.write(`${a}
4
- `));await p.upload(F()),await ct(u);const v=new Set,O=d(async(a,w)=>{await p.uploadBytes(M.rowPart(m.run_id,a,w.replace(/\.jsonl\.zst$/,"")),L(g(u,"rows",a,w))),v.add(`${a}/${w}`)},"uploadPart");for(const a of T(g(u,"rows",P)))await O(P,a);o("blobs","drain"),_=!0,await S.drainDaemon({settle_limit_ms:6e5}),o("drain","dump"),await p.upload(F());const R=await dt(u,e),k=[];for(const a of R.requests){const w=ot(a.id,a.dir,a.file);w!==null&&k.push(w)}await p.upload(k),o("dump","upload");for(const a of T(g(u,"rows")))for(const w of T(g(u,"rows",a)))v.has(`${a}/${w}`)||await O(a,w);const C=[];if(e==="hosted")for(const a of R.runningNodes){const{data:w,prefixes:K}=await at(a);C.push(...K),await p.uploadBytes(M.nodeFiles(m.run_id,a.node),w)}await p.uploadBytes(M.source(m.run_id),Buffer.from(JSON.stringify(st(R.source,C))));const z=JSON.parse(L(g(u,et),"utf8"));for(const a of rt)await t.putStore(m.run_id,a,z[a]);o("upload","load"),E=!0;let G;try{await t.load(m.run_id)}catch(a){G=a}try{await Rt(t,m.run_id,G)}catch(a){throw a instanceof s&&a.code==="move_outcome_unknown"||(E=!1),a}return E=!1,N=!0,o("load","restart"),m.run_id}catch(f){throw $=f,f}finally{if(Q(u,{recursive:!0,force:!0}),!N&&!E&&c(),_&&!E)try{await It(N,S)}catch(f){if($===void 0)throw f;const m=f instanceof s?f.code:"drain_not_ended";throw new s(m,`${$ instanceof Error?$.message:String($)} (and ${f instanceof Error?f.message:String(f)})`,h.GENERAL,{next:"Run `crtr sys import resume`."})}}}d(Tt,"exportRun");async function xt(e){await gt(e);const t=new A(e.apiUrl,()=>I(e.directoryUrl));let r;try{r=await t.machineCredential(e.runId)}catch(n){if(!(n instanceof s)||n.details?.code!=="credential_exists")throw n;r=await t.machineCredential(e.runId,!0)}ht(r.credential),pt({apiUrl:e.apiUrl,environmentId:r.environment_id,runId:e.runId,directoryUrl:e.directoryUrl,account:e.account}),await At(e.directoryUrl),await ft(),await ut(),U()}d(xt,"finishMove");async function At(e){try{await yt(e,await I(e))}catch(t){process.stderr.write(`this computer was not registered with the directory: ${t instanceof Error?t.message:String(t)}
1
+ var W=Object.defineProperty;var d=(e,t)=>W(e,"name",{value:t,configurable:!0});import{mkdtempSync as X,readFileSync as L,readdirSync as R,rmSync as Q}from"node:fs";import{tmpdir as Z}from"node:os";import{join as g}from"node:path";import{CrtrError as s,general as tt}from"../../../core/errors.js";import{ExitCode as h}from"../../../types.js";import{cliClient as T}from"../../api-client.js";import{ImportCloud as A,STORE_FILE as et,STORE_ORDER as rt}from"../../../core/import/export/cloud.js";import{Uploader as nt,localObjects as F,reviewSourceObject as ot}from"../../../core/import/export/files.js";import{BODIES_TABLE as P,bundleKeys as M}from"../../../core/import/bundle/layout.js";import{crtrVersion as it}from"../../../shared/crtr-version.js";import{nodeArchive as at}from"../../../core/import/export/archive.js";import{buildSourceJson as st}from"../../../core/import/export/source.js";import{runDaemonBodiesDump as ct,runDaemonImportDump as dt,runDaemonInstallId as lt,spawnDaemon as ut,stopAllDaemons as ft}from"../../../daemon/manage.js";import{deleteMoveRecord as U,moveUnfinishedError as mt,readMachineConfig as wt,readMoveRecord as D,writeMachineConfig as pt,writeMachineCredential as ht,writeMoveRecord as b}from"../../../daemon/machine-link/config.js";import{notifyMoveFinished as gt}from"../../../daemon/machine-link/move-notify.js";import{registerSignedInMac as yt}from"../../../core/directory/join.js";import{controlPlaneUrl as _t,forgetSignIn as Et,personAccount as B,personBearer as I,readPersonCredential as $t,signIn as St,signOut as vt}from"../../../core/directory/person-credential.js";import{NORTHLIGHT_DIRECTORY_URL as Ut}from"../../../core/directory/issuer.js";import{isPidAlive as j}from"../../../core/canvas/pid.js";const y=d(e=>new Promise(t=>setTimeout(t,e)),"sleep");function ee(){return wt()?.directoryUrl??$t()?.directoryUrl??Ut}d(ee,"defaultDirectoryUrl");async function J(e){let t="the daemon still reports a drain";for(let r=1;r<=3;r++){try{if((await e.endDaemonDrain()).drained===!1)return}catch(n){t=n instanceof Error?n.message:String(n)}r<3&&await y(1e3)}throw new s("drain_not_ended",`the local daemon's pause could not be confirmed ended: ${t}`,h.GENERAL,{next:"Run `crtr sys import resume`."})}d(J,"endDrainConfirmed");async function It(e,t){e||await J(t)}d(It,"settleDrainAtEnd");const xt=3e4;async function Nt(e,t,r){let n=2e3;for(;;){let i;try{i=await e.get(t)}catch(c){const l=c instanceof s?c.details?.status:void 0;if(c instanceof s&&(c.code==="not_signed_in"||typeof l=="number"&&l<500&&l!==408&&l!==429))throw new s("move_outcome_unknown",`could not confirm whether Northlight finished loading this computer's records: ${c.message}`,h.GENERAL,{next:"Run `crtr sys signin` to settle the move."});process.stderr.write(`waiting for Northlight: ${c instanceof Error?c.message:String(c)}
2
+ `),await y(n),n=Math.min(n*2,xt);continue}if(n=2e3,i.state==="done")return;if(i.state==="failed"||i.state==="rolled_back")throw tt(`the import failed at ${i.failure?.step??i.step??"an unknown step"}: ${i.failure?.message??i.state}`,{code:i.failure?.code??"import_failed"});if(i.state==="uploading"&&r!==void 0)throw r;await y(2e3)}}d(Nt,"awaitRunOutcome");async function Rt(e,t,r,n,i=()=>{},c=()=>{}){let l=Date.now();const o=d((f,m)=>{const p=Date.now(),v=`${f}=${((p-l)/1e3).toFixed(1)}s`;n.timings.push(v),process.stderr.write(`${f} ${((p-l)/1e3).toFixed(1)}s
3
+ `),l=p,n.name=m},"next"),u=X(g(Z(),"crtr-import-")),S=T({local:!0});let _=!1,x=!1,E=!1,$;try{n.name="start";const{installId:f}=await lt(),m=r===void 0?await t.start({source_install_id:f,source_kind:e,release:it()}):{run_id:r};i(m.run_id),n.name="blobs";const p=new nt(t,m.run_id,a=>process.stderr.write(`${a}
4
+ `));await p.upload(F()),await ct(u);const v=new Set,O=d(async(a,w)=>{await p.uploadBytes(M.rowPart(m.run_id,a,w.replace(/\.jsonl\.zst$/,"")),L(g(u,"rows",a,w))),v.add(`${a}/${w}`)},"uploadPart");for(const a of R(g(u,"rows",P)))await O(P,a);o("blobs","drain"),_=!0,await S.drainDaemon({settle_limit_ms:6e5}),o("drain","dump"),await p.upload(F());const N=await dt(u,e),k=[];for(const a of N.requests){const w=ot(a.id,a.dir,a.file);w!==null&&k.push(w)}await p.upload(k),o("dump","upload");for(const a of R(g(u,"rows")))for(const w of R(g(u,"rows",a)))v.has(`${a}/${w}`)||await O(a,w);const C=[];if(e==="hosted")for(const a of N.runningNodes){const{data:w,prefixes:K}=await at(a);C.push(...K),await p.uploadBytes(M.nodeFiles(m.run_id,a.node),w)}await p.uploadBytes(M.source(m.run_id),Buffer.from(JSON.stringify(st(N.source,C))));const z=JSON.parse(L(g(u,et),"utf8"));for(const a of rt)await t.putStore(m.run_id,a,z[a]);o("upload","load"),E=!0;let G;try{await t.load(m.run_id)}catch(a){G=a}try{await Nt(t,m.run_id,G)}catch(a){throw a instanceof s&&a.code==="move_outcome_unknown"||(E=!1),a}return E=!1,x=!0,o("load","restart"),m.run_id}catch(f){throw $=f,f}finally{if(Q(u,{recursive:!0,force:!0}),!x&&!E&&c(),_&&!E)try{await It(x,S)}catch(f){if($===void 0)throw f;const m=f instanceof s?f.code:"drain_not_ended";throw new s(m,`${$ instanceof Error?$.message:String($)} (and ${f instanceof Error?f.message:String(f)})`,h.GENERAL,{next:"Run `crtr sys import resume`."})}}}d(Rt,"exportRun");async function Tt(e){await gt(e);const t=new A(e.apiUrl,()=>I(e.directoryUrl));let r;try{r=await t.machineCredential(e.runId)}catch(n){if(!(n instanceof s)||n.details?.code!=="credential_exists")throw n;r=await t.machineCredential(e.runId,!0)}ht(r.credential),pt({apiUrl:e.apiUrl,environmentId:r.environment_id,runId:e.runId,directoryUrl:e.directoryUrl,account:e.account}),await At(e.directoryUrl),await ft(),await ut(),U()}d(Tt,"finishMove");async function At(e){try{await yt(e,await I(e))}catch(t){process.stderr.write(`this computer was not registered with the directory: ${t instanceof Error?t.message:String(t)}
5
5
  Run \`crtr sys signin\` again to register it.
6
- `)}}d(At,"registerThisMac");const V=3,Mt=3e4;async function re(e){const t={name:"sign-in",timings:[]};let r,n="",i;try{const o=await B(e.directoryUrl),u=e.apiUrl??await _t(e.directoryUrl),S=new A(u,()=>I(e.directoryUrl));i={apiUrl:u,directoryUrl:e.directoryUrl,account:o,notify:e.notify,notified:!1,pid:process.pid},await Tt("machine",S,void 0,t,_=>{n=_,b({...i,runId:_,state:"running"})},U)}catch(o){throw o instanceof s&&o.code==="move_outcome_unknown"?o:await H(t.name,o,e.notify)}r={...i,runId:n,state:"committed"},b(r);let c;const l=Date.now();for(let o=1;o<=V;o++)try{return await xt(r),t.timings.push(`restart=${((Date.now()-l)/1e3).toFixed(1)}s`),process.stderr.write(`restart ${((Date.now()-l)/1e3).toFixed(1)}s
6
+ `)}}d(At,"registerThisMac");const V=3,Mt=3e4;async function re(e){const t={name:"sign-in",timings:[]};let r,n="",i;try{const o=await B(e.directoryUrl),u=e.apiUrl??await _t(e.directoryUrl),S=new A(u,()=>I(e.directoryUrl));i={apiUrl:u,directoryUrl:e.directoryUrl,account:o,notify:e.notify,notified:!1,pid:process.pid},await Rt("machine",S,void 0,t,_=>{n=_,b({...i,runId:_,state:"running"})},U)}catch(o){throw o instanceof s&&o.code==="move_outcome_unknown"?o:await H(t.name,o,e.notify)}r={...i,runId:n,state:"committed"},b(r);let c;const l=Date.now();for(let o=1;o<=V;o++)try{return await Tt(r),t.timings.push(`restart=${((Date.now()-l)/1e3).toFixed(1)}s`),process.stderr.write(`restart ${((Date.now()-l)/1e3).toFixed(1)}s
7
7
  `),{runId:r.runId,account:r.account.display,timings:t.timings.join(" ")}}catch(u){c=u,process.stderr.write(`switch-over attempt ${o} failed: ${u instanceof Error?u.message:String(u)}
8
8
  `),o<V&&await y(Mt),r=D()??r}throw mt(c instanceof Error?c.message:String(c))}d(re,"runMove");async function H(e,t,r){const n=t instanceof Error?t.message:String(t),i=t instanceof s&&t.code==="drain_not_ended"?"crtr is still local, but its pause could not be ended: run `crtr sys import resume`":"crtr is still local and working as before",c=`The move to Northlight failed at ${e}: ${n}. ${i}.`,l=await q(c,r),o=t instanceof s&&t.code!=="error"?t.code:t instanceof s&&typeof t.details?.code=="string"?t.details.code:"move_failed";return new s(o,`the move to Northlight failed at ${e}: ${n}. ${i}, and ${Y(l)}`,h.GENERAL)}d(H,"undoMove");const Y=d(e=>e===void 0?"this computer is signed out.":`this computer's sign-in was removed here but could not be revoked at Northlight (${e}); revoke it on your Northlight account page.`,"signedOutText");async function q(e,t){U();let r;try{await vt()}catch(n){Et(),r=n instanceof Error?n.message:String(n),process.stderr.write(`could not revoke the sign-in at Northlight: ${r}
9
- `)}if(t===null)return r;try{await x({local:!0}).sendMessage(t,{from:null,body:`${e} Tell the person the move failed.${r===void 0?"":` ${Y(r)}`}`})}catch(n){process.stderr.write(`could not message ${t}: ${n instanceof Error?n.message:String(n)}
10
- `)}return r}d(q,"dropMove");async function Dt(e){const t=D();if(t===void 0||t.state==="activated")return;const r=d(async()=>{await St(t.directoryUrl,e,{accept:d(async o=>o.account.id===t.account.id?void 0:new s("signin_other_account",`This computer's move belongs to the Northlight account ${t.account.display}. Sign in to that account.`,h.USAGE),"accept")})},"signBackIn");if(t.state==="committed"){if(e!==void 0)try{await B(t.directoryUrl)}catch(o){if(!(o instanceof s&&o.code==="not_signed_in"))throw o;await r()}return t}if(t.pid>0&&j(t.pid))throw new s("move_running",`a move to Northlight is already running (process ${t.pid}).`,h.USAGE,{next:"Wait for it to finish; the node that asked is messaged when it does."});const n=d(()=>new A(t.apiUrl,()=>I(t.directoryUrl)).get(t.runId),"ask");let i;try{i=await n()}catch(o){if(!(o instanceof s&&o.code==="not_signed_in")||e===void 0)throw o;await r(),i=await n()}if(i.state==="done"){const o={...t,state:"committed"};return b(o),o}if(i.state==="loading"||i.state==="committed")throw new s("move_running","Northlight is still loading this computer's records from an earlier move.",h.USAGE,{next:"Retry in a minute."});if(i.state!=="failed"&&i.state!=="rolled_back"&&i.state!=="uploading")throw new s("move_outcome_unknown","Northlight did not report a settled outcome for this move.",h.GENERAL,{next:"Run `crtr sys signin` to settle the move."});const c=i.failure?.step??"an earlier step",l=i.failure==null?"the process that was moving this computer stopped before Northlight had the records":i.failure.message;U();try{await J(x({local:!0}))}catch(o){throw await H(c,new s("drain_not_ended",`${l} (and ${o instanceof Error?o.message:String(o)})`,h.GENERAL),t.notify)}await q(`The move to Northlight failed at ${c}: ${l}. crtr is still local and working as before.`,t.notify)}d(Dt,"settleEarlierMove");const bt=6e4,Ot=5e3;async function ne(e,t){for(await y(Ot);!e();){const r=D();if(r===void 0||r.state!=="running"||r.pid>0&&j(r.pid))return;try{await Dt();return}catch(n){if(t(n),n instanceof s&&n.code==="not_signed_in")return}await y(bt)}}d(ne,"settleMoveAtDaemonStart");export{ee as defaultDirectoryUrl,J as endDrainConfirmed,Tt as exportRun,xt as finishMove,At as registerThisMac,re as runMove,It as settleDrainAtEnd,Dt as settleEarlierMove,ne as settleMoveAtDaemonStart};
9
+ `)}if(t===null)return r;try{await T({local:!0}).sendMessage(t,{from:null,body:`${e} Tell the person the move failed.${r===void 0?"":` ${Y(r)}`}`})}catch(n){process.stderr.write(`could not message ${t}: ${n instanceof Error?n.message:String(n)}
10
+ `)}return r}d(q,"dropMove");async function Dt(e){const t=D();if(t===void 0||t.state==="activated")return;const r=d(async()=>{await St(t.directoryUrl,e,{accept:d(async o=>o.account.id===t.account.id?void 0:new s("signin_other_account",`This computer's move belongs to the Northlight account ${t.account.display}. Sign in to that account.`,h.USAGE),"accept")})},"signBackIn");if(t.state==="committed"){if(e!==void 0)try{await B(t.directoryUrl)}catch(o){if(!(o instanceof s&&o.code==="not_signed_in"))throw o;await r()}return t}if(t.pid>0&&j(t.pid))throw new s("move_running",`a move to Northlight is already running (process ${t.pid}).`,h.USAGE,{next:"Wait for it to finish; the node that asked is messaged when it does."});const n=d(()=>new A(t.apiUrl,()=>I(t.directoryUrl)).get(t.runId),"ask");let i;try{i=await n()}catch(o){if(!(o instanceof s&&o.code==="not_signed_in")||e===void 0)throw o;await r(),i=await n()}if(i.state==="done"){const o={...t,state:"committed"};return b(o),o}if(i.state==="loading"||i.state==="committed")throw new s("move_running","Northlight is still loading this computer's records from an earlier move.",h.USAGE,{next:"Retry in a minute."});if(i.state!=="failed"&&i.state!=="rolled_back"&&i.state!=="uploading")throw new s("move_outcome_unknown","Northlight did not report a settled outcome for this move.",h.GENERAL,{next:"Run `crtr sys signin` to settle the move."});const c=i.failure?.step??"an earlier step",l=i.failure==null?"the process that was moving this computer stopped before Northlight had the records":i.failure.message;U();try{await J(T({local:!0}))}catch(o){throw await H(c,new s("drain_not_ended",`${l} (and ${o instanceof Error?o.message:String(o)})`,h.GENERAL),t.notify)}await q(`The move to Northlight failed at ${c}: ${l}. crtr is still local and working as before.`,t.notify)}d(Dt,"settleEarlierMove");const bt=6e4,Ot=5e3;async function ne(e,t){for(await y(Ot);!e();){const r=D();if(r===void 0||r.state!=="running"||r.pid>0&&j(r.pid))return;try{await Dt();return}catch(n){if(t(n),n instanceof s&&n.code==="not_signed_in")return}await y(bt)}}d(ne,"settleMoveAtDaemonStart");export{Nt as awaitRunOutcome,ee as defaultDirectoryUrl,J as endDrainConfirmed,Rt as exportRun,Tt as finishMove,At as registerThisMac,re as runMove,It as settleDrainAtEnd,Dt as settleEarlierMove,ne as settleMoveAtDaemonStart};
@@ -0,0 +1 @@
1
+ export declare const retry: import("../../../core/command.js").LeafDef;
@@ -0,0 +1 @@
1
+ var a=Object.defineProperty;var r=(e,t)=>a(e,"name",{value:t,configurable:!0});import{defineLeaf as d}from"../../../core/command.js";import{usage as s}from"../../../core/errors.js";import{ImportCloud as u}from"../../../core/import/export/cloud.js";import{controlPlaneUrl as l,personBearer as p}from"../../../core/directory/person-credential.js";import{awaitRunOutcome as m,defaultDirectoryUrl as f}from"./move.js";const _=d({name:"retry",description:"load a failed import again from the bundle it already uploaded",whenToUse:"an import failed while Northlight was loading it (a refused or conflicting row) and the cause is fixed: no new upload and no new confirm code",help:{name:"sys import retry",summary:"re-queue a failed run so Northlight loads its kept upload again, then wait for the outcome",guide:"Works for a run that failed before its copy committed and whose upload is under 7 days old (Northlight deletes older ones; run the import again then). The bundle is what was uploaded, so rows this computer changed since are not in it. Prints the final state, or the new failure.",params:[{kind:"positional",name:"run_id",type:"string",required:!0,constraint:"The failed import run (`imp_\u2026`)."},{kind:"flag",name:"api-url",type:"string",required:!1,constraint:"Control plane base URL; default is the one the sign-in is for."}],output:[{name:"run_id",type:"string",required:!0,constraint:"The import run."},{name:"state",type:"string",required:!0,constraint:"Final state of the run, `done`."}],outputKind:"object",effects:["Moves the run from `failed` back to `loading` on the control plane; nothing local changes."]},run:r(async e=>{const t=String(e.run_id??"");if(t==="")throw s("name the failed run: crtr sys import retry <run_id>");const n=f(),i=e.apiUrl===void 0?await l(n):String(e.apiUrl),o=new u(i,()=>p(n));return await o.retry(t),await m(o,t,void 0),{run_id:t,state:"done"}},"run"),render:r(e=>`<import run="${e.run_id}" state="${e.state}"/>`,"render")});export{_ as retry};
@@ -1 +1 @@
1
- var g=Object.defineProperty;var i=(e,t)=>g(e,"name",{value:t,configurable:!0});import{defineBranch as w,defineLeaf as y}from"../../../core/command.js";import{general as v,usage as r}from"../../../core/errors.js";import{ImportCloud as k}from"../../../core/import/export/cloud.js";import{ensureSignedIn as p}from"../../../core/directory/person-credential.js";import{isPidAlive as _}from"../../../core/canvas/pid.js";import{showSignIn as d}from"../signin.js";import{insideBroker as R}from"../join.js";import{defaultDirectoryUrl as f,exportRun as T,settleEarlierMove as b,finishMove as I,runMove as O}from"./move.js";import{resume as N}from"./resume.js";const q="CRTR_IMPORT_WAIT_PID";async function U(e){for(;_(e);)await new Promise(t=>setTimeout(t,200))}i(U,"waitForExit");const x=y({name:"start",description:"export this runtime into the person's Northlight account",whenToUse:"moving this computer or hosted runtime's canvas into Northlight: run it from a plain terminal, not from inside a node",help:{name:"sys import start",summary:"upload blobs, pause the daemon, dump rows and file stores, and have the control plane load them",guide:"Order: open the run, upload blobs and request files, drain the daemon (turns in flight settle for up to 10 minutes), upload them again, dump every table and the file stores, upload the rows, request the load and wait for `done` or `failed`, printing each step's time. Before `done`, a failure ends the drain and this runtime carries on as before; a computer's move also signs it out. On `done` the daemon stays drained: a hosted runtime until hosting quiesces it (`crtr sys import resume` ends it), a computer until it has switched over \u2014 machine credential, `runtime/machine.json`, daemon restarted in machine role \u2014 which is retried three times over a minute and otherwise finished by `crtr sys signin`. A machine import signs the person in first when this computer has no stored sign-in. `crtr sys signin` normally starts a computer's move itself. With `--run`, hosting has already opened the run: the exporter uses it and reads that run's import token from the environment variable `CRTR_IMPORT_TOKEN`.",params:[{kind:"flag",name:"kind",type:"enum",choices:["machine","hosted"],required:!0,constraint:"`machine` for a person's computer, `hosted` for a hosted runtime (also archives running nodes' files)."},{kind:"flag",name:"api-url",type:"string",required:!1,constraint:"Control plane base URL (http or https). Required with `--kind hosted`; with `--kind machine` the default is the control plane the person's sign-in is for."},{kind:"flag",name:"run",type:"string",required:!1,constraint:"An import run hosting opened for this runtime (only with `--kind hosted`); its import token is read from `CRTR_IMPORT_TOKEN`."},{kind:"flag",name:"directory-url",type:"string",required:!1,constraint:"Directory base URL (http or https) the person signs in against, with `--kind machine`. Default: the one in `runtime/machine.json`, else the stored sign-in's, else Northlight's."},{kind:"flag",name:"notify",type:"string",required:!1,constraint:"With `--kind machine`: a node id told by message when the move fails or finishes."}],output:[{name:"run_id",type:"string",required:!0,constraint:"The import run."},{name:"state",type:"string",required:!0,constraint:"Final state of the run, `done`."},{name:"timings",type:"string",required:!0,constraint:"Per-step seconds."}],outputKind:"object",effects:["Drains the local daemon (no new wake or cron fire); the drain is a `runtime_state` row, so it survives a daemon restart. Ended on a failure before `done`; kept after `done`.","Machine: writes `runtime/import/move.json` (0600) from the run's start until the switch-over, then deletes it. On `done`: writes `runtime/machine.json` and `runtime/secrets/machine-credential` (0600) and restarts the daemon in machine role. On a failure before `done`: revokes and deletes the stored sign-in.","Machine with `--notify`: sends that node one message when the move fails or finishes.","Opens a temporary directory holding the opened file stores (0600), removed before the command ends."]},run:i(async e=>{const t=e.kind,o=e.run===void 0?void 0:String(e.run),n=e.apiUrl===void 0?void 0:String(e.apiUrl),h=e.notify===void 0?null:String(e.notify);if(t==="hosted"){if(n===void 0)throw r("--kind hosted needs --api-url: the control plane hosting opened the run on");if(h!==null)throw r("--notify names the node that asked for a computer's move: use it only with --kind machine")}else if(o!==void 0)throw r("--run takes an existing run, which only a hosted import has: use --kind hosted");const s=Number(process.env[q]??"");if(Number.isInteger(s)&&s>0&&await U(s),R())throw v("import_inside_node: run this from a plain terminal; a node's broker ends with the daemon restart",{code:"import_inside_node"});if(t==="machine"){const a=await b(d);if(a!==void 0)return await I(a),{run_id:a.runId,state:"done",timings:""};const l=e.directoryUrl===void 0?f():String(e.directoryUrl);await p(l,d);const c=await O({directoryUrl:l,...n===void 0?{}:{apiUrl:n},notify:h});return{run_id:c.runId,state:"done",timings:c.timings}}const m=(o===void 0?await p(f(),d):process.env.CRTR_IMPORT_TOKEN??"").trim();if(m==="")throw r("set CRTR_IMPORT_TOKEN to the run's import token");const u={name:"start",timings:[]};return{run_id:await T("hosted",new k(n,m),o,u),state:"done",timings:u.timings.join(" ")}},"run"),render:i(e=>`<import run="${e.run_id}" state="${e.state}" timings="${e.timings}"/>`,"render")}),W=w({name:"import",description:"move this runtime into the person's Northlight account",whenToUse:"importing this computer or hosted runtime into Northlight",help:{name:"sys import",summary:"export this runtime to Northlight",model:"The exporter pauses the local daemon, uploads a bundle the control plane loads into the shared database, and on a computer switches it to the machine role."},children:[x,N]});export{q as WAIT_FOR_PID_ENV,W as sysImportBranch};
1
+ var g=Object.defineProperty;var i=(e,t)=>g(e,"name",{value:t,configurable:!0});import{defineBranch as w,defineLeaf as y}from"../../../core/command.js";import{general as v,usage as r}from"../../../core/errors.js";import{ImportCloud as k}from"../../../core/import/export/cloud.js";import{ensureSignedIn as p}from"../../../core/directory/person-credential.js";import{isPidAlive as _}from"../../../core/canvas/pid.js";import{showSignIn as d}from"../signin.js";import{insideBroker as R}from"../join.js";import{defaultDirectoryUrl as f,exportRun as T,settleEarlierMove as b,finishMove as I,runMove as O}from"./move.js";import{resume as N}from"./resume.js";import{retry as q}from"./retry.js";const U="CRTR_IMPORT_WAIT_PID";async function x(e){for(;_(e);)await new Promise(t=>setTimeout(t,200))}i(x,"waitForExit");const M=y({name:"start",description:"export this runtime into the person's Northlight account",whenToUse:"moving this computer or hosted runtime's canvas into Northlight: run it from a plain terminal, not from inside a node",help:{name:"sys import start",summary:"upload blobs, pause the daemon, dump rows and file stores, and have the control plane load them",guide:"Order: open the run, upload blobs and request files, drain the daemon (turns in flight settle for up to 10 minutes), upload them again, dump every table and the file stores, upload the rows, request the load and wait for `done` or `failed`, printing each step's time. Before `done`, a failure ends the drain and this runtime carries on as before; a computer's move also signs it out. On `done` the daemon stays drained: a hosted runtime until hosting quiesces it (`crtr sys import resume` ends it), a computer until it has switched over \u2014 machine credential, `runtime/machine.json`, daemon restarted in machine role \u2014 which is retried three times over a minute and otherwise finished by `crtr sys signin`. A machine import signs the person in first when this computer has no stored sign-in. `crtr sys signin` normally starts a computer's move itself. With `--run`, hosting has already opened the run: the exporter uses it and reads that run's import token from the environment variable `CRTR_IMPORT_TOKEN`.",params:[{kind:"flag",name:"kind",type:"enum",choices:["machine","hosted"],required:!0,constraint:"`machine` for a person's computer, `hosted` for a hosted runtime (also archives running nodes' files)."},{kind:"flag",name:"api-url",type:"string",required:!1,constraint:"Control plane base URL (http or https). Required with `--kind hosted`; with `--kind machine` the default is the control plane the person's sign-in is for."},{kind:"flag",name:"run",type:"string",required:!1,constraint:"An import run hosting opened for this runtime (only with `--kind hosted`); its import token is read from `CRTR_IMPORT_TOKEN`."},{kind:"flag",name:"directory-url",type:"string",required:!1,constraint:"Directory base URL (http or https) the person signs in against, with `--kind machine`. Default: the one in `runtime/machine.json`, else the stored sign-in's, else Northlight's."},{kind:"flag",name:"notify",type:"string",required:!1,constraint:"With `--kind machine`: a node id told by message when the move fails or finishes."}],output:[{name:"run_id",type:"string",required:!0,constraint:"The import run."},{name:"state",type:"string",required:!0,constraint:"Final state of the run, `done`."},{name:"timings",type:"string",required:!0,constraint:"Per-step seconds."}],outputKind:"object",effects:["Drains the local daemon (no new wake or cron fire); the drain is a `runtime_state` row, so it survives a daemon restart. Ended on a failure before `done`; kept after `done`.","Machine: writes `runtime/import/move.json` (0600) from the run's start until the switch-over, then deletes it. On `done`: writes `runtime/machine.json` and `runtime/secrets/machine-credential` (0600) and restarts the daemon in machine role. On a failure before `done`: revokes and deletes the stored sign-in.","Machine with `--notify`: sends that node one message when the move fails or finishes.","Opens a temporary directory holding the opened file stores (0600), removed before the command ends."]},run:i(async e=>{const t=e.kind,o=e.run===void 0?void 0:String(e.run),n=e.apiUrl===void 0?void 0:String(e.apiUrl),h=e.notify===void 0?null:String(e.notify);if(t==="hosted"){if(n===void 0)throw r("--kind hosted needs --api-url: the control plane hosting opened the run on");if(h!==null)throw r("--notify names the node that asked for a computer's move: use it only with --kind machine")}else if(o!==void 0)throw r("--run takes an existing run, which only a hosted import has: use --kind hosted");const s=Number(process.env[U]??"");if(Number.isInteger(s)&&s>0&&await x(s),R())throw v("import_inside_node: run this from a plain terminal; a node's broker ends with the daemon restart",{code:"import_inside_node"});if(t==="machine"){const a=await b(d);if(a!==void 0)return await I(a),{run_id:a.runId,state:"done",timings:""};const l=e.directoryUrl===void 0?f():String(e.directoryUrl);await p(l,d);const c=await O({directoryUrl:l,...n===void 0?{}:{apiUrl:n},notify:h});return{run_id:c.runId,state:"done",timings:c.timings}}const m=(o===void 0?await p(f(),d):process.env.CRTR_IMPORT_TOKEN??"").trim();if(m==="")throw r("set CRTR_IMPORT_TOKEN to the run's import token");const u={name:"start",timings:[]};return{run_id:await T("hosted",new k(n,m),o,u),state:"done",timings:u.timings.join(" ")}},"run"),render:i(e=>`<import run="${e.run_id}" state="${e.state}" timings="${e.timings}"/>`,"render")}),$=w({name:"import",description:"move this runtime into the person's Northlight account",whenToUse:"importing this computer or hosted runtime into Northlight",help:{name:"sys import",summary:"export this runtime to Northlight",model:"The exporter pauses the local daemon, uploads a bundle the control plane loads into the shared database, and on a computer switches it to the machine role."},children:[M,N,q]});export{U as WAIT_FOR_PID_ENV,$ as sysImportBranch};
@@ -25,6 +25,7 @@ export declare class ImportCloud {
25
25
  uploadUrls(run: string, keys: string[]): Promise<ImportUploadUrlsDTO>;
26
26
  putStore(run: string, name: ImportStoreNameDTO, body: unknown): Promise<void>;
27
27
  load(run: string): Promise<ImportRunDTO>;
28
+ retry(run: string): Promise<ImportRunDTO>;
28
29
  get(run: string): Promise<ImportRunDTO>;
29
30
  /** `rotate` replaces a credential already issued for this run's machine (without it a second call answers 409 `credential_exists`). */
30
31
  machineCredential(run: string, rotate?: boolean): Promise<{
@@ -1 +1 @@
1
- var _=Object.defineProperty;var h=(s,t)=>_(s,"name",{value:t,configurable:!0});import{CrtrError as $,general as d}from"../../errors.js";import{ExitCode as O}from"../../../types.js";import{crtrVersion as R}from"../../../shared/crtr-version.js";import{NORTHLIGHT_UNREACHABLE as x}from"../../directory/reach.js";const v="stores.json",D=["auth","credentials","env","settings","plugins"],B=10*6e4,U=3e4,b=6e4,T=64*1024,S=h(s=>s===408||s===429||s>=500,"isTransientStatus");function M(s){const t=s.cause;return`failed: ${s instanceof Error?s.message:String(s)}${typeof t?.code=="string"?` (${t.code})`:""}`}h(M,"failureText");function k(s,t){const e=`npm i -g @north-light/cli@${s}`;return new $("release_mismatch",`Northlight accepts only crtr ${s} for this step, and this computer runs ${R()}. Install it with \`${e}\`, then run \`crtr sys signin\` again.`,O.GENERAL,{status:t,code:"release_mismatch",accepted:s,next:`Run \`${e}\`, then \`crtr sys signin\`.`})}h(k,"releaseMismatch");class L{static{h(this,"ImportCloud")}apiUrl;token;retryBaseMs;putIdleMs;retryBudgetMs;constructor(t,e,r=500,c=b,a=B){this.apiUrl=t,this.token=e,this.retryBaseMs=r,this.putIdleMs=c,this.retryBudgetMs=a}async backoff(t,e){return Date.now()-e>=this.retryBudgetMs?!1:(await new Promise(r=>setTimeout(r,Math.min(this.retryBaseMs*2**(t-1),U)*(.5+Math.random()/2))),!0)}async call(t,e,r,c=!1){let a;for(let o=1;;o+=1)try{return await this.callOnce(t,e,r,c)}catch(i){const n=i instanceof $?i.details?.status:void 0,u=i instanceof $&&(i.code===x||i.details?.network===!0||typeof n=="number"&&S(n));if(!c||!u||(a??=Date.now(),!await this.backoff(o,a)))throw i}}async callOnce(t,e,r,c){let a,o;const i=`Bearer ${typeof this.token=="string"?this.token:await this.token()}`;try{o=await fetch(new URL(e,this.apiUrl),{method:t,headers:{authorization:i,...r===void 0?{}:{"content-type":"application/json"}},...r===void 0?{}:{body:JSON.stringify(r)},...c?{signal:AbortSignal.timeout(this.putIdleMs)}:{}}),a=await o.text()}catch(n){throw d(`${t} ${e} ${M(n)}`,{network:!0})}if(!o.ok){let n;try{n=JSON.parse(a).error?.code}catch{n=void 0}const u=n==="release_mismatch"?/control plane accepts (\S+)/.exec(a)?.[1]?.replace(/[^0-9A-Za-z.+-]+$/,""):void 0;throw u!==void 0?k(u,o.status):d(`${t} ${e} answered ${o.status}: ${a.slice(0,500)}`,{status:o.status,...typeof n=="string"?{code:n}:{}})}return a===""?void 0:JSON.parse(a)}start(t){return this.call("POST","/v1/imports",t)}uploadUrls(t,e){return this.call("POST",`/v1/imports/${t}/upload-urls`,{keys:e},!0)}putStore(t,e,r){return this.call("PUT",`/v1/imports/${t}/stores/${e}`,r,!0)}load(t){return this.call("POST",`/v1/imports/${t}/load`,{})}get(t){return this.call("GET",`/v1/imports/${t}`)}machineCredential(t,e=!1){return this.call("POST",`/v1/imports/${t}/machine-credential${e?"?rotate=1":""}`,{})}async put(t,e,r,c){let a=!1,o;for(let i=1;;i+=1){let n,u;const g=new AbortController;let p;const m=h(()=>{clearTimeout(p),p=setTimeout(()=>g.abort(new Error(`no progress for ${Math.round(this.putIdleMs/1e3)}s`)),this.putIdleMs)},"arm");let f=0;const E=new ReadableStream({pull(l){if(m(),f>=e.length){l.close();return}l.enqueue(e.subarray(f,f+T)),f+=T}},{highWaterMark:0});try{m();const l=await fetch(t,{method:"PUT",headers:{"content-length":String(e.length)},body:E,duplex:"half",signal:g.signal});if(m(),l.ok){await l.arrayBuffer();return}const w=l.status;let y="";try{y=(await l.text()).slice(0,300)}catch{}if(n=`answered ${w}: ${y}`,w===403&&c!==void 0&&!a){a=!0,t=await c();continue}u=S(w)}catch(l){n=M(l),u=!0}finally{clearTimeout(p)}if(!u)throw d(`upload of ${r} ${n}`,{key:r});if(o??=Date.now(),!await this.backoff(i,o))throw d(`upload of ${r} ${n} after ${i} tries`,{key:r})}}}export{L as ImportCloud,v as STORE_FILE,D as STORE_ORDER,k as releaseMismatch};
1
+ var _=Object.defineProperty;var h=(s,t)=>_(s,"name",{value:t,configurable:!0});import{CrtrError as w,general as d}from"../../errors.js";import{ExitCode as O}from"../../../types.js";import{crtrVersion as R}from"../../../shared/crtr-version.js";import{NORTHLIGHT_UNREACHABLE as x}from"../../directory/reach.js";const N="stores.json",D=["auth","credentials","env","settings","plugins"],B=10*6e4,P=3e4,U=6e4,T=64*1024,S=h(s=>s===408||s===429||s>=500,"isTransientStatus");function M(s){const t=s.cause;return`failed: ${s instanceof Error?s.message:String(s)}${typeof t?.code=="string"?` (${t.code})`:""}`}h(M,"failureText");function b(s,t){const e=`npm i -g @north-light/cli@${s}`;return new w("release_mismatch",`Northlight accepts only crtr ${s} for this step, and this computer runs ${R()}. Install it with \`${e}\`, then run \`crtr sys signin\` again.`,O.GENERAL,{status:t,code:"release_mismatch",accepted:s,next:`Run \`${e}\`, then \`crtr sys signin\`.`})}h(b,"releaseMismatch");class L{static{h(this,"ImportCloud")}apiUrl;token;retryBaseMs;putIdleMs;retryBudgetMs;constructor(t,e,r=500,l=U,a=B){this.apiUrl=t,this.token=e,this.retryBaseMs=r,this.putIdleMs=l,this.retryBudgetMs=a}async backoff(t,e){return Date.now()-e>=this.retryBudgetMs?!1:(await new Promise(r=>setTimeout(r,Math.min(this.retryBaseMs*2**(t-1),P)*(.5+Math.random()/2))),!0)}async call(t,e,r,l=!1){let a;for(let o=1;;o+=1)try{return await this.callOnce(t,e,r,l)}catch(i){const n=i instanceof w?i.details?.status:void 0,u=i instanceof w&&(i.code===x||i.details?.network===!0||typeof n=="number"&&S(n));if(!l||!u||(a??=Date.now(),!await this.backoff(o,a)))throw i}}async callOnce(t,e,r,l){let a,o;const i=`Bearer ${typeof this.token=="string"?this.token:await this.token()}`;try{o=await fetch(new URL(e,this.apiUrl),{method:t,headers:{authorization:i,...r===void 0?{}:{"content-type":"application/json"}},...r===void 0?{}:{body:JSON.stringify(r)},...l?{signal:AbortSignal.timeout(this.putIdleMs)}:{}}),a=await o.text()}catch(n){throw d(`${t} ${e} ${M(n)}`,{network:!0})}if(!o.ok){let n;try{n=JSON.parse(a).error?.code}catch{n=void 0}const u=n==="release_mismatch"?/control plane accepts (\S+)/.exec(a)?.[1]?.replace(/[^0-9A-Za-z.+-]+$/,""):void 0;throw u!==void 0?b(u,o.status):d(`${t} ${e} answered ${o.status}: ${a.slice(0,500)}`,{status:o.status,...typeof n=="string"?{code:n}:{}})}return a===""?void 0:JSON.parse(a)}start(t){return this.call("POST","/v1/imports",t)}uploadUrls(t,e){return this.call("POST",`/v1/imports/${t}/upload-urls`,{keys:e},!0)}putStore(t,e,r){return this.call("PUT",`/v1/imports/${t}/stores/${e}`,r,!0)}load(t){return this.call("POST",`/v1/imports/${t}/load`,{})}retry(t){return this.call("POST",`/v1/imports/${t}/retry`,{})}get(t){return this.call("GET",`/v1/imports/${t}`)}machineCredential(t,e=!1){return this.call("POST",`/v1/imports/${t}/machine-credential${e?"?rotate=1":""}`,{})}async put(t,e,r,l){let a=!1,o;for(let i=1;;i+=1){let n,u;const g=new AbortController;let p;const m=h(()=>{clearTimeout(p),p=setTimeout(()=>g.abort(new Error(`no progress for ${Math.round(this.putIdleMs/1e3)}s`)),this.putIdleMs)},"arm");let f=0;const E=new ReadableStream({pull(c){if(m(),f>=e.length){c.close();return}c.enqueue(e.subarray(f,f+T)),f+=T}},{highWaterMark:0});try{m();const c=await fetch(t,{method:"PUT",headers:{"content-length":String(e.length)},body:E,duplex:"half",signal:g.signal});if(m(),c.ok){await c.arrayBuffer();return}const $=c.status;let y="";try{y=(await c.text()).slice(0,300)}catch{}if(n=`answered ${$}: ${y}`,$===403&&l!==void 0&&!a){a=!0,t=await l();continue}u=S($)}catch(c){n=M(c),u=!0}finally{clearTimeout(p)}if(!u)throw d(`upload of ${r} ${n}`,{key:r});if(o??=Date.now(),!await this.backoff(i,o))throw d(`upload of ${r} ${n} after ${i} tries`,{key:r})}}}export{L as ImportCloud,N as STORE_FILE,D as STORE_ORDER,b as releaseMismatch};
@@ -18,10 +18,11 @@ export declare function checkStagedReferences(input: RewriteInput, own: {
18
18
  person: string;
19
19
  runId: string;
20
20
  }): Promise<void>;
21
- /** Before `checkStagedReferences`: a staged `messages` row whose `object_id` or `actor_id` names a target object that check would refuse is dropped, with the
22
- * `deliveries` and `message_causes` rows of those messages. A message is history, not a binding, and the object it names is another account's (a soft-deleted
23
- * row of an earlier import from a different install). Ids with no target row keep the stub treatment; every other table still refuses. Returns rows dropped per table. */
24
- export declare function dropRefusedMessages(input: RewriteInput, own: {
21
+ /** Before `checkStagedReferences`: a staged row, in any table but `objects`, that names a target object `checkStagedReferences` would refuse (another account's: a shared
22
+ * repo document, a soft-deleted object of an earlier import from a different install) is dropped, with the rows that depend on it (the `deliveries` and `message_causes` of a
23
+ * dropped message, then every row whose foreign key names a dropped row). Ids with no target row keep the stub treatment. An `objects` row that names such an object (a
24
+ * document parented under it) is still refused. Returns rows dropped per table. */
25
+ export declare function dropForeignReferences(input: RewriteInput, own: {
25
26
  installId: string;
26
27
  person: string;
27
28
  runId: string;
@@ -1,20 +1,20 @@
1
- var P=Object.defineProperty;var c=(n,t)=>P(n,"name",{value:t,configurable:!0});import{parseBlobKey as w}from"../bundle/blob-keys.js";import{q as f}from"./catalog.js";import{decodeKeys as J}from"./copy.js";import{objectIdColumns as Y}from"./rewrite.js";import{ImportLaneError as F}from"./stage.js";const K=/^user:[A-Za-z0-9._-]+$/,C=c(n=>n.replace(/^user:/,""),"bare"),g=c((n,t)=>`${f(n)}.${f(t)}`,"sq"),N=c(async(n,t,...a)=>await n.prepareUncached(t).all(...a),"all");function T(n,t){return new F("bind","person_mismatch",n,t)}c(T,"mismatch");function se(n,t,a,p){if(n===t||n===a)return a;throw T(`${p} names ${n}, which is neither the bundle's person nor the importing person`,{where:p,value:n})}c(se,"boundSub");async function ne(n,t,a,p){if(!K.test(a))throw T(`the bundle's person ${JSON.stringify(a)} is not a user:<id> principal`,{where:"source.json person",value:a});if(a===p)return;const u=c(r=>g(t,r),"T"),o=await n.prepareUncached(`SELECT 'identities' AS tbl FROM ${u("identities")} WHERE scheme IN ('user', 'local-user') AND external_id = ?
2
- UNION ALL SELECT 'grants' FROM ${u("grants")} WHERE sub = ? UNION ALL SELECT 'profiles' FROM ${u("profiles")} WHERE person = ?
3
- UNION ALL SELECT 'nodes' FROM ${u("nodes")} WHERE sub = ? LIMIT 1`).get(a,a,a,a);if(o!==void 0)throw T(`the bundle's person ${a} is already a person in the target (${o.tbl}), not the importing person ${p}`,{where:`${o.tbl}`,value:a})}c(ne,"checkSourcePerson");const B=[["nodes","sub"],["crons","sub"],["grants","sub"],["profiles","person"],["charges","sub"],["limits","sub"],["audit_rows","sub"],["provider_approvals","sub"],["uploads","sub"],["files","sub"],["shares","sub"]],z=[["charges","payer"],["limits","payer"],["audit_rows","payer"],["audit_rows","grantee"],["charges","grantee"],["run_events","grantee"],["idempotency_keys","grantee"],["uploads","grantee"],["files","grantee"],["provider_approvals","grantee"],["profiles","grantee"],["crons","grantee"]];async function re(n){const{db:t,schema:a,sourcePerson:p,targetPerson:u}=n,o=c(s=>g(a,s),"S"),r=c((s,d)=>{throw T(`${s} names ${d.join(", ")}, who is neither the bundle's person ${p} nor the importing person ${u}`,{where:s,values:d})},"refuse");for(const[s,d]of B){const _=await N(t,`SELECT DISTINCT ${f(d)} AS v FROM ${o(s)} WHERE ${f(d)} IS NOT NULL AND ${f(d)} <> '' AND ${f(d)} NOT IN (?, ?) LIMIT 5`,p,u);_.length>0&&r(`${s}.${d}`,_.map($=>$.v))}for(const[s,d]of z){const _=await N(t,`SELECT DISTINCT ${f(d)} AS v FROM ${o(s)} WHERE ${f(d)} LIKE 'user:%' AND ${f(d)} NOT IN (?, ?) LIMIT 5`,p,u);_.length>0&&r(`${s}.${d}`,_.map($=>$.v))}const b=await N(t,`SELECT DISTINCT external_id AS v FROM ${o("identities")} WHERE scheme IN ('user', 'local-user') AND external_id NOT IN (?, ?) LIMIT 5`,p,u);b.length>0&&r("identities.external_id",b.map(s=>s.v));const h=await N(t,`SELECT DISTINCT adapter_json::jsonb #>> '{principal,sub}' AS v FROM ${o("daemon_actions")}
4
- WHERE adapter_json::jsonb #>> '{principal,sub}' IS NOT NULL AND adapter_json::jsonb #>> '{principal,sub}' NOT IN (?, ?) LIMIT 5`,p,u);h.length>0&&r("daemon_actions principal.sub",h.map(s=>s.v));const l=await N(t,`SELECT DISTINCT subject_id AS v FROM ${o("relations")} WHERE relation = 'acts_for' AND subject_type = 'user' AND subject_id NOT IN (?, ?) LIMIT 5`,C(p),C(u));l.length>0&&r("relations acts_for subject",l.map(s=>s.v));const E=Number((await t.prepareUncached(`DELETE FROM ${o("relations")} WHERE resource_type = 'crtr/group'`).run()).changes);return E>0?{relations:E}:{}}c(re,"checkStagedPersons");async function G(n,t){return(await N(n,`SELECT m.inserted_keys FROM import_manifest m JOIN import_runs r ON r.run_id = m.run_id
5
- WHERE m.table_name = 'objects' AND r.source_install_id = ? AND r.person = ? AND r.run_id <> ? AND r.state IN ('committed', 'done', 'failed')`,t.installId,t.person,t.runId)).flatMap(p=>J(p.inserted_keys).map(u=>u[0]))}c(G,"earlierImportedObjects");async function ae(n,t){const{db:a,schema:p,catalog:u,targetPerson:o}=n,r=await H(n,t);if(r.length>0)throw T(`the bundle refers to objects that are not ${o}'s: ${r.slice(0,10).map(b=>`${b.tbl}.${b.col}=${b.value}`).join(", ")}`,{references:r.slice(0,10)});await V(n)}c(ae,"checkStagedReferences");async function ie(n,t){const{db:a,schema:p,catalog:u}=n;if(!u.tables.has("messages"))return{};const o=c(s=>g(p,s),"S"),r=[...new Set((await H(n,t)).filter(s=>s.tbl==="messages").map(s=>s.value))];if(r.length===0)return{};const b="(object_id = ANY(?::text[]) OR actor_id = ANY(?::text[]))",h=`(SELECT message_id FROM ${o("messages")} WHERE ${b})`,l={};for(const[s,d]of[["deliveries","message_id"],["message_causes","message_id"]]){if(!u.tables.has(s))continue;const _=Number((await a.prepareUncached(`DELETE FROM ${o(s)} WHERE ${d} IN ${h}`).run(r,r)).changes);_>0&&(l[s]=_)}const E=Number((await a.prepareUncached(`DELETE FROM ${o("messages")} WHERE ${b}`).run(r,r)).changes);return E>0&&(l.messages=E),l}c(ie,"dropRefusedMessages");async function H(n,t){const{db:a,schema:p,target:u,catalog:o,targetPerson:r}=n,b=c(_=>g(p,_),"S"),h=c(_=>g(u,_),"T"),l=C(r);await a.exec(`CREATE TABLE ${b("_refs")} (tbl text NOT NULL, col text NOT NULL, value text NOT NULL)`);const E=[];for(const[_,$]of Y(o))if(!(!o.tables.has(_)||_==="relations"))for(const m of $)!(_==="nodes"&&m==="profile_id")&&!(_==="crons"&&m==="profile")&&E.push([_,m,""]);E.push(["relations","resource_id","WHERE resource_type = 'crtr/object'"]);for(const[_,$,m]of E)await a.prepareUncached(`INSERT INTO ${b("_refs")} SELECT ?, ?, ${f($)}::text FROM ${b(_)} ${m===""?"WHERE":`${m} AND`} ${f($)} IS NOT NULL
6
- AND ${f($)}::text NOT IN (SELECT id FROM ${b("objects")}) AND ${f($)}::text IN (SELECT id FROM ${h("objects")})`).run(_,$);const s=await G(a,t),d=await N(a,`WITH RECURSIVE chain(start, id) AS (
7
- SELECT DISTINCT value, value FROM ${b("_refs")}
8
- UNION SELECT c.start, o.owner FROM chain c JOIN ${h("objects")} o ON o.id = c.id JOIN ${h("objects")} up ON up.id = o.owner AND up.type <> 'app'),
1
+ var P=Object.defineProperty;var i=(r,o)=>P(r,"name",{value:o,configurable:!0});import{parseBlobKey as R}from"../bundle/blob-keys.js";import{q as N}from"./catalog.js";import{decodeKeys as J}from"./copy.js";import{objectIdColumns as K}from"./rewrite.js";import{ImportLaneError as W}from"./stage.js";const Y=/^user:[A-Za-z0-9._-]+$/,k=i(r=>r.replace(/^user:/,""),"bare"),S=i((r,o)=>`${N(r)}.${N(o)}`,"sq"),m=i(async(r,o,...c)=>await r.prepareUncached(o).all(...c),"all");function T(r,o){return new W("bind","person_mismatch",r,o)}i(T,"mismatch");function ne(r,o,c,p){if(r===o||r===c)return c;throw T(`${p} names ${r}, which is neither the bundle's person nor the importing person`,{where:p,value:r})}i(ne,"boundSub");async function se(r,o,c,p){if(!Y.test(c))throw T(`the bundle's person ${JSON.stringify(c)} is not a user:<id> principal`,{where:"source.json person",value:c});if(c===p)return;const a=i(l=>S(o,l),"T"),n=await r.prepareUncached(`SELECT 'identities' AS tbl FROM ${a("identities")} WHERE scheme IN ('user', 'local-user') AND external_id = ?
2
+ UNION ALL SELECT 'grants' FROM ${a("grants")} WHERE sub = ? UNION ALL SELECT 'profiles' FROM ${a("profiles")} WHERE person = ?
3
+ UNION ALL SELECT 'nodes' FROM ${a("nodes")} WHERE sub = ? LIMIT 1`).get(c,c,c,c);if(n!==void 0)throw T(`the bundle's person ${c} is already a person in the target (${n.tbl}), not the importing person ${p}`,{where:`${n.tbl}`,value:c})}i(se,"checkSourcePerson");const B=[["nodes","sub"],["crons","sub"],["grants","sub"],["profiles","person"],["charges","sub"],["limits","sub"],["audit_rows","sub"],["provider_approvals","sub"],["uploads","sub"],["files","sub"],["shares","sub"]],G=[["charges","payer"],["limits","payer"],["audit_rows","payer"],["audit_rows","grantee"],["charges","grantee"],["run_events","grantee"],["idempotency_keys","grantee"],["uploads","grantee"],["files","grantee"],["provider_approvals","grantee"],["profiles","grantee"],["crons","grantee"]];async function re(r){const{db:o,schema:c,sourcePerson:p,targetPerson:a}=r,n=i(t=>S(c,t),"S"),l=i((t,s)=>{throw T(`${t} names ${s.join(", ")}, who is neither the bundle's person ${p} nor the importing person ${a}`,{where:t,values:s})},"refuse");for(const[t,s]of B){const _=await m(o,`SELECT DISTINCT ${N(s)} AS v FROM ${n(t)} WHERE ${N(s)} IS NOT NULL AND ${N(s)} <> '' AND ${N(s)} NOT IN (?, ?) LIMIT 5`,p,a);_.length>0&&l(`${t}.${s}`,_.map(h=>h.v))}for(const[t,s]of G){const _=await m(o,`SELECT DISTINCT ${N(s)} AS v FROM ${n(t)} WHERE ${N(s)} LIKE 'user:%' AND ${N(s)} NOT IN (?, ?) LIMIT 5`,p,a);_.length>0&&l(`${t}.${s}`,_.map(h=>h.v))}const f=await m(o,`SELECT DISTINCT external_id AS v FROM ${n("identities")} WHERE scheme IN ('user', 'local-user') AND external_id NOT IN (?, ?) LIMIT 5`,p,a);f.length>0&&l("identities.external_id",f.map(t=>t.v));const b=await m(o,`SELECT DISTINCT adapter_json::jsonb #>> '{principal,sub}' AS v FROM ${n("daemon_actions")}
4
+ WHERE adapter_json::jsonb #>> '{principal,sub}' IS NOT NULL AND adapter_json::jsonb #>> '{principal,sub}' NOT IN (?, ?) LIMIT 5`,p,a);b.length>0&&l("daemon_actions principal.sub",b.map(t=>t.v));const d=await m(o,`SELECT DISTINCT subject_id AS v FROM ${n("relations")} WHERE relation = 'acts_for' AND subject_type = 'user' AND subject_id NOT IN (?, ?) LIMIT 5`,k(p),k(a));d.length>0&&l("relations acts_for subject",d.map(t=>t.v));const E=Number((await o.prepareUncached(`DELETE FROM ${n("relations")} WHERE resource_type = 'crtr/group'`).run()).changes);return E>0?{relations:E}:{}}i(re,"checkStagedPersons");async function z(r,o){return(await m(r,`SELECT m.inserted_keys FROM import_manifest m JOIN import_runs r ON r.run_id = m.run_id
5
+ WHERE m.table_name = 'objects' AND r.source_install_id = ? AND r.person = ? AND r.run_id <> ? AND r.state IN ('committed', 'done', 'failed')`,o.installId,o.person,o.runId)).flatMap(p=>J(p.inserted_keys).map(a=>a[0]))}i(z,"earlierImportedObjects");async function ae(r,o){const{db:c,schema:p,catalog:a,targetPerson:n}=r,l=await H(r,o);if(l.length>0)throw T(`the bundle refers to objects that are not ${n}'s: ${l.slice(0,10).map(f=>`${f.tbl}.${f.col}=${f.value}`).join(", ")}`,{references:l.slice(0,10)});await V(r)}i(ae,"checkStagedReferences");async function ie(r,o){const{db:c,schema:p,catalog:a}=r,n=i(t=>S(p,t),"S"),l=(await H(r,o)).filter(t=>t.tbl!=="objects"),f={},b=new Map;for(const t of l){const s=`${t.tbl}.${t.col}`;b.has(s)||b.set(s,{tbl:t.tbl,col:t.col,values:new Set}),b.get(s).values.add(t.value)}const d=i(t=>{const s=a.tables.get(t)?.primaryKey??[];return s.length===1?N(s[0]):null},"keysOf"),E=i(async(t,s,..._)=>{const h=d(t),g=await c.prepareUncached(`DELETE FROM ${n(t)} WHERE ${s} RETURNING ${h===null?"1 AS k":`${h}::text AS k`}`).all(..._);if(g.length===0||(f[t]=(f[t]??0)+g.length,h===null))return;const L=g.map($=>$.k),O=a.foreignKeys.filter($=>$.parent===t&&$.columns.length===1&&$.parentColumns.length===1&&$.parentColumns[0]===h.replace(/"/g,"")&&a.tables.has($.table));for(const $ of O)await E($.table,`${N($.columns[0])}::text = ANY(?::text[])`,L);if(t==="messages")for(const $ of["deliveries","message_causes"])a.tables.has($)&&!O.some(j=>j.table===$)&&await E($,"message_id = ANY(?::text[])",L)},"removeWhere");for(const{tbl:t,col:s,values:_}of b.values()){if(!a.tables.has(t))continue;const h=t==="relations"?" AND resource_type = 'crtr/object'":"";await E(t,`${N(s)}::text = ANY(?::text[])${h}`,[..._])}return f}i(ie,"dropForeignReferences");async function H(r,o){const{db:c,schema:p,target:a,catalog:n,targetPerson:l}=r,f=i(_=>S(p,_),"S"),b=i(_=>S(a,_),"T"),d=k(l);await c.exec(`CREATE TABLE ${f("_refs")} (tbl text NOT NULL, col text NOT NULL, value text NOT NULL)`);const E=[];for(const[_,h]of K(n))if(!(!n.tables.has(_)||_==="relations"))for(const g of h)!(_==="nodes"&&g==="profile_id")&&!(_==="crons"&&g==="profile")&&E.push([_,g,""]);E.push(["relations","resource_id","WHERE resource_type = 'crtr/object'"]);for(const[_,h,g]of E)await c.prepareUncached(`INSERT INTO ${f("_refs")} SELECT ?, ?, ${N(h)}::text FROM ${f(_)} ${g===""?"WHERE":`${g} AND`} ${N(h)} IS NOT NULL
6
+ AND ${N(h)}::text NOT IN (SELECT id FROM ${f("objects")}) AND ${N(h)}::text IN (SELECT id FROM ${b("objects")})`).run(_,h);const t=await z(c,o),s=await m(c,`WITH RECURSIVE chain(start, id) AS (
7
+ SELECT DISTINCT value, value FROM ${f("_refs")}
8
+ UNION SELECT c.start, o.owner FROM chain c JOIN ${b("objects")} o ON o.id = c.id JOIN ${b("objects")} up ON up.id = o.owner AND up.type <> 'app'),
9
9
  ok(id) AS (
10
- SELECT o.id FROM ${h("objects")} o WHERE o.type = 'app'
11
- UNION SELECT d.object FROM ${h("documents")} d WHERE d.source_path IS NOT NULL
12
- UNION SELECT i.object FROM ${h("identities")} i WHERE i.scheme IN ('user', 'local-user') AND i.external_id = ?
13
- UNION SELECT r.resource_id FROM ${h("relations")} r WHERE r.resource_type = 'crtr/object' AND r.relation = 'acts_for' AND r.subject_type = 'user' AND r.subject_id = ?
14
- UNION SELECT r.resource_id FROM ${h("relations")} r JOIN ${h("relations")} m ON m.resource_type = 'crtr/group' AND m.relation = 'member' AND m.resource_id = r.subject_id
10
+ SELECT o.id FROM ${b("objects")} o WHERE o.type = 'app'
11
+ UNION SELECT d.object FROM ${b("documents")} d WHERE d.source_path IS NOT NULL
12
+ UNION SELECT i.object FROM ${b("identities")} i WHERE i.scheme IN ('user', 'local-user') AND i.external_id = ?
13
+ UNION SELECT r.resource_id FROM ${b("relations")} r WHERE r.resource_type = 'crtr/object' AND r.relation = 'acts_for' AND r.subject_type = 'user' AND r.subject_id = ?
14
+ UNION SELECT r.resource_id FROM ${b("relations")} r JOIN ${b("relations")} m ON m.resource_type = 'crtr/group' AND m.relation = 'member' AND m.resource_id = r.subject_id
15
15
  AND m.subject_type = 'user' AND m.subject_id = ?
16
16
  WHERE r.resource_type = 'crtr/object' AND r.relation IN ('reader', 'editor', 'messenger', 'user_of') AND r.subject_type = 'crtr/group' AND r.subject_relation = 'member'
17
17
  UNION SELECT unnest(?::text[]))
18
- SELECT r.tbl, r.col, r.value FROM ${b("_refs")} r
19
- WHERE NOT EXISTS (SELECT 1 FROM chain c JOIN ok ON ok.id = c.id WHERE c.start = r.value)`,r,l,l,s);return await a.exec(`DROP TABLE ${b("_refs")}`),d}c(H,"foreignReferences");async function V(n){const{db:t,schema:a,target:p,targetPerson:u}=n,o=c(l=>g(a,l),"S"),r=c(l=>g(p,l),"T"),b=[["nodes","profile_id"],["crons","profile"],["profiles","id"]];for(const[l,E]of b){const s=await N(t,`SELECT DISTINCT s.${f(E)} AS v FROM ${o(l)} s JOIN ${r("profiles")} p ON p.id = s.${f(E)} WHERE p.person <> ? LIMIT 5`,u);if(s.length>0)throw T(`${l}.${E} names profiles that belong to another person: ${s.map(d=>d.v).join(", ")}`,{where:`${l}.${E}`,values:s.map(d=>d.v)})}for(const[l,E]of[["nodes","grant_id"],["crons","grant_id"]]){const s=await N(t,`SELECT DISTINCT s.${f(E)} AS v FROM ${o(l)} s JOIN ${r("grants")} g ON g.id = s.${f(E)} WHERE g.sub <> ? LIMIT 5`,u);if(s.length>0)throw T(`${l}.${E} names grants that belong to another person: ${s.map(d=>d.v).join(", ")}`,{where:`${l}.${E}`,values:s.map(d=>d.v)})}const h=await N(t,`SELECT DISTINCT d.adapter_json::jsonb #>> '{principal,grant_id}' AS v FROM ${o("daemon_actions")} d
20
- JOIN ${r("grants")} g ON g.id = d.adapter_json::jsonb #>> '{principal,grant_id}' WHERE g.sub <> ? LIMIT 5`,u);if(h.length>0)throw T(`a queued action names grants that belong to another person: ${h.map(l=>l.v).join(", ")}`,{where:"daemon_actions principal.grant_id",values:h.map(l=>l.v)})}c(V,"checkStagedProfilesAndGrants");const k=c((n,t)=>new F("bind","bundle_invalid",n,t),"bundleInvalid");async function ce(n){const{db:t,schema:a,target:p,targetPerson:u}=n,o=c(e=>g(a,e),"S"),r=new Set((await N(t,`SELECT node_id AS v FROM ${o("nodes")}`)).map(e=>e.v)),b=await N(t,`SELECT conversation_id, seq::text AS seq, blob_key FROM ${o("conversation_parts")}`),h=await N(t,`SELECT run_id, path, blob_key FROM ${o("upload_uses")} WHERE blob_key IS NOT NULL`),l=await N(t,`SELECT object, output_key FROM ${o("jobs")} WHERE output_key IS NOT NULL`),E=c(e=>e.split("/")[1]??"","jobOwner"),s=c((e,i,S,O)=>{const D=w(i);if(D===null||D.kind!==S||O!==void 0&&i!==O)throw k(`${e} holds ${JSON.stringify(i)}, which is not a ${S} blob key${O===void 0?"":` of the shape ${O}`}`,{where:e,value:i})},"shaped");for(const e of b)if(s("conversation_parts.blob_key",e.blob_key,"conversation"),e.blob_key.split("/")[2]!==e.conversation_id)throw k(`conversation_parts.blob_key ${e.blob_key} is not under its conversation ${e.conversation_id}`,{where:"conversation_parts.blob_key",value:e.blob_key});for(const e of h)s("upload_uses.blob_key",e.blob_key,"attachment");for(const e of l)s("jobs.output_key",e.output_key,"job",`jobs/${E(e.output_key)}/${e.object}/output`);const d=new Set;for(const{blob_key:e}of b){const i=w(e);i!==null&&i.kind==="conversation"&&!r.has(i.owner)&&d.add(i.owner)}for(const{blob_key:e}of h){const i=w(e);i!==null&&i.kind==="attachment"&&!r.has(i.owner)&&d.add(i.owner)}for(const{output_key:e}of l)r.has(E(e))||d.add(E(e));const _=new Map((d.size===0?[]:await N(t,`SELECT node_id, sub FROM ${g(p,"nodes")} WHERE node_id = ANY(?::text[])`,[...d])).map(e=>[e.node_id,e.sub])),$=c(e=>r.has(e)||_.get(e)===u,"held"),m=c(e=>!r.has(e)&&!_.has(e),"gone"),A={},I=c((e,i)=>{i>0&&(A[e]=(A[e]??0)+i)},"count"),R=c(async(e,...i)=>Number((await t.prepareUncached(e).run(...i)).changes),"drop"),W=new Set((await N(t,`SELECT DISTINCT session_id AS v FROM ${o("sessions")} WHERE session_id IS NOT NULL`)).map(e=>e.v)),L=new Map;for(const{conversation_id:e,blob_key:i}of b){const S=w(i),O=L.get(e);O!==null&&(S===null||S.kind!=="conversation"?L.set(e,null):L.set(e,[...O??[],S.owner]))}const v=[...L].filter(([e,i])=>i!==null&&!W.has(e)&&i.every(m)).map(([e])=>e);v.length>0&&(I("conversation_parts",await R(`DELETE FROM ${o("conversation_parts")} WHERE conversation_id = ANY(?::text[])`,v)),I("conversation_entries",await R(`DELETE FROM ${o("conversation_entries")} WHERE conversation_id = ANY(?::text[])`,v)));const U=new Set(v),j=c((e,i)=>{const S=w(i).owner;if(!$(S))throw T(`${e} holds ${i}, which belongs to node ${S}, who is not in the bundle`,{where:e,value:i})},"owned");for(const e of b)U.has(e.conversation_id)||j("conversation_parts.blob_key",e.blob_key);const y=h.filter(e=>{const i=w(e.blob_key);return i!==null&&i.kind==="attachment"&&m(i.owner)&&!r.has(e.run_id)});y.length>0&&I("upload_uses",await R(`DELETE FROM ${o("upload_uses")} u USING unnest(?::text[], ?::text[]) d(run_id, path) WHERE u.run_id = d.run_id AND u.path = d.path`,y.map(e=>e.run_id),y.map(e=>e.path)));const x=new Set(y);for(const e of h)x.has(e)||j("upload_uses.blob_key",e.blob_key);const M=l.filter(e=>e.output_key===`jobs/${E(e.output_key)}/${e.object}/output`&&m(E(e.output_key)));M.length>0&&I("jobs",await R(`DELETE FROM ${o("jobs")} WHERE object = ANY(?::text[])`,M.map(e=>e.object)));const q=new Set(M);for(const e of l)q.has(e)||j("jobs.output_key",e.output_key);return A}c(ce,"checkStagedBlobKeys");async function ue(n){const{db:t,schema:a}=n;for(const p of await N(t,`SELECT request_id, request_dir, presentation_dir, file FROM ${g(a,"human_requests")}`))for(const u of["request_dir","presentation_dir","file"]){const o=p[u];if(o===null||!o.startsWith("requests/"))continue;const r=w(o.includes("/",9)?o:`${o}/x`);if(r===null||r.kind!=="request")throw k(`human_requests.${u} holds ${JSON.stringify(o)}, which is not a request blob key`,{where:`human_requests.${u}`,value:o});if(r.owner!==p.request_id)throw T(`human_requests.${u} of ${p.request_id} holds ${o}, which belongs to request ${r.owner}`,{where:`human_requests.${u}`,value:o})}}c(ue,"checkStagedRequestKeys");export{se as boundSub,ne as checkSourcePerson,ce as checkStagedBlobKeys,re as checkStagedPersons,ae as checkStagedReferences,ue as checkStagedRequestKeys,ie as dropRefusedMessages};
18
+ SELECT r.tbl, r.col, r.value FROM ${f("_refs")} r
19
+ WHERE NOT EXISTS (SELECT 1 FROM chain c JOIN ok ON ok.id = c.id WHERE c.start = r.value)`,l,d,d,t);return await c.exec(`DROP TABLE ${f("_refs")}`),s}i(H,"foreignReferences");async function V(r){const{db:o,schema:c,target:p,targetPerson:a}=r,n=i(d=>S(c,d),"S"),l=i(d=>S(p,d),"T"),f=[["nodes","profile_id"],["crons","profile"],["profiles","id"]];for(const[d,E]of f){const t=await m(o,`SELECT DISTINCT s.${N(E)} AS v FROM ${n(d)} s JOIN ${l("profiles")} p ON p.id = s.${N(E)} WHERE p.person <> ? LIMIT 5`,a);if(t.length>0)throw T(`${d}.${E} names profiles that belong to another person: ${t.map(s=>s.v).join(", ")}`,{where:`${d}.${E}`,values:t.map(s=>s.v)})}for(const[d,E]of[["nodes","grant_id"],["crons","grant_id"]]){const t=await m(o,`SELECT DISTINCT s.${N(E)} AS v FROM ${n(d)} s JOIN ${l("grants")} g ON g.id = s.${N(E)} WHERE g.sub <> ? LIMIT 5`,a);if(t.length>0)throw T(`${d}.${E} names grants that belong to another person: ${t.map(s=>s.v).join(", ")}`,{where:`${d}.${E}`,values:t.map(s=>s.v)})}const b=await m(o,`SELECT DISTINCT d.adapter_json::jsonb #>> '{principal,grant_id}' AS v FROM ${n("daemon_actions")} d
20
+ JOIN ${l("grants")} g ON g.id = d.adapter_json::jsonb #>> '{principal,grant_id}' WHERE g.sub <> ? LIMIT 5`,a);if(b.length>0)throw T(`a queued action names grants that belong to another person: ${b.map(d=>d.v).join(", ")}`,{where:"daemon_actions principal.grant_id",values:b.map(d=>d.v)})}i(V,"checkStagedProfilesAndGrants");const D=i((r,o)=>new W("bind","bundle_invalid",r,o),"bundleInvalid");async function ce(r){const{db:o,schema:c,target:p,targetPerson:a}=r,n=i(e=>S(c,e),"S"),l=new Set((await m(o,`SELECT node_id AS v FROM ${n("nodes")}`)).map(e=>e.v)),f=await m(o,`SELECT conversation_id, seq::text AS seq, blob_key FROM ${n("conversation_parts")}`),b=await m(o,`SELECT run_id, path, blob_key FROM ${n("upload_uses")} WHERE blob_key IS NOT NULL`),d=await m(o,`SELECT object, output_key FROM ${n("jobs")} WHERE output_key IS NOT NULL`),E=i(e=>e.split("/")[1]??"","jobOwner"),t=i((e,u,w,I)=>{const F=R(u);if(F===null||F.kind!==w||I!==void 0&&u!==I)throw D(`${e} holds ${JSON.stringify(u)}, which is not a ${w} blob key${I===void 0?"":` of the shape ${I}`}`,{where:e,value:u})},"shaped");for(const e of f)if(t("conversation_parts.blob_key",e.blob_key,"conversation"),e.blob_key.split("/")[2]!==e.conversation_id)throw D(`conversation_parts.blob_key ${e.blob_key} is not under its conversation ${e.conversation_id}`,{where:"conversation_parts.blob_key",value:e.blob_key});for(const e of b)t("upload_uses.blob_key",e.blob_key,"attachment");for(const e of d)t("jobs.output_key",e.output_key,"job",`jobs/${E(e.output_key)}/${e.object}/output`);const s=new Set;for(const{blob_key:e}of f){const u=R(e);u!==null&&u.kind==="conversation"&&!l.has(u.owner)&&s.add(u.owner)}for(const{blob_key:e}of b){const u=R(e);u!==null&&u.kind==="attachment"&&!l.has(u.owner)&&s.add(u.owner)}for(const{output_key:e}of d)l.has(E(e))||s.add(E(e));const _=new Map((s.size===0?[]:await m(o,`SELECT node_id, sub FROM ${S(p,"nodes")} WHERE node_id = ANY(?::text[])`,[...s])).map(e=>[e.node_id,e.sub])),h=i(e=>l.has(e)||_.get(e)===a,"held"),g=i(e=>!l.has(e)&&!_.has(e),"gone"),L={},O=i((e,u)=>{u>0&&(L[e]=(L[e]??0)+u)},"count"),$=i(async(e,...u)=>Number((await o.prepareUncached(e).run(...u)).changes),"drop"),j=new Set((await m(o,`SELECT DISTINCT session_id AS v FROM ${n("sessions")} WHERE session_id IS NOT NULL`)).map(e=>e.v)),y=new Map;for(const{conversation_id:e,blob_key:u}of f){const w=R(u),I=y.get(e);I!==null&&(w===null||w.kind!=="conversation"?y.set(e,null):y.set(e,[...I??[],w.owner]))}const v=[...y].filter(([e,u])=>u!==null&&!j.has(e)&&u.every(g)).map(([e])=>e);v.length>0&&(O("conversation_parts",await $(`DELETE FROM ${n("conversation_parts")} WHERE conversation_id = ANY(?::text[])`,v)),O("conversation_entries",await $(`DELETE FROM ${n("conversation_entries")} WHERE conversation_id = ANY(?::text[])`,v)));const x=new Set(v),M=i((e,u)=>{const w=R(u).owner;if(!h(w))throw T(`${e} holds ${u}, which belongs to node ${w}, who is not in the bundle`,{where:e,value:u})},"owned");for(const e of f)x.has(e.conversation_id)||M("conversation_parts.blob_key",e.blob_key);const A=b.filter(e=>{const u=R(e.blob_key);return u!==null&&u.kind==="attachment"&&g(u.owner)&&!l.has(e.run_id)});A.length>0&&O("upload_uses",await $(`DELETE FROM ${n("upload_uses")} u USING unnest(?::text[], ?::text[]) d(run_id, path) WHERE u.run_id = d.run_id AND u.path = d.path`,A.map(e=>e.run_id),A.map(e=>e.path)));const U=new Set(A);for(const e of b)U.has(e)||M("upload_uses.blob_key",e.blob_key);const C=d.filter(e=>e.output_key===`jobs/${E(e.output_key)}/${e.object}/output`&&g(E(e.output_key)));C.length>0&&O("jobs",await $(`DELETE FROM ${n("jobs")} WHERE object = ANY(?::text[])`,C.map(e=>e.object)));const q=new Set(C);for(const e of d)q.has(e)||M("jobs.output_key",e.output_key);return L}i(ce,"checkStagedBlobKeys");async function le(r){const{db:o,schema:c}=r;for(const p of await m(o,`SELECT request_id, request_dir, presentation_dir, file FROM ${S(c,"human_requests")}`))for(const a of["request_dir","presentation_dir","file"]){const n=p[a];if(n===null||!n.startsWith("requests/"))continue;const l=R(n.includes("/",9)?n:`${n}/x`);if(l===null||l.kind!=="request")throw D(`human_requests.${a} holds ${JSON.stringify(n)}, which is not a request blob key`,{where:`human_requests.${a}`,value:n});if(l.owner!==p.request_id)throw T(`human_requests.${a} of ${p.request_id} holds ${n}, which belongs to request ${l.owner}`,{where:`human_requests.${a}`,value:n})}}i(le,"checkStagedRequestKeys");export{ne as boundSub,se as checkSourcePerson,ce as checkStagedBlobKeys,re as checkStagedPersons,ae as checkStagedReferences,le as checkStagedRequestKeys,ie as dropForeignReferences};
@@ -19,3 +19,9 @@ export declare function deleteRunPrefix(blobs: BlobStore, runId: string, options
19
19
  keepNodeFiles?: boolean;
20
20
  bestEffort?: boolean;
21
21
  }): Promise<void>;
22
+ /** A run that failed before its copy committed keeps its uploaded bundle so `crtr sys import retry` can load it again; the storage sweep deletes it this many days after the failure. */
23
+ export declare const FAILED_UPLOAD_RETENTION_DAYS = 7;
24
+ /** `import_runs.step` of a failed run whose kept upload the sweep deleted. */
25
+ export declare const UPLOAD_DELETED_STEP = "upload_deleted";
26
+ /** Deletes the kept uploads of runs that failed before their copy committed and have been failed for `FAILED_UPLOAD_RETENTION_DAYS`. Returns how many runs were cleared. */
27
+ export declare function sweepFailedUploads(db: CanvasDb, blobs: BlobStore, now: number): Promise<number>;
@@ -1 +1 @@
1
- var B=Object.defineProperty;var l=(e,t)=>B(e,"name",{value:t,configurable:!0});import{R2_MAX_CONNECTIONS as M}from"../../blobs/r2.js";import{ownerBlobPrefixes as R,parseBlobKey as E,runBlobPrefix as O}from"../bundle/blob-keys.js";import{bundleKeys as k}from"../bundle/layout.js";import{emitEvent as v}from"../../events/emit.js";import{q as d}from"./catalog.js";import{ImportLaneError as x}from"./stage.js";const T=M;function N(){const e=process.env.CRTR_IMPORT_BLOB_WORKERS;if(e===void 0||e==="")return T;const t=Number(e);if(!Number.isInteger(t)||t<1||t>1024)throw new Error(`CRTR_IMPORT_BLOB_WORKERS must be an integer from 1 to 1024, got ${JSON.stringify(e)}`);return t}l(N,"workerLimit");async function w(e,t){if(e.length===0)return;let i=0,n;const a=l(async()=>{for(;n===void 0&&i<e.length;)try{await t(e[i++])}catch(r){n??={error:r}}},"worker");if(await Promise.all(Array.from({length:Math.min(N(),e.length)},a)),n!==void 0)throw n.error}l(w,"forEachBounded");async function U(e,t,i,n,a,r,f){const m={nodes:new Set((await e.prepareUncached(`SELECT node_id AS v FROM ${d(t)}.nodes UNION SELECT node_id FROM ${d(i)}.nodes WHERE sub = ?`).all(n)).map(o=>o.v)),human_requests:new Set((await e.prepareUncached(`SELECT request_id AS v FROM ${d(t)}.human_requests`).all()).map(o=>o.v))},c=O(r),u={moved:0,left:0},p=[];for(const o of await a.listObjects(c)){const s=E(o.key.slice(c.length));s===null||!m[s.ownerTable].has(s.owner)?u.left+=1:p.push(o)}const y=new Map,_=new Set(p.map(o=>o.key.slice(c.length)));return await w([...new Set([..._].map(C))],async o=>{for(const s of await a.listObjects(o))_.has(s.key)&&y.set(s.key,s)}),await w(p,async o=>{const s=o.key.slice(c.length),g=y.get(s);if(g===void 0){if(f.push(s),!await a.copy(o.key,s))throw S(o.key)}else if(!await P(a,o,g))throw new x("blobs","unique_conflict",`${s} already exists with other contents; the import does not replace it`,{key:s});u.moved+=1}),u}l(U,"moveRunBlobs");const C=l(e=>e.split("/").slice(0,2).join("/")+"/","ownerPrefix"),S=l(e=>new x("blobs","bundle_invalid",`${e} was listed and is gone`),"gone");async function P(e,t,i){if(t.size!==i.size)return!1;if(t.etag!==null&&i.etag!==null)return t.etag===i.etag;for(let n=0;n<t.size;n+=b){const a={start:n,length:Math.min(b,t.size-n)},[r,f]=await Promise.all([e.get(t.key,a),e.get(i.key,a)]);if(r===null)throw S(t.key);if(f===null||!r.equals(f))return!1}return!0}l(P,"sameObject");const b=256*1024;async function h(e,t,i=!1){await w(t,i?n=>e.delete(n).catch(a=>{v({level:"warn",event:"import.blob_delete_failed",error:a,fields:{key:n}})}):n=>e.delete(n))}l(h,"deleteBlobs");async function W(e,t,i){const n=[...t.flatMap(r=>R("nodes",r).map(f=>({prefix:f,owner:r,table:"nodes"}))),...i.flatMap(r=>R("human_requests",r).map(f=>({prefix:f,owner:r,table:"human_requests"})))],a=[];await w(n,async({prefix:r,owner:f,table:m})=>{for(const c of await e.list(r)){const u=E(c);u!==null&&u.ownerTable===m&&u.owner===f&&a.push(c)}}),await h(e,a)}l(W,"deleteOwnedBlobs");async function z(e,t){await h(e,await e.list(O(t)))}l(z,"deleteRunBlobs");async function I(e,t,i={}){const n=`${k.prefix(t)}node-files/`;let a;try{a=await e.list(k.prefix(t))}catch(r){if(i.bestEffort!==!0)throw r;v({level:"warn",event:"import.prefix_delete_failed",error:r,fields:{run_id:t}});return}await h(e,i.keepNodeFiles===!0?a.filter(r=>!r.startsWith(n)):a,i.bestEffort===!0)}l(I,"deleteRunPrefix");export{h as deleteBlobs,W as deleteOwnedBlobs,z as deleteRunBlobs,I as deleteRunPrefix,U as moveRunBlobs};
1
+ var v=Object.defineProperty;var l=(e,t)=>v(e,"name",{value:t,configurable:!0});import{R2_MAX_CONNECTIONS as A}from"../../blobs/r2.js";import{ownerBlobPrefixes as O,parseBlobKey as R,runBlobPrefix as S}from"../bundle/blob-keys.js";import{bundleKeys as g}from"../bundle/layout.js";import{emitEvent as T}from"../../events/emit.js";import{q as m}from"./catalog.js";import{ImportLaneError as N}from"./stage.js";const M=A;function D(){const e=process.env.CRTR_IMPORT_BLOB_WORKERS;if(e===void 0||e==="")return M;const t=Number(e);if(!Number.isInteger(t)||t<1||t>1024)throw new Error(`CRTR_IMPORT_BLOB_WORKERS must be an integer from 1 to 1024, got ${JSON.stringify(e)}`);return t}l(D,"workerLimit");async function w(e,t){if(e.length===0)return;let i=0,n;const a=l(async()=>{for(;n===void 0&&i<e.length;)try{await t(e[i++])}catch(r){n??={error:r}}},"worker");if(await Promise.all(Array.from({length:Math.min(D(),e.length)},a)),n!==void 0)throw n.error}l(w,"forEachBounded");async function j(e,t,i,n,a,r,f){const p={nodes:new Set((await e.prepareUncached(`SELECT node_id AS v FROM ${m(t)}.nodes UNION SELECT node_id FROM ${m(i)}.nodes WHERE sub = ?`).all(n)).map(o=>o.v)),human_requests:new Set((await e.prepareUncached(`SELECT request_id AS v FROM ${m(t)}.human_requests`).all()).map(o=>o.v))},c=S(r),u={moved:0,left:0},d=[];for(const o of await a.listObjects(c)){const s=R(o.key.slice(c.length));s===null||!p[s.ownerTable].has(s.owner)?u.left+=1:d.push(o)}const h=new Map,E=new Set(d.map(o=>o.key.slice(c.length)));return await w([...new Set([...E].map(I))],async o=>{for(const s of await a.listObjects(o))E.has(s.key)&&h.set(s.key,s)}),await w(d,async o=>{const s=o.key.slice(c.length),y=h.get(s);if(y===void 0){if(f.push(s),!await a.copy(o.key,s))throw L(o.key)}else if(!await P(a,o,y))throw new N("blobs","unique_conflict",`${s} already exists with other contents; the import does not replace it`,{key:s});u.moved+=1}),u}l(j,"moveRunBlobs");const I=l(e=>e.split("/").slice(0,2).join("/")+"/","ownerPrefix"),L=l(e=>new N("blobs","bundle_invalid",`${e} was listed and is gone`),"gone");async function P(e,t,i){if(t.size!==i.size)return!1;if(t.etag!==null&&i.etag!==null)return t.etag===i.etag;for(let n=0;n<t.size;n+=k){const a={start:n,length:Math.min(k,t.size-n)},[r,f]=await Promise.all([e.get(t.key,a),e.get(i.key,a)]);if(r===null)throw L(t.key);if(f===null||!r.equals(f))return!1}return!0}l(P,"sameObject");const k=256*1024;async function _(e,t,i=!1){await w(t,i?n=>e.delete(n).catch(a=>{T({level:"warn",event:"import.blob_delete_failed",error:a,fields:{key:n}})}):n=>e.delete(n))}l(_,"deleteBlobs");async function z(e,t,i){const n=[...t.flatMap(r=>O("nodes",r).map(f=>({prefix:f,owner:r,table:"nodes"}))),...i.flatMap(r=>O("human_requests",r).map(f=>({prefix:f,owner:r,table:"human_requests"})))],a=[];await w(n,async({prefix:r,owner:f,table:p})=>{for(const c of await e.list(r)){const u=R(c);u!==null&&u.ownerTable===p&&u.owner===f&&a.push(c)}}),await _(e,a)}l(z,"deleteOwnedBlobs");async function H(e,t){await _(e,await e.list(S(t)))}l(H,"deleteRunBlobs");async function b(e,t,i={}){const n=`${g.prefix(t)}node-files/`;let a;try{a=await e.list(g.prefix(t))}catch(r){if(i.bestEffort!==!0)throw r;T({level:"warn",event:"import.prefix_delete_failed",error:r,fields:{run_id:t}});return}await _(e,i.keepNodeFiles===!0?a.filter(r=>!r.startsWith(n)):a,i.bestEffort===!0)}l(b,"deleteRunPrefix");const B=7,x="upload_deleted";async function J(e,t,i){const n=new Date(i-B*864e5).toISOString(),a=await e.prepare("SELECT run_id FROM import_runs WHERE state = 'failed' AND committed_at IS NULL AND finished_at IS NOT NULL AND finished_at <= ? AND step IS DISTINCT FROM ? LIMIT 20").all(n,x);for(const{run_id:r}of a)await b(t,r),await e.prepare("UPDATE import_runs SET step = ? WHERE run_id = ?").run(x,r);return a.length}l(J,"sweepFailedUploads");export{B as FAILED_UPLOAD_RETENTION_DAYS,x as UPLOAD_DELETED_STEP,_ as deleteBlobs,z as deleteOwnedBlobs,H as deleteRunBlobs,b as deleteRunPrefix,j as moveRunBlobs,J as sweepFailedUploads};
@@ -1,14 +1,14 @@
1
- var A=Object.defineProperty;var d=(e,a)=>A(e,"name",{value:a,configurable:!0});import{createProfileBlaxelEnvironment as U}from"../../environments.js";import{KEY_MAPPED_TABLES as M,mapPath as S}from"../bundle/layout.js";import{IDEMPOTENCY_WINDOW_MS as C}from"../../runs/operations.js";import{ImportLaneError as N}from"./stage.js";import{withHeaderCwd as g}from"../../conversation-store/row-store.js";import{runBlobKey as H}from"../bundle/blob-keys.js";import{q as l}from"./catalog.js";const c=d((e,a)=>`${l(e)}.${l(a)}`,"sq");async function J(e,a,o){if(o.length===0)return 0;const n=d(E=>c(a,E),"S"),i=`(SELECT node_id FROM ${n("nodes")} WHERE status IN ('active', 'idle'))`;let s=0;const p=d(async(E,r,t,$=!1)=>{const R=await e.prepareUncached(`SELECT ${l(r)}::text AS value FROM ${n(E)} WHERE ${t} AND ${l(r)} IS NOT NULL`).all();for(const{value:m}of R){const T=$?v(m,o):S(o,m);T!==m&&(await e.prepareUncached(`UPDATE ${n(E)} SET ${l(r)} = ? WHERE ${l(r)}::text = ? AND ${t}`).run(T,m),s+=1)}},"apply");return await p("nodes","cwd",`node_id IN ${i}`),await p("worktrees","path",`node_id IN ${i}`),await p("worktrees","repo_root",`node_id IN ${i}`),await p("crons","cwd",`anchor_node IN ${i}`),await p("provider_approvals","prepared_files","TRUE",!0),await p("upload_uses","path",`run_id IN ${i}`),s}d(J,"rewritePaths");async function Y(e,a,o,n,i){if(o.length===0)return 0;const s=d(r=>c(a,r),"S"),p=await e.prepareUncached(`SELECT conversation_id, blob_key FROM ${s("conversation_parts")} WHERE seq = 0
2
- AND split_part(blob_key, '/', 2) IN (SELECT node_id FROM ${s("nodes")} WHERE status IN ('active', 'idle'))`).all();let E=0;for(const{conversation_id:r,blob_key:t}of p){const $=H(i,t),R=await n.get($);if(R===null)throw new N("rewrite-paths","bundle_invalid",`${$} is missing: the header of conversation ${r} cannot be rewritten`);const m=g(R,r,T=>S(o,T));m!==null&&(await n.put($,m),E+=1),await e.prepareUncached(`UPDATE ${s("conversation_parts")} SET bytes = ?, cycle_offset = NULL WHERE conversation_id = ? AND seq = 0`).run((m??R).length,r)}return E}d(Y,"rewriteConversationHeaders");async function X(e,a){const o=c(a,"human_requests"),n=d(s=>`CASE WHEN ${s} IS NULL OR ${s} NOT LIKE '/%' THEN ${s}
1
+ var A=Object.defineProperty;var d=(e,a)=>A(e,"name",{value:a,configurable:!0});import{createProfileBlaxelEnvironment as U}from"../../environments.js";import{KEY_MAPPED_TABLES as M,mapPath as S}from"../bundle/layout.js";import{IDEMPOTENCY_WINDOW_MS as C}from"../../runs/operations.js";import{ImportLaneError as N}from"./stage.js";import{withHeaderCwd as g}from"../../conversation-store/row-store.js";import{runBlobKey as H}from"../bundle/blob-keys.js";import{q as l}from"./catalog.js";const c=d((e,a)=>`${l(e)}.${l(a)}`,"sq");async function J(e,a,o){if(o.length===0)return 0;const n=d(E=>c(a,E),"S"),i=`(SELECT node_id FROM ${n("nodes")} WHERE status IN ('active', 'idle'))`;let s=0;const p=d(async(E,r,t,$=!1)=>{const _=await e.prepareUncached(`SELECT ${l(r)}::text AS value FROM ${n(E)} WHERE ${t} AND ${l(r)} IS NOT NULL`).all();for(const{value:m}of _){const T=$?b(m,o):S(o,m);T!==m&&(await e.prepareUncached(`UPDATE ${n(E)} SET ${l(r)} = ? WHERE ${l(r)}::text = ? AND ${t}`).run(T,m),s+=1)}},"apply");return await p("nodes","cwd",`node_id IN ${i}`),await p("worktrees","path",`node_id IN ${i}`),await p("worktrees","repo_root",`node_id IN ${i}`),await p("crons","cwd",`anchor_node IN ${i}`),await p("provider_approvals","prepared_files","TRUE",!0),await p("upload_uses","path",`run_id IN ${i}`),s}d(J,"rewritePaths");async function Y(e,a,o,n,i){if(o.length===0)return 0;const s=d(r=>c(a,r),"S"),p=await e.prepareUncached(`SELECT conversation_id, blob_key FROM ${s("conversation_parts")} WHERE seq = 0
2
+ AND split_part(blob_key, '/', 2) IN (SELECT node_id FROM ${s("nodes")} WHERE status IN ('active', 'idle'))`).all();let E=0;for(const{conversation_id:r,blob_key:t}of p){const $=H(i,t),_=await n.get($);if(_===null)throw new N("rewrite-paths","bundle_invalid",`${$} is missing: the header of conversation ${r} cannot be rewritten`);const m=g(_,r,T=>S(o,T));m!==null&&(await n.put($,m),E+=1),await e.prepareUncached(`UPDATE ${s("conversation_parts")} SET bytes = ?, cycle_offset = NULL WHERE conversation_id = ? AND seq = 0`).run((m??_).length,r)}return E}d(Y,"rewriteConversationHeaders");async function X(e,a){const o=c(a,"human_requests"),n=d(s=>`CASE WHEN ${s} IS NULL OR ${s} NOT LIKE '/%' THEN ${s}
3
3
  WHEN rtrim(${s}, '/') = rtrim(request_dir, '/') THEN 'requests/' || request_id
4
4
  WHEN ${s} LIKE rtrim(request_dir, '/') || '/%' THEN 'requests/' || request_id || '/' || substr(${s}, length(rtrim(request_dir, '/')) + 2)
5
5
  ELSE 'requests/' || request_id || '/source/' || regexp_replace(${s}, '^.*/', '') END`,"moved"),i=await e.prepareUncached(`UPDATE ${o} SET file = ${n("file")}, presentation_dir = ${n("presentation_dir")},
6
- request_dir = CASE WHEN request_dir LIKE '/%' THEN 'requests/' || request_id ELSE request_dir END`).run();return Number(i.changes)}d(X,"rewriteRequestPaths");function v(e,a){const o=d(n=>typeof n=="string"?S(a,n):Array.isArray(n)?n.map(o):n!==null&&typeof n=="object"?Object.fromEntries(Object.entries(n).map(([i,s])=>[i,o(s)])):n,"walk");try{return JSON.stringify(o(JSON.parse(e)))}catch{return S(a,e)}}d(v,"rewriteJsonPaths");async function G(e,a,o,n,i){const s=d(r=>c(a,r),"S"),p=await e.prepareUncached(`SELECT id, name FROM ${s("profiles")} ORDER BY id`).all();let E=0;for(const r of p){const t=await e.prepareUncached(`SELECT o.id FROM ${s("objects")} o JOIN ${s("identities")} i ON i.object = o.id AND i.scheme = 'profile' AND i.external_id = ?
7
- WHERE o.type = 'profile' AND o.name = ?`).get(r.id,r.name),$=await e.prepareUncached(`SELECT 1 AS found FROM ${c(o,"profiles")} WHERE person = ? AND name = ? AND id <> ?`).get(i,r.name,r.id),R=t===void 0?void 0:await e.prepareUncached(`SELECT 1 AS found FROM ${c(o,"objects")} WHERE type = 'profile' AND home_machine IS NULL AND name = ? AND id <> ?`).get(r.name,t.id);if($===void 0&&R===void 0)continue;const m=`${r.name}-${n}`;await e.prepareUncached(`UPDATE ${s("profiles")} SET name = ? WHERE id = ?`).run(m,r.id),t!==void 0&&await e.prepareUncached(`UPDATE ${s("objects")} SET name = ? WHERE id = ?`).run(m,t.id),E+=1}return E}d(G,"renameClashingProfiles");async function z(e,a,o,n){const i=await e.prepareUncached(`UPDATE ${c(a,"charges")} s SET id = s.id || ':install-' || ?::text FROM ${c(o,"charges")} t
8
- WHERE s.id LIKE 'legacy:%' AND t.id = s.id AND (s.payer IS DISTINCT FROM t.payer OR s.units IS DISTINCT FROM t.units OR s.usd IS DISTINCT FROM t.usd)`).run(n);return Number(i.changes)}d(z,"renameClashingLegacyCharges");async function Q(e,a,o){const n=`FROM ${c(o,"watches")} t WHERE t.watcher = s.watcher AND t.object = s.object`,i=await e.prepareUncached(`DELETE FROM ${c(a,"watch_subscriptions")} u USING ${c(a,"watches")} s WHERE u.watch = s.watch_id AND EXISTS (SELECT 1 ${n})`).run(),s=await e.prepareUncached(`DELETE FROM ${c(a,"watches")} s WHERE EXISTS (SELECT 1 ${n})`).run();return{watches:Number(s.changes),watch_subscriptions:Number(i.changes)}}d(Q,"dropExistingWatches");async function V(e,a){const o=await e.prepareUncached(`UPDATE ${c(a,"crons")} c SET anchor_node = c.created_by WHERE c.anchor_node IS NULL AND c.created_by IN (SELECT node_id FROM ${c(a,"nodes")})`).run();return Number(o.changes)}d(V,"anchorCronsToCreator");async function Z(e,a,o){const n=await e.prepareUncached(`DELETE FROM ${c(a,"idempotency_keys")} s WHERE EXISTS (SELECT 1 FROM ${c(o,"idempotency_keys")} t WHERE t.grantee = s.grantee AND t.key = s.key)`).run();return Number(n.changes)}d(Z,"dropExistingIdempotencyKeys");async function ee(e,a){const o=await e.prepareUncached(`DELETE FROM ${c(a,"idempotency_keys")} WHERE created_at <= ?`).run(new Date(Date.now()-C).toISOString());return Number(o.changes)}d(ee,"dropExpiredIdempotencyKeys");async function ne(e,a,o,n,i){const s=d(r=>c(a,r),"S"),p=[],E=await e.prepareUncached(`SELECT id, grantee FROM ${s("profiles")} WHERE environment_id IS NULL ORDER BY id`).all();for(const r of E){let t=n.kind==="machine"?n.environmentObject??null:null;if(n.kind==="hosted"){const $=await e.prepareUncached(`SELECT environment_id FROM ${c(o,"profiles")} WHERE id = ?`).get(r.id);if($?.environment_id!=null)t=$.environment_id;else{t=await U(e,{profileId:r.id,grantee:r.grantee??"app:terminal",person:i}),p.push({table:"objects",key:[t]},{table:"environments",key:[t]});for(const R of await e.prepareUncached("SELECT resource_type, resource_id, relation, subject_type, subject_id, subject_relation FROM relations WHERE resource_id = ?").all(t))p.push({table:"relations",key:[R.resource_type,R.resource_id,R.relation,R.subject_type,R.subject_id,R.subject_relation]})}}if(t===null)throw new N("fill","bundle_invalid",`profile ${r.id} has no environment and the source names none`);await e.prepareUncached(`UPDATE ${s("profiles")} SET environment_id = ? WHERE id = ?`).run(t,r.id)}return p}d(ne,"fillEnvironments");async function te(e,a,o,n){const i=d(E=>c(a,E),"S"),s={},p=d(async(E,r,...t)=>{const $=Number((await e.prepareUncached(r).run(...t)).changes);$>0&&(s[E]=(s[E]??0)+$)},"del");await p("limits",`DELETE FROM ${i("limits")} WHERE source <> 'person'`),n.kind==="hosted"&&(await e.prepareUncached(`UPDATE ${i("profiles")} SET environment_id = NULL WHERE environment_id IN (SELECT object FROM ${i("environments")})`).run(),await e.prepareUncached(`UPDATE ${i("objects")} SET home_machine = 'import-hosted-source' WHERE id IN (SELECT object FROM ${i("environments")})`).run());for(const[E,r]of Object.entries(M))await p(E,`DELETE FROM ${i(E)} WHERE ${l(r)}::text IN (SELECT source_key FROM import_key_map WHERE source_install_id = ? AND table_name = ?)`,n.installId,E);for(const E of o.tables.values())E.columns.includes("claimed_by")&&E.columns.includes("lease_expires_at")&&await e.prepareUncached(`UPDATE ${i(E.name)} SET claimed_by = NULL, lease_expires_at = NULL WHERE claimed_by IS NOT NULL OR lease_expires_at IS NOT NULL`).run();return s}d(te,"pruneStaged");async function re(e,a,o){const n=d(p=>c(a,p),"S"),i=`(SELECT d.object FROM ${n("documents")} d WHERE EXISTS (SELECT 1 FROM ${c(o,"documents")} t WHERE t.object = d.object))`;await e.exec(`CREATE TABLE ${n("_arr_revisions")} AS SELECT r.* FROM ${n("revisions")} r WHERE r.document IN ${i};
6
+ request_dir = CASE WHEN request_dir LIKE '/%' THEN 'requests/' || request_id ELSE request_dir END`).run();return Number(i.changes)}d(X,"rewriteRequestPaths");function b(e,a){const o=d(n=>typeof n=="string"?S(a,n):Array.isArray(n)?n.map(o):n!==null&&typeof n=="object"?Object.fromEntries(Object.entries(n).map(([i,s])=>[i,o(s)])):n,"walk");try{return JSON.stringify(o(JSON.parse(e)))}catch{return S(a,e)}}d(b,"rewriteJsonPaths");async function G(e,a,o,n,i){const s=d(r=>c(a,r),"S"),p=await e.prepareUncached(`SELECT id, name FROM ${s("profiles")} ORDER BY id`).all();let E=0;for(const r of p){const t=await e.prepareUncached(`SELECT o.id FROM ${s("objects")} o JOIN ${s("identities")} i ON i.object = o.id AND i.scheme = 'profile' AND i.external_id = ?
7
+ WHERE o.type = 'profile' AND o.name = ?`).get(r.id,r.name),$=await e.prepareUncached(`SELECT 1 AS found FROM ${c(o,"profiles")} WHERE person = ? AND name = ? AND id <> ?`).get(i,r.name,r.id),_=t===void 0?void 0:await e.prepareUncached(`SELECT 1 AS found FROM ${c(o,"objects")} WHERE type = 'profile' AND home_machine IS NULL AND name = ? AND id <> ?`).get(r.name,t.id);if($===void 0&&_===void 0)continue;const m=`${r.name}-${n}`;await e.prepareUncached(`UPDATE ${s("profiles")} SET name = ? WHERE id = ?`).run(m,r.id),t!==void 0&&await e.prepareUncached(`UPDATE ${s("objects")} SET name = ? WHERE id = ?`).run(m,t.id),E+=1}return E}d(G,"renameClashingProfiles");async function z(e,a,o,n){const i=await e.prepareUncached(`UPDATE ${c(a,"charges")} s SET id = s.id || ':install-' || ?::text FROM ${c(o,"charges")} t
8
+ WHERE s.id LIKE 'legacy:%' AND t.id = s.id AND (s.payer IS DISTINCT FROM t.payer OR s.units IS DISTINCT FROM t.units OR s.usd IS DISTINCT FROM t.usd)`).run(n);return Number(i.changes)}d(z,"renameClashingLegacyCharges");async function Q(e,a,o){const n=`FROM ${c(o,"watches")} t WHERE t.watcher = s.watcher AND t.object = s.object`,i=await e.prepareUncached(`DELETE FROM ${c(a,"watch_subscriptions")} u USING ${c(a,"watches")} s WHERE u.watch = s.watch_id AND EXISTS (SELECT 1 ${n})`).run(),s=await e.prepareUncached(`DELETE FROM ${c(a,"watches")} s WHERE EXISTS (SELECT 1 ${n})`).run();return{watches:Number(s.changes),watch_subscriptions:Number(i.changes)}}d(Q,"dropExistingWatches");async function V(e,a){const o=await e.prepareUncached(`UPDATE ${c(a,"crons")} c SET anchor_node = c.created_by WHERE c.anchor_node IS NULL AND c.created_by IN (SELECT node_id FROM ${c(a,"nodes")})`).run();return Number(o.changes)}d(V,"anchorCronsToCreator");async function Z(e,a,o){const n=await e.prepareUncached(`DELETE FROM ${c(a,"idempotency_keys")} s WHERE EXISTS (SELECT 1 FROM ${c(o,"idempotency_keys")} t WHERE t.grantee = s.grantee AND t.key = s.key)`).run();return Number(n.changes)}d(Z,"dropExistingIdempotencyKeys");async function ee(e,a){const o=await e.prepareUncached(`DELETE FROM ${c(a,"idempotency_keys")} WHERE created_at <= ?`).run(new Date(Date.now()-C).toISOString());return Number(o.changes)}d(ee,"dropExpiredIdempotencyKeys");async function ne(e,a,o,n,i){const s=d(r=>c(a,r),"S"),p=[],E=await e.prepareUncached(`SELECT id, grantee FROM ${s("profiles")} WHERE environment_id IS NULL ORDER BY id`).all();for(const r of E){let t=n.kind==="machine"?n.environmentObject??null:null;if(n.kind==="hosted"){const $=await e.prepareUncached(`SELECT environment_id FROM ${c(o,"profiles")} WHERE id = ?`).get(r.id);if($?.environment_id!=null)t=$.environment_id;else{t=await U(e,{profileId:r.id,grantee:r.grantee??"app:terminal",person:i}),p.push({table:"objects",key:[t]},{table:"environments",key:[t]});for(const _ of await e.prepareUncached("SELECT resource_type, resource_id, relation, subject_type, subject_id, subject_relation FROM relations WHERE resource_id = ?").all(t))p.push({table:"relations",key:[_.resource_type,_.resource_id,_.relation,_.subject_type,_.subject_id,_.subject_relation]})}}if(t===null)throw new N("fill","bundle_invalid",`profile ${r.id} has no environment and the source names none`);await e.prepareUncached(`UPDATE ${s("profiles")} SET environment_id = ? WHERE id = ?`).run(t,r.id)}return p}d(ne,"fillEnvironments");async function te(e,a,o,n){const i=d(E=>c(a,E),"S"),s={},p=d(async(E,r,...t)=>{const $=Number((await e.prepareUncached(r).run(...t)).changes);$>0&&(s[E]=(s[E]??0)+$)},"del");await p("limits",`DELETE FROM ${i("limits")} WHERE source <> 'person'`),n.kind==="hosted"&&(await e.prepareUncached(`UPDATE ${i("profiles")} SET environment_id = NULL WHERE environment_id IN (SELECT object FROM ${i("environments")})`).run(),await e.prepareUncached(`UPDATE ${i("objects")} SET home_machine = 'import-hosted-source' WHERE id IN (SELECT object FROM ${i("environments")})`).run());for(const[E,r]of Object.entries(M))await p(E,`DELETE FROM ${i(E)} WHERE ${l(r)}::text IN (SELECT source_key FROM import_key_map WHERE source_install_id = ? AND table_name = ?)`,n.installId,E);for(const E of o.tables.values())E.columns.includes("claimed_by")&&E.columns.includes("lease_expires_at")&&await e.prepareUncached(`UPDATE ${i(E.name)} SET claimed_by = NULL, lease_expires_at = NULL WHERE claimed_by IS NOT NULL OR lease_expires_at IS NOT NULL`).run();return s}d(te,"pruneStaged");async function re(e,a,o){const n=d(p=>c(a,p),"S"),i=`(SELECT d.object FROM ${n("documents")} d WHERE EXISTS (SELECT 1 FROM ${c(o,"documents")} t WHERE t.object = d.object))`;await e.exec(`CREATE TABLE ${n("_arr_revisions")} AS SELECT r.* FROM ${n("revisions")} r WHERE r.document IN ${i};
9
9
  CREATE TABLE ${n("_arr_parents")} AS SELECT p.* FROM ${n("revision_parents")} p WHERE p.child IN (SELECT rev_id FROM ${n("revisions")} WHERE document IN ${i})`);const s=await e.prepareUncached(`SELECT r.document, r.rev_id, r.body_hash, r.rationale, r.created_at,
10
10
  COALESCE((SELECT array_agg(p.parent) FROM ${n("revision_parents")} p WHERE p.child = r.rev_id), ARRAY[]::text[]) AS parents
11
- FROM ${n("revisions")} r WHERE r.document IN ${i} ORDER BY r.document, r.number`).all();return await e.prepareUncached(`DELETE FROM ${n("revision_parents")} WHERE child IN (SELECT rev_id FROM ${n("revisions")} WHERE document IN ${i})`).run(),await e.prepareUncached(`DELETE FROM ${n("revisions")} WHERE document IN ${i}`).run(),await e.prepareUncached(`DELETE FROM ${n("objects")} WHERE id IN ${i}`).run(),await e.prepareUncached(`DELETE FROM ${n("documents")} WHERE object IN ${i}`).run(),s.map(p=>({...p}))}d(re,"takeRepoSyncedDocuments");const b={edges:["created_at"],relations:["created_at"]},W={charges:["payer","units","usd"]};async function ae(e,a,o,n,i,s,p){const E=d(t=>[...p.get(t)??[],...t==="profiles"?["environment_id"]:[],...b[t]??[],"claimed_by","lease_expires_at"],"ignored"),r=[];for(const t of i){const $=n.tables.get(t);if($===void 0||s.has(t)||$.primaryKey.length===0)continue;const R=$.primaryKey,m=R.some(u=>$.identity.includes(u)),T=R.map(u=>`s.${l(u)} = t.${l(u)}`).join(" AND "),L=m?"TRUE":R.map(u=>`s.${l(u)} IS DISTINCT FROM t.${l(u)}`).join(" OR "),I=new Set([...$.identity,...p.get(t)??[]]);for(const u of n.uniqueKeys.filter(h=>h.table===t&&!h.columns.every(f=>I.has(f)))){const h=u.predicate===null?"":` WHERE ${u.predicate}`,f=u.columns.map(_=>`s.${l(_)} = t.${l(_)}`).join(" AND "),O=await e.prepareUncached(`SELECT ${u.columns.map(_=>`s.${l(_)}::text`).join(" || ',' || ")} AS value
12
- FROM (SELECT * FROM ${c(a,t)}${h}) s JOIN (SELECT * FROM ${c(o,t)}${h}) t ON ${f} AND (${L}) LIMIT 10`).all();O.length>0&&r.push({table:t,key:u.name,values:O.map(_=>_.value)});const D=m?"TRUE":R.map(_=>`a.${l(_)} IS DISTINCT FROM b.${l(_)}`).join(" OR "),y=await e.prepareUncached(`SELECT DISTINCT ${u.columns.map(_=>`a.${l(_)}::text`).join(" || ',' || ")} AS value
13
- FROM (SELECT ctid AS row_id, * FROM ${c(a,t)}${h}) a JOIN (SELECT ctid AS row_id, * FROM ${c(a,t)}${h}) b ON ${u.columns.map(_=>`a.${l(_)} = b.${l(_)}`).join(" AND ")} AND a.row_id < b.row_id AND (${D}) LIMIT 10`).all();y.length>0&&r.push({table:t,key:u.name,values:y.map(_=>_.value),staged:!0})}const w=$.columns.filter(u=>!$.identity.includes(u)&&!E(t).includes(u)&&(W[t]?.includes(u)??!0));if(w.length>0&&!m){const u=w.map(f=>`s.${l(f)} IS DISTINCT FROM t.${l(f)}`).join(" OR "),h=await e.prepareUncached(`SELECT ${R.map(f=>`s.${l(f)}::text`).join(" || ',' || ")} AS value
11
+ FROM ${n("revisions")} r WHERE r.document IN ${i} ORDER BY r.document, r.number`).all();return await e.prepareUncached(`DELETE FROM ${n("revision_parents")} WHERE child IN (SELECT rev_id FROM ${n("revisions")} WHERE document IN ${i})`).run(),await e.prepareUncached(`DELETE FROM ${n("revisions")} WHERE document IN ${i}`).run(),await e.prepareUncached(`DELETE FROM ${n("objects")} WHERE id IN ${i}`).run(),await e.prepareUncached(`DELETE FROM ${n("documents")} WHERE object IN ${i}`).run(),s.map(p=>({...p}))}d(re,"takeRepoSyncedDocuments");const v={edges:["created_at"],relations:["created_at","written_by"]},W={charges:["payer","units","usd"]};async function ae(e,a,o,n,i,s,p){const E=d(t=>[...p.get(t)??[],...t==="profiles"?["environment_id"]:[],...v[t]??[],"claimed_by","lease_expires_at"],"ignored"),r=[];for(const t of i){const $=n.tables.get(t);if($===void 0||s.has(t)||$.primaryKey.length===0)continue;const _=$.primaryKey,m=_.some(u=>$.identity.includes(u)),T=_.map(u=>`s.${l(u)} = t.${l(u)}`).join(" AND "),L=m?"TRUE":_.map(u=>`s.${l(u)} IS DISTINCT FROM t.${l(u)}`).join(" OR "),I=new Set([...$.identity,...p.get(t)??[]]);for(const u of n.uniqueKeys.filter(h=>h.table===t&&!h.columns.every(f=>I.has(f)))){const h=u.predicate===null?"":` WHERE ${u.predicate}`,f=u.columns.map(R=>`s.${l(R)} = t.${l(R)}`).join(" AND "),y=await e.prepareUncached(`SELECT ${u.columns.map(R=>`s.${l(R)}::text`).join(" || ',' || ")} AS value
12
+ FROM (SELECT * FROM ${c(a,t)}${h}) s JOIN (SELECT * FROM ${c(o,t)}${h}) t ON ${f} AND (${L}) LIMIT 10`).all();y.length>0&&r.push({table:t,key:u.name,values:y.map(R=>R.value)});const D=m?"TRUE":_.map(R=>`a.${l(R)} IS DISTINCT FROM b.${l(R)}`).join(" OR "),O=await e.prepareUncached(`SELECT DISTINCT ${u.columns.map(R=>`a.${l(R)}::text`).join(" || ',' || ")} AS value
13
+ FROM (SELECT ctid AS row_id, * FROM ${c(a,t)}${h}) a JOIN (SELECT ctid AS row_id, * FROM ${c(a,t)}${h}) b ON ${u.columns.map(R=>`a.${l(R)} = b.${l(R)}`).join(" AND ")} AND a.row_id < b.row_id AND (${D}) LIMIT 10`).all();O.length>0&&r.push({table:t,key:u.name,values:O.map(R=>R.value),staged:!0})}const w=$.columns.filter(u=>!$.identity.includes(u)&&!E(t).includes(u)&&(W[t]?.includes(u)??!0));if(w.length>0&&!m){const u=w.map(f=>`s.${l(f)} IS DISTINCT FROM t.${l(f)}`).join(" OR "),h=await e.prepareUncached(`SELECT ${_.map(f=>`s.${l(f)}::text`).join(" || ',' || ")} AS value
14
14
  FROM ${c(a,t)} s JOIN ${c(o,t)} t ON ${T} WHERE ${u} LIMIT 10`).all();h.length>0&&r.push({table:t,key:"primary key payload",values:h.map(f=>f.value)})}}if(r.length>0){const t=r[0];throw new N("pre-check","unique_conflict",`${t.table} ${t.key} collides ${t.staged===!0?"within the bundle":"with the target"}: ${t.values.join(", ")}`,{collisions:r})}}d(ae,"precheck");export{V as anchorCronsToCreator,Z as dropExistingIdempotencyKeys,Q as dropExistingWatches,ee as dropExpiredIdempotencyKeys,ne as fillEnvironments,ae as precheck,te as pruneStaged,z as renameClashingLegacyCharges,G as renameClashingProfiles,Y as rewriteConversationHeaders,J as rewritePaths,X as rewriteRequestPaths,re as takeRepoSyncedDocuments};
@@ -1,2 +1,2 @@
1
- var Z=Object.defineProperty;var m=(e,p)=>Z(e,"name",{value:p,configurable:!0});import{createZstdCompress as x}from"node:zlib";import{once as D}from"node:events";import{keyBatches as V}from"./keys.js";import{blobStore as X}from"../../blobs/index.js";import{openDb as E,withCanvasWrite as A}from"../../canvas/db.js";import{runAsPerson as B}from"../../canvas/person.js";import{insertImportedRevisions as ee}from"../../graph/documents.js";import{getById as te}from"../../graph/objects.js";import{bundleKeys as N,decodeRows as ae,rowKeys as L,SEQ_TABLES as ne}from"../bundle/layout.js";import{readCatalog as ie}from"./catalog.js";import{appendManifest as W,copyRows as se}from"./copy.js";import{anchorCronsToCreator as re,pruneStaged as oe,precheck as de,dropExistingIdempotencyKeys as pe,dropExpiredIdempotencyKeys as ce,dropExistingWatches as ue,renameClashingLegacyCharges as le,renameClashingProfiles as fe,rewriteConversationHeaders as me,rewritePaths as _e,rewriteRequestPaths as we,takeRepoSyncedDocuments as ge}from"./prepare.js";import{boundSub as be,dropRefusedMessages as he,checkSourcePerson as ye,checkStagedBlobKeys as Se,checkStagedPersons as ve,checkStagedReferences as Ee,checkStagedRequestKeys as Re}from"./bind.js";import{deleteBlobs as Ie,deleteRunBlobs as Oe,deleteRunPrefix as Pe,moveRunBlobs as je}from"./blobs.js";import{dropStubRows as ke,findFleetGrant as Te,grantMissing as Ce,mapProfileIds as Me,renameClashingRepos as De,rewriteIds as Ae,rewritePerson as Be,scopeRepoIdentities as Ne}from"./rewrite.js";import{dropStaging as K,ImportLaneError as g,stage as Le,stagingSchema as We,targetSchema as Ke}from"./stage.js";import{verifyRun as He}from"./verify.js";import{sandboxPathMap as Je,writeNodeFiles as Ue}from"./path-map.js";import{allStoreKeys as Fe,readPluginsStore as Ge,recordImportedActivations as $e,writeStores as qe}from"./stores.js";import{openImportGrants as Ye}from"./open-grants.js";import{publishImportedPlugins as ze}from"./publish-plugins.js";import{COPIED_TABLES as Qe}from"../bundle/layout.js";import{emitEvent as Ze}from"../../events/emit.js";import{ClaimLostError as xe}from"../../../daemon/reconcilers/row-claim.js";const Ve=10*6e4,Xe=30*6e4,R=m(()=>new Date().toISOString(),"now"),H=m(async(e,p)=>{await(await E()).prepare("UPDATE import_runs SET step = ? WHERE run_id = ?").run(p,e)},"setStep");async function et(e,p){const s=await e.get(N.source(p));if(s===null)throw new g("stage","bundle_invalid","source.json is missing");const n=JSON.parse(s.toString("utf8"));if(typeof n.rowParts!="object"||n.rowParts===null)throw new g("stage","bundle_invalid","source.json names no row parts");return n}m(et,"readSource");async function tt(e,p,s,n,a,r,o){const i=[];for(const t of L(s.run_id,"grants",n)){const c=await e.get(t);if(c===null)throw new g("stage","bundle_invalid",`row file ${t} is missing`);i.push(...ae(c))}if(i.length===0)return;const _=i.map(t=>({sub:be(t.sub,n.person,s.person,"grants.sub"),grantee:t.grantee}));await o(s.run_id);const f=[];for(const t of _)await Te(p,a,r,t.sub,t.grantee)===void 0&&f.push(t.grantee);if(f.length>0)throw Ce(f)}m(tt,"ensureGrants");async function Ct(e,p,s={}){const n=s.blobs??await X(),a=await E(),r=We(e.run_id);let o="start";const i=m(async t=>{o=t,await p.assertOwned(),await H(e.run_id,t),await s.atStep?.(t)},"at");let _=e.state==="committed";const f=[];try{const t=await et(n,e.run_id);if(e.source_kind==="machine"&&t.installId!==e.source_install_id)throw new g("stage","bundle_invalid",`source.json names install ${t.installId}, the run is for ${e.source_install_id}`);t.installId=e.source_install_id;const c=await Ke(a),I=[...Qe],h=await ie(a,c,[...I,"grants"]);if(!_){const l={},P=[],j=[],k=s.fleetRuntime??process.env.CRTR_RUNTIME??null;await ye(a,c,t.person,e.person),await i("open-grants"),await tt(n,a,e,t,c,k,s.openGrants??Ye),await i("publish-plugins");const J=await Ge(n,e.run_id),S=await B(e.person,()=>ze(J));if(S.unavailable.length>0){if(e.loaded_at===void 0||e.loaded_at===null)throw new g("publish-plugins","import_failed","a loading run has no loaded_at");if(Date.now()-Date.parse(e.loaded_at)>=Ve)throw new g("publish-plugins","directory_unavailable",`the directory did not answer for: ${S.unavailable.slice(0,10).join(", ")}; rerun the import once it is reachable`,{plugins:S.unavailable});await p.assertOwned(),await H(e.run_id,"waiting_for_directory");return}j.push(...S.refused),await i("stage");const U=await Le(a,e.run_id,t.counts,d=>L(e.run_id,d,t),d=>n.get(d));for(const[d,u]of Object.entries(U))l[d]={staged:u,inserted:0,mapped:0,dropped:0};const w={db:a,schema:r,target:c,catalog:h,sourcePerson:t.person,targetPerson:e.person,fleetRuntime:k,shippedBodies:t.shippedBodies??{}};await i("bind-staged");for(const[d,u]of Object.entries(await ve(w)))b(l,d,u);for(const[d,u]of Object.entries(await Se(w)))b(l,d,u);await i("rewrite-person"),await Be(w),await Ne(w),await i("prune");const F=await oe(a,r,h,t),v=t.kind==="hosted"?Je(t.pathPrefixes??[]):[];await i("rewrite-paths"),await _e(a,r,v),await me(a,r,v,n,e.run_id),await we(a,r),await Re(w);const G=await Me(w);await fe(a,r,c,t.installId,e.person),await i("rewrite-ids");const T=await Ae(w,G);await i("drop");const $=await ge(a,r,c),q=await ke(w);for(const[d,u]of Object.entries({...F}))b(l,d,u);for(const[d,u]of Object.entries(q))b(l,d,u);for(const[d,u]of Object.entries(await he(w,{installId:t.installId,person:e.person,runId:e.run_id})))b(l,d,u);await Ee(w,{installId:t.installId,person:e.person,runId:e.run_id}),await De(w),await le(a,r,c,t.installId);for(const[d,u]of Object.entries(await ue(a,r,c)))b(l,d,u);b(l,"idempotency_keys",await pe(a,r,c)),b(l,"idempotency_keys",await ce(a,r)),t.kind==="hosted"&&await re(a,r),await i("pre-check");const Y=new Map([["messages",["seq"]],...ne.map(d=>[d,["seq"]])]);await de(a,r,c,h,I,new Set,Y),await i("blobs"),await je(a,r,c,e.person,n,e.run_id,f),await i("copy"),await B(e.person,()=>A(async d=>{await p.assertOwned({extendLeaseMs:Xe});const u=await se({db:d,runId:e.run_id,schema:r,target:c,catalog:h,source:t,person:e.person,idMap:T,pathMap:v}),C=await it(d,e.run_id,$);C>0&&(u.inserted.revisions=(u.inserted.revisions??0)+C),await Ue(d,r,e.run_id,t);const M=await qe({db:d,blobs:n,runId:e.run_id,person:e.person,objectMap:T.object});for(const[z,Q]of Object.entries(M.inserted))u.inserted[z]=Q.length;return P.push(...M.unresolvedPlugins),await d.prepare("UPDATE import_runs SET counts_json = ?, loaded_at = COALESCE(loaded_at, ?) WHERE run_id = ?").run(JSON.stringify({...nt(l,u),unresolved_plugins:P,refused_plugins:j}),R(),e.run_id),u})),_=!0,await s.atStep?.("committed")}await i("verify");const y=await He(a,e.run_id,r,c,h,t.installId);if(await a.prepare("UPDATE import_runs SET verify_json = ? WHERE run_id = ?").run(JSON.stringify(y),e.run_id),!y.ok)throw new g("verify","verify_failed","the committed rows differ from the staged rows or an invariant failed",{differences:y.differences,invariants:y.invariants});await i("manifest");const O=N.manifest(e.run_id);await n.put(O,await st(e.run_id)),await K(a,e.run_id);for(const l of Fe(e.run_id))await n.delete(l);await Oe(n,e.run_id),await A(async l=>{await $e(l,e.run_id,e.person),await l.prepare("UPDATE import_runs SET state = 'done', step = 'done', manifest_key = ?, finished_at = ? WHERE run_id = ?").run(O,R(),e.run_id)})}catch(t){if(t instanceof xe)throw t;const c=at(t,o);Ze({level:"error",event:"import.run.failed",error:t,fields:{run_id:e.run_id,step:c.step,code:c.code}}),await K(a,e.run_id).catch(()=>{}),_||await Ie(n,f,!0),await a.prepare("UPDATE import_runs SET state = 'failed', failure_json = ?, finished_at = ? WHERE run_id = ?").run(JSON.stringify(c),R(),e.run_id),await Pe(n,e.run_id,{keepNodeFiles:_,bestEffort:!0})}}m(Ct,"processRun");function at(e,p){if(e instanceof g)return{step:e.step,code:e.code,message:e.message,...e.detail===void 0?{}:{detail:e.detail}};const s=e.code;return{step:p,code:typeof s=="string"?s:"import_failed",message:e instanceof Error?e.message:String(e)}}m(at,"failureOf");function b(e,p,s){(e[p]??={staged:0,inserted:0,mapped:0,dropped:0}).dropped+=s}m(b,"addDropped");function nt(e,p){for(const[s,n]of Object.entries(p.inserted))(e[s]??={staged:0,inserted:0,mapped:0,dropped:0}).inserted=n;for(const[s,n]of Object.entries(p.mapped))(e[s]??={staged:0,inserted:0,mapped:0,dropped:0}).mapped=n;return e}m(nt,"withInserted");async function it(e,p,s){const n=new Set((await e.prepareUncached("SELECT rev_id FROM revisions WHERE rev_id IN (SELECT jsonb_array_elements_text(?::jsonb))").all(JSON.stringify(s.map(o=>o.rev_id)))).map(o=>o.rev_id)),a=s.filter(o=>!n.has(o.rev_id)),r=new Map;for(const o of s)r.set(o.document,[...r.get(o.document)??[],o]);for(const[o,i]of r){const _=await te(e,o);_!==null&&await ee(e,_,i.map(f=>({rev_id:f.rev_id,parents:f.parents,body_hash:f.body_hash,rationale:f.rationale,created_at:f.created_at})))}return await W(e,p,"revisions",a.map(o=>[o.rev_id])),await W(e,p,"revision_parents",a.flatMap(o=>o.parents.map(i=>[o.rev_id,i]))),a.length}m(it,"arrive");async function st(e){const s=await(await E()).prepare("SELECT table_name, inserted_keys FROM import_manifest WHERE run_id = ? ORDER BY table_name").all(e),n=x(),a=[];n.on("data",i=>a.push(i));const r=D(n,"end"),o=m(async i=>{n.write(i,"utf8")||await D(n,"drain")},"put");for(const i of s){await o(`{"table":${JSON.stringify(i.table_name)},"keys":[`);let _=!0;for await(const f of V(i.inserted_keys))await o((_?"":",")+f.map(t=>JSON.stringify(t)).join(",")),_=!1;await o(`]}
1
+ var Z=Object.defineProperty;var m=(e,p)=>Z(e,"name",{value:p,configurable:!0});import{createZstdCompress as x}from"node:zlib";import{once as D}from"node:events";import{keyBatches as V}from"./keys.js";import{blobStore as X}from"../../blobs/index.js";import{openDb as E,withCanvasWrite as A}from"../../canvas/db.js";import{runAsPerson as B}from"../../canvas/person.js";import{insertImportedRevisions as ee}from"../../graph/documents.js";import{getById as te}from"../../graph/objects.js";import{bundleKeys as N,decodeRows as ae,rowKeys as L,SEQ_TABLES as ne}from"../bundle/layout.js";import{readCatalog as ie}from"./catalog.js";import{appendManifest as W,copyRows as se}from"./copy.js";import{anchorCronsToCreator as re,pruneStaged as oe,precheck as de,dropExistingIdempotencyKeys as pe,dropExpiredIdempotencyKeys as ce,dropExistingWatches as ue,renameClashingLegacyCharges as le,renameClashingProfiles as fe,rewriteConversationHeaders as me,rewritePaths as _e,rewriteRequestPaths as we,takeRepoSyncedDocuments as ge}from"./prepare.js";import{boundSub as be,dropForeignReferences as he,checkSourcePerson as ye,checkStagedBlobKeys as Se,checkStagedPersons as ve,checkStagedReferences as Ee,checkStagedRequestKeys as Re}from"./bind.js";import{deleteBlobs as Ie,deleteRunBlobs as Oe,deleteRunPrefix as Pe,moveRunBlobs as je}from"./blobs.js";import{dropStubRows as ke,findFleetGrant as Te,grantMissing as Ce,mapProfileIds as Me,renameClashingRepos as De,rewriteIds as Ae,rewritePerson as Be,scopeRepoIdentities as Ne}from"./rewrite.js";import{dropStaging as K,ImportLaneError as g,stage as Le,stagingSchema as We,targetSchema as Ke}from"./stage.js";import{verifyRun as He}from"./verify.js";import{sandboxPathMap as Fe,writeNodeFiles as Je}from"./path-map.js";import{allStoreKeys as Ue,readPluginsStore as Ge,recordImportedActivations as $e,writeStores as qe}from"./stores.js";import{openImportGrants as Ye}from"./open-grants.js";import{publishImportedPlugins as ze}from"./publish-plugins.js";import{COPIED_TABLES as Qe}from"../bundle/layout.js";import{emitEvent as Ze}from"../../events/emit.js";import{ClaimLostError as xe}from"../../../daemon/reconcilers/row-claim.js";const Ve=10*6e4,Xe=30*6e4,R=m(()=>new Date().toISOString(),"now"),H=m(async(e,p)=>{await(await E()).prepare("UPDATE import_runs SET step = ? WHERE run_id = ?").run(p,e)},"setStep");async function et(e,p){const s=await e.get(N.source(p));if(s===null)throw new g("stage","bundle_invalid","source.json is missing");const n=JSON.parse(s.toString("utf8"));if(typeof n.rowParts!="object"||n.rowParts===null)throw new g("stage","bundle_invalid","source.json names no row parts");return n}m(et,"readSource");async function tt(e,p,s,n,a,r,o){const i=[];for(const t of L(s.run_id,"grants",n)){const c=await e.get(t);if(c===null)throw new g("stage","bundle_invalid",`row file ${t} is missing`);i.push(...ae(c))}if(i.length===0)return;const _=i.map(t=>({sub:be(t.sub,n.person,s.person,"grants.sub"),grantee:t.grantee}));await o(s.run_id);const f=[];for(const t of _)await Te(p,a,r,t.sub,t.grantee)===void 0&&f.push(t.grantee);if(f.length>0)throw Ce(f)}m(tt,"ensureGrants");async function Ct(e,p,s={}){const n=s.blobs??await X(),a=await E(),r=We(e.run_id);let o="start";const i=m(async t=>{o=t,await p.assertOwned(),await H(e.run_id,t),await s.atStep?.(t)},"at");let _=e.state==="committed";const f=[];try{const t=await et(n,e.run_id);if(e.source_kind==="machine"&&t.installId!==e.source_install_id)throw new g("stage","bundle_invalid",`source.json names install ${t.installId}, the run is for ${e.source_install_id}`);t.installId=e.source_install_id;const c=await Ke(a),I=[...Qe],h=await ie(a,c,[...I,"grants"]);if(!_){const l={},P=[],j=[],k=s.fleetRuntime??process.env.CRTR_RUNTIME??null;await ye(a,c,t.person,e.person),await i("open-grants"),await tt(n,a,e,t,c,k,s.openGrants??Ye),await i("publish-plugins");const F=await Ge(n,e.run_id),S=await B(e.person,()=>ze(F));if(S.unavailable.length>0){if(e.loaded_at===void 0||e.loaded_at===null)throw new g("publish-plugins","import_failed","a loading run has no loaded_at");if(Date.now()-Date.parse(e.loaded_at)>=Ve)throw new g("publish-plugins","directory_unavailable",`the directory did not answer for: ${S.unavailable.slice(0,10).join(", ")}; rerun the import once it is reachable`,{plugins:S.unavailable});await p.assertOwned(),await H(e.run_id,"waiting_for_directory");return}j.push(...S.refused),await i("stage");const J=await Le(a,e.run_id,t.counts,d=>L(e.run_id,d,t),d=>n.get(d));for(const[d,u]of Object.entries(J))l[d]={staged:u,inserted:0,mapped:0,dropped:0};const w={db:a,schema:r,target:c,catalog:h,sourcePerson:t.person,targetPerson:e.person,fleetRuntime:k,shippedBodies:t.shippedBodies??{}};await i("bind-staged");for(const[d,u]of Object.entries(await ve(w)))b(l,d,u);for(const[d,u]of Object.entries(await Se(w)))b(l,d,u);await i("rewrite-person"),await Be(w),await Ne(w),await i("prune");const U=await oe(a,r,h,t),v=t.kind==="hosted"?Fe(t.pathPrefixes??[]):[];await i("rewrite-paths"),await _e(a,r,v),await me(a,r,v,n,e.run_id),await we(a,r),await Re(w);const G=await Me(w);await fe(a,r,c,t.installId,e.person),await i("rewrite-ids");const T=await Ae(w,G);await i("drop");const $=await ge(a,r,c),q=await ke(w);for(const[d,u]of Object.entries({...U}))b(l,d,u);for(const[d,u]of Object.entries(q))b(l,d,u);for(const[d,u]of Object.entries(await he(w,{installId:t.installId,person:e.person,runId:e.run_id})))b(l,d,u);await Ee(w,{installId:t.installId,person:e.person,runId:e.run_id}),await De(w),await le(a,r,c,t.installId);for(const[d,u]of Object.entries(await ue(a,r,c)))b(l,d,u);b(l,"idempotency_keys",await pe(a,r,c)),b(l,"idempotency_keys",await ce(a,r)),t.kind==="hosted"&&await re(a,r),await i("pre-check");const Y=new Map([["messages",["seq"]],...ne.map(d=>[d,["seq"]])]);await de(a,r,c,h,I,new Set,Y),await i("blobs"),await je(a,r,c,e.person,n,e.run_id,f),await i("copy"),await B(e.person,()=>A(async d=>{await p.assertOwned({extendLeaseMs:Xe});const u=await se({db:d,runId:e.run_id,schema:r,target:c,catalog:h,source:t,person:e.person,idMap:T,pathMap:v}),C=await it(d,e.run_id,$);C>0&&(u.inserted.revisions=(u.inserted.revisions??0)+C),await Je(d,r,e.run_id,t);const M=await qe({db:d,blobs:n,runId:e.run_id,person:e.person,objectMap:T.object});for(const[z,Q]of Object.entries(M.inserted))u.inserted[z]=Q.length;return P.push(...M.unresolvedPlugins),await d.prepare("UPDATE import_runs SET counts_json = ?, loaded_at = COALESCE(loaded_at, ?) WHERE run_id = ?").run(JSON.stringify({...nt(l,u),unresolved_plugins:P,refused_plugins:j}),R(),e.run_id),u})),_=!0,await s.atStep?.("committed")}await i("verify");const y=await He(a,e.run_id,r,c,h,t.installId);if(await a.prepare("UPDATE import_runs SET verify_json = ? WHERE run_id = ?").run(JSON.stringify(y),e.run_id),!y.ok)throw new g("verify","verify_failed","the committed rows differ from the staged rows or an invariant failed",{differences:y.differences,invariants:y.invariants});await i("manifest");const O=N.manifest(e.run_id);await n.put(O,await st(e.run_id)),await K(a,e.run_id);for(const l of Ue(e.run_id))await n.delete(l);await Oe(n,e.run_id),await A(async l=>{await $e(l,e.run_id,e.person),await l.prepare("UPDATE import_runs SET state = 'done', step = 'done', manifest_key = ?, finished_at = ? WHERE run_id = ?").run(O,R(),e.run_id)})}catch(t){if(t instanceof xe)throw t;const c=at(t,o);Ze({level:"error",event:"import.run.failed",error:t,fields:{run_id:e.run_id,step:c.step,code:c.code}}),await K(a,e.run_id).catch(()=>{}),_||await Ie(n,f,!0),await a.prepare("UPDATE import_runs SET state = 'failed', failure_json = ?, finished_at = ? WHERE run_id = ?").run(JSON.stringify(c),R(),e.run_id),_&&await Pe(n,e.run_id,{keepNodeFiles:!0,bestEffort:!0})}}m(Ct,"processRun");function at(e,p){if(e instanceof g)return{step:e.step,code:e.code,message:e.message,...e.detail===void 0?{}:{detail:e.detail}};const s=e.code;return{step:p,code:typeof s=="string"?s:"import_failed",message:e instanceof Error?e.message:String(e)}}m(at,"failureOf");function b(e,p,s){(e[p]??={staged:0,inserted:0,mapped:0,dropped:0}).dropped+=s}m(b,"addDropped");function nt(e,p){for(const[s,n]of Object.entries(p.inserted))(e[s]??={staged:0,inserted:0,mapped:0,dropped:0}).inserted=n;for(const[s,n]of Object.entries(p.mapped))(e[s]??={staged:0,inserted:0,mapped:0,dropped:0}).mapped=n;return e}m(nt,"withInserted");async function it(e,p,s){const n=new Set((await e.prepareUncached("SELECT rev_id FROM revisions WHERE rev_id IN (SELECT jsonb_array_elements_text(?::jsonb))").all(JSON.stringify(s.map(o=>o.rev_id)))).map(o=>o.rev_id)),a=s.filter(o=>!n.has(o.rev_id)),r=new Map;for(const o of s)r.set(o.document,[...r.get(o.document)??[],o]);for(const[o,i]of r){const _=await te(e,o);_!==null&&await ee(e,_,i.map(f=>({rev_id:f.rev_id,parents:f.parents,body_hash:f.body_hash,rationale:f.rationale,created_at:f.created_at})))}return await W(e,p,"revisions",a.map(o=>[o.rev_id])),await W(e,p,"revision_parents",a.flatMap(o=>o.parents.map(i=>[o.rev_id,i]))),a.length}m(it,"arrive");async function st(e){const s=await(await E()).prepare("SELECT table_name, inserted_keys FROM import_manifest WHERE run_id = ? ORDER BY table_name").all(e),n=x(),a=[];n.on("data",i=>a.push(i));const r=D(n,"end"),o=m(async i=>{n.write(i,"utf8")||await D(n,"drain")},"put");for(const i of s){await o(`{"table":${JSON.stringify(i.table_name)},"keys":[`);let _=!0;for await(const f of V(i.inserted_keys))await o((_?"":",")+f.map(t=>JSON.stringify(t)).join(",")),_=!1;await o(`]}
2
2
  `)}return n.end(),await r,Buffer.concat(a)}m(st,"manifestFile");export{Xe as COPY_LEASE_MS,Ve as GRANT_WAIT_MS,Ct as processRun};
@@ -1 +1 @@
1
- var v=Object.defineProperty;var a=(t,n)=>v(t,"name",{value:n,configurable:!0});import{randomBytes as $}from"node:crypto";import{ApiError as o}from"../../../api/errors.js";import{blobStore as c}from"../../../core/blobs/index.js";import{presignPutUrl as O,r2ConfigFromEnv as T}from"../../../core/blobs/r2.js";import{openDb as m}from"../../../core/canvas/db.js";import{emitEvent as R}from"../../../core/events/emit.js";import{bundleKeys as f}from"../../../core/import/bundle/layout.js";import{deleteRunPrefix as D}from"../../../core/import/load/blobs.js";import{putStore as N,StoreBodyError as A,STORE_NAMES as P}from"../../../core/import/load/stores.js";import{rollbackRun as j}from"../../../core/import/load/rollback.js";import{crtrVersion as y}from"../../../shared/crtr-version.js";import{importTokenFor as I}from"../import-auth.js";const g=3600;function b(t){if(t.principal.class!=="person"||t.principal.sub===void 0)throw new o(403,"person_only","an import is made by a signed-in person");return t.principal.sub}a(b,"personOf");async function _(t,n=!1){const e=t.params.run_id??"",r=await(await m()).prepare("SELECT * FROM import_runs WHERE run_id = ?").get(e),s=t.principal;if(s.class==="import"){if(s.run===null&&!n)throw new o(403,"permission_error","the service credential starts and reads runs; the import token uploads and loads");if(r===void 0||(s.run===null?r.source_kind!=="hosted":s.run!==r.run_id))throw new o(404,"import_not_found",`no import run ${e}`);if(s.run!==null&&!n&&r.state!=="uploading"&&r.state!=="loading")throw new o(403,"import_token_expired",`import run ${r.run_id} is ${r.state}: its import token no longer works`);return r}if(r===void 0||r.person!==b(t))throw new o(404,"import_not_found",`no import run ${e}`);return r}a(_,"ownRun");function U(t,n,e){const r=t.principal;if(r.class!=="import")return b(t);if(r.run!==null)throw new o(403,"permission_error","an import token reaches only its own run");const s=n.person;if(typeof s!="string"||!/^user:.+/.test(s))throw new o(400,"invalid_body","person (user:<id>) is required");if(e!=="hosted")throw new o(400,"invalid_body","the service credential starts hosted runs only: source_kind must be hosted");return s}a(U,"startPerson");const S=a(t=>{if(t===null||typeof t!="object"||Array.isArray(t))throw new o(400,"invalid_body","the body must be a JSON object");return t},"objectBody");async function L(t){const n=S(t.body),e=U(t,n,n.source_kind),r=n.source_install_id,s=n.source_kind,d=n.release;if(typeof r!="string"||r===""||s!=="machine"&&s!=="hosted"||typeof d!="string")throw new o(400,"invalid_body","source_install_id, source_kind (machine | hosted) and release are required");if(d!==y())throw new o(409,"release_mismatch",`the source runs ${d}, the control plane accepts ${y()}`);const p=await m();let i=await p.prepare("SELECT run_id, state FROM import_runs WHERE source_install_id = ? AND state IN ('uploading', 'loading', 'committed', 'done')").get(r);if(i?.state==="uploading"){const k={step:"uploading",code:"superseded",message:`a new import run was started for install ${r} before this one asked for the load`};await p.prepare("UPDATE import_runs SET state = 'failed', failure_json = ?, finished_at = ? WHERE run_id = ? AND state = 'uploading'").run(JSON.stringify(k),new Date().toISOString(),i.run_id);const h=i.run_id;c().then(w=>D(w,h,{bestEffort:!0})).catch(w=>R({level:"warn",event:"import.prefix_delete_failed",error:w,fields:{run_id:h}})),i=await p.prepare("SELECT run_id, state FROM import_runs WHERE source_install_id = ? AND state IN ('uploading', 'loading', 'committed', 'done')").get(r)}if(i?.state==="done")throw new o(409,"already_imported",`install ${r} was imported by run ${i.run_id}`);if(i!==void 0)throw new o(409,"import_running",`install ${r} has an open run ${i.run_id} (${i.state})`);const u=`imp_${$(8).toString("hex")}`;await p.prepare("INSERT INTO import_runs (run_id, source_install_id, source_kind, person, release, state, created_at) VALUES (?, ?, ?, ?, ?, 'uploading', ?)").run(u,r,s,e,d,new Date().toISOString());const l=t.principal.class==="import"?I(u):null;return{status:201,body:{run_id:u,upload:{rows_prefix:f.prefix(u),url_template:`POST /v1/imports/${u}/upload-urls {"keys":[...]}`},...l===null?{}:{import_token:l}}}}a(L,"handleStart");async function W(t){const n=await _(t);if(n.state!=="uploading")throw new o(409,"import_not_uploading",`import run ${n.run_id} is ${n.state}`);const e=S(t.body).keys;if(!Array.isArray(e)||e.some(i=>typeof i!="string"))throw new o(400,"invalid_body","keys must be a list of blob keys");const r=f.prefix(n.run_id);for(const i of e)if(!(i.startsWith(r)&&!i.startsWith(`${r}stores/`)&&i!==f.manifest(n.run_id))||i.split("/").some(l=>l===""||l==="."||l===".."))throw new o(400,"invalid_key",`${i} is not a key this run may upload`);const s=T();if(s===null)throw new o(501,"upload_not_supported","this control plane keeps blobs in a directory: there is no URL to upload to");const d={};for(const i of e)d[i]=O(s,i,g);return{status:200,body:{urls:d,expires_at:new Date(Date.now()+g*1e3).toISOString()}}}a(W,"handleUploadUrls");async function C(t){const n=await _(t);if(n.state!=="uploading")throw new o(409,"import_not_uploading",`import run ${n.run_id} is ${n.state}`);const e=t.params.name;if(!P.includes(e))throw new o(404,"unknown_store",`no file store ${e}`);try{await N(await c(),n.run_id,e,t.body)}catch(r){throw r instanceof A?new o(400,"invalid_body",r.message):r}return{status:204}}a(C,"handleStore");async function F(t){const n=await _(t),e=await m();if(n.state==="uploading"){if(await(await c()).get(f.source(n.run_id))===null)throw new o(409,"bundle_invalid","source.json is not uploaded");await e.prepare("UPDATE import_runs SET state = 'loading', step = 'queued', loaded_at = ? WHERE run_id = ? AND state = 'uploading'").run(new Date().toISOString(),n.run_id)}else if(n.state!=="loading"&&n.state!=="committed"&&n.state!=="done")throw new o(409,"import_not_uploading",`import run ${n.run_id} is ${n.state}`);return{status:202,body:await E(n.run_id)}}a(F,"handleLoad");async function E(t){const n=await(await m()).prepare("SELECT * FROM import_runs WHERE run_id = ?").get(t),e=n.counts_json===null?{}:JSON.parse(n.counts_json),{unresolved_plugins:r,refused_plugins:s,...d}=e;return{run_id:n.run_id,source_install_id:n.source_install_id,source_kind:n.source_kind,person:n.person,release:n.release,state:n.state,step:n.step,counts:d,verify:n.verify_json===null?null:JSON.parse(n.verify_json),failure:n.failure_json===null?null:JSON.parse(n.failure_json),unresolved_plugins:r??[],refused_plugins:s??[],created:n.created_at,loaded:n.loaded_at,finished:n.finished_at}}a(E,"runDto");async function H(t){const n=await _(t,!0);return{status:200,body:await E(n.run_id)}}a(H,"handleGet");async function J(t){const n=await _(t),e=await j(n.run_id,await c());if(!e.rolled_back)throw new o(409,"rollback_has_dependents",`later rows depend on import run ${n.run_id}`,e.dependents);return{status:200,body:e}}a(J,"handleRollback");const rn=[{method:"POST",pattern:"/v1/imports",handler:L},{method:"POST",pattern:"/v1/imports/:run_id/upload-urls",handler:W},{method:"PUT",pattern:"/v1/imports/:run_id/stores/:name",handler:C},{method:"POST",pattern:"/v1/imports/:run_id/load",handler:F},{method:"GET",pattern:"/v1/imports/:run_id",handler:H},{method:"POST",pattern:"/v1/imports/:run_id/rollback",handler:J}];export{rn as importRoutes};
1
+ var $=Object.defineProperty;var s=(n,t)=>$(n,"name",{value:t,configurable:!0});import{randomBytes as O}from"node:crypto";import{ApiError as o}from"../../../api/errors.js";import{blobStore as c}from"../../../core/blobs/index.js";import{presignPutUrl as T,r2ConfigFromEnv as v}from"../../../core/blobs/r2.js";import{openDb as m}from"../../../core/canvas/db.js";import{emitEvent as D}from"../../../core/events/emit.js";import{bundleKeys as f}from"../../../core/import/bundle/layout.js";import{FAILED_UPLOAD_RETENTION_DAYS as N,UPLOAD_DELETED_STEP as R,deleteRunPrefix as A}from"../../../core/import/load/blobs.js";import{putStore as L,StoreBodyError as P,STORE_NAMES as U}from"../../../core/import/load/stores.js";import{rollbackRun as I}from"../../../core/import/load/rollback.js";import{crtrVersion as g}from"../../../shared/crtr-version.js";import{importTokenFor as j}from"../import-auth.js";const E=3600;function b(n){if(n.principal.class!=="person"||n.principal.sub===void 0)throw new o(403,"person_only","an import is made by a signed-in person");return n.principal.sub}s(b,"personOf");async function p(n,t=!1){const r=n.params.run_id??"",e=await(await m()).prepare("SELECT * FROM import_runs WHERE run_id = ?").get(r),i=n.principal;if(i.class==="import"){if(i.run===null&&!t)throw new o(403,"permission_error","the service credential starts and reads runs; the import token uploads and loads");if(e===void 0||(i.run===null?e.source_kind!=="hosted":i.run!==e.run_id))throw new o(404,"import_not_found",`no import run ${r}`);if(i.run!==null&&!t&&e.state!=="uploading"&&e.state!=="loading")throw new o(403,"import_token_expired",`import run ${e.run_id} is ${e.state}: its import token no longer works`);return e}if(e===void 0||e.person!==b(n))throw new o(404,"import_not_found",`no import run ${r}`);return e}s(p,"ownRun");function W(n,t,r){const e=n.principal;if(e.class!=="import")return b(n);if(e.run!==null)throw new o(403,"permission_error","an import token reaches only its own run");const i=t.person;if(typeof i!="string"||!/^user:.+/.test(i))throw new o(400,"invalid_body","person (user:<id>) is required");if(r!=="hosted")throw new o(400,"invalid_body","the service credential starts hosted runs only: source_kind must be hosted");return i}s(W,"startPerson");const S=s(n=>{if(n===null||typeof n!="object"||Array.isArray(n))throw new o(400,"invalid_body","the body must be a JSON object");return n},"objectBody");async function F(n){const t=S(n.body),r=W(n,t,t.source_kind),e=t.source_install_id,i=t.source_kind,d=t.release;if(typeof e!="string"||e===""||i!=="machine"&&i!=="hosted"||typeof d!="string")throw new o(400,"invalid_body","source_install_id, source_kind (machine | hosted) and release are required");if(d!==g())throw new o(409,"release_mismatch",`the source runs ${d}, the control plane accepts ${g()}`);const _=await m();let a=await _.prepare("SELECT run_id, state FROM import_runs WHERE source_install_id = ? AND state IN ('uploading', 'loading', 'committed', 'done')").get(e);if(a?.state==="uploading"){const k={step:"uploading",code:"superseded",message:`a new import run was started for install ${e} before this one asked for the load`};await _.prepare("UPDATE import_runs SET state = 'failed', failure_json = ?, finished_at = ? WHERE run_id = ? AND state = 'uploading'").run(JSON.stringify(k),new Date().toISOString(),a.run_id);const y=a.run_id;c().then(h=>A(h,y,{bestEffort:!0})).catch(h=>D({level:"warn",event:"import.prefix_delete_failed",error:h,fields:{run_id:y}})),a=await _.prepare("SELECT run_id, state FROM import_runs WHERE source_install_id = ? AND state IN ('uploading', 'loading', 'committed', 'done')").get(e)}if(a?.state==="done")throw new o(409,"already_imported",`install ${e} was imported by run ${a.run_id}`);if(a!==void 0)throw new o(409,"import_running",`install ${e} has an open run ${a.run_id} (${a.state})`);const u=`imp_${O(8).toString("hex")}`;await _.prepare("INSERT INTO import_runs (run_id, source_install_id, source_kind, person, release, state, created_at) VALUES (?, ?, ?, ?, ?, 'uploading', ?)").run(u,e,i,r,d,new Date().toISOString());const l=n.principal.class==="import"?j(u):null;return{status:201,body:{run_id:u,upload:{rows_prefix:f.prefix(u),url_template:`POST /v1/imports/${u}/upload-urls {"keys":[...]}`},...l===null?{}:{import_token:l}}}}s(F,"handleStart");async function H(n){const t=await p(n);if(t.state!=="uploading")throw new o(409,"import_not_uploading",`import run ${t.run_id} is ${t.state}`);const r=S(n.body).keys;if(!Array.isArray(r)||r.some(a=>typeof a!="string"))throw new o(400,"invalid_body","keys must be a list of blob keys");const e=f.prefix(t.run_id);for(const a of r)if(!(a.startsWith(e)&&!a.startsWith(`${e}stores/`)&&a!==f.manifest(t.run_id))||a.split("/").some(l=>l===""||l==="."||l===".."))throw new o(400,"invalid_key",`${a} is not a key this run may upload`);const i=v();if(i===null)throw new o(501,"upload_not_supported","this control plane keeps blobs in a directory: there is no URL to upload to");const d={};for(const a of r)d[a]=T(i,a,E);return{status:200,body:{urls:d,expires_at:new Date(Date.now()+E*1e3).toISOString()}}}s(H,"handleUploadUrls");async function C(n){const t=await p(n);if(t.state!=="uploading")throw new o(409,"import_not_uploading",`import run ${t.run_id} is ${t.state}`);const r=n.params.name;if(!U.includes(r))throw new o(404,"unknown_store",`no file store ${r}`);try{await L(await c(),t.run_id,r,n.body)}catch(e){throw e instanceof P?new o(400,"invalid_body",e.message):e}return{status:204}}s(C,"handleStore");async function M(n){const t=await p(n),r=await m();if(t.state==="uploading"){if(await(await c()).get(f.source(t.run_id))===null)throw new o(409,"bundle_invalid","source.json is not uploaded");await r.prepare("UPDATE import_runs SET state = 'loading', step = 'queued', loaded_at = ? WHERE run_id = ? AND state = 'uploading'").run(new Date().toISOString(),t.run_id)}else if(t.state!=="loading"&&t.state!=="committed"&&t.state!=="done")throw new o(409,"import_not_uploading",`import run ${t.run_id} is ${t.state}`);return{status:202,body:await w(t.run_id)}}s(M,"handleLoad");async function J(n){const t=await p(n),r=await m();if(t.state==="loading")return{status:202,body:await w(t.run_id)};const e=(await r.prepare("SELECT committed_at FROM import_runs WHERE run_id = ?").get(t.run_id)).committed_at;if(t.state!=="failed"||e!==null)throw new o(409,"import_not_retryable",`import run ${t.run_id} is ${t.state}${e===null?"":" and its copy committed (roll it back instead)"}: only a run that failed before its copy can be retried`);if(t.step===R||await(await c()).get(f.source(t.run_id))===null)throw new o(409,"upload_gone",`the uploaded bundle of import run ${t.run_id} was deleted (kept ${N} days): run the import again`);const i=await r.prepare("SELECT run_id FROM import_runs WHERE source_install_id = ? AND run_id <> ? AND state IN ('uploading', 'loading', 'committed', 'done')").get(t.source_install_id,t.run_id);if(i!==void 0)throw new o(409,"import_running",`install ${t.source_install_id} has another open run ${i.run_id}`);return await r.prepare("UPDATE import_runs SET state = 'loading', step = 'queued', failure_json = NULL, finished_at = NULL, loaded_at = ?, claimed_by = NULL, lease_expires_at = NULL WHERE run_id = ? AND state = 'failed'").run(new Date().toISOString(),t.run_id),{status:202,body:await w(t.run_id)}}s(J,"handleRetry");async function w(n){const t=await(await m()).prepare("SELECT * FROM import_runs WHERE run_id = ?").get(n),r=t.counts_json===null?{}:JSON.parse(t.counts_json),{unresolved_plugins:e,refused_plugins:i,...d}=r;return{run_id:t.run_id,source_install_id:t.source_install_id,source_kind:t.source_kind,person:t.person,release:t.release,state:t.state,step:t.step,counts:d,verify:t.verify_json===null?null:JSON.parse(t.verify_json),failure:t.failure_json===null?null:JSON.parse(t.failure_json),unresolved_plugins:e??[],refused_plugins:i??[],created:t.created_at,loaded:t.loaded_at,finished:t.finished_at}}s(w,"runDto");async function q(n){const t=await p(n,!0);return{status:200,body:await w(t.run_id)}}s(q,"handleGet");async function B(n){const t=await p(n),r=await I(t.run_id,await c());if(!r.rolled_back)throw new o(409,"rollback_has_dependents",`later rows depend on import run ${t.run_id}`,r.dependents);return{status:200,body:r}}s(B,"handleRollback");const it=[{method:"POST",pattern:"/v1/imports",handler:F},{method:"POST",pattern:"/v1/imports/:run_id/upload-urls",handler:H},{method:"PUT",pattern:"/v1/imports/:run_id/stores/:name",handler:C},{method:"POST",pattern:"/v1/imports/:run_id/load",handler:M},{method:"GET",pattern:"/v1/imports/:run_id",handler:q},{method:"POST",pattern:"/v1/imports/:run_id/retry",handler:J},{method:"POST",pattern:"/v1/imports/:run_id/rollback",handler:B}];export{it as importRoutes};