@north-light/cli 0.3.757 → 0.3.759
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/contract.d.ts +1 -1
- package/dist/api/contract.js +1 -1
- package/dist/builtin-memory/crouter-sdk/release-notes.md +6 -0
- package/dist/commands/sys/import/move.d.ts +5 -0
- package/dist/commands/sys/import/move.js +7 -7
- package/dist/commands/sys/import/retry.d.ts +1 -0
- package/dist/commands/sys/import/retry.js +1 -0
- package/dist/commands/sys/import/start.js +1 -1
- package/dist/core/grants/mirror.js +2 -2
- package/dist/core/grants/shadow.js +1 -1
- package/dist/core/import/export/cloud.d.ts +1 -0
- package/dist/core/import/export/cloud.js +1 -1
- package/dist/core/import/load/bind.d.ts +5 -4
- package/dist/core/import/load/bind.js +16 -16
- package/dist/core/import/load/blobs.d.ts +6 -0
- package/dist/core/import/load/blobs.js +1 -1
- package/dist/core/import/load/prepare.js +8 -8
- package/dist/core/import/load/run.js +1 -1
- package/dist/daemon/api/handlers/imports.js +1 -1
- package/dist/daemon/api/handlers/providers.js +1 -1
- package/dist/daemon/api/operations.js +1 -1
- package/dist/daemon/reconcilers/storage-maintenance.js +1 -1
- package/docs/sdk/release-notes.md +6 -0
- package/package.json +3 -3
- package/packages/crouter-api/dist/api/contract.js +1 -1
- package/packages/crouter-api/dist/commands/sys/import/move.js +1 -1
- package/packages/crouter-api/dist/commands/sys/import/retry.js +38 -0
- package/packages/crouter-api/dist/commands/sys/import/start.js +2 -1
- package/packages/crouter-api/dist/core/grants/mirror.js +2 -2
- package/packages/crouter-api/dist/core/grants/shadow.js +25 -1
- package/packages/crouter-api/dist/core/import/export/cloud.js +1 -0
- package/packages/crouter-api/dist/core/import/load/prepare.js +2 -2
- package/packages/crouter-api/dist/daemon/api/handlers/providers.js +6 -4
- package/packages/crouter-api/dist/daemon/api/operations.js +1 -0
- package/packages/crouter-api/package.json +1 -1
- package/packages/crouter-identity/dist/index.js +5 -2
- package/packages/crouter-identity/package.json +1 -1
- package/packages/crouter-plugin/package.json +3 -3
- package/runtime.lock.json +14 -14
package/dist/api/contract.d.ts
CHANGED
|
@@ -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.
|
|
2
|
+
export declare const CONTRACT_LEVEL = "1.80";
|
|
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`. */
|
package/dist/api/contract.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var c=Object.defineProperty;var e=(r,t)=>c(r,"name",{value:t,configurable:!0});const f="1.
|
|
1
|
+
var c=Object.defineProperty;var e=(r,t)=>c(r,"name",{value:t,configurable:!0});const f="1.80",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};
|
|
@@ -9,6 +9,12 @@ when-and-why-to-read: When you need Release notes, this knowledge should be read
|
|
|
9
9
|
|
|
10
10
|
Changes to `@north-light/sdk` that can change what an existing app sees. Newest first.
|
|
11
11
|
|
|
12
|
+
## 0.3.759
|
|
13
|
+
|
|
14
|
+
### A grant can hold a whole provider as `<provider>:*`
|
|
15
|
+
|
|
16
|
+
`grant.get().resolved_scopes` may contain `<provider>:*` (for example `integrations:*`) in place of one entry per group. It means every group of that provider the grant may hold. Check a scope with the new `holds(resolved_scopes, scope)` export instead of comparing strings, because `integrations:gmail` is held while only `integrations:*` is listed. The directory sends this form only to a runtime that understands it.
|
|
17
|
+
|
|
12
18
|
## 0.3.755
|
|
13
19
|
|
|
14
20
|
### An app can start runs in its own environment with no person
|
|
@@ -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
|
|
2
|
-
`),await y(n),n=Math.min(n*2,
|
|
3
|
-
`),l=p,n.name=m},"next"),u=X(g(Z(),"crtr-import-")),S=
|
|
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
|
|
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
|
|
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
|
|
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(
|
|
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
|
|
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};
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
var I=Object.defineProperty;var n=(e,r)=>I(e,"name",{value:r,configurable:!0});import{createHash as L}from"node:crypto";import{parsePrincipal as T,parseScope as C}from"@north-light/identity";import{openDb as d,withCanvasWrite as M}from"../canvas/db.js";import{isUnsandboxedMachine as A}from"../runtime/unsandboxed.js";import{replaceWrittenBy as O,userSubject as F}from"../permissions/facts.js";import{GROUP_TYPE as f,OBJECT_TYPE as $}from"../permissions/builtin.js";import{shadowCheck as k}from"./shadow.js";const U=["not_started","pending","ready","failed","unavailable"],P=["ultra","strong","medium","light"];function G(e,r,t){if(e==null||e==="user")return r;if(e==="app")return t;if(typeof e!="string"||T(e)===null)throw new TypeError("invalid grant payer");return e}n(G,"principalPayer");function H(e){const r=e.payer===null?null:T(e.payer);return r!==null&&r.kind==="app"&&r.path.length===0}n(H,"endpointPays");function x(){const e=process.env.CRTR_RUNTIME;return e?{sql:" AND runtime = ?",args:[e]}:{sql:"",args:[]}}n(x,"runtimeScope");async function c(e,r,t=[]){const s=x();return await(await d()).prepare(`SELECT ${e} FROM grants WHERE (${r})${s.sql}`).all(...t,...s.args)}n(c,"grantRows");async function u(e,r,t=[]){return(await c(e,r,t))[0]}n(u,"grantRow");function W(e){return!/\u0000|[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/.test(e)}n(W,"jsonbSafe");function l(e){if(!Array.isArray(e))throw new TypeError("grant scopes must be a list");return e.map(r=>{if(!r||typeof r!="object"||typeof r.scope!="string"||!W(r.scope)||!["always","ask"].includes(r.mode))throw new TypeError("invalid grant scope entry");return{scope:r.scope,mode:r.mode}})}n(l,"entries");function J(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const{state:r,message:t,next:s,step:o}=e;return typeof r!="string"||!U.includes(r)||t!==void 0&&typeof t!="string"||o!==void 0&&typeof o!="string"||typeof s!="string"||!s?null:{state:r,...t===void 0?{}:{message:t},next:s,...o===void 0?{}:{step:o}}}n(J,"dependencyOf");function j(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const r={};for(const[t,s]of Object.entries(e)){const o=J(s);o&&(r[t]=o)}return r}n(j,"dependenciesOf");function V(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const{base_url:r,rungs:t}=e;if(typeof r!="string"||!r||!t||typeof t!="object"||Array.isArray(t))return null;const s={};for(const o of P){const a=t[o];typeof a=="string"&&a&&(s[o]=a)}return Object.keys(s).length?{base_url:r.replace(/\/+$/,""),rungs:s}:null}n(V,"inferenceEndpointOf");function w(e,r,t,s){return r===e&&t&&s}n(w,"computedFor");function _(e){if(!w(e.rev,e.computed_rev,e.scopes_json!==null,e.resolved_scopes_json!==null))throw new TypeError("grant columns are not computed for this revision");return{id:e.id,runtime:e.runtime,sub:e.sub,grantee:e.grantee,grantee_prefix:e.grantee_prefix??null,rev:e.rev,scopes:l(JSON.parse(e.scopes_json)),resolved_scopes:l(JSON.parse(e.resolved_scopes_json)),spend_cap:e.spend_cap,expires_at:e.expires_at,status:e.status,revoked_at:e.revoked_at,approved_at:e.approved_at,payer:e.payer,dependencies:j(JSON.parse(e.dependencies_json??"{}")),run_notice_url:e.run_notice_url??null,inference_endpoint:e.inference_endpoint_json?V(JSON.parse(e.inference_endpoint_json)):null,synced_at:e.synced_at??""}}n(_,"record");function p(e){if(!e||e.status!=="active")return null;try{const r=Z(_(e));return r!==null&&k(r),r}catch(r){if(r instanceof TypeError||r instanceof SyntaxError)return null;throw r}}n(p,"active");function y(e){return e.grantee!=="app:terminal"&&A()}n(y,"mirrorOnly");async function de(){return(await Y()).filter(e=>!y(e))}n(de,"localGrants");async function le(e,r){return!y({grantee:e})&&await u("1","grantee = ? AND sub <> ? AND status <> 'removed'",[e,r])!==void 0}n(le,"otherLiveGrantOfApp");const g="[A-Za-z0-9_-]{1,64}",q=new RegExp(`^(${g}):(${g})$`);function B(e){const r=new Set;for(const t of e)if(t.status==="active")for(const{scope:s}of t.resolved_scopes){const o=q.exec(s);o&&o[1]!=="crtr"&&r.add(o[1])}return[...r].sort()}n(B,"providerIdsFromGrants");async function fe(){const e=x();return(await(await d()).prepare(`SELECT DISTINCT m[1] AS id FROM (
|
|
1
|
+
var I=Object.defineProperty;var n=(e,r)=>I(e,"name",{value:r,configurable:!0});import{createHash as L}from"node:crypto";import{parsePrincipal as T,parseScope as C}from"@north-light/identity";import{openDb as d,withCanvasWrite as M}from"../canvas/db.js";import{isUnsandboxedMachine as A}from"../runtime/unsandboxed.js";import{replaceWrittenBy as O,userSubject as F}from"../permissions/facts.js";import{GROUP_TYPE as f,OBJECT_TYPE as $}from"../permissions/builtin.js";import{shadowCheck as k}from"./shadow.js";const U=["not_started","pending","ready","failed","unavailable"],P=["ultra","strong","medium","light"];function G(e,r,t){if(e==null||e==="user")return r;if(e==="app")return t;if(typeof e!="string"||T(e)===null)throw new TypeError("invalid grant payer");return e}n(G,"principalPayer");function H(e){const r=e.payer===null?null:T(e.payer);return r!==null&&r.kind==="app"&&r.path.length===0}n(H,"endpointPays");function x(){const e=process.env.CRTR_RUNTIME;return e?{sql:" AND runtime = ?",args:[e]}:{sql:"",args:[]}}n(x,"runtimeScope");async function c(e,r,t=[]){const s=x();return await(await d()).prepare(`SELECT ${e} FROM grants WHERE (${r})${s.sql}`).all(...t,...s.args)}n(c,"grantRows");async function u(e,r,t=[]){return(await c(e,r,t))[0]}n(u,"grantRow");function W(e){return!/\u0000|[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/.test(e)}n(W,"jsonbSafe");function l(e){if(!Array.isArray(e))throw new TypeError("grant scopes must be a list");return e.map(r=>{if(!r||typeof r!="object"||typeof r.scope!="string"||!W(r.scope)||!["always","ask"].includes(r.mode))throw new TypeError("invalid grant scope entry");return{scope:r.scope,mode:r.mode}})}n(l,"entries");function J(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const{state:r,message:t,next:s,step:o}=e;return typeof r!="string"||!U.includes(r)||t!==void 0&&typeof t!="string"||o!==void 0&&typeof o!="string"||typeof s!="string"||!s?null:{state:r,...t===void 0?{}:{message:t},next:s,...o===void 0?{}:{step:o}}}n(J,"dependencyOf");function j(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const r={};for(const[t,s]of Object.entries(e)){const o=J(s);o&&(r[t]=o)}return r}n(j,"dependenciesOf");function V(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const{base_url:r,rungs:t}=e;if(typeof r!="string"||!r||!t||typeof t!="object"||Array.isArray(t))return null;const s={};for(const o of P){const a=t[o];typeof a=="string"&&a&&(s[o]=a)}return Object.keys(s).length?{base_url:r.replace(/\/+$/,""),rungs:s}:null}n(V,"inferenceEndpointOf");function w(e,r,t,s){return r===e&&t&&s}n(w,"computedFor");function _(e){if(!w(e.rev,e.computed_rev,e.scopes_json!==null,e.resolved_scopes_json!==null))throw new TypeError("grant columns are not computed for this revision");return{id:e.id,runtime:e.runtime,sub:e.sub,grantee:e.grantee,grantee_prefix:e.grantee_prefix??null,rev:e.rev,scopes:l(JSON.parse(e.scopes_json)),resolved_scopes:l(JSON.parse(e.resolved_scopes_json)),spend_cap:e.spend_cap,expires_at:e.expires_at,status:e.status,revoked_at:e.revoked_at,approved_at:e.approved_at,payer:e.payer,dependencies:j(JSON.parse(e.dependencies_json??"{}")),run_notice_url:e.run_notice_url??null,inference_endpoint:e.inference_endpoint_json?V(JSON.parse(e.inference_endpoint_json)):null,synced_at:e.synced_at??""}}n(_,"record");function p(e){if(!e||e.status!=="active")return null;try{const r=Z(_(e));return r!==null&&k(r),r}catch(r){if(r instanceof TypeError||r instanceof SyntaxError)return null;throw r}}n(p,"active");function y(e){return e.grantee!=="app:terminal"&&A()}n(y,"mirrorOnly");async function de(){return(await Y()).filter(e=>!y(e))}n(de,"localGrants");async function le(e,r){return!y({grantee:e})&&await u("1","grantee = ? AND sub <> ? AND status <> 'removed'",[e,r])!==void 0}n(le,"otherLiveGrantOfApp");const g="[A-Za-z0-9_-]{1,64}",q=new RegExp(`^(${g}):(${g}|\\*)$`);function B(e){const r=new Set;for(const t of e)if(t.status==="active")for(const{scope:s}of t.resolved_scopes){const o=q.exec(s);o&&o[1]!=="crtr"&&r.add(o[1])}return[...r].sort()}n(B,"providerIdsFromGrants");async function fe(){const e=x();return(await(await d()).prepare(`SELECT DISTINCT m[1] AS id FROM (
|
|
2
2
|
SELECT DISTINCT e->>'scope' AS scope FROM (
|
|
3
3
|
SELECT t::jsonb AS j FROM (SELECT DISTINCT resolved_scopes_json AS t FROM grants WHERE ${m}${S()}${e.sql}) d OFFSET 0) p
|
|
4
4
|
CROSS JOIN LATERAL jsonb_array_elements(CASE WHEN jsonb_typeof(p.j) = 'array' THEN p.j ELSE '[]' END) e) s
|
|
5
|
-
CROSS JOIN LATERAL regexp_match(s.scope, '^(${g})
|
|
5
|
+
CROSS JOIN LATERAL regexp_match(s.scope, '^(${g}):(?:${g}|\\*)$') m
|
|
6
6
|
WHERE m[1] <> 'crtr'`).all(...e.args)).map(t=>t.id).sort()}n(fe,"activeProviderIds");async function _e(){const e=x();return await(await d()).prepare(`SELECT 1 FROM grants WHERE ${m}${S()}${e.sql} LIMIT 1`).get(...e.args)!==void 0}n(_e,"anyActiveGrant");async function ye(e,r){return await u("1",`sub = ? AND ${m}${S()} AND EXISTS (
|
|
7
7
|
SELECT 1 FROM jsonb_array_elements(CASE WHEN jsonb_typeof(resolved_scopes_json::jsonb) = 'array' THEN resolved_scopes_json::jsonb ELSE '[]' END) e
|
|
8
8
|
WHERE starts_with(e->>'scope', ?))`,[e,`${r}:`])!==void 0}n(ye,"activeGrantNamesApp");const m="status = 'active' AND computed_rev = rev AND scopes_json IS NOT NULL AND resolved_scopes_json IS NOT NULL",X="computed_rev = rev AND scopes_json IS NOT NULL AND resolved_scopes_json IS NOT NULL";function S(){return A()?" AND grantee = 'app:terminal'":""}n(S,"localOnly");async function ge(){return(await c("DISTINCT sub",X)).map(e=>e.sub)}n(ge,"grantSubs");async function Ee(e){return b(e===void 0?await c("*","status = 'active'"):await c("*","sub = ? AND status = 'active'",[e]))}n(Ee,"activeGrants");async function ve(e){const r=await c("*","sub = ? AND status = 'active'",[e]);return new Set(B(r.flatMap(t=>{try{return[_(t)]}catch(s){if(s instanceof TypeError||s instanceof SyntaxError)return[];throw s}})))}n(ve,"grantedProviderIds");function xe(e,r){return e.source_marketplace===null&&e.source_path===null&&r.has(e.name)}n(xe,"isProviderBundleRow");async function me(e){return(await c("*","sub = ? AND status = 'active'",[e])).flatMap(t=>{const s=p(t);return s===null?[]:[s]})}n(me,"activeGrantsOfPerson");async function Y(){return b(await c("*","true"))}n(Y,"allGrants");async function Se(e){return(await c("sub, status, rev, computed_rev, resolved_scopes_json, scopes_json IS NOT NULL AS has_scopes","sub = ?",[e])).flatMap(t=>{if(!w(t.rev,t.computed_rev,t.has_scopes,t.resolved_scopes_json!==null))return[];try{return[{sub:t.sub,status:t.status,resolved_scopes:l(JSON.parse(t.resolved_scopes_json))}]}catch(s){if(s instanceof TypeError||s instanceof SyntaxError)return[];throw s}})}n(Se,"grantsOfPerson");function b(e){return e.flatMap(r=>{try{return[_(r)]}catch(t){if(t instanceof TypeError||t instanceof SyntaxError)return[];throw t}})}n(b,"records");function z(e){return e.expires_at!==null&&!(Date.parse(e.expires_at)>Date.now())}n(z,"grantExpired");function Z(e){if(e.status!=="active"||z(e))return null;try{const r=e.resolved_scopes.map(({scope:t})=>C(t));return{...e,resolved:e.resolved_scopes.flatMap(({mode:t},s)=>t==="always"?[r[s]]:[])}}catch(r){if(r instanceof TypeError||r instanceof SyntaxError)return null;throw r}}n(Z,"activeRecord");function N(e){return Array.isArray(e)?`[${e.map(N).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().filter(r=>e[r]!==void 0).map(r=>`${JSON.stringify(r)}:${N(e[r])}`).join(",")}}`:JSON.stringify(e)??"null"}n(N,"canonicalJson");function Ne(e){const r={rev:e.rev,resolved_scopes:e.resolved_scopes,spend_cap:e.spend_cap,payer:e.payer,dependencies:e.dependencies??{},...e.inference_endpoint?{inference_endpoint:e.inference_endpoint}:{}};return L("sha256").update(N(r)).digest("base64url").slice(0,22)}n(Ne,"grantVersion");async function Te(e){return!!await u("1","id = ?",[e])}n(Te,"hasGrant");async function Ae(e){return await u("rev, status","id = ?",[e])??null}n(Ae,"grantSyncState");async function Oe(e,r){return await u("rev, status","grantee = ? AND sub = ?",[e,r])??null}n(Oe,"grantSyncStateFor");async function K(e){const r=await u("*","id = ?",[e]);if(!r)return null;try{return _(r)}catch(t){if(t instanceof TypeError||t instanceof SyntaxError)return null;throw t}}n(K,"grantRecord");async function je(e){const r=await u("*","id = ?",[e]);if(!r)return{standing:"inactive",rev:null,sub:null,grantee:null,status:null,removal_done_at:null,record:null};const t={rev:r.rev,sub:r.sub,grantee:r.grantee,status:r.status,removal_done_at:r.removal_done_at??null};if(r.status!=="active")return{...t,standing:"inactive",record:null};if(r.computed_rev!==r.rev)return{...t,standing:"lagging",record:null};const s=p(r);return s===null?{...t,standing:"inactive",record:null}:{...t,standing:"active",record:s}}n(je,"grantStanding");async function we(e){return(await c("id",e)).map(r=>r.id)}n(we,"grantIdsWhere");async function be(e){const r=e?await K(e):null;return r!==null&&H(r)?"app":"user"}n(be,"payerOfGrant");async function Q(e){return p(await u("*","id = ?",[e]))}n(Q,"activeGrant");async function he(e,r){const t=await u("*","grantee = ? AND grantee_prefix IS NULL AND sub = ?",[e,r]);if(t)return p(t);const s=await c("*","sub = ? AND grantee_prefix IS NOT NULL AND starts_with(?, grantee_prefix)",[r,e]);return s.sort((o,a)=>a.grantee_prefix.length-o.grantee_prefix.length),p(s[0])}n(he,"grantFor");async function Re(e){if(y({grantee:e}))return null;const r=await c("*","grantee = ? AND status = 'active'",[e]);if(r.length>1)throw new Error(`multiple active grants for ${e}`);return p(r[0])}n(Re,"activeGrantForApp");async function De(e){const r=await Q(e);return r&&r.run_notice_url&&!y(r)?{url:r.run_notice_url,sub:r.sub,grantee:r.grantee}:null}n(De,"runNoticeTarget");async function Ie(e){const r=await c("*","grantee = 'app:terminal' AND sub = ? AND status = 'active'",[e]);if(r.length>1)throw new Error(`multiple active terminal grants for ${e}`);return p(r[0])}n(Ie,"terminalGrant");async function Le(){return(await(await d()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get())?.value??null}n(Le,"grantsSource");async function Ce(e){return(await(await d()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get())?.value===e}n(Ce,"hasSyncedGrants");async function Me(e){return(await e.prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get())?.value!=="local"?0:(await e.prepare("DELETE FROM runtime_state WHERE key = 'grants_source'").run(),Number((await e.prepare("DELETE FROM grants").run()).changes))}n(Me,"dropLocalGrantMirror");function Fe(e){if(e===void 0)return[];if(!Array.isArray(e))throw new TypeError("invalid grant sync response");const r=[];for(const t of e){const{team:s,members:o}=t??{};if(!(typeof s!="string"||!/^team:\S+$/.test(s))){if(!Array.isArray(o)||o.some(a=>typeof a!="string"||!/^user:[^\s*]+$/.test(a)))throw new TypeError("invalid grant sync response");r.push({team:s,members:o})}}return r}n(Fe,"teamsOf");async function $e(e,r,t,s=[]){const o=new Set;for(const a of e){if(o.has(a.id)||!a.id||!a.runtime||!a.sub||!a.grantee||!Number.isInteger(a.rev)||!["active","revoked","removed"].includes(a.status))throw new TypeError("invalid grant sync response");if(a.grantee==="*"!=(a.grantee_prefix!=null))throw new TypeError("invalid grant sync response");o.add(a.id),l(a.scopes),l(a.resolved_scopes)}await M(async a=>{let E=0;const v=[...o];E+=Number((await(v.length?a.prepareUncached(`DELETE FROM grants WHERE id NOT IN (${v.map(()=>"?").join(",")})`).run(...v):a.prepareUncached("DELETE FROM grants").run())).changes);const h=a.prepare(`INSERT INTO grants
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var S=Object.defineProperty;var a=(e,r)=>S(e,"name",{value:r,configurable:!0});import{directoryIssuer as v}from"../directory/issuer.js";import{outboundFetch as $}from"../events/outbound.js";import{warn as u}from"../output.js";import{canonicalJson as
|
|
1
|
+
var S=Object.defineProperty;var a=(e,r)=>S(e,"name",{value:r,configurable:!0});import{directoryIssuer as v}from"../directory/issuer.js";import{outboundFetch as $}from"../events/outbound.js";import{warn as u}from"../output.js";import{canonicalJson as _,principalPayer as k}from"./mirror.js";let y=5e3;function T(e){y=e}a(T,"setShadowTtl");const A=512,M=["status","scopes","resolved_scopes","spend_cap","payer","dependencies","run_notice_url","inference_endpoint"];function z(){g.clear()}a(z,"resetShadowCache");const g=new Map,f=new Map,o={agree:0,disagree:0,lagging:0,error:0};async function x(e,r,n){const{mintDirectoryToken:i}=await import("./sync.js"),c=await i(e),t=n?`&epochs=${n.epochs.global},${n.epochs.sub}`:"",s=`${e}/v1/runtime/grant-answers?sub=${encodeURIComponent(r)}${t}`,d=await $("grant_shadow",s,{headers:{Authorization:`Bearer ${c.access_token}`},signal:AbortSignal.timeout(1e4)});if(!d.ok)throw new Error(`grant-answers ${d.status}`);const p=await d.json();if(p.unchanged){if(!n)throw new Error("grant-answers said unchanged to a caller holding nothing");return{...n,epochs:p.epochs,checkedAt:Date.now()}}return{epochs:p.epochs,grants:new Map((p.grants??[]).map(m=>[String(m.id),m])),checkedAt:Date.now()}}a(x,"fetchAnswer");async function b(e,r){const n=g.get(r);if(n&&Date.now()-n.checkedAt<y)return n;const i=f.get(r);if(i)return i;const c=x(e,r,n).then(t=>(g.delete(r),g.set(r,t),g.size>A&&g.delete(g.keys().next().value),t)).finally(()=>f.delete(r));return f.set(r,c),c}a(b,"answerFor");const h=new Set;async function P(){await Promise.all([...h])}a(P,"shadowIdle");async function C(e){const r=v();if(r===null)return;const n=(await b(r,e.sub)).grants.get(e.id);if(!n){o.disagree++,u(`grant_shadow disagree ${JSON.stringify({grant:e.id,sub:e.sub,fields:["missing"]})}`);return}if(n.rev!==e.rev){o.lagging++;return}const i={...n,payer:k(n.payer,e.sub,e.grantee)},c={...e,resolved_scopes:O(e.resolved_scopes,n.resolved_scopes)},t=M.filter(s=>_(i[s]??null)!==_(c[s]??null));if(t.length===0){o.agree++;return}o.disagree++,u(`grant_shadow disagree ${JSON.stringify({grant:e.id,sub:e.sub,rev:e.rev,fields:t})}`)}a(C,"compare");function O(e,r){if(!Array.isArray(r))return e;const n=new Set(r.flatMap(t=>{const s=t?.scope;return typeof s=="string"?[s]:[]})),i=new Set([...n].filter(t=>t.endsWith(":*")).map(t=>t.slice(0,-2)));if(i.size===0)return e;const c=new Set;return e.flatMap(t=>{const s=t.scope.slice(0,t.scope.indexOf(":"));return s==="crtr"||!i.has(s)||n.has(t.scope)?[t]:c.has(s)?[]:(c.add(s),[{...t,scope:`${s}:*`}])})}a(O,"compactLike");let w,l={agree:0,disagree:0,lagging:0,error:0};function D(){w||(w=setInterval(()=>{const e={agree:o.agree-l.agree,disagree:o.disagree-l.disagree,lagging:o.lagging-l.lagging,error:o.error-l.error};l={...o},e.agree+e.disagree+e.lagging+e.error>0&&u(`grant_shadow_summary ${JSON.stringify({window_s:60,...e})}`)},6e4),w.unref())}a(D,"startSummary");function U(e){if(!process.env.CRTR_RUNTIME)return;D();const r=C(e).catch(n=>{o.error++,u(`grant_shadow error ${JSON.stringify({grant:e.id,message:n instanceof Error?n.message:String(n)})}`)}).finally(()=>h.delete(r));h.add(r)}a(U,"shadowCheck");export{z as resetShadowCache,T as setShadowTtl,U as shadowCheck,o as shadowCounts,P as shadowIdle};
|
|
@@ -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
|
|
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
|
|
22
|
-
*
|
|
23
|
-
* row
|
|
24
|
-
|
|
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
|
|
2
|
-
UNION ALL SELECT 'grants' FROM ${
|
|
3
|
-
UNION ALL SELECT 'nodes' FROM ${
|
|
4
|
-
WHERE adapter_json::jsonb #>> '{principal,sub}' IS NOT NULL AND adapter_json::jsonb #>> '{principal,sub}' NOT IN (?, ?) LIMIT 5`,p,
|
|
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')`,
|
|
6
|
-
AND ${
|
|
7
|
-
SELECT DISTINCT value, value FROM ${
|
|
8
|
-
UNION SELECT c.start, o.owner FROM chain c JOIN ${
|
|
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 ${
|
|
11
|
-
UNION SELECT d.object FROM ${
|
|
12
|
-
UNION SELECT i.object FROM ${
|
|
13
|
-
UNION SELECT r.resource_id FROM ${
|
|
14
|
-
UNION SELECT r.resource_id FROM ${
|
|
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 ${
|
|
19
|
-
WHERE NOT EXISTS (SELECT 1 FROM chain c JOIN ok ON ok.id = c.id WHERE c.start = r.value)`,
|
|
20
|
-
JOIN ${
|
|
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
|
|
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
|
|
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),
|
|
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
|
|
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),
|
|
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
|
|
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
|
|
12
|
-
FROM (SELECT * FROM ${c(a,t)}${h}) s JOIN (SELECT * FROM ${c(o,t)}${h}) t ON ${f} AND (${L}) LIMIT 10`).all();
|
|
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(
|
|
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};
|