@north-light/cli 0.3.756 → 0.3.758
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/contract.d.ts +1 -1
- package/dist/api/contract.js +1 -1
- package/dist/builtin-memory/internal/storage-tiers.md +2 -2
- package/dist/clients/attach/viewer.js +432 -432
- package/dist/commands/profile/new.js +1 -1
- package/dist/commands/profile/project.js +1 -1
- 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/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/core/profiles/manifest.js +1 -1
- package/dist/core/profiles/project-dir.d.ts +3 -0
- package/dist/core/profiles/project-dir.js +1 -0
- package/dist/daemon/api/handlers/imports.js +1 -1
- package/dist/daemon/api/handlers/profiles.js +1 -1
- package/dist/daemon/api/operations.js +1 -1
- package/dist/daemon/crtrd.js +12 -12
- package/dist/daemon/reconcilers/storage-maintenance.js +1 -1
- package/package.json +3 -3
- package/packages/crouter-api/dist/api/contract.js +1 -1
- package/packages/crouter-api/dist/commands/profile/new.js +2 -2
- package/packages/crouter-api/dist/commands/profile/project.js +2 -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/import/export/cloud.js +1 -0
- package/packages/crouter-api/dist/core/import/load/prepare.js +2 -2
- package/packages/crouter-api/dist/core/profiles/manifest.js +12 -18
- package/packages/crouter-api/dist/core/profiles/project-dir.js +20 -0
- package/packages/crouter-api/dist/daemon/api/operations.js +1 -0
- package/packages/crouter-api/package.json +1 -1
- package/packages/crouter-identity/package.json +1 -1
- package/packages/crouter-plugin/package.json +3 -3
- package/runtime.lock.json +14 -14
- package/scripts/install-runtime.mjs +1 -30
- package/dist/core/canvas/import-sqlite.d.ts +0 -46
- package/dist/core/canvas/import-sqlite.js +0 -19
- package/dist/core/canvas/migrations.d.ts +0 -16
- package/dist/core/canvas/migrations.js +0 -1073
- package/dist/migrations/004-canvas-documents/legacy-edges.d.ts +0 -6
- package/dist/migrations/004-canvas-documents/legacy-edges.js +0 -18
|
@@ -1 +1 @@
|
|
|
1
|
-
var f=Object.defineProperty;var n=(e,t)=>f(e,"name",{value:t,configurable:!0});import{defineLeaf as c}from"../../core/command.js";import{usage as s}from"../../core/errors.js";import{
|
|
1
|
+
var f=Object.defineProperty;var n=(e,t)=>f(e,"name",{value:t,configurable:!0});import{defineLeaf as c}from"../../core/command.js";import{usage as s}from"../../core/errors.js";import{resolveExistingProjectDir as u}from"../../core/profiles/project-dir.js";import{cliClient as d}from"../api-client.js";import{resolveMetaPairs as h}from"./meta.js";const k=c({name:"new",description:"create a new profile",whenToUse:"you are establishing a new agent identity \u2014 a stable id, a display name, and its own documents (a profile owns documents like any other owner). Pass at most one initial project directory here (the parser has no repeatable-flag support); use `profile project add` afterward for every additional one. Use `--root` (no name) to provision the canonical stable root profile \u2014 the default identity a home falls back to \u2014 idempotently, without spawning a node.",help:{name:"profile new",summary:"create a profile of the caller's app in the scoped store, with its own app directory",params:[{kind:"flag",name:"name",type:"string",required:!1,constraint:"Display name for the profile. Also slugified into the stable profile id \u2014 the id never changes on later rename. Required unless `--root` is given; mutually exclusive with `--root`."},{kind:"flag",name:"root",type:"bool",required:!1,constraint:"Provision the canonical stable root profile (fixed id `root-00000000`, name `root`) \u2014 the fallback default identity for a home \u2014 instead of a fresh named one. Idempotent: re-running returns the existing root. Node-free (no `node new --root` needed). Mutually exclusive with `--name`/`--project`/`--repo`/`--default-kind`/`--meta`."},{kind:"flag",name:"project",type:"path",required:!1,constraint:"One initial project directory. Must already exist and be a directory; resolved to its absolute real path before storing. Creates a purview relationship: the repos enclosing it join the view of every node of the profile, with no delivery limit (`profile project add` starts them at `preview`). Singular \u2014 add more with `crtr profile project add` after creation."},{kind:"flag",name:"repo",type:"string",required:!1,repeatable:!0,constraint:"GitHub repository `owner/name` (repeat per repository). Makes a cloud dev profile: a Blaxel sandbox environment with 4096 MB whose recipe checks out these repositories at `/work/<name>`. Cloud only; mutually exclusive with `--project`. The GitHub App must be installed on each repository."},{kind:"flag",name:"default-kind",type:"string",required:!1,constraint:"Installed persona kind for node creates under this profile that omit --kind. Defaults to general when omitted; the daemon validates it against its installed kind registry."},{kind:"flag",name:"meta",type:"string",required:!1,repeatable:!0,constraint:"KEY=VALUE metadata entry (repeat per entry). KEY starts with a letter or digit, followed by letters, digits, `_`, or `-`. Each entry reaches every broker launched under the profile as `CRTR_PROFILE_META_<KEY>` env; readable back via `profile show` \u2014 not for secrets (those go to `profile env`)."}],output:[{name:"profile_id",type:"string",required:!0,constraint:"Stable directory id (`<slug>-<shortid>`). Pass this, or the name, to every other `profile` verb and to `--profile` elsewhere."},{name:"profile_path",type:"string",required:!0,constraint:"Absolute path to the profile directory, `<app space>/profiles/<id>`: its settings root. Documents the profile owns are canvas documents, read with `crtr canvas read`, not files here."},{name:"projects",type:"ProfileProject[]",required:!0,constraint:"Explicit `{path}` project relationships in manifest order. `path` defines purview and puts the repos enclosing it in the view of every node of the profile. Empty when --project was omitted."},{name:"app",type:"string",required:!0,constraint:"The app that owns this profile."},{name:"default_kind",type:"string",required:!0,constraint:"Default persona kind for node creates that omit --kind; `general` when none is stored."},{name:"metadata",type:"object",required:!0,constraint:"Stored metadata map; empty when --meta was omitted."},{name:"created_at",type:"string",required:!0,constraint:"ISO 8601 creation timestamp."}],outputKind:"object",effects:["Creates a profile row owned by the caller's app (the terminal app for a person) and its directory under that app's space. A name the caller's app already holds is refused."]},run:n(async e=>{const t=e.name,r=e.project,a=e.defaultKind,i=h(e.meta,"meta"),p=e.root===!0,o=e.repo??[];if(p){if(t!==void 0||r!==void 0||o.length>0||a!==void 0||Object.keys(i).length>0)throw s("`--root` provisions the canonical stable root profile and takes no `--name`/`--project`/`--repo`/`--default-kind`/`--meta`.");return l(await d().ensureProfile("root"))}if(o.length>0&&r!==void 0)throw s("`--repo` and `--project` are mutually exclusive: a dev profile works in sandbox checkouts, not local directories.");if(t===void 0)throw s("provide `--name <name>` to create a profile, or `--root` to provision the stable root profile.");return l(await d().createProfile({name:t,...r!==void 0?{projects:[{path:u(r)}]}:{},...o.length>0?{repositories:o}:{},...a!==void 0?{default_kind:a}:{},...Object.keys(i).length>0?{metadata:i}:{}}))},"run")});function l(e){return{profile_id:e.id,profile_path:e.profile_path,projects:e.projects,app:e.app,default_kind:e.default_kind,metadata:e.metadata,created_at:e.created_at}}n(l,"newProfileOutput");export{k as newLeaf};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var p=Object.defineProperty;var t=(e,r)=>p(e,"name",{value:r,configurable:!0});import{defineLeaf as i,defineBranch as l}from"../../core/command.js";import{resolve as c}from"node:path";import{resolveExistingProjectDir as h}from"../../core/profiles/project-dir.js";import{usage as f}from"../../core/errors.js";import{cliClient as n}from"../api-client.js";import{resolveProfileViaDaemon as a}from"./daemon-profiles.js";import{PROFILE_PROJECT_MEMORY_VALUES as m}from"../../api/dto/profiles.js";const u=i({name:"add",description:"add a project to a profile's purview",whenToUse:"a profile needs purview over another project directory \u2014 extend it after creation.",help:{name:"profile project add",summary:"add a project relationship to a profile, deduped by real path",params:[{kind:"positional",name:"profile",required:!0,constraint:"Profile id or manifest name; a close-enough name resolves to the nearest profile, reported on stderr."},{kind:"flag",name:"dir",type:"path",required:!1,constraint:"Directory to add; exactly one of `--dir` and `--repo`. Must exist and be a directory; resolved to its absolute real path before storing. The repo its checkout identifies as is stored with it; a folder no repo identifies keeps the path only. A path already on the profile keeps its position and nothing changes."},{kind:"flag",name:"repo",type:"string",required:!1,constraint:"Repo handle to add with no folder; exactly one of `--dir` and `--repo`. Must name a repo you may read. A node with no checkout (a sandbox) still gets that repo's documents."}],output:[{name:"profile_id",type:"string",required:!0,constraint:"Stable directory id."},{name:"projects",type:"ProfileProject[]",required:!0,constraint:"The updated `{repo?, path?}` entries in profile order. `path` defines purview for config; `repo` is the repo object id whose documents join the view."}],outputKind:"object",effects:["Appends a new project relationship (a folder, with the repo it identifies as, or a repo alone) to the profile row. Purview follows `path` for config, and every repo enclosing `path` joins the view of every node of the profile: its documents are readable, listed, and delivered at boot and workspace-open. Each such repo starts at a `preview` delivery limit unless the profile already limits that handle (change it with `profile project limit`). Running brokers discover the updated projects on their next scope read."]},run:t(async e=>{const{id:r}=await a(e.profile),o=e.dir,s=e.repo;if(o===void 0==(s===void 0))throw f("pass exactly one of --dir and --repo",{next:"Use --dir <directory> for a folder or --repo <handle> for a repo with no folder."});const d=await n().updateProfile(r,{add_project:o!==void 0?{path:h(o)}:{repo:s}});return{profile_id:d.id,projects:d.projects}},"run")}),w=i({name:"remove",description:"remove a project relationship from a profile's purview",whenToUse:"a profile no longer needs purview over one of its listed project directories \u2014 narrow it back. Works even if the directory itself was since deleted.",help:{name:"profile project remove",summary:"remove a project directory from a profile's manifest",params:[{kind:"positional",name:"profile",required:!0,constraint:"Profile id or manifest name; a close-enough name resolves to the nearest profile, reported on stderr."},{kind:"flag",name:"dir",type:"path",required:!0,constraint:"Directory to remove, matched against the stored project `path`. Does not require the directory to still exist on disk. The profile's app home does not change."}],output:[{name:"profile_id",type:"string",required:!0,constraint:"Stable directory id."},{name:"projects",type:"ProfileProject[]",required:!0,constraint:"The updated `{path}` relationships in profile order."}],outputKind:"object",effects:["Removes a project relationship from the profile row. This narrows purview and drops the path's repos from the view of the profile's nodes (unless a node's cwd is inside them); delivery limits are left in place. Running brokers discover the updated projects on their next scope read."]},run:t(async e=>{const{id:r}=await a(e.profile),o=await n().updateProfile(r,{remove_project:c(e.dir)});return{profile_id:o.id,projects:o.projects}},"run")}),y=i({name:"limit",description:"set how much of one owner's documents automatic delivery may disclose",whenToUse:"a profile's nodes should get less of one owner's documents (a repo, `user`, an app, a plugin) at boot and workspace-open \u2014 or that limit should be lifted.",help:{name:"profile project limit",summary:"set a profile's automatic delivery limit for one owner handle",params:[{kind:"positional",name:"profile",required:!0,constraint:"Profile id or manifest name; a close-enough name resolves to the nearest profile, reported on stderr."},{kind:"flag",name:"owner",type:"string",required:!0,constraint:"Owner the limit applies to. A bare handle (`crouter`, `user`) matches an owner of any type holding that handle. `<type>:<handle>` names one owner exactly \u2014 `repo:crouter`, `profile:work`, `app:terminal`, `person:user` \u2014 and wins over a bare key; use it when a repo and another owner share a handle. A profile's own documents are never capped, whichever key matches."},{kind:"flag",name:"level",type:"enum",choices:[...m],required:!0,constraint:"Maximum automatic delivery of this owner's documents at boot and workspace-open: `none`, `name`, `preview`, or `content`. `content` is no limit and removes the entry. Does not change explicit `crtr canvas read` access."}],output:[{name:"profile_id",type:"string",required:!0,constraint:"Stable directory id."},{name:"delivery_limits",type:"object",required:!0,constraint:"The profile\u2019s limits after the change, keyed by owner handle or `<type>:<handle>`; an owner not listed is not limited."}],outputKind:"object",effects:["Sets or removes one entry in the profile's `delivery_limits`. It caps only automatic `boot` and `workspace-open` delivery; a node's own documents and its own profile's documents are never capped. A `<type>:<handle>` key (for example `repo:crouter`) names one owner exactly and wins over a bare handle key."]},run:t(async e=>{const{id:r}=await a(e.profile),o=await n().updateProfile(r,{set_delivery_limit:{owner:e.owner,level:e.level}});return{profile_id:o.id,delivery_limits:o.delivery_limits}},"run")}),q=l({name:"project",description:"manage a profile's project purview and automatic delivery limits",whenToUse:"changing a profile\u2019s project purview after creation, or limiting how much of one owner's documents its nodes get automatically.",help:{name:"profile project",summary:"manage project purview and per-owner automatic delivery limits",model:"Each `{path}` relationship widens purview: the profile resolves config from `path`, and every node of the profile sees the repos enclosing `path` in addition to the repos enclosing its own cwd (cwd repos first, then projects in manifest order). Rule `if: {repo}` conditions hold for any of those repos (cwd repos and project repos); `--owner repo` stays with the cwd's repos, while a node may change a project repo's documents when its file permissions allow writing that checkout. `add` appends a new real path and starts its repos at a `preview` limit; `remove` narrows purview. `limit` sets the profile's `delivery_limits` entry for one owner handle, which caps automatic boot and workspace-open delivery of that owner's documents, whether the repo is in view through the cwd or the project list; explicit reads are not capped. Purview and delivery limits are both independent of a per-cwd default pin (`crtr profile default`)."},children:[u,w,y]});export{q as projectBranch};
|
|
@@ -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};
|
|
@@ -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};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var Z=Object.defineProperty;var m=(e,p)=>Z(e,"name",{value:p,configurable:!0});import{createZstdCompress as x}from"node:zlib";import{once as D}from"node:events";import{keyBatches as V}from"./keys.js";import{blobStore as X}from"../../blobs/index.js";import{openDb as E,withCanvasWrite as A}from"../../canvas/db.js";import{runAsPerson as B}from"../../canvas/person.js";import{insertImportedRevisions as ee}from"../../graph/documents.js";import{getById as te}from"../../graph/objects.js";import{bundleKeys as N,decodeRows as ae,rowKeys as L,SEQ_TABLES as ne}from"../bundle/layout.js";import{readCatalog as ie}from"./catalog.js";import{appendManifest as W,copyRows as se}from"./copy.js";import{anchorCronsToCreator as re,pruneStaged as oe,precheck as de,dropExistingIdempotencyKeys as pe,dropExpiredIdempotencyKeys as ce,dropExistingWatches as ue,renameClashingLegacyCharges as le,renameClashingProfiles as fe,rewriteConversationHeaders as me,rewritePaths as _e,rewriteRequestPaths as we,takeRepoSyncedDocuments as ge}from"./prepare.js";import{boundSub as be,
|
|
1
|
+
var Z=Object.defineProperty;var m=(e,p)=>Z(e,"name",{value:p,configurable:!0});import{createZstdCompress as x}from"node:zlib";import{once as D}from"node:events";import{keyBatches as V}from"./keys.js";import{blobStore as X}from"../../blobs/index.js";import{openDb as E,withCanvasWrite as A}from"../../canvas/db.js";import{runAsPerson as B}from"../../canvas/person.js";import{insertImportedRevisions as ee}from"../../graph/documents.js";import{getById as te}from"../../graph/objects.js";import{bundleKeys as N,decodeRows as ae,rowKeys as L,SEQ_TABLES as ne}from"../bundle/layout.js";import{readCatalog as ie}from"./catalog.js";import{appendManifest as W,copyRows as se}from"./copy.js";import{anchorCronsToCreator as re,pruneStaged as oe,precheck as de,dropExistingIdempotencyKeys as pe,dropExpiredIdempotencyKeys as ce,dropExistingWatches as ue,renameClashingLegacyCharges as le,renameClashingProfiles as fe,rewriteConversationHeaders as me,rewritePaths as _e,rewriteRequestPaths as we,takeRepoSyncedDocuments as ge}from"./prepare.js";import{boundSub as be,dropForeignReferences as he,checkSourcePerson as ye,checkStagedBlobKeys as Se,checkStagedPersons as ve,checkStagedReferences as Ee,checkStagedRequestKeys as Re}from"./bind.js";import{deleteBlobs as Ie,deleteRunBlobs as Oe,deleteRunPrefix as Pe,moveRunBlobs as je}from"./blobs.js";import{dropStubRows as ke,findFleetGrant as Te,grantMissing as Ce,mapProfileIds as Me,renameClashingRepos as De,rewriteIds as Ae,rewritePerson as Be,scopeRepoIdentities as Ne}from"./rewrite.js";import{dropStaging as K,ImportLaneError as g,stage as Le,stagingSchema as We,targetSchema as Ke}from"./stage.js";import{verifyRun as He}from"./verify.js";import{sandboxPathMap as Fe,writeNodeFiles as Je}from"./path-map.js";import{allStoreKeys as Ue,readPluginsStore as Ge,recordImportedActivations as $e,writeStores as qe}from"./stores.js";import{openImportGrants as Ye}from"./open-grants.js";import{publishImportedPlugins as ze}from"./publish-plugins.js";import{COPIED_TABLES as Qe}from"../bundle/layout.js";import{emitEvent as Ze}from"../../events/emit.js";import{ClaimLostError as xe}from"../../../daemon/reconcilers/row-claim.js";const Ve=10*6e4,Xe=30*6e4,R=m(()=>new Date().toISOString(),"now"),H=m(async(e,p)=>{await(await E()).prepare("UPDATE import_runs SET step = ? WHERE run_id = ?").run(p,e)},"setStep");async function et(e,p){const s=await e.get(N.source(p));if(s===null)throw new g("stage","bundle_invalid","source.json is missing");const n=JSON.parse(s.toString("utf8"));if(typeof n.rowParts!="object"||n.rowParts===null)throw new g("stage","bundle_invalid","source.json names no row parts");return n}m(et,"readSource");async function tt(e,p,s,n,a,r,o){const i=[];for(const t of L(s.run_id,"grants",n)){const c=await e.get(t);if(c===null)throw new g("stage","bundle_invalid",`row file ${t} is missing`);i.push(...ae(c))}if(i.length===0)return;const _=i.map(t=>({sub:be(t.sub,n.person,s.person,"grants.sub"),grantee:t.grantee}));await o(s.run_id);const f=[];for(const t of _)await Te(p,a,r,t.sub,t.grantee)===void 0&&f.push(t.grantee);if(f.length>0)throw Ce(f)}m(tt,"ensureGrants");async function Ct(e,p,s={}){const n=s.blobs??await X(),a=await E(),r=We(e.run_id);let o="start";const i=m(async t=>{o=t,await p.assertOwned(),await H(e.run_id,t),await s.atStep?.(t)},"at");let _=e.state==="committed";const f=[];try{const t=await et(n,e.run_id);if(e.source_kind==="machine"&&t.installId!==e.source_install_id)throw new g("stage","bundle_invalid",`source.json names install ${t.installId}, the run is for ${e.source_install_id}`);t.installId=e.source_install_id;const c=await Ke(a),I=[...Qe],h=await ie(a,c,[...I,"grants"]);if(!_){const l={},P=[],j=[],k=s.fleetRuntime??process.env.CRTR_RUNTIME??null;await ye(a,c,t.person,e.person),await i("open-grants"),await tt(n,a,e,t,c,k,s.openGrants??Ye),await i("publish-plugins");const F=await Ge(n,e.run_id),S=await B(e.person,()=>ze(F));if(S.unavailable.length>0){if(e.loaded_at===void 0||e.loaded_at===null)throw new g("publish-plugins","import_failed","a loading run has no loaded_at");if(Date.now()-Date.parse(e.loaded_at)>=Ve)throw new g("publish-plugins","directory_unavailable",`the directory did not answer for: ${S.unavailable.slice(0,10).join(", ")}; rerun the import once it is reachable`,{plugins:S.unavailable});await p.assertOwned(),await H(e.run_id,"waiting_for_directory");return}j.push(...S.refused),await i("stage");const J=await Le(a,e.run_id,t.counts,d=>L(e.run_id,d,t),d=>n.get(d));for(const[d,u]of Object.entries(J))l[d]={staged:u,inserted:0,mapped:0,dropped:0};const w={db:a,schema:r,target:c,catalog:h,sourcePerson:t.person,targetPerson:e.person,fleetRuntime:k,shippedBodies:t.shippedBodies??{}};await i("bind-staged");for(const[d,u]of Object.entries(await ve(w)))b(l,d,u);for(const[d,u]of Object.entries(await Se(w)))b(l,d,u);await i("rewrite-person"),await Be(w),await Ne(w),await i("prune");const U=await oe(a,r,h,t),v=t.kind==="hosted"?Fe(t.pathPrefixes??[]):[];await i("rewrite-paths"),await _e(a,r,v),await me(a,r,v,n,e.run_id),await we(a,r),await Re(w);const G=await Me(w);await fe(a,r,c,t.installId,e.person),await i("rewrite-ids");const T=await Ae(w,G);await i("drop");const $=await ge(a,r,c),q=await ke(w);for(const[d,u]of Object.entries({...U}))b(l,d,u);for(const[d,u]of Object.entries(q))b(l,d,u);for(const[d,u]of Object.entries(await he(w,{installId:t.installId,person:e.person,runId:e.run_id})))b(l,d,u);await Ee(w,{installId:t.installId,person:e.person,runId:e.run_id}),await De(w),await le(a,r,c,t.installId);for(const[d,u]of Object.entries(await ue(a,r,c)))b(l,d,u);b(l,"idempotency_keys",await pe(a,r,c)),b(l,"idempotency_keys",await ce(a,r)),t.kind==="hosted"&&await re(a,r),await i("pre-check");const Y=new Map([["messages",["seq"]],...ne.map(d=>[d,["seq"]])]);await de(a,r,c,h,I,new Set,Y),await i("blobs"),await je(a,r,c,e.person,n,e.run_id,f),await i("copy"),await B(e.person,()=>A(async d=>{await p.assertOwned({extendLeaseMs:Xe});const u=await se({db:d,runId:e.run_id,schema:r,target:c,catalog:h,source:t,person:e.person,idMap:T,pathMap:v}),C=await it(d,e.run_id,$);C>0&&(u.inserted.revisions=(u.inserted.revisions??0)+C),await Je(d,r,e.run_id,t);const M=await qe({db:d,blobs:n,runId:e.run_id,person:e.person,objectMap:T.object});for(const[z,Q]of Object.entries(M.inserted))u.inserted[z]=Q.length;return P.push(...M.unresolvedPlugins),await d.prepare("UPDATE import_runs SET counts_json = ?, loaded_at = COALESCE(loaded_at, ?) WHERE run_id = ?").run(JSON.stringify({...nt(l,u),unresolved_plugins:P,refused_plugins:j}),R(),e.run_id),u})),_=!0,await s.atStep?.("committed")}await i("verify");const y=await He(a,e.run_id,r,c,h,t.installId);if(await a.prepare("UPDATE import_runs SET verify_json = ? WHERE run_id = ?").run(JSON.stringify(y),e.run_id),!y.ok)throw new g("verify","verify_failed","the committed rows differ from the staged rows or an invariant failed",{differences:y.differences,invariants:y.invariants});await i("manifest");const O=N.manifest(e.run_id);await n.put(O,await st(e.run_id)),await K(a,e.run_id);for(const l of Ue(e.run_id))await n.delete(l);await Oe(n,e.run_id),await A(async l=>{await $e(l,e.run_id,e.person),await l.prepare("UPDATE import_runs SET state = 'done', step = 'done', manifest_key = ?, finished_at = ? WHERE run_id = ?").run(O,R(),e.run_id)})}catch(t){if(t instanceof xe)throw t;const c=at(t,o);Ze({level:"error",event:"import.run.failed",error:t,fields:{run_id:e.run_id,step:c.step,code:c.code}}),await K(a,e.run_id).catch(()=>{}),_||await Ie(n,f,!0),await a.prepare("UPDATE import_runs SET state = 'failed', failure_json = ?, finished_at = ? WHERE run_id = ?").run(JSON.stringify(c),R(),e.run_id),_&&await Pe(n,e.run_id,{keepNodeFiles:!0,bestEffort:!0})}}m(Ct,"processRun");function at(e,p){if(e instanceof g)return{step:e.step,code:e.code,message:e.message,...e.detail===void 0?{}:{detail:e.detail}};const s=e.code;return{step:p,code:typeof s=="string"?s:"import_failed",message:e instanceof Error?e.message:String(e)}}m(at,"failureOf");function b(e,p,s){(e[p]??={staged:0,inserted:0,mapped:0,dropped:0}).dropped+=s}m(b,"addDropped");function nt(e,p){for(const[s,n]of Object.entries(p.inserted))(e[s]??={staged:0,inserted:0,mapped:0,dropped:0}).inserted=n;for(const[s,n]of Object.entries(p.mapped))(e[s]??={staged:0,inserted:0,mapped:0,dropped:0}).mapped=n;return e}m(nt,"withInserted");async function it(e,p,s){const n=new Set((await e.prepareUncached("SELECT rev_id FROM revisions WHERE rev_id IN (SELECT jsonb_array_elements_text(?::jsonb))").all(JSON.stringify(s.map(o=>o.rev_id)))).map(o=>o.rev_id)),a=s.filter(o=>!n.has(o.rev_id)),r=new Map;for(const o of s)r.set(o.document,[...r.get(o.document)??[],o]);for(const[o,i]of r){const _=await te(e,o);_!==null&&await ee(e,_,i.map(f=>({rev_id:f.rev_id,parents:f.parents,body_hash:f.body_hash,rationale:f.rationale,created_at:f.created_at})))}return await W(e,p,"revisions",a.map(o=>[o.rev_id])),await W(e,p,"revision_parents",a.flatMap(o=>o.parents.map(i=>[o.rev_id,i]))),a.length}m(it,"arrive");async function st(e){const s=await(await E()).prepare("SELECT table_name, inserted_keys FROM import_manifest WHERE run_id = ? ORDER BY table_name").all(e),n=x(),a=[];n.on("data",i=>a.push(i));const r=D(n,"end"),o=m(async i=>{n.write(i,"utf8")||await D(n,"drain")},"put");for(const i of s){await o(`{"table":${JSON.stringify(i.table_name)},"keys":[`);let _=!0;for await(const f of V(i.inserted_keys))await o((_?"":",")+f.map(t=>JSON.stringify(t)).join(",")),_=!1;await o(`]}
|
|
2
2
|
`)}return n.end(),await r,Buffer.concat(a)}m(st,"manifestFile");export{Xe as COPY_LEASE_MS,Ve as GRANT_WAIT_MS,Ct as processRun};
|