@north-light/cli 0.3.629 → 0.3.630
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/core/import/load/blobs.d.ts +8 -1
- package/dist/core/import/load/blobs.js +1 -1
- package/dist/core/import/load/rollback.js +4 -4
- package/dist/core/import/load/run.js +2 -2
- package/dist/daemon/api/handlers/imports.js +1 -1
- package/package.json +2 -2
- package/packages/crouter-identity/package.json +1 -1
- package/runtime.lock.json +13 -13
|
@@ -6,9 +6,16 @@ export interface MovedBlobs {
|
|
|
6
6
|
}
|
|
7
7
|
/** `created` collects the keys this call wrote, so the caller can delete them if the run fails before its copy commits. */
|
|
8
8
|
export declare function moveRunBlobs(db: CanvasDb, schema: string, target: string, person: string, blobs: BlobStore, runId: string, created: string[]): Promise<MovedBlobs>;
|
|
9
|
-
/** Delete the keys, concurrently. With `bestEffort`, a key that cannot be deleted is skipped and the rest still go; otherwise the first failure is thrown. */
|
|
9
|
+
/** Delete the keys, concurrently. With `bestEffort`, a key that cannot be deleted is logged and skipped and the rest still go; otherwise the first failure is thrown. */
|
|
10
10
|
export declare function deleteBlobs(blobs: BlobStore, keys: readonly string[], bestEffort?: boolean): Promise<void>;
|
|
11
11
|
/** Delete every blob `moveRunBlobs` can have moved for these owners (the keys `parseBlobKey` accepts under each owner's prefixes): one paged listing per owner and kind, then the deletes, with no request per key to check. */
|
|
12
12
|
export declare function deleteOwnedBlobs(blobs: BlobStore, nodes: readonly string[], requests: readonly string[]): Promise<void>;
|
|
13
13
|
/** Delete the run's uploaded copies (after the run is done). */
|
|
14
14
|
export declare function deleteRunBlobs(blobs: BlobStore, runId: string): Promise<void>;
|
|
15
|
+
/** Delete everything the run uploaded under `imports/<run>/` once the run can never be loaded again. The node-file archives are kept (`keepNodeFiles`) for a run that failed after its
|
|
16
|
+
* copy committed: its `import_node_files` rows stay until rollback, and a hosted node's start reads the archive. By default a storage error is thrown (rollback reports it to its caller).
|
|
17
|
+
* With `bestEffort`, a run whose state is already settled keeps that state: a list error is logged, and a key that cannot be deleted is logged and skipped while the rest still go. */
|
|
18
|
+
export declare function deleteRunPrefix(blobs: BlobStore, runId: string, options?: {
|
|
19
|
+
keepNodeFiles?: boolean;
|
|
20
|
+
bestEffort?: boolean;
|
|
21
|
+
}): Promise<void>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
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,6 +1,6 @@
|
|
|
1
|
-
var A=Object.defineProperty;var u=(n,d)=>A(n,"name",{value:d,configurable:!0});import{openDb as
|
|
2
|
-
AND EXISTS (SELECT 1 FROM _rb p WHERE p.tbl = '${e.parent}' AND ${
|
|
3
|
-
AND NOT EXISTS (SELECT 1 FROM _rb o WHERE o.tbl = 'objects' AND o.k ->> 0 = r.document)`).all()).map(e=>e.document);for(const e of
|
|
1
|
+
var A=Object.defineProperty;var u=(n,d)=>A(n,"name",{value:d,configurable:!0});import{openDb as C,withCanvasWrite as h}from"../../canvas/db.js";import{keyMatch as l,q as a,readCatalog as D,rowKey as S,topologicalOrder as M}from"./catalog.js";import{deleteOwnedBlobs as g,deleteRunPrefix as W}from"./blobs.js";import{decodeKeys as $}from"./copy.js";import{IMPORT_ROLLBACK_LOCK as F}from"../../graph/deletion.js";import{OBJECT_ID_COLUMNS as H}from"./rewrite.js";import{targetSchema as y}from"./stage.js";class N extends Error{static{u(this,"Refused")}}async function Y(n,d){const c=await(await C()).prepare("SELECT source_install_id, source_kind, state, created_at FROM import_runs WHERE run_id = ?").get(n);if(c===void 0)throw new Error(`no import run ${n}`);if(c.state!=="done"&&c.state!=="committed"&&c.state!=="failed")throw new Error(`import run ${n} is ${c.state}, not rollbackable`);const E={run_id:n,rolled_back:!1,dependents:{},deleted:{}},R={nodes:[],human_requests:[]};try{await h(async t=>{await t.prepare("SELECT pg_advisory_xact_lock(hashtext(?))").get(F);const i=await y(t),L=(await t.prepareUncached("SELECT table_name FROM information_schema.tables WHERE table_schema = ? AND table_type = 'BASE TABLE'").all(i)).map(e=>e.table_name),_=await D(t,i,L);_.tables.get("env_vars").primaryKey=["person","owner_kind","owner_id","name"],await t.exec("CREATE TEMP TABLE _rb (tbl text NOT NULL, k jsonb NOT NULL) ON COMMIT DROP");const T=await t.prepare("SELECT table_name, inserted_keys FROM import_manifest WHERE run_id = ?").all(n);for(const{table_name:e,inserted_keys:o}of T){const r=$(o);(e==="nodes"||e==="human_requests")&&R[e].push(...r.map(s=>s[0]));for(let s=0;s<r.length;s+=5e3)await t.prepare("INSERT INTO _rb SELECT ?, e FROM jsonb_array_elements(?::jsonb) e").run(e,JSON.stringify(r.slice(s,s+5e3)))}const m=new Set(T.map(e=>e.table_name));await t.exec("ANALYZE _rb");for(const e of _.foreignKeys){const o=_.tables.get(e.parent),r=_.tables.get(e.table);if(e.table==="import_node_files"||!m.has(e.parent)||o===void 0||r===void 0||e.parentColumns.join()!==o.primaryKey.join())continue;const s=m.has(e.table)?`AND NOT EXISTS (SELECT 1 FROM _rb o WHERE o.tbl = '${e.table}' AND ${l(r,S(r),"c","o.k")})`:"",p=Number((await t.prepareUncached(`SELECT count(*) AS n FROM ${a(i)}.${a(e.table)} c WHERE ${e.columns.map(k=>`c.${a(k)} IS NOT NULL`).join(" AND ")}
|
|
2
|
+
AND EXISTS (SELECT 1 FROM _rb p WHERE p.tbl = '${e.parent}' AND ${l(r,e.columns,"c","p.k")}) ${s}`).get()).n);p>0&&(E.dependents[e.table]=(E.dependents[e.table]??0)+p)}for(const[e,o]of H){const r=_.tables.get(e);if(r===void 0||!r.columns.includes(o)||r.primaryKey.length===0)continue;const s=m.has(e)?`AND NOT EXISTS (SELECT 1 FROM _rb o WHERE o.tbl = '${e}' AND ${l(r,r.primaryKey,"c","o.k")})`:"",p=Number((await t.prepareUncached(`SELECT count(*) AS n FROM ${a(i)}.${a(e)} c WHERE c.${a(o)} IN (SELECT k ->> 0 FROM _rb WHERE tbl = 'objects') ${s}`).get()).n);p>0&&(E.dependents[`${e}.${o}`]=p)}const O=Number((await t.prepare("SELECT count(*) AS n FROM import_runs WHERE source_install_id = ? AND run_id <> ? AND created_at > ? AND (state IN ('loading', 'committed', 'done') OR (state = 'failed' AND committed_at IS NOT NULL))").get(c.source_install_id,n,c.created_at)).n);O>0&&(E.dependents.import_runs=O);const f=Number((await t.prepare("SELECT count(*) AS n FROM import_id_map m WHERE m.run_id <> ? AND m.kind = 'object' AND m.target_value IN (SELECT k ->> 0 FROM _rb WHERE tbl = 'objects')").get(n)).n);if(f>0&&(E.dependents.import_id_map=f),Object.keys(E.dependents).length>0)throw new N;const w=(await t.prepareUncached(`SELECT DISTINCT r.document FROM ${a(i)}.revisions r WHERE r.rev_id IN (SELECT k ->> 0 FROM _rb WHERE tbl = 'revisions')
|
|
3
|
+
AND NOT EXISTS (SELECT 1 FROM _rb o WHERE o.tbl = 'objects' AND o.k ->> 0 = r.document)`).all()).map(e=>e.document);for(const e of M(_,[...m]).reverse()){const o=_.tables.get(e);if(o===void 0)continue;e==="run_events"&&await t.prepareUncached(`SELECT 1 FROM ${a(i)}.run_events t WHERE EXISTS (SELECT 1 FROM _rb k WHERE k.tbl = 'run_events' AND ${l(o,S(o),"t","k.k")}) ORDER BY t."run_id" COLLATE "C", t."sequence_number" FOR UPDATE`).all();const r=await t.prepareUncached(`DELETE FROM ${a(i)}.${a(e)} t WHERE EXISTS (SELECT 1 FROM _rb k WHERE k.tbl = '${e}' AND ${l(o,S(o),"t","k.k")})`).run();E.deleted[e]=r.changes}for(const e of w)await t.prepareUncached(`UPDATE ${a(i)}.documents d SET
|
|
4
4
|
heads_key = COALESCE((SELECT string_agg(r.rev_id, ',' ORDER BY r.rev_id) FROM ${a(i)}.revisions r WHERE r.document = d.object AND NOT EXISTS (SELECT 1 FROM ${a(i)}.revision_parents p WHERE p.parent = r.rev_id)), ''),
|
|
5
5
|
revision = COALESCE((SELECT max(r.number) FROM ${a(i)}.revisions r WHERE r.document = d.object AND NOT EXISTS (SELECT 1 FROM ${a(i)}.revision_parents p WHERE p.parent = r.rev_id)), 0)
|
|
6
|
-
WHERE d.object = ?`).run(e);await t.prepareUncached("DELETE FROM import_key_map km WHERE km.source_install_id = ? AND EXISTS (SELECT 1 FROM _rb r WHERE r.tbl = km.table_name AND r.k ->> 0 = km.target_key)").run(c.source_install_id),await t.prepare("DELETE FROM import_id_map WHERE run_id = ?").run(n),await t.prepare("DELETE FROM import_manifest WHERE run_id = ?").run(n),await t.prepare("UPDATE import_runs SET state = 'rolled_back', step = 'rolled_back', finished_at = ? WHERE run_id = ?").run(new Date().toISOString(),n),await
|
|
6
|
+
WHERE d.object = ?`).run(e);await t.prepareUncached("DELETE FROM import_key_map km WHERE km.source_install_id = ? AND EXISTS (SELECT 1 FROM _rb r WHERE r.tbl = km.table_name AND r.k ->> 0 = km.target_key)").run(c.source_install_id),await t.prepare("DELETE FROM import_id_map WHERE run_id = ?").run(n),await t.prepare("DELETE FROM import_manifest WHERE run_id = ?").run(n),await t.prepare("UPDATE import_runs SET state = 'rolled_back', step = 'rolled_back', finished_at = ? WHERE run_id = ?").run(new Date().toISOString(),n),await v(t,c)})}catch(t){if(t instanceof N)return E;throw t}return await W(d,n),await g(d,R.nodes,R.human_requests),E.rolled_back=!0,E}u(Y,"rollbackRun");async function v(n,d){if(d.source_kind!=="machine")return;const b=await n.prepare("SELECT object FROM environments WHERE machine_id = ? AND kind = 'machine'").get(d.source_install_id);b!==void 0&&await n.prepare("UPDATE machine_credentials SET revoked_at = ? WHERE environment = ? AND revoked_at IS NULL").run(new Date().toISOString(),b.object)}u(v,"revokeFor");export{Y as rollbackRun};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var z=Object.defineProperty;var
|
|
1
|
+
var z=Object.defineProperty;var c=(e,i)=>z(e,"name",{value:i,configurable:!0});import{zstdCompressSync as Q}from"node:zlib";import{blobStore as V}from"../../blobs/index.js";import{openDb as S,withCanvasWrite as M}from"../../canvas/db.js";import{insertImportedRevisions as X}from"../../graph/documents.js";import{getById as Z}from"../../graph/objects.js";import{bundleKeys as v,decodeRows as x,rowKeys as ee,SEQ_TABLES as te}from"../bundle/layout.js";import{readCatalog as ae}from"./catalog.js";import{copyRows as ne,decodeKeys as N,encodeKeys as L}from"./copy.js";import{pruneStaged as ie,precheck as se,renameClashingProfiles as re,rewriteConversationHeaders as oe,rewritePaths as de,rewriteRequestPaths as pe,takeRepoSyncedDocuments as ue}from"./prepare.js";import{boundSub as ce,checkSourcePerson as fe,checkStagedBlobKeys as le,checkStagedPersons as _e,checkStagedReferences as me,checkStagedRequestKeys as we}from"./bind.js";import{deleteBlobs as ge,deleteRunBlobs as be,deleteRunPrefix as he,moveRunBlobs as Ee}from"./blobs.js";import{dropStubRows as ye,findFleetGrant as Se,grantMissing as ve,mapProfileIds as Re,renameClashingRepos as Oe,rewriteIds as Pe,rewritePerson as Te,scopeRepoIdentities as ke}from"./rewrite.js";import{dropStaging as B,ImportLaneError as w,stage as Ie,stagingSchema as je,targetSchema as De}from"./stage.js";import{verifyRun as Ae}from"./verify.js";import{sandboxPathMap as Ce,writeNodeFiles as Me}from"./path-map.js";import{allStoreKeys as Ne,readPluginsStore as Le,recordImportedActivations as Be,writeStores as We}from"./stores.js";import{publishImportedPlugins as He}from"./publish-plugins.js";import{COPIED_TABLES as Ke}from"../bundle/layout.js";import{ClaimLostError as Ue}from"../../../daemon/reconcilers/row-claim.js";const W=10*6e4,Fe=30*6e4,R=c(()=>new Date().toISOString(),"now"),O=c(async(e,i)=>{await(await S()).prepare("UPDATE import_runs SET step = ? WHERE run_id = ?").run(i,e)},"setStep");async function Je(e,i){const n=await e.get(v.source(i));if(n===null)throw new w("stage","bundle_invalid","source.json is missing");return JSON.parse(n.toString("utf8"))}c(Je,"readSource");async function qe(e,i,n,r,s,d){const t=await e.get(v.rows(n.run_id,"grants")),l=t===null?[]:x(t),m=[];for(const a of l){const u=ce(a.sub,r,n.person,"grants.sub");await Se(i,s,d,u,a.grantee)===void 0&&m.push(a.grantee)}if(m.length===0)return!0;if(n.loaded_at===void 0||n.loaded_at===null)throw new w("stage","import_failed","a loading run has no loaded_at");if(Date.now()-Date.parse(n.loaded_at)>=W)throw ve(m);return!1}c(qe,"grantsReady");async function mt(e,i,n={}){const r=n.blobs??await V(),s=await S(),d=je(e.run_id),t=c(async a=>{await i.assertOwned(),await O(e.run_id,a),await n.atStep?.(a)},"at");let l=e.state==="committed";const m=[];try{const a=await Je(r,e.run_id);if(e.source_kind==="machine"&&a.installId!==e.source_install_id)throw new w("stage","bundle_invalid",`source.json names install ${a.installId}, the run is for ${e.source_install_id}`);a.installId=e.source_install_id;const u=await De(s),P=[...Ke],g=await ae(s,u,[...P,"grants"]);if(!l){const f={},k=[],I=[],j=n.fleetRuntime??process.env.CRTR_RUNTIME??null;if(await fe(s,u,a.person,e.person),!await qe(r,s,e,a.person,u,j)){await i.assertOwned(),await O(e.run_id,"waiting_for_grants");return}await t("publish-plugins");const h=await He(await Le(r,e.run_id));if(h.unavailable.length>0){if(e.loaded_at===void 0||e.loaded_at===null)throw new w("publish-plugins","import_failed","a loading run has no loaded_at");if(Date.now()-Date.parse(e.loaded_at)>=W)throw new w("publish-plugins","directory_unavailable",`the directory did not answer for: ${h.unavailable.slice(0,10).join(", ")}; rerun the import once it is reachable`,{plugins:h.unavailable});await i.assertOwned(),await O(e.run_id,"waiting_for_directory");return}I.push(...h.refused),await t("stage");const K=await Ie(s,e.run_id,a.counts,o=>ee(e.run_id,o,a),o=>r.get(o));for(const[o,p]of Object.entries(K))f[o]={staged:p,inserted:0,mapped:0,dropped:0};const _={db:s,schema:d,target:u,catalog:g,sourcePerson:a.person,targetPerson:e.person,fleetRuntime:j,shippedBodies:a.shippedBodies??{}};await t("bind-staged");for(const[o,p]of Object.entries(await _e(_)))E(f,o,p);for(const[o,p]of Object.entries(await le(_)))E(f,o,p);await t("rewrite-person"),await Te(_),await ke(_),await t("prune");const U=await ie(s,d,g,a),y=a.kind==="hosted"?Ce(a.pathPrefixes??[]):[];await t("rewrite-paths"),await de(s,d,y),await oe(s,d,y,r,e.run_id),await pe(s,d),await we(_);const F=await Re(_);await re(s,d,u,a.installId,e.person),await t("rewrite-ids");const D=await Pe(_,F);await t("drop");const J=await ue(s,d,u),q=await ye(_);for(const[o,p]of Object.entries({...U}))E(f,o,p);for(const[o,p]of Object.entries(q))E(f,o,p);await me(_),await Oe(_),await t("pre-check");const $=new Map([["messages",["seq"]],...te.map(o=>[o,["seq"]])]);await se(s,d,u,g,P,new Set,$),await t("blobs"),await Ee(s,d,u,e.person,r,e.run_id,m),await t("copy"),await M(async o=>{await i.assertOwned({extendLeaseMs:Fe});const p=await ne({db:o,runId:e.run_id,schema:d,target:u,catalog:g,source:a,person:e.person,idMap:D,pathMap:y}),A=await Ye(o,e.run_id,J);A>0&&(p.inserted.revisions=(p.inserted.revisions??0)+A),await Me(o,d,e.run_id,a);const C=await We({db:o,blobs:r,runId:e.run_id,person:e.person,objectMap:D.object});for(const[G,Y]of Object.entries(C.inserted))p.inserted[G]=Y.length;return k.push(...C.unresolvedPlugins),await o.prepare("UPDATE import_runs SET counts_json = ?, loaded_at = COALESCE(loaded_at, ?) WHERE run_id = ?").run(JSON.stringify({...Ge(f,p),unresolved_plugins:k,refused_plugins:I}),R(),e.run_id),p}),l=!0,await n.atStep?.("committed")}await t("verify");const b=await Ae(s,e.run_id,d,u,g,a.installId);if(await s.prepare("UPDATE import_runs SET verify_json = ? WHERE run_id = ?").run(JSON.stringify(b),e.run_id),!b.ok)throw new w("verify","verify_failed","the committed rows differ from the staged rows or an invariant failed",{differences:b.differences,invariants:b.invariants});await t("manifest");const T=v.manifest(e.run_id);await r.put(T,await ze(e.run_id)),await B(s,e.run_id);for(const f of Ne(e.run_id))await r.delete(f);await be(r,e.run_id),await M(async f=>{await Be(f,e.run_id,e.person),await f.prepare("UPDATE import_runs SET state = 'done', step = 'done', manifest_key = ?, finished_at = ? WHERE run_id = ?").run(T,R(),e.run_id)})}catch(a){if(a instanceof Ue)throw a;const u=$e(a);await B(s,e.run_id).catch(()=>{}),l||await ge(r,m,!0),await s.prepare("UPDATE import_runs SET state = 'failed', failure_json = ?, finished_at = ? WHERE run_id = ?").run(JSON.stringify(u),R(),e.run_id),await he(r,e.run_id,{keepNodeFiles:l,bestEffort:!0})}}c(mt,"processRun");function $e(e){if(e instanceof w)return{step:e.step,code:e.code,message:e.message,...e.detail===void 0?{}:{detail:e.detail}};const i=e.code;return{step:"unknown",code:typeof i=="string"?i:"import_failed",message:e instanceof Error?e.message:String(e)}}c($e,"failureOf");function E(e,i,n){(e[i]??={staged:0,inserted:0,mapped:0,dropped:0}).dropped+=n}c(E,"addDropped");function Ge(e,i){for(const[n,r]of Object.entries(i.inserted))(e[n]??={staged:0,inserted:0,mapped:0,dropped:0}).inserted=r;for(const[n,r]of Object.entries(i.mapped))(e[n]??={staged:0,inserted:0,mapped:0,dropped:0}).mapped=r;return e}c(Ge,"withInserted");async function Ye(e,i,n){const r=new Set((await e.prepareUncached("SELECT rev_id FROM revisions WHERE rev_id IN (SELECT jsonb_array_elements_text(?::jsonb))").all(JSON.stringify(n.map(t=>t.rev_id)))).map(t=>t.rev_id)),s=n.filter(t=>!r.has(t.rev_id)),d=new Map;for(const t of n)d.set(t.document,[...d.get(t.document)??[],t]);for(const[t,l]of d){const m=await Z(e,t);m!==null&&await X(e,m,l.map(a=>({rev_id:a.rev_id,parents:a.parents,body_hash:a.body_hash,rationale:a.rationale,created_at:a.created_at})))}return await H(e,i,"revisions",s.map(t=>[t.rev_id])),await H(e,i,"revision_parents",s.flatMap(t=>t.parents.map(l=>[t.rev_id,l]))),s.length}c(Ye,"arrive");async function H(e,i,n,r){if(r.length===0)return;const s=await e.prepare("SELECT inserted_keys FROM import_manifest WHERE run_id = ? AND table_name = ?").get(i,n);s===void 0?await e.prepare("INSERT INTO import_manifest (run_id, table_name, inserted_keys) VALUES (?, ?, ?)").run(i,n,L(r)):await e.prepare("UPDATE import_manifest SET inserted_keys = ? WHERE run_id = ? AND table_name = ?").run(L([...N(s.inserted_keys),...r]),i,n)}c(H,"appendManifest");async function ze(e){const n=await(await S()).prepare("SELECT table_name, inserted_keys FROM import_manifest WHERE run_id = ? ORDER BY table_name").all(e);return Q(Buffer.from(n.map(r=>JSON.stringify({table:r.table_name,keys:N(r.inserted_keys)})).join(`
|
|
2
2
|
`)+`
|
|
3
|
-
`))}
|
|
3
|
+
`))}c(ze,"manifestFile");export{Fe as COPY_LEASE_MS,W as GRANT_WAIT_MS,mt as processRun};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var k=Object.defineProperty;var a=(t,n)=>k(t,"name",{value:n,configurable:!0});import{randomBytes as E}from"node:crypto";import{ApiError as o}from"../../../api/errors.js";import{blobStore as
|
|
1
|
+
var k=Object.defineProperty;var a=(t,n)=>k(t,"name",{value:n,configurable:!0});import{randomBytes as E}from"node:crypto";import{ApiError as o}from"../../../api/errors.js";import{blobStore as c}from"../../../core/blobs/index.js";import{presignPutUrl as $,r2ConfigFromEnv as v}from"../../../core/blobs/r2.js";import{openDb as m}from"../../../core/canvas/db.js";import{bundleKeys as f}from"../../../core/import/bundle/layout.js";import{deleteRunPrefix as O}from"../../../core/import/load/blobs.js";import{putStore as T,StoreBodyError as R,STORE_NAMES as D}from"../../../core/import/load/stores.js";import{rollbackRun as N}from"../../../core/import/load/rollback.js";import{crtrVersion as w}from"../../../shared/crtr-version.js";import{importTokenFor as A}from"../import-auth.js";const h=3600;function y(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(y,"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!==y(t))throw new o(404,"import_not_found",`no import run ${e}`);return r}a(_,"ownRun");function P(t,n,e){const r=t.principal;if(r.class!=="import")return y(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(P,"startPerson");const g=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 j(t){const n=g(t.body),e=P(t,n,n.source_kind),r=n.source_install_id,s=n.source_kind,u=n.release;if(typeof r!="string"||r===""||s!=="machine"&&s!=="hosted"||typeof u!="string")throw new o(400,"invalid_body","source_install_id, source_kind (machine | hosted) and release are required");if(u!==w())throw new o(409,"release_mismatch",`the source runs ${u}, the control plane accepts ${w()}`);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 S={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(S),new Date().toISOString(),i.run_id),await O(await c(),i.run_id,{bestEffort:!0}),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 d=`imp_${E(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(d,r,s,e,u,new Date().toISOString());const l=t.principal.class==="import"?A(d):null;return{status:201,body:{run_id:d,upload:{rows_prefix:f.prefix(d),url_template:`POST /v1/imports/${d}/upload-urls {"keys":[...]}`},...l===null?{}:{import_token:l}}}}a(j,"handleStart");async function I(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=g(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=v();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 u={};for(const i of e)u[i]=$(s,i,h);return{status:200,body:{urls:u,expires_at:new Date(Date.now()+h*1e3).toISOString()}}}a(I,"handleUploadUrls");async function U(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(!D.includes(e))throw new o(404,"unknown_store",`no file store ${e}`);try{await T(await c(),n.run_id,e,t.body)}catch(r){throw r instanceof R?new o(400,"invalid_body",r.message):r}return{status:204}}a(U,"handleStore");async function L(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 b(n.run_id)}}a(L,"handleLoad");async function b(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,...u}=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:u,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(b,"runDto");async function W(t){const n=await _(t,!0);return{status:200,body:await b(n.run_id)}}a(W,"handleGet");async function C(t){const n=await _(t),e=await N(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(C,"handleRollback");const Z=[{method:"POST",pattern:"/v1/imports",handler:j},{method:"POST",pattern:"/v1/imports/:run_id/upload-urls",handler:I},{method:"PUT",pattern:"/v1/imports/:run_id/stores/:name",handler:U},{method:"POST",pattern:"/v1/imports/:run_id/load",handler:L},{method:"GET",pattern:"/v1/imports/:run_id",handler:W},{method:"POST",pattern:"/v1/imports/:run_id/rollback",handler:C}];export{Z as importRoutes};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/cli",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.630",
|
|
4
4
|
"description": "crtr — agent runtime with memory, plugins, and marketplaces",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -145,7 +145,7 @@
|
|
|
145
145
|
},
|
|
146
146
|
"license": "UNLICENSED",
|
|
147
147
|
"dependencies": {
|
|
148
|
-
"@north-light/identity": "0.3.
|
|
148
|
+
"@north-light/identity": "0.3.630",
|
|
149
149
|
"@earendil-works/chord": "1.1.0",
|
|
150
150
|
"@earendil-works/pi-agent-core": "1.1.0",
|
|
151
151
|
"@earendil-works/pi-ai": "1.1.0",
|
package/runtime.lock.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/cli",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.630",
|
|
4
4
|
"lockfileVersion": 3,
|
|
5
5
|
"requires": true,
|
|
6
6
|
"packages": {
|
|
7
7
|
"": {
|
|
8
8
|
"name": "@north-light/cli",
|
|
9
|
-
"version": "0.3.
|
|
9
|
+
"version": "0.3.630",
|
|
10
10
|
"hasInstallScript": true,
|
|
11
11
|
"license": "UNLICENSED",
|
|
12
12
|
"workspaces": [
|
|
@@ -28,7 +28,7 @@
|
|
|
28
28
|
"@milkdown/preset-gfm": "^7.22.3",
|
|
29
29
|
"@milkdown/prose": "^7.22.3",
|
|
30
30
|
"@milkdown/utils": "^7.22.3",
|
|
31
|
-
"@north-light/identity": "0.3.
|
|
31
|
+
"@north-light/identity": "0.3.630",
|
|
32
32
|
"cron-parser": "^5.6.0",
|
|
33
33
|
"esbuild": "^0.27.7",
|
|
34
34
|
"jose": "^6.2.12",
|
|
@@ -11956,17 +11956,17 @@
|
|
|
11956
11956
|
},
|
|
11957
11957
|
"packages/crouter-api": {
|
|
11958
11958
|
"name": "@north-light/api",
|
|
11959
|
-
"version": "0.3.
|
|
11959
|
+
"version": "0.3.630",
|
|
11960
11960
|
"license": "UNLICENSED"
|
|
11961
11961
|
},
|
|
11962
11962
|
"packages/crouter-env-docker": {
|
|
11963
11963
|
"name": "@north-light/env-docker",
|
|
11964
|
-
"version": "0.3.
|
|
11964
|
+
"version": "0.3.630",
|
|
11965
11965
|
"license": "UNLICENSED"
|
|
11966
11966
|
},
|
|
11967
11967
|
"packages/crouter-identity": {
|
|
11968
11968
|
"name": "@north-light/identity",
|
|
11969
|
-
"version": "0.3.
|
|
11969
|
+
"version": "0.3.630",
|
|
11970
11970
|
"license": "UNLICENSED",
|
|
11971
11971
|
"dependencies": {
|
|
11972
11972
|
"jose": "^6.2.1"
|
|
@@ -11974,21 +11974,21 @@
|
|
|
11974
11974
|
},
|
|
11975
11975
|
"packages/crouter-plugin": {
|
|
11976
11976
|
"name": "@north-light/plugin",
|
|
11977
|
-
"version": "0.3.
|
|
11977
|
+
"version": "0.3.630",
|
|
11978
11978
|
"license": "UNLICENSED",
|
|
11979
11979
|
"dependencies": {
|
|
11980
|
-
"@north-light/api": "0.3.
|
|
11981
|
-
"@north-light/identity": "0.3.
|
|
11980
|
+
"@north-light/api": "0.3.630",
|
|
11981
|
+
"@north-light/identity": "0.3.630"
|
|
11982
11982
|
}
|
|
11983
11983
|
},
|
|
11984
11984
|
"packages/crouter-sdk": {
|
|
11985
11985
|
"name": "@north-light/sdk",
|
|
11986
|
-
"version": "0.3.
|
|
11986
|
+
"version": "0.3.630",
|
|
11987
11987
|
"license": "UNLICENSED",
|
|
11988
11988
|
"dependencies": {
|
|
11989
|
-
"@north-light/api": "0.3.
|
|
11990
|
-
"@north-light/identity": "0.3.
|
|
11991
|
-
"@north-light/plugin": "0.3.
|
|
11989
|
+
"@north-light/api": "0.3.630",
|
|
11990
|
+
"@north-light/identity": "0.3.630",
|
|
11991
|
+
"@north-light/plugin": "0.3.630",
|
|
11992
11992
|
"jose": "^6.2.1"
|
|
11993
11993
|
},
|
|
11994
11994
|
"bin": {
|