@north-light/cli 0.3.695 → 0.3.696
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/clients/attach/session/connection.js +1 -1
- package/dist/clients/attach/viewer.js +374 -374
- package/dist/core/broker-client/transport-relay.d.ts +12 -1
- package/dist/core/broker-client/transport-relay.js +1 -1
- package/dist/core/runtime/runner/machine/executor.d.ts +0 -3
- package/dist/core/runtime/runner/machine/executor.js +1 -1
- package/dist/core/runtime/runner/machine/machine-executor.test.js +2 -2
- package/dist/core/runtime/runner/machine/ops.d.ts +5 -6
- package/dist/core/runtime/runner/machine/runner.d.ts +3 -0
- package/dist/core/runtime/runner/machine/runner.js +1 -1
- package/dist/daemon/api/bridge.js +4 -4
- package/dist/daemon/api/handlers/attach.js +1 -1
- package/dist/daemon/machine-daemon.js +1 -1
- package/dist/daemon/machine-link/client.d.ts +2 -0
- package/dist/daemon/machine-link/client.js +1 -1
- package/dist/daemon/machine-link/forward.d.ts +2 -4
- package/dist/daemon/machine-link/forward.js +1 -1
- package/dist/daemon/machine-link/holder.js +5 -5
- package/dist/daemon/reconcilers/node-lifecycle/machine-sweep.d.ts +1 -1
- package/dist/daemon/reconcilers/node-lifecycle/machine-sweep.js +2 -2
- package/package.json +3 -3
- package/packages/crouter-api/dist/clients/attach/session/connection.js +37 -24
- package/packages/crouter-api/dist/core/broker-client/transport-relay.js +24 -7
- package/packages/crouter-api/dist/core/runtime/runner/machine/runner.js +10 -8
- package/packages/crouter-api/dist/daemon/machine-link/forward.js +12 -11
- package/packages/crouter-api/dist/daemon/machine-link/holder.js +5 -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/self-update.mjs +7 -3
|
@@ -20,10 +20,15 @@ export interface LocalRelayTarget {
|
|
|
20
20
|
export declare class RelayTransport extends EventEmitter implements Transport {
|
|
21
21
|
private readonly nodeId;
|
|
22
22
|
private readonly target;
|
|
23
|
+
/** Whether the first dial wakes an exact parked resident; every redial does. */
|
|
24
|
+
private wakeParked;
|
|
23
25
|
private ws;
|
|
24
26
|
private closeEmitted;
|
|
25
|
-
constructor(nodeId: string, target: RelayTarget | LocalRelayTarget
|
|
27
|
+
constructor(nodeId: string, target: RelayTarget | LocalRelayTarget,
|
|
28
|
+
/** Whether the first dial wakes an exact parked resident; every redial does. */
|
|
29
|
+
wakeParked?: boolean);
|
|
26
30
|
private refusal;
|
|
31
|
+
private refusalError;
|
|
27
32
|
private get url();
|
|
28
33
|
private dial;
|
|
29
34
|
connect(): void;
|
|
@@ -46,5 +51,11 @@ export declare class RelayTransport extends EventEmitter implements Transport {
|
|
|
46
51
|
* with no listener throws, and this transport must never throw uncaught. */
|
|
47
52
|
private emitError;
|
|
48
53
|
}
|
|
54
|
+
/** The status, code and message of a refused upgrade's `{error:{code,message}}` body, for a caller that shows the refusal as the API error it is. */
|
|
55
|
+
export interface Refusal {
|
|
56
|
+
status: number;
|
|
57
|
+
code: string;
|
|
58
|
+
message: string;
|
|
59
|
+
}
|
|
49
60
|
/** `409 broker_not_ready: <message>` from a refused upgrade's `{error:{code,message}}` body. */
|
|
50
61
|
export declare function refusalMessage(status: number | undefined, body: string): string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var d=Object.defineProperty;var a=(s,e)=>d(s,"name",{value:e,configurable:!0});import{EventEmitter as l}from"node:events";import{WebSocket as h}from"ws";import{classify as f}from"../fault-classifier.js";import{AttachRefusedError as u,BrokerUnavailableError as m}from"./transport.js";function g(s,e,t){if("socketPath"in s)return`ws+unix://${s.socketPath}:/v1/nodes/${encodeURIComponent(e)}/attach?revive=0`;const r=new URL(s.previewEndpoint);return r.protocol=r.protocol==="http:"?"ws:":"wss:",r.pathname=`/v1/nodes/${encodeURIComponent(e)}/attach`,r.search=t?"?wakeParked=1":"",r.hash="",r.toString()}a(g,"relayUrl");class O extends l{static{a(this,"RelayTransport")}nodeId;target;wakeParked;ws;closeEmitted=!1;constructor(e,t,r=!0){super(),this.nodeId=e,this.target=t,this.wakeParked=r}refusal;refusalError;get url(){return g(this.target,this.nodeId,this.wakeParked)}dial(){const e=new h(this.url,{..."relayToken"in this.target?{headers:{authorization:`Bearer ${this.target.relayToken}`}}:{},perMessageDeflate:!1});return e.on("unexpected-response",(t,r)=>{let o="";r.on("data",n=>{o.length<2048&&(o+=n.toString())}),r.on("end",()=>{this.refusal=w(r.statusCode,o),this.refusalError=p(r.statusCode,o),e.terminate()})}),this.ws=e,e}connect(){const e=this.dial();e.on("open",()=>{this.emit("connect")}),e.on("message",t=>this.onMessage(t)),e.on("error",t=>this.onError(t)),e.on("close",(t,r)=>this.onClose(t,r.toString()))}redial(e){return this.wakeParked=!0,this.destroy(),this.closeEmitted=!1,new Promise((t,r)=>{const o=this.dial();let n=!1;o.on("open",()=>{n||(n=!0,this.emit("connect"),t())}),o.on("message",i=>this.onMessage(i)),o.on("error",i=>{if(n){this.onError(i);return}n=!0;try{o.terminate()}catch{}r(this.refusal===void 0?i:Object.assign(new Error(this.refusal),{refusal:this.refusalError}))}),o.on("close",(i,c)=>{n&&this.onClose(i,c.toString())})})}send(e){const t=this.ws;if(!(t===void 0||t.readyState!==h.OPEN))try{t.send(JSON.stringify(e))}catch{}}destroy(){const e=this.ws;if(e!==void 0&&e.readyState<=h.OPEN)try{e.close(1e3)}catch{}}onMessage(e){let t;try{t=JSON.parse(e.toString())}catch{return}this.emit("frame",t)}onError(e){this.emitError(Object.assign(new Error(`relay transport error: ${this.refusal??e.message}`),{refusal:this.refusalError}))}onClose(e,t){if(this.closeEmitted)return;this.closeEmitted=!0;const r=f("viewer\u2194broker",{code:e,reason:t}),o=e===1008||r.kind==="protocol"||e===1011&&(/^no running broker/.test(t)||/^no node /.test(t));e===1008?this.emitError(new u(this.nodeId,t)):o&&this.emitError(new m(this.nodeId)),this.emit("close")}emitError(e){this.listenerCount("error")>0&&this.emit("error",e)}}function p(s,e){try{const t=JSON.parse(e).error;if(s!==void 0&&typeof t?.code=="string")return{status:s,code:t.code,message:typeof t.message=="string"?t.message:""}}catch{}}a(p,"refusalOf");function w(s,e){try{const t=JSON.parse(e).error;if(typeof t?.code=="string")return`attach refused (${s??"?"} ${t.code}): ${typeof t.message=="string"?t.message:""}`}catch{}return`attach refused (${s??"?"})`}a(w,"refusalMessage");export{O as RelayTransport,w as refusalMessage};
|
|
@@ -23,9 +23,6 @@ export declare function findBrokers(): Promise<Array<{
|
|
|
23
23
|
node: string;
|
|
24
24
|
command: string;
|
|
25
25
|
}>>;
|
|
26
|
-
/** Reads the start bundle. A transient failure (connection error, timeout, 502/503/504) is asked again with doubling backoff until the budget above is spent, so a brief
|
|
27
|
-
* control-plane restart does not end the launch; any other non-2xx answer is permanent and fails at once with its status. The link dropping (`signal`) ends the wait. */
|
|
28
|
-
export declare function fetchBundle(apiUrl: string, executionId: string, token: string, signal?: AbortSignal): Promise<StartBundleDTO>;
|
|
29
26
|
/** The recipe's `-e` extension paths name files of the control plane's install (`/opt/crouter/runtime/generations/...`), and its release may ship a different
|
|
30
27
|
* set of canvas extensions than this install. So the mandatory canvas extensions are this install's complete list (`mergeCanvasExtensions`), whatever the recipe
|
|
31
28
|
* carried of them; the recipe's own extensions are kept and must exist on this machine, or the launch is refused. Every other argument is the recipe's. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var $=Object.defineProperty;var c=(n,r)=>$(n,"name",{value:r,configurable:!0});import{spawn as B}from"node:child_process";import{closeSync as j,existsSync as w,mkdirSync as b,openSync as K,statSync as J}from"node:fs";import{rm as V}from"node:fs/promises";import{basename as O,dirname as N,join as I}from"node:path";import{fileURLToPath as X}from"node:url";import{emitEvent as W}from"../../../events/emit.js";import{contextDir as Y,jobDir as q,nodeRunDir as P,crtrHome as M,viewSocketPath as z}from"../../../canvas/paths.js";import{captureTeardownSnapshot as Q,isAnyPidAlive as Z,killProcessTreePids as D,listProcessTableAsync as g}from"../../../canvas/pid.js";import{scopesFilePath as L}from"../../../canvas/paths.js";import{writeFileBeneath as A}from"../../../spaces/open-beneath.js";import{FRONT_DOOR_ENV as ee}from"../../front-door-env.js";import{brokerCommandDeclaresCanvasHome as ne}from"../../broker-ownership.js";import{isShippedCanvasExtension as oe}from"../../../canvas/extensions.js";import{CANVAS_EXTENSIONS as te,mergeCanvasExtensions as re}from"../../canvas-extensions.js";import{layoutRoot as ie,runtimeRoot as ce}from"../../../layout.js";import{composeAppProcessEnv as se,overlayBrokerEnv as ae}from"../../spawn-env.js";const k=c(()=>I(N(X(import.meta.url)),"..","..","broker-cli.js"),"brokerEntry"),G=c(n=>{if(n!==void 0)try{process.kill(-n,"SIGKILL")}catch{}},"killGroup"),de=c(n=>new Promise(r=>setTimeout(r,n)),"sleep");async function x(){const n=[],r=await g();if(r===null)throw new Error("the process table could not be read, so which brokers are running is unknown");for(const{pid:t,command:e}of r){const o=/broker-cli\.js .*--epoch (\S+) (\S+)\s*$/.exec(e);o!==null&&n.push({pid:t,execution:o[1],node:o[2],command:e})}return n}c(x,"findBrokers");const ue=["CRTR_HOME","CRTR_RUNTIME_HOME"];function H(n,r){const t={...n};for(const e of ue)delete t[e];return t.CRTR_CONTEXT_DIR!==void 0&&(t.CRTR_CONTEXT_DIR=Y(r.id,t.CRTR_GRANTEE??r.app)),t.CRTR_SCOPES_FILE!==void 0&&(t.CRTR_SCOPES_FILE=L(r.id)),t}c(H,"localLaunchEnv");function fe(n){const r=c(i=>O(i).replace(/\.[jt]s$/,""),"stem"),t=new Set(te.map(r)),e=c(i=>oe(i)||O(N(i))==="pi-extensions"&&(t.has(r(i))||r(i).startsWith("canvas-")&&!w(i)),"shipped"),o=[],s=[];for(let i=0;i<n.length;i++)if(n[i]==="-e"&&n[i+1]!==void 0){const d=n[++i];if(e(d))continue;if(!w(d))throw new Error(`extension ${d} does not exist on this machine`);s.push(d)}else o.push(n[i]);return[...re(s).flatMap(i=>["-e",i]),...o]}c(fe,"localExtensionArgv");function le(n,r,t){const e=JSON.parse(n);return JSON.stringify({...e,argv:fe(e.argv),env:H(e.env??{},r),...t===void 0?{}:{start:t}})}c(le,"machineLaunchRecipe");function pe(n,r,t){const e=n.launch,o=ae({argv:[],env:H(e.env??{},n.node)},se(n.node.cwd,null,n.node.app,n.machine_env??{},{}));return Object.assign(o,{CRTR_HOME:ie(),CRTR_RUNTIME_HOME:process.env.CRTR_RUNTIME_HOME??ce(),CRTR_API_URL:r.apiUrl,CRTR_EXECUTION_ID:t,CRTR_ENVIRONMENT_ID:r.environmentId,CRTR_VIEW_WSS:"0",[ee]:"1"})}c(pe,"machineBrokerEnv");async function U(n,r,t){const{tree:e,identities:o}=Q(n,null,t);if(o===null)return{confirmed:!1,error:`the process tree of broker ${n} could not be read, so shutdown cannot be confirmed`};const s=c(async(i,d)=>{for(let l=0;Z(i);l+=100){if(l>=d)return!1;await de(100)}return!0},"waitUntilDead");try{process.kill(n,"SIGTERM")}catch{}return await s([n],r),D(e,"SIGTERM",o),await s(e,2e3)?{confirmed:!0}:(D(e,"SIGKILL",o),await s(e,5e3)?{confirmed:!0}:{confirmed:!1,error:`broker process tree of ${n} survived SIGKILL`})}c(U,"stopBroker");async function Pe(n=1e4){const t=(await Promise.all((await x()).filter(e=>ne(e.command,M())).map(e=>U(e.pid,n)))).filter(e=>!e.confirmed);if(t.length>0)throw new Error(t.map(e=>e.error??"a broker did not stop").join("; "))}c(Pe,"stopAllBrokers");function Me(n){const r=(n.stopGraceS??10)*1e3,t=c(async e=>(await x()).find(o=>o.execution===e),"brokerOf");return{async start(e,o){const s={};let i=performance.now();const d=c(a=>{const u=performance.now();s[a]=Math.round((u-i)*10)/10,i=u},"stepDone"),l=await t(e.executionId);if(d("process_lookup"),l!==void 0)return{pid:l.pid,timings:s};if(o?.throwIfAborted(),!w(e.cwd)||!J(e.cwd).isDirectory())throw new Error(`the node's cwd ${e.cwd} is not a directory on this machine`);if(!w(k()))throw new Error(`the broker entry ${k()} does not exist`);if(e.bundle===void 0)throw new Error("the control plane carried no start bundle: it runs an older release than this Mac");const{bundle:E}=e,T=E.launch,m=P(e.nodeId);b(m,{recursive:!0}),A(m,I(m,"broker-launch.json"),le(e.launchJson,E.node,e.start),{atomic:!0,mode:384}),T.env?.CRTR_SCOPES_FILE!==void 0&&A(m,L(e.nodeId),JSON.stringify(T.scopes??[]),{atomic:!0});const S=q(e.nodeId);b(S,{recursive:!0});const R=K(I(S,"broker.log"),"a"),y=pe(E,n,e.executionId);delete y.CRTR_NODE_TOKEN,d("file_writes");try{o?.throwIfAborted();const a=B(process.execPath,[k(),"--canvas-home",M(),"--epoch",e.executionId,e.nodeId],{cwd:e.cwd,detached:!0,stdio:["ignore",R,R,"pipe"],env:y});let u,v=!1;const C=c(()=>{u!==void 0&&n.onExit?.({execution:e.executionId,node:e.nodeId,...u})},"report");a.once("exit",(_,f)=>{u={code:_,signal:f},v&&C()});const p=a.stdio[3];if(p==null||!("end"in p))throw G(a.pid),new Error("broker token pipe did not open");const F=await new Promise((_,f)=>{a.once("error",f),a.once("spawn",()=>{a.off("error",f),p.once("error",h=>{G(a.pid),f(h)}),p.end(e.nodeToken,h=>{h?f(h):_(a.pid)})})});return v=!0,C(),a.unref(),d("spawn_and_token_pipe"),W({level:"info",event:"machine.start.timing",node_id:e.nodeId,fields:{execution:e.executionId,...s}}),{pid:F,timings:s}}finally{j(R)}},async wake({execution:e}){const o=await t(e.executionId);if(o===void 0)return"no_broker";try{return process.kill(o.pid,"SIGUSR1"),"signalled"}catch(s){if(s.code==="ESRCH")return"no_broker";throw s}},async stop({execution:e,options:o}){const s=await t(e.executionId);return s===void 0?{confirmed:!0}:await U(s.pid,r,o.excludePid)},async status({execution:e}){const o=await t(e.executionId);return o===void 0?{state:"gone"}:{state:"running",pid:o.pid}},async"status.all"(e){return{running:(await x()).map(o=>({execution:o.execution,pid:o.pid}))}},async delete({nodeId:e}){return await V(P(e),{recursive:!0,force:!0}),null},async viewer({execution:e}){return{kind:"unix",path:z(e.nodeId)}}}}c(Me,"createMachineExecutor");export{Me as createMachineExecutor,x as findBrokers,fe as localExtensionArgv,pe as machineBrokerEnv,le as machineLaunchRecipe,Pe as stopAllBrokers};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var N=Object.defineProperty;var u=(n,o)=>N(n,"name",{value:o,configurable:!0});import{after as q,before as x,test as
|
|
1
|
+
var N=Object.defineProperty;var u=(n,o)=>N(n,"name",{value:o,configurable:!0});import{after as q,before as x,test as m}from"node:test";import t from"node:assert/strict";import{spawn as y}from"node:child_process";import{mkdirSync as f,mkdtempSync as E,readFileSync as P,rmSync as v,writeFileSync as _}from"node:fs";import{tmpdir as w}from"node:os";import{join as p}from"node:path";import{EventEmitter as A}from"node:events";import{Readable as k}from"node:stream";import{createNode as D}from"../../../canvas/canvas.js";import{closeDb as H,openDb as T}from"../../../canvas/db.js";import{isPidAlive as R}from"../../../canvas/pid.js";import{bindPerson as M,installTerminalGrant as L,useEmptyPersonSettings as F}from"../../../__tests__/helpers/person.js";import{setAppEnvVar as O}from"../../../profiles/app-env-store.js";import{setProfileEnvVar as S}from"../../../profiles/env-store.js";import{createProfile as U}from"../../../profiles/manifest.js";import{putEnvRow as j}from"../../../secrets/env-rows.js";import{appSpace as V}from"../../../layout.js";import{executionStartRoutes as G}from"../../../../daemon/api/handlers/execution-start.js";import{Router as J}from"../../../../daemon/api/router.js";import{contextDir as C,scopesFilePath as g}from"../../../canvas/paths.js";import{layoutRoot as $,runtimeRoot as X}from"../../../layout.js";import{CANVAS_EXTENSIONS as d}from"../../canvas-extensions.js";import{createMachineExecutor as K,localExtensionArgv as B,machineBrokerEnv as h,machineLaunchRecipe as I}from"./executor.js";let l;const Y={HOME:process.env.HOME,CRTR_HOME:process.env.CRTR_HOME};x(()=>{process.env.HOME=l=E(p(w(),"crtr-machine-exec-")),process.env.CRTR_HOME=p(l,".crouter"),f(process.env.CRTR_HOME,{recursive:!0})}),q(async()=>{await H(),v(l,{recursive:!0,force:!0});for(const[n,o]of Object.entries(Y))o===void 0?delete process.env[n]:process.env[n]=o});async function z(n,o){const i=new J().registerAll(G),a=Object.assign(k.from([]),{method:"GET",url:`/v1/executions/${o}/start`,headers:{}});let r="";const e=Object.assign(new A,{headersSent:!1,writableEnded:!1,writableFinished:!1});return e.setHeader=()=>e,e.writeHead=()=>(e.headersSent=!0,e),e.end=s=>(s&&(r+=s),e.writableEnded=!0,e.writableFinished=!0,e),await i.handle(a,e,null,n),JSON.parse(r)}u(z,"bundleFor"),m("a machine broker gets the profile, app and deployment rows, the app pi dir and the launch env, with the process runner's precedence",async()=>{await F(),await T();const n=await L(),o=(await U("machine-env")).profileId;await O("app:terminal","SHARED","from-app",n),await O("app:terminal","APP_SECRET","app-secret",n),await S(o,"SHARED","from-profile",n),await S(o,"PROFILE_VAR","profile-value",n),await j({person:null,kind:"deployment",id:"_deployment"},"DEPLOY_VAR","deploy-value");const i=p(l,"work");f(i,{recursive:!0}),await D({node_id:"m1",name:"m1",created:new Date().toISOString(),cwd:i,kind:"general",mode:"base",lifecycle:"resident",status:"active",parent:null,profile_id:o,grantee:"app:terminal"}),await(await T()).prepare("INSERT INTO executions (execution_id, node_id, state, started_at, launch_json, runner) VALUES ('em1', 'm1', 'launching', 't', ?, 'machine')").run(JSON.stringify({argv:["x"],env:{LAUNCH_VAR:"launch",CRTR_NODE_ID:"m1"}}));const a={class:"broker",app:"app:terminal",node:"m1",run:null,uid:process.getuid?.()??0,sub:await M(),grant:null,client_id:null,scopes:null},r=await z(a,"em1");t.equal(r.machine_env?.APP_SECRET,"app-secret");const e=h(r,{apiUrl:"http://cloud.invalid",environmentId:"env1"},"em1");t.equal(e.APP_SECRET,"app-secret"),t.equal(e.PROFILE_VAR,"profile-value"),t.equal(e.DEPLOY_VAR,"deploy-value"),t.equal(e.SHARED,"from-profile","the profile's row wins over the app's"),t.equal(e.LAUNCH_VAR,"launch"),t.equal(e.PI_CODING_AGENT_DIR,p(V("app:terminal").home,".pi","agent")),t.equal(e.CRTR_API_URL,"http://cloud.invalid"),t.equal(e.CRTR_EXECUTION_ID,"em1"),t.doesNotThrow(()=>h({...r,node:{...r.node,profile:"profile-the-mac-does-not-hold"}},{apiUrl:"http://cloud.invalid",environmentId:"env1"},"em1")),t.equal(e.GITHUB_TOKEN,void 0)}),m("stop ends the broker and the detached command it left behind, and confirms both gone",async()=>{const n=E(p(w(),"crtr-machine-stop-")),o=p(n,"child.pid"),i=p(n,"broker-cli.js");_(i,`const { spawn } = require('node:child_process');
|
|
2
2
|
const c = spawn('sleep', ['300'], { detached: true, stdio: 'ignore' }); c.unref();
|
|
3
3
|
require('node:fs').writeFileSync(${JSON.stringify(o)}, String(c.pid));
|
|
4
|
-
setInterval(() => {}, 1000);`);const a=
|
|
4
|
+
setInterval(() => {}, 1000);`);const a=y(process.execPath,[i,"--canvas-home",n,"--epoch","exec-stop-1","node-stop-1"],{detached:!0,stdio:"ignore"});a.unref();try{let r=0;for(let c=0;c<100&&r===0;c++)try{r=Number(P(o,"utf8"))}catch{await new Promise(b=>setTimeout(b,50))}t.ok(r>0&&R(r),"the detached child is running");const e=K({apiUrl:"http://cloud.invalid",environmentId:"env1",stopGraceS:3});t.ok((await e["status.all"]({})).running.some(c=>c.execution==="exec-stop-1"&&c.pid===a.pid),"status.all lists the running broker");const s=await e.stop({execution:{executionId:"exec-stop-1",nodeId:"node-stop-1"},options:{reason:"test"}});t.deepEqual(s,{confirmed:!0}),t.equal(R(a.pid),!1,"the broker is gone"),t.equal(R(r),!1,"the detached child is gone")}finally{try{process.kill(-a.pid,"SIGKILL")}catch{}v(n,{recursive:!0,force:!0})}}),m("a bundle the control plane built on its Linux layout starts a broker on this machine's own home, runtime, context, scopes and extension paths",()=>{const n={CRTR_HOME:"/work/crtr",CRTR_RUNTIME_HOME:"/opt/crouter/runtime",CRTR_CONTEXT_DIR:"/work/crtr/apps/terminal/nodes/m2/context",CRTR_SCOPES_FILE:"/work/crtr/runtime/nodes/m2/run/scopes.json",CRTR_NODE_ID:"m2",CRTR_KIND:"general",CRTR_GRANTEE:"app:terminal",CRTR_PROFILE_ID:"p-1"},i={launch:{argv:[...d.flatMap(e=>["-e",`/opt/crouter/runtime/generations/96276ec4/dist/pi-extensions/${e.split("/").pop()}`]),"-n","m2"],env:n,scopes:["a:b"]},node:{id:"m2",app:"app:terminal",cwd:l,profile:null},machine_env:{APP_SECRET:"s"}},a=h(i,{apiUrl:"http://cloud.invalid",environmentId:"env1"},"em2");t.equal(a.CRTR_HOME,$()),t.equal(a.CRTR_RUNTIME_HOME,process.env.CRTR_RUNTIME_HOME??X()),t.equal(a.CRTR_CONTEXT_DIR,C("m2","app:terminal")),t.equal(a.CRTR_SCOPES_FILE,g("m2")),t.equal(a.CRTR_NODE_ID,"m2"),t.equal(a.CRTR_PROFILE_ID,"p-1"),t.equal(a.APP_SECRET,"s");for(const[e,s]of Object.entries(a))t.ok(!/\/work\/crtr|\/opt\/crouter/.test(s??""),`${e} names a control plane path: ${s}`);const r=JSON.parse(I(JSON.stringify(i.launch),i.node));t.deepEqual(r.argv.filter((e,s)=>r.argv[s-1]==="-e"),d),t.equal(r.argv.at(-1),"m2"),t.equal(r.env.CRTR_HOME,void 0),t.equal(r.env.CRTR_CONTEXT_DIR,C("m2","app:terminal")),t.equal(r.env.CRTR_SCOPES_FILE,g("m2")),t.deepEqual(r.scopes,["a:b"]),t.ok(!/\/work\/crtr|\/opt\/crouter/.test(JSON.stringify(r))),t.throws(()=>I(JSON.stringify({argv:["-e","/opt/crouter/runtime/generations/x/custom.js"],env:{}}),{id:"m2",app:"app:terminal"}),/does not exist on this machine/)}),m("the broker's mandatory extensions are this install's complete list, whatever set the control plane's release shipped",()=>{const n=u(e=>["-e",`/opt/crouter/runtime/generations/old/dist/pi-extensions/${e}.js`],"server"),o=p(l,"custom-ext.js");_(o,"");const i=[...d,o].flatMap(e=>["-e",e]),r=[...d.map(e=>e.split("/").pop().replace(/\.[jt]s$/,"")).slice(1).flatMap(n),...n("canvas-retired-hook"),"-e",o,"-n","label","prompt text"];t.deepEqual(B(r),[...i,"-n","label","prompt text"])});
|
|
@@ -12,15 +12,14 @@ export type MachineOp = (typeof MACHINE_OPS)[number];
|
|
|
12
12
|
* the UPDATE that finishes any call (answered, failed, lost or offline) sets `args_json` to '{}', and a requeue from `sent` to `pending` keeps it. A row nothing finishes (its awaiter died and no link ever claims it) keeps its arguments: no code deletes `machine_calls` rows. */
|
|
13
13
|
export type MachineStartArgs = RunnerStartInput & {
|
|
14
14
|
nodeToken: string;
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
/** The start data written into `broker-launch.json` for the broker; absent, the broker asks `cycle-start` as before. */
|
|
15
|
+
bundle: StartBundleDTO;
|
|
16
|
+
/** The start data written into `broker-launch.json` for the broker; absent, the broker asks `cycle-start`. */
|
|
18
17
|
start?: StartDataDTO;
|
|
19
18
|
};
|
|
20
|
-
/** `timings` are the Mac's own step durations in ms inside `executor.start
|
|
19
|
+
/** `timings` are the Mac's own step durations in ms inside `executor.start`. */
|
|
21
20
|
export interface MachineStartResult {
|
|
22
21
|
pid: number | null;
|
|
23
|
-
timings
|
|
22
|
+
timings: Record<string, number>;
|
|
24
23
|
}
|
|
25
24
|
export interface MachineWakeArgs {
|
|
26
25
|
execution: RunnerExecution;
|
|
@@ -33,7 +32,7 @@ export interface MachineStatusArgs {
|
|
|
33
32
|
execution: RunnerExecution;
|
|
34
33
|
}
|
|
35
34
|
/** Every broker running on the machine, from one scan of its process table: the control plane's timed check of all its executions
|
|
36
|
-
* there in one call.
|
|
35
|
+
* there in one call. */
|
|
37
36
|
export type MachineStatusAllArgs = Record<string, never>;
|
|
38
37
|
export interface MachineStatusAllResult {
|
|
39
38
|
running: Array<{
|
|
@@ -1,9 +1,12 @@
|
|
|
1
|
+
import type { StartBundleDTO } from '../../../../api/index.js';
|
|
1
2
|
import type { Runner, RunnerStartInput } from '../types.js';
|
|
2
3
|
export interface MachineRunnerDeps {
|
|
3
4
|
/** The machine environment a node runs in. Default: the node's profile's `environment_id`, which must be kind `machine`. */
|
|
4
5
|
environmentOf?(nodeId: string): Promise<string>;
|
|
5
6
|
/** Mints the execution's node token (the execution must be `launching` and have none). Default: `mintNodeToken`. */
|
|
6
7
|
mintToken?(input: RunnerStartInput): Promise<string>;
|
|
8
|
+
/** The start bundle the `start` call carries. Default: `buildStartBundle` for the node, as create-and-start builds it. */
|
|
9
|
+
bundle?(input: RunnerStartInput): Promise<StartBundleDTO>;
|
|
7
10
|
}
|
|
8
11
|
/** The machine environment of a node's profile, or null when the profile points at no machine environment. */
|
|
9
12
|
export declare function machineEnvironmentOfNode(nodeId: string): Promise<string | null>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var m=Object.defineProperty;var i=(r,e)=>m(r,"name",{value:e,configurable:!0});import{getNode as f}from"../../../canvas/canvas.js";import{openDb as w}from"../../../canvas/db.js";import{personIdAsync as l}from"../../../canvas/person.js";import{mintExecutionToken as u}from"../../../canvas/node-tokens.js";import{callMachine as d}from"./call.js";import{machineEnvironmentOfProfile as h}from"./environment.js";import{MachineLostError as p,MachineOfflineError as E}from"./ops.js";async function y(r){const e=await(await w()).prepare("SELECT profile_id FROM nodes WHERE node_id = ?").get(r);return e?.profile_id==null?null:await h(e.profile_id)}i(y,"machineEnvironmentOfNode");const I=i(async r=>{const e=await y(r);if(e===null)throw new Error(`node ${r} has no machine environment`);return e},"defaultEnvironmentOf"),v=i(async r=>{const{buildStartBundle:e}=await import("../../../../daemon/api/handlers/execution-start.js"),n=await f(r.nodeId);return await e({nodeId:r.nodeId,app:n?.grantee??"app:terminal",sub:n?.sub??await l(),launchJson:r.launchJson,runner:"machine"})},"defaultBundle"),s=i(r=>r instanceof Error?r:new Error(String(r)),"asError");function S(r={}){const e=r.environmentOf??I;return{kind:"machine",async start(n){const a=await e(n.nodeId),t=await(r.bundle??v)(n),c=await(r.mintToken??(o=>u(o.executionId,o.nodeId)))(n);try{return{pid:(await d(a,"start",{...n,nodeToken:c,bundle:t})).pid,exited:null}}catch(o){throw o instanceof p?new E(a,o.message,!0):o}},async wake(n){return await d(await e(n.nodeId),"wake",{execution:n})},async stop(n,a){try{const t=await d(await e(n.nodeId),"stop",{execution:n,options:a});return t.error===void 0?{confirmed:t.confirmed}:{confirmed:t.confirmed,error:new Error(t.error)}}catch(t){return{confirmed:!1,error:s(t)}}},async status(n){try{return await d(await e(n.nodeId),"status",{execution:n})}catch(a){return{state:"unknown",error:s(a).message}}},async delete(n){await d(await e(n),"delete",{nodeId:n})},async viewerAddress(n){return{kind:"machine",environmentId:await e(n.nodeId),nodeId:n.nodeId}}}}i(S,"createMachineRunner");export{S as createMachineRunner,y as machineEnvironmentOfNode};
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
var
|
|
1
|
+
var re=Object.defineProperty;var i=(r,e)=>re(r,"name",{value:e,configurable:!0});import{WebSocketServer as te}from"ws";import{general as ne}from"../../core/errors.js";import{toErrorBody as ie}from"./map.js";import{isSafeNodeId as D,viewSocketPath as oe}from"../../core/canvas/paths.js";import{getNode as U}from"../../core/canvas/index.js";import{requestPersonId as ae,runAsPerson as ce}from"../../core/canvas/person-state.js";import{BROKER_READ_CAPS as se,CLIENT_READ_CAPS as fe,FrameDecoder as le,FrameOverflowError as ue}from"../../core/runtime/broker-protocol.js";import{emitEvent as A}from"../../core/events/emit.js";import{addStepTiming as de}from"../../core/step-timings.js";import{markAt as me,timedSpan as T,withLoggedStepTimings as he}from"../../core/logged-step-timings.js";import{classify as O}from"../../core/fault-classifier.js";import{clearFault as E,markNodeRead as pe,recordFault as V}from"../../core/canvas/recovery.js";import{decideAttachRevive as we}from"../../core/runtime/revive.js";import{connectViewSocket as ye,connectWssView as ke,probeViewSocket as ve,waitForBrokerViewSocket as ge,waitForWssView as L}from"../../core/runtime/view-socket.js";import{liveExecutionForNode as _e,recordExecutionAwake as be}from"../../core/canvas/executions.js";import{settleSandboxBeforeWake as Ae}from"../reconcilers/ledger-sandbox.js";import{runnerForExecution as Ee}from"../../core/runtime/runner/index.js";import{isBeneathRefusal as Se}from"../../core/spaces/open-beneath.js";import{openMachineView as xe,waitForMachineView as H}from"../machine-link/forward.js";import{attachViewer as J,detachViewer as Re,holdViewerForRedial as $e,presentViewer as Be}from"./viewer-presence.js";const j=3e4,Ce=new te({noServer:!0,maxPayload:se.maxLineBytes}),Te=25e3,Oe=6e4;function Ve(r,e=Te,a=Oe){let n=!0,c=!1,m=Date.now();const h=i(()=>{n=!0},"acknowledge"),u=i(()=>{c||(c=!0,clearInterval(v),r.off("pong",h))},"stop");r.on("pong",h);const v=setInterval(()=>{if(Date.now()-m>a){n=!0;return}if(!n){u(),r.terminate();return}n=!1;try{r.ping()}catch{u(),r.terminate()}},e);return v.unref(),{stop:u,noteActivity:i(()=>{m=Date.now()},"noteActivity")}}i(Ve,"startRemoteAttachHeartbeat");function N(r){const e=Buffer.from(r,"utf8");return e.byteLength<=123?r:e.subarray(0,123).toString("utf8")}i(N,"clampReason");function k(r,e,a,n,c){de("refused_status",e);const m=JSON.stringify({error:{code:n,message:c,origin:"runtime"}}),h=`HTTP/1.1 ${e} ${a}\r
|
|
2
2
|
content-type: application/json; charset=utf-8\r
|
|
3
|
-
content-length: ${Buffer.byteLength(
|
|
3
|
+
content-length: ${Buffer.byteLength(m)}\r
|
|
4
4
|
connection: close\r
|
|
5
5
|
\r
|
|
6
|
-
`+
|
|
6
|
+
`+m;try{r.end(h)}catch{try{r.destroy()}catch{}}}i(k,"refuseUpgrade");function q(r,e){const{status:a,body:n}=ie(e);k(r,a,"Refused",n.error.code,n.error.message)}i(q,"refuseWithError");function Ne(r){if(new URL(r.url??"/","http://127.0.0.1").searchParams.get("revive")==="0")return!0;const a=r.headers["x-crtr-attach-revive"];return(Array.isArray(a)?a[0]:a)==="0"}i(Ne,"reviveOptedOut");function Pe(r){return new URL(r.url??"/","http://127.0.0.1").searchParams.get("wakeParked")==="1"}i(Pe,"wakeParkedRequested");function K(r){return r===1e3||r===1001||r===1005}i(K,"isCleanViewerClose");function w(r,e,a){a.catch(n=>A({level:"error",event:e,node_id:r,error:n}))}i(w,"detach");async function Q(r){const e=await _e(r);return e===null||e.runner==="process"?{kind:"unix",path:oe(r)}:(e.runner==="blaxel"&&e.idleAt!==null&&(await Ae(e.executionId,Date.now()),await be(e.executionId)),Ee(e.runner).viewerAddress(e))}i(Q,"brokerViewAddress");function Fe(r,e){return e.kind==="machine"?xe(e.environmentId,r):e.kind==="wss"?ke(e.url,e.headers):ye(r)}i(Fe,"connectBrokerView");function Me(r,e,a){return e.kind==="wss"?L(e.url,e.headers,void 0,a):ve(r,a)}i(Me,"probeBrokerView");async function We(r,e,a,n,c){const m=[];let h=i(t=>{m.push(t)},"relayMessage");if(r.on("message",t=>h(t)),!D(e)){c?.destroy();try{r.close(1008,N(`invalid node id: ${e}`))}catch{}return}if(await U(e)===null){c?.destroy();try{r.close(1011,N(`no node ${e}`))}catch{}return}const u=performance.now();await E(e,{link:"viewer\u2194crtrd"});const v=performance.now(),o=c??Fe(e,a),f=i(()=>Math.round((performance.now()-v)*10)/10,"sinceOpen"),g=i(t=>{A({level:"info",event:"daemon.timing.bridge_channel",node_id:e,fields:{step:t,address_kind:a.kind,since_open_ms:f(),since_bridge_start_ms:Math.round((performance.now()-u)*10)/10}})},"bridgeMark");c===void 0&&g("channel_opened");const _=new le(fe);let y=!1,S=!1,x,P=!1,F=!1,$="controller",M=Promise.resolve(),R=!1;const B=[];let C=!1;const W=i(()=>{c===void 0&&g("channel_connected"),P=!0,!y&&R&&w(e,"daemon.bridge.presence_failed",J(e,r)),w(e,"daemon.bridge.connect_failed",E(e,{link:"relay\u2194broker"}))},"onBrokerConnect");c===void 0&&o.on("connect",W);const p=i((t,l,s=!1)=>{if(!y){if(y=!0,w(e,"daemon.bridge.presence_failed",s?$e(e,r):Re(e,r)),x?.stop(),!o.destroyed)try{o.destroy()}catch{}try{r.close(t,N(l))}catch{}}},"teardown");x=Ve(r);const z=i(async t=>{x?.noteActivity();let l;try{l=_.push(t)}catch(s){const d=s instanceof ue?`broker sent an oversized frame (${s.message})`:`failed to decode a broker frame for ${e}`;p(1009,d);return}B.push(...l),C||await G()},"onData"),G=i(async()=>{C=!0;try{for(;B.length>0&&!y;){const t=B.splice(0);let l;try{l=await n($)}catch(d){A({level:"error",event:"daemon.bridge.attach_recheck_failed",node_id:e,error:d}),p(1011,"revoked");return}if(y)return;if(!l){p(1008,"revoked");return}let s=!1;for(const d of t)r.readyState===r.OPEN&&(r.send(JSON.stringify(d)),d?.type==="welcome"&&(s=!0,g("welcome_forwarded")));if(R&&s)try{await Be(e,r)&&await pe(e)}catch(d){A({level:"warn",event:"daemon.bridge.present_failed",node_id:e,error:d})}}}finally{C=!1}},"drainOutbound");o.on("data",t=>w(e,"daemon.bridge.data_failed",z(t)));const X=i(async t=>{const l=t.code==="ECONNREFUSED"||t.code==="ENOENT"?`no running broker for ${e}`:`view socket error for ${e}: ${t.message}`;try{const s=O("relay\u2194broker",t);await V(e,{link:"relay\u2194broker",op:"bridge socket",kind:s.kind,retry:{disposition:"manual"},message:t.message})}finally{p(1011,l,!0)}},"onSocketError");o.on("error",t=>w(e,"daemon.bridge.socket_error_failed",X(t)));const Y=i(async t=>{if(!(y||t))try{await E(e,{link:"relay\u2194broker"})}finally{p(1e3,"broker socket closed",!0)}},"onSocketClose");o.on("close",t=>w(e,"daemon.bridge.socket_close_failed",Y(t)));const Z=i(async(t,l)=>{const s=l.toString("utf8");if(y){K(t)&&await E(e,{link:"viewer\u2194crtrd"});return}try{if(K(t))await E(e,{link:"viewer\u2194crtrd"});else if(!S){S=!0;const d=O("viewer\u2194crtrd",{code:t,reason:s});await V(e,{link:"viewer\u2194crtrd",op:"remote attach websocket",kind:d.kind,retry:{disposition:"auto"},message:s||`remote attach closed (${t})`})}}finally{p(t,s||`remote attach closed (${t})`)}},"onWsClose");r.on("close",(t,l)=>w(e,"daemon.bridge.ws_close_failed",Z(t,l)));const I=i(async()=>{try{if(!S){S=!0;const t=O("viewer\u2194crtrd",{code:1006,reason:"remote attach websocket error"});await V(e,{link:"viewer\u2194crtrd",op:"remote attach websocket",kind:t.kind,retry:{disposition:"auto"},message:"remote attach websocket error"})}}finally{p(1011,"remote attach websocket error")}},"onWsError");r.on("error",()=>w(e,"daemon.bridge.ws_error_failed",I())),h=i(t=>{if(y||o.destroyed)return;x?.noteActivity();const s=(Array.isArray(t)?Buffer.concat(t):Buffer.isBuffer(t)?t:Buffer.from(new Uint8Array(t))).toString("utf8");if(!F)try{const b=JSON.parse(s);b?.type==="hello"&&(g("hello_received"),F=!0,$=b.role==="observer"?"observer":"controller",R=b.attends!==!1,R&&P&&w(e,"daemon.bridge.presence_failed",J(e,r)))}catch{}const d=s.endsWith(`
|
|
7
7
|
`)?s:s+`
|
|
8
|
-
`,
|
|
8
|
+
`,ee=i(()=>{try{o.write(d)}catch{}},"write");M=M.then(async()=>{y||(await n($)?ee():p(1008,"revoked"))}).catch(b=>{A({level:"error",event:"daemon.bridge.attach_recheck_failed",node_id:e,error:b}),p(1011,"revoked")})},"relayMessage");for(const t of m.splice(0))h(t);c!==void 0&&(c.destroyed?p(1011,`no running broker for ${e}`,!0):W())}i(We,"bridgeConnection");async function cr(r,e,a,n,c){await he("attach_upgrade",{node:n},r,()=>De(r,e,a,n,c))}i(cr,"handleAttachUpgrade");async function De(r,e,a,n,c){const m=ae(),h=m===void 0?c:o=>ce(m,()=>c(o));e.on("error",()=>{});let u,v=!1;try{if(!D(n)){k(e,400,"Bad Request","invalid_node_id",`invalid node id: ${n}`);return}if(await T("admission",async()=>await U(n)===null)){k(e,404,"Not Found","node_not_found",`no node ${n}`);return}let o;if(Ne(r)){o=await Q(n);let f;if(o.kind==="machine"?(u=await H(o.environmentId,n,void 0,250)??void 0,f=u!==void 0):f=await Me(n,o,o.kind==="wss"?j:250),!f){k(e,409,"Conflict","node_dormant",`node ${n} is dormant and revive was opted out (?revive=0)`);return}}else{let f;try{const _=await T("revive_decision",async()=>await we(n,{resume:!0,capacity:"refuse"},Pe(r)));if(_.parked){k(e,409,"Conflict","node_dormant",`node ${n} is parked; attach with ?wakeParked=1 to wake it`);return}f=_.result.launch?.exited}catch(_){q(e,_);return}if(o=await T("address_lookup",async()=>await Q(n)),o.kind==="machine"&&(u=await H(o.environmentId,n,f,j)??void 0),!(o.kind==="machine"?u!==void 0:o.kind==="wss"?await L(o.url,o.headers,f):await ge(n,f))){o.kind==="machine"?q(e,ne(`the broker for ${n} on its machine did not accept a viewer after revive`)):k(e,409,"Conflict","broker_not_ready",`broker view socket for ${n} did not become listenable after revive`);return}}if(e.destroyed)return;me("upgrading"),Ce.handleUpgrade(r,e,a,f=>{v=!0,w(n,"daemon.bridge.connection_failed",We(f,n,o,h,u).catch(g=>{throw u?.destroy(),g}))})}catch(o){const f=o instanceof Error?o.message:String(o);if(Se(o)){k(e,400,"Bad Request","invalid_request",f);return}k(e,500,"Internal Server Error","internal",`attach upgrade failed: ${f}`)}finally{v||u?.destroy()}}i(De,"attachUpgrade");export{Te as REMOTE_ATTACH_HEARTBEAT_MS,Oe as REMOTE_ATTACH_QUIET_MS,cr as handleAttachUpgrade,K as isCleanViewerClose,k as refuseUpgrade,Ve as startRemoteAttachHeartbeat};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var p=Object.defineProperty;var o=(e,t)=>p(e,"name",{value:t,configurable:!0});import{getNode as v}from"../../../core/canvas/canvas.js";import{decideAttachRevive as k}from"../../../core/runtime/revive.js";import{viewSocketPath as h}from"../../../core/canvas/paths.js";import{waitForBrokerViewSocket as y}from"../../../core/runtime/placement-tmux.js";import{liveExecutionForNode as b}from"../../../core/canvas/executions.js";import{runnerForExecution as P}from"../../../core/runtime/runner/index.js";import{markAt as g,timedSpan as u,withLoggedStepTimings as A}from"../../../core/logged-step-timings.js";import{notFound as S,usage as i}from"../../../core/errors.js";import{mayOnNode as d,ownerOnly as _}from"../router.js";function N(e){if(e==null)return{resume:!0,revive:!0,wakeParked:!0};if(typeof e!="object")throw i("attach body must be a JSON object { resume?, revive?, wakeParked? }");const t=e.resume,r=e.revive,a=e.wakeParked;if(t!==void 0&&typeof t!="boolean")throw i("resume must be a boolean");if(r!==void 0&&typeof r!="boolean")throw i("revive must be a boolean");if(a!==void 0&&typeof a!="boolean")throw i("wakeParked must be a boolean");return{resume:t??!0,revive:r??!0,wakeParked:a??!0}}o(N,"parseAttachBody");async function F(e,t,r){return t==="controller"?await d(e,"message",r):await d(e,"read",r)?!0:t==="either"&&await d(e,"message",r)}o(F,"mayAttachNode");async function O(e){return await A("attach_post",{node:e.params.id},e.req,async()=>{const t=await E(e);return g("response_ready"),t})}o(O,"handleAttach");async function E(e){const t=e.params.id;if(await u("admission",async()=>await v(t)===null||!await F(e.principal,"either",t)))throw S(`unknown node: ${t}`,{received:t});const{resume:r,revive:a,wakeParked:l}=N(e.body);let m=!1,c=!1,f=!1;if(a){const n=await u("revive_decision",async()=>await k(t,{resume:r,capacity:"refuse"},l));if(f=n.parked,!n.parked){m=n.result.launch!==void 0,c=n.result.resumed;const s=await u("address_lookup",async()=>await b(t)),w=s===null?null:await P(s.runner).viewerAddress(s);(w===null||w.kind==="unix")&&await y(t)}}return{status:200,body:{node_id:t,socket_path:h(t),revived:m,resumed:c,parked:f}}}o(E,"attachEnsure");const C=_([{method:"POST",pattern:"/v1/nodes/:id/attach",handler:O}]);export{C as attachRoutes,F as mayAttachNode};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var x=Object.defineProperty;var s=(e,r)=>x(e,"name",{value:r,configurable:!0});import{chmodSync as j,closeSync as O,existsSync as D,mkdirSync as g,openSync as C,unlinkSync as F,writeFileSync as H,rmSync as M}from"node:fs";import{createServer as U}from"node:http";import{dirname as E,join as I}from"node:path";import{spawn as Y}from"node:child_process";import{SELF_UPDATE_SCRIPT as T}from"../core/self-update.js";import{apiSocketPath as A,crtrHome as B}from"../core/canvas/paths.js";import{bindDaemonEventSource as G}from"../core/events/source.js";import{emitEvent as l}from"../core/events/emit.js";import{createMachineExecutor as N,stopAllBrokers as $}from"../core/runtime/runner/machine/executor.js";import{machineCheckoutHandlers as J}from"../core/checkout-identities.js";import{machineWorktreeHandlers as X}from"../core/worktree-machine.js";import{readPersonCredential as z}from"../core/directory/person-credential.js";import{socketDir as L}from"../core/layout.js";import{isDaemonRunning as W,pidfilePath as v,readPidfile as K}from"./pidfile.js";import{cancelMachineCron as Q,runMachineCron as V,stopOrphanedMachineCrons as Z}from"./cron/machine-exec.js";import{startMachineLink as q}from"./machine-link/client.js";import{deleteMoveRecord as b,readMachineConfig as ee,readMachineCredential as R,readMoveRecord as ne,writeMoveRecord as te}from"./machine-link/config.js";import{jobExitReporting as re,stopMachineJob as oe}from"./machine-link/job-sweep.js";import{notifyMoveFinished as ie}from"./machine-link/move-notify.js";const ae=10*6e4;let k=0;function se(e){if(Date.now()-k<ae||!/^\d+\.\d+\.\d+$/.test(e))return;k=Date.now(),l({level:"warn",event:"daemon.machine.updating",fields:{release:e}});const r=I(E(T),"..","bin","crtr"),o=C(I(B(),"crtrd.err"),"a");Y("/bin/sh",["-c",'"$0" "$1" --version "$2" && "$0" "$3" sys daemon restart',process.execPath,T,e,r],{detached:!0,stdio:["ignore",o,o]}).unref(),O(o)}s(se,"updateToRelease");const P=1024;function ce(e,r){return{ok:!0,daemon_up:!0,store_accessible:!1,brokers_reconciled:!1,link_connected:e,signed_in:r,startup_phase:e?"ready":"recovering"}}s(ce,"machineHealth");async function Oe(){const e=ee();if(e===void 0)throw new Error("crtrd --role machine needs runtime/machine.json: this install has not been imported as a machine");const r=z()!==void 0;if(r&&R(),W())throw new Error("a crtrd is already running for this home");G(),r||(await $(),await Z(),l({level:"info",event:"daemon.machine.signed_out",fields:{environment:e.environmentId}})),g(L(),{recursive:!0,mode:493});const o=A();D(o)&&F(o);let n;const m=re(()=>n),i=U((t,a)=>{const u=(t.url??"").split("?")[0];if(t.method==="POST"&&(u==="/job-exit"||u==="/job-activity")){const _=[];let h=0;t.on("data",d=>{h+=d.length,h<=P&&_.push(d)}),t.on("end",()=>{if(h>P){a.writeHead(413),a.end();return}let d={};try{d=JSON.parse(Buffer.concat(_).toString("utf8"))}catch{}const S=typeof d.node=="string"&&typeof d.job=="string";a.writeHead(S?202:400,{"content-type":"application/json; charset=utf-8"}),a.end("{}"),S&&(u==="/job-exit"?m.notice:m.activity)(d.node,d.job)});return}const w=(t.method??"GET")==="GET"&&(t.url??"/").split("?")[0]==="/healthz";a.writeHead(w?200:404,{"content-type":"application/json; charset=utf-8"}),a.end(JSON.stringify(w?ce(n?.connected()===!0,r):{error:{code:"not_found",message:"a machine-role crtrd serves only /healthz",origin:"runtime"}}))});await new Promise((t,a)=>{i.once("error",a),i.listen(o,()=>{i.off("error",a),j(o,384),t()})}),g(E(v()),{recursive:!0}),H(v(),String(process.pid),"utf8");let f;await fe(e.runId,r,()=>f!==void 0);const c=N({apiUrl:e.apiUrl,environmentId:e.environmentId,onExit:s(t=>n?.reportExit(t),"onExit")});n=r?q({apiUrl:e.apiUrl,environmentId:e.environmentId,credential:R,onOpen:m.onOpen,onBehind:se,handlers:{start:c.start,wake:c.wake,stop:c.stop,status:c.status,"status.all":c["status.all"],delete:c.delete,viewer:c.viewer,"cron.run":V,"cron.cancel":Q,"job.stop":s(t=>oe(t),"job.stop"),...X,...J}}):void 0,l({level:"info",event:"daemon.machine.started",fields:{environment:e.environmentId}});const y=s(()=>f??=(async()=>{n?.stop(),await new Promise(t=>{i.close(()=>t()),i.closeAllConnections()}),K()===process.pid&&(M(o,{force:!0}),M(v(),{force:!0})),process.off("SIGINT",p),process.off("SIGTERM",p)})(),"teardown"),p=s(()=>{y().then(()=>process.exit(0),()=>process.exit(1))},"onSignal");return process.on("SIGINT",p),process.on("SIGTERM",p),y}s(Oe,"runMachineDaemon");const de=5e3,me=3e5;async function fe(e,r,o){let n;try{n=ne()}catch(i){l({level:"warn",event:"daemon.machine.move_record_unreadable",fields:{error:i.message}});return}if(n===void 0||n.state==="running"||n.runId!==e)return;if(n.notified||n.notify===null){b();return}if(n.state==="committed"&&(n={...n,state:"activated"},te(n)),!r)return;const m=n;(async()=>{let i=de;for(;;){try{await ie(m),b();return}catch(f){l({level:"warn",event:"daemon.machine.move_notify_failed",fields:{node:m.notify??"",error:f.message}})}if(await new Promise(f=>{setTimeout(f,i).unref()}),o())return;i=Math.min(i*2,me)}})()}s(fe,"settleFinishedMove");export{ce as machineHealth,Oe as runMachineDaemon};
|
|
@@ -30,6 +30,8 @@ export interface MachineLinkOptions {
|
|
|
30
30
|
jobReportTimeoutMs?: number;
|
|
31
31
|
/** Called each time the link opens, including the first: the caller's recovery pass for what happened while it was closed. */
|
|
32
32
|
onOpen?: () => void;
|
|
33
|
+
/** Called when the control plane refuses the link (426) because this Mac is on an older release; the argument is the control plane's release. */
|
|
34
|
+
onBehind?: (release: string) => void;
|
|
33
35
|
}
|
|
34
36
|
export interface MachineLink {
|
|
35
37
|
stop(): void;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var j=Object.defineProperty;var
|
|
1
|
+
var j=Object.defineProperty;var s=(t,a)=>j(t,"name",{value:a,configurable:!0});import{randomUUID as J}from"node:crypto";import{WebSocket as v}from"ws";import{APIError as O}from"../../api/errors.js";import{emitEvent as x}from"../../core/events/emit.js";import{RUNTIME_VERSION_HEADER as W}from"../../api/runtime-version.js";import{crtrVersion as K}from"../../shared/crtr-version.js";import{connectViewSocket as q}from"../../core/runtime/view-socket.js";import{CLOSE_REVOKED as D,LINK_MAX_PAYLOAD_BYTES as F,parseFrame as Y}from"./frames.js";const $=1e3,X=6e4,z=64*1024,H=4*1024*1024,Q=1024*1024,G=8*1024*1024,Z=15e3,ee=75e3;function ne(t){const a=[];let c=0;const p=new Set,M=s(()=>{for(;a.length>0&&t.open()&&t.bufferedAmount<z;){const l=a.shift();c-=l.length,t.send(l,M)}if(c<Q&&p.size>0){for(const l of p)l.resume();p.clear()}},"pump");return{push(l,d){t.open()&&(a.push(l),c+=l.length,d!==void 0&&c>H&&(d.pause(),p.add(d)),M())},waiting:s(()=>({bytes:c,frames:a.length}),"waiting"),forget(l){p.delete(l)}}}s(ne,"createViewQueue");function te(t,a){const c=new URL(`/v1/machines/${encodeURIComponent(a)}/link`,t);return c.protocol=c.protocol==="https:"?"wss:":c.protocol==="http:"?"ws:":c.protocol,c.toString()}s(te,"linkUrl");function fe(t){const a=t.backoffMinMs??$,c=t.backoffMaxMs??X,p=t.openView??q,M=t.silenceMs??ee;let l=!1,d,_=a,k;const E=new Map,P=200,S=[],L=s(()=>{const u=d;for(;S.length>0&&u?.readyState===v.OPEN;)u.send(JSON.stringify({type:"exit",...S.shift()}))},"flushExits"),I=s((u,o)=>{x({level:"error",event:u,fields:{environment:t.environmentId},error:o})},"fault");let T;const A=s(()=>{if(l)return;if(T!==void 0){if(t.credential()===T){k=setTimeout(A,_),_=Math.min(_*2,c);return}T=void 0}const u=t.credential(),o=new v(te(t.apiUrl,t.environmentId),{headers:{authorization:`Bearer ${u}`,[W]:K()},maxPayload:F});d=o;const f=new Map,m=new Map,h=s(e=>{o.readyState===v.OPEN&&o.send(JSON.stringify(e))},"send"),g=ne({get bufferedAmount(){return o.bufferedAmount},open:s(()=>o.readyState===v.OPEN,"open"),send:s((e,n)=>o.send(e,n),"send")}),w=s((e,n)=>g.push(JSON.stringify(e),n),"sendView"),N=s(e=>Math.round(e*10)/10,"round"),R=s(async e=>{const n=t.handlers[e.op];if(n===void 0){h({type:"result",call_id:e.call_id,ok:!1,error:`this machine does not execute ${e.op}`});return}const r=new AbortController,i=s(()=>r.abort(new Error("the machine link closed")),"onClose");o.once("close",i);try{h({type:"result",call_id:e.call_id,ok:!0,value:await n(e.args,r.signal)??null})}catch(y){h({type:"result",call_id:e.call_id,ok:!1,error:y instanceof Error?y.message:String(y)})}finally{o.off("close",i)}},"runCall"),V=s(e=>{const n=p(e.node);f.set(e.channel,n);const r=performance.now();n.once("connect",()=>{const i=performance.now(),y=g.waiting(),B=o.bufferedAmount;h({type:"view.ready",channel:e.channel}),x({level:"info",event:"daemon.timing.view_ready_sent",fields:{channel:e.channel,node:e.node,open_to_connect_ms:N(i-r),queued_bytes:y.bytes,queued_frames:y.frames,link_buffered_bytes_before:B,link_buffered_bytes_after:o.bufferedAmount}})}),n.on("data",i=>w({type:"view.data",channel:e.channel,bytes:i.toString("base64")},n)),n.once("error",i=>{g.forget(n),f.delete(e.channel)&&w({type:"view.close",channel:e.channel,error:i.message})}),n.once("close",()=>{g.forget(n),f.delete(e.channel)&&w({type:"view.close",channel:e.channel})})},"openChannel"),U=s((e,n)=>{const r=f.get(e);if(r===void 0||r.write(n))return;const i=(m.get(e)??0)+n.length;if(i>G){f.delete(e),m.delete(e),r.destroy(),w({type:"view.close",channel:e,error:"the broker is not draining the viewer channel"});return}m.has(e)||r.once("drain",()=>m.delete(e)),m.set(e,i)},"writeToChannel");let b;const C=s(()=>{b!==void 0&&clearTimeout(b),b=setTimeout(()=>{x({level:"warn",event:"daemon.machine_link.silent",fields:{environment:t.environmentId}}),o.terminate()},M)},"heard");o.on("open",()=>{_=a,C(),L(),t.onOpen?.()}),o.on("ping",C),o.on("message",e=>{C();const n=Y(e);if(n!==null)try{switch(n.type){case"call":R(n);return;case"job.reported":{const r=E.get(n.id);E.delete(n.id),n.error===void 0?r?.resolve():r?.reject(new O(n.error.status,n.error.code,n.error.message));return}case"view.open":V(n);return;case"view.data":U(n.channel,Buffer.from(n.bytes,"base64"));return;case"view.close":{const r=f.get(n.channel);f.delete(n.channel),r?.destroy();return}default:return}}catch(r){I("daemon.machine_link.frame_failed",r)}}),o.on("unexpected-response",(e,n)=>{let r="";n.on("data",i=>{r+=i.toString("utf8")}).on("close",()=>{o.terminate(),I("daemon.machine_link.refused",new Error(`${n.statusCode??"no status"} ${r}`));try{n.statusCode===426&&t.onBehind?.(JSON.parse(r).error.message)}catch(i){I("daemon.machine_link.client_error",i)}})}),o.on("error",e=>I("daemon.machine_link.client_error",e)),o.on("close",e=>{b!==void 0&&clearTimeout(b);for(const n of f.values())n.destroy();f.clear(),d===o&&(d=void 0);for(const[n,r]of E)E.delete(n),r.reject(new O(503,"machine_offline","the machine link closed before the job report was answered"));l||(e===D&&(x({level:"error",event:"daemon.machine_link.revoked",fields:{environment:t.environmentId}}),T=u),k=setTimeout(A,_),_=Math.min(_*2,c))})},"connect");return A(),{stop(){l=!0,k!==void 0&&clearTimeout(k),d?.close()},connected:s(()=>d?.readyState===v.OPEN,"connected"),reportJob(u,o,f){const m=d;if(m?.readyState!==v.OPEN)return Promise.reject(new O(503,"machine_offline","the machine link is not open"));const h=J();return new Promise((g,w)=>{const N=setTimeout(()=>{E.delete(h),w(new O(504,"request_timeout","the control plane did not answer the job report"))},t.jobReportTimeoutMs??Z);E.set(h,{resolve:s(()=>{clearTimeout(N),g()},"resolve"),reject:s(R=>{clearTimeout(N),w(R)},"reject")}),m.send(JSON.stringify({type:"job.report",id:h,node:u,job:o,request:f}))})},reportExit(u){S.push(u),S.length>P&&S.shift(),L()}}}s(fe,"startMachineLink");export{Z as JOB_REPORT_TIMEOUT_MS,X as LINK_BACKOFF_MAX_MS,$ as LINK_BACKOFF_MIN_MS,ee as LINK_SILENCE_MS,G as VIEW_WRITE_LIMIT_BYTES,ne as createViewQueue,te as linkUrl,fe as startMachineLink};
|
|
@@ -6,10 +6,8 @@ import { type MachineLinkRefusal } from './holder.js';
|
|
|
6
6
|
export declare const VIEW_BUFFER_LIMIT_BYTES: number;
|
|
7
7
|
/** A viewer channel to a node on a machine: over the link this process holds, or forwarded to the API process that does. */
|
|
8
8
|
export declare function openMachineView(environmentId: string, nodeId: string): BrokerViewLink;
|
|
9
|
-
/**
|
|
10
|
-
export declare function
|
|
11
|
-
/** Wait for the node's broker on the Mac to accept a viewer, retrying while its view.sock refuses; false on the deadline or when the launch exits. */
|
|
12
|
-
export declare function waitForMachineView(environmentId: string, nodeId: string, exited: Promise<unknown> | undefined, waitMs: number): Promise<boolean>;
|
|
9
|
+
/** Wait for the node's broker on the Mac to accept a viewer, retrying while its view.sock refuses; the accepted channel, open, or null on the deadline or when the launch exits. A caller that does not use the channel destroys it. */
|
|
10
|
+
export declare function waitForMachineView(environmentId: string, nodeId: string, exited: Promise<unknown> | undefined, waitMs: number): Promise<BrokerViewLink | null>;
|
|
13
11
|
/** The environment id of a forwarded viewer upgrade path, or null for any other path. */
|
|
14
12
|
export declare function machineViewEnvironment(req: IncomingMessage): string | null;
|
|
15
13
|
/** The holder's side: authenticate the forwarding API process, open a channel on the link this process holds and pipe it. Returns a refusal for the caller to write, or null once upgraded. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var b=Object.defineProperty;var a=(i,e)=>b(i,"name",{value:e,configurable:!0});import{EventEmitter as x}from"node:events";import{createHmac as I,timingSafeEqual as A}from"node:crypto";import{WebSocket as
|
|
1
|
+
var b=Object.defineProperty;var a=(i,e)=>b(i,"name",{value:e,configurable:!0});import{EventEmitter as x}from"node:events";import{createHmac as I,timingSafeEqual as A}from"node:crypto";import{WebSocket as m,WebSocketServer as R}from"ws";import{markAt as P}from"../../core/logged-step-timings.js";import{addStepTiming as k}from"../../core/step-timings.js";import{emitEvent as B}from"../../core/events/emit.js";import{openDb as O}from"../../core/canvas/db.js";import{loadSecretsKey as T}from"../../core/secrets/key.js";import{LINK_MAX_PAYLOAD_BYTES as _,parseFrame as v}from"./frames.js";import{apiAddress as D,heldLinkOf as g,MachineViewLink as E,UNROUTABLE_PREFIX as L}from"./holder.js";const y=8*1024*1024,$=1013,M=/^\/v1\/machines\/([A-Za-z0-9_-]+)\/view$/,q=new R({noServer:!0,maxPayload:_}),S=a(i=>I("sha256",T().key).update(`machine-view:${i}`).digest("hex"),"forwardToken");function N(i,e){const r=g(i);return r!==null?new E(r,e):new U(i,e)}a(N,"openMachineView");class U extends x{static{a(this,"ForwardedViewLink")}environmentId;nodeId;ws;ended=!1;failed=!1;queued=[];queuedBytes=0;constructor(e,r){super(),this.environmentId=e,this.nodeId=r;const s=performance.now();this.once("connect",()=>B({level:"info",event:"daemon.timing.forwarded_view_ready",fields:{environment:this.environmentId,node:this.nodeId,open_to_ready_ms:Math.round((performance.now()-s)*10)/10}})),this.dial().catch(t=>this.finish(t instanceof Error?t.message:String(t)))}get destroyed(){return this.ended}write(e){return this.ended?!1:this.ws?.readyState!==m.OPEN?(this.queuedBytes+=e.length,this.queuedBytes>y?(this.finish("machine view: the holder did not accept the channel before its queue filled"),!1):(this.queued.push(e),!0)):this.ws.bufferedAmount>y?(this.finish("machine view: the holder is not draining the channel"),!1):(this.sendData(e),!0)}destroy(){return this.ended||(this.ws?.readyState===m.OPEN&&this.ws.send(JSON.stringify({type:"view.close",channel:""})),this.finish(void 0)),this}sendData(e){this.ws?.send(JSON.stringify({type:"view.data",channel:"",bytes:Buffer.from(e).toString("base64")}))}async dial(){const e=await(await O()).prepare("SELECT api_address, lease_expires_at FROM machine_links WHERE environment = ?").get(this.environmentId);if(e===void 0||Date.parse(e.lease_expires_at)<=Date.now())throw new Error(`machine_offline: machine ${this.environmentId} has no live link`);if(e.api_address.startsWith(L))throw new Error(`machine_unreachable: the API process holding the link wrote ${e.api_address}; set CRTR_API_ADDRESS or listen on TCP`);if(e.api_address===D())throw new Error(`machine_offline: the link row names this API process (${e.api_address}) but it holds no link`);if(this.ended)return;const r=new URL(`/v1/machines/${encodeURIComponent(this.environmentId)}/view`,e.api_address.includes("://")?e.api_address:`ws://${e.api_address}`);r.protocol=r.protocol==="https:"?"wss:":r.protocol==="http:"?"ws:":r.protocol,r.searchParams.set("node",this.nodeId);const s=new m(r.toString(),{headers:{authorization:`Bearer ${S(this.environmentId)}`},maxPayload:_});this.ws=s,s.on("open",()=>{for(const t of this.queued.splice(0))this.sendData(t)}),s.on("unexpected-response",(t,n)=>{n.resume(),this.finish(n.statusCode===409?"machine_offline: the holder no longer holds the link":`machine view refused by ${e.api_address}: ${n.statusCode}`)}),s.on("message",t=>{const n=v(t);n!==null&&(n.type==="view.ready"?this.emit("connect"):n.type==="view.data"?this.emit("data",Buffer.from(n.bytes,"base64")):n.type==="view.close"&&this.finish(n.error))}),s.on("error",t=>this.finish(t.message)),s.on("close",()=>this.finish("machine view forward closed"))}finish(e){this.ended||(this.ended=!0,this.ws?.close(),e!==void 0&&!this.failed&&(this.failed=!0,this.emit("error",Object.assign(new Error(e),{code:"ECONNRESET"}))),this.emit("close",this.failed))}}function C(i,e,r){return new Promise(s=>{const t=N(i,e),n=setTimeout(()=>{s(null),t.destroy()},r);t.on("error",()=>{}),t.on("connect",()=>{clearTimeout(n),s(t)}),t.on("close",()=>{clearTimeout(n),s(null)})})}a(C,"openReadyMachineView");async function G(i,e,r,s){const t=Date.now()+s;let n=!1;r?.then(()=>{n=!0});for(let l=1;Date.now()<=t&&!n;l++){const f=performance.now(),h=await C(i,e,Math.max(1,Math.min(2e3,t-Date.now())));if(k(`probe_${l}_${h!==null?"ready":"failed"}_ms`,performance.now()-f),h!==null)return P("ready_received"),h;await new Promise(u=>setTimeout(u,250))}return null}a(G,"waitForMachineView");function Q(i){const e=M.exec(new URL(i.url??"/","http://runtime.local").pathname);return e===null?null:e[1]}a(Q,"machineViewEnvironment");function ee(i,e,r,s){const t=i.headers.authorization,n=/^Bearer (\S+)$/.exec(Array.isArray(t)?t[0]??"":t??"")?.[1]??"",l=Buffer.from(S(s)),f=Buffer.from(n);if(f.length!==l.length||!A(f,l))return{status:401,text:"Unauthorized",code:"unauthorized",message:"machine view forward credential refused"};const h=new URL(i.url??"/","http://runtime.local").searchParams.get("node");if(h===null||h==="")return{status:400,text:"Bad Request",code:"bad_request",message:"node is required"};const u=g(s);return u===null?{status:409,text:"Conflict",code:"machine_offline",message:"this API process holds no link for the machine"}:(q.handleUpgrade(i,e,r,d=>{const o=new E(u,h),p=a(c=>{d.readyState===m.OPEN&&d.send(JSON.stringify(c))},"send");o.on("connect",()=>p({type:"view.ready",channel:""})),o.on("data",c=>{if(d.bufferedAmount>y){o.destroy(),d.close($,"viewer too slow");return}p({type:"view.data",channel:"",bytes:c.toString("base64")})}),o.on("error",c=>p({type:"view.close",channel:"",error:c.message})),o.on("close",()=>d.close()),d.on("message",c=>{const w=v(c);w?.type==="view.data"?o.write(Buffer.from(w.bytes,"base64")):w?.type==="view.close"&&o.destroy()}),d.on("close",()=>o.destroy()),d.on("error",()=>o.destroy())}),null)}a(ee,"handleMachineViewUpgrade");export{y as VIEW_BUFFER_LIMIT_BYTES,ee as handleMachineViewUpgrade,Q as machineViewEnvironment,N as openMachineView,G as waitForMachineView};
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
var
|
|
1
|
+
var y=Object.defineProperty;var s=(i,e)=>y(i,"name",{value:e,configurable:!0});import{importedNodesHeld as T}from"../reconcilers/live-obligation.js";import{EventEmitter as f}from"node:events";import{hostname as I}from"node:os";import{randomUUID as L}from"node:crypto";import{WebSocket as b,WebSocketServer as O}from"ws";import{openDb as r}from"../../core/canvas/db.js";import{emitEvent as h}from"../../core/events/emit.js";import{endExecution as x,recordExecutionExit as C}from"../../core/canvas/executions.js";import{machineEnvironmentOfNode as p}from"../../core/runtime/runner/machine/runner.js";import{storeJobReport as M}from"../api/handlers/bash-jobs.js";import{APIError as E}from"../../api/errors.js";import{brokerSignalBus as U}from"../broker-signals/bus.js";import{verifyMachineCredential as w}from"./credential.js";import{compareReleaseVersions as H,RUNTIME_VERSION_HEADER as P}from"../../api/runtime-version.js";import{crtrVersion as g}from"../../shared/crtr-version.js";import{CLOSE_REVOKED as W,CLOSE_SUPERSEDED as v,LINK_MAX_PAYLOAD_BYTES as j,parseFrame as F}from"./frames.js";const $=45e3,B=15e3,K=3e4,V=1e3,S=10,X=new O({noServer:!0,maxPayload:j}),c=new Map,J="unroutable:";let D;const pe=s(i=>{D=i},"setApiAddress"),G=s(()=>process.env.CRTR_API_ADDRESS??D??`${J}${I()}:${process.pid}`,"apiAddress"),u=s(()=>new Date(Date.now()+$).toISOString(),"lease");class z extends f{static{s(this,"HeldLink")}environmentId;generation;ws;token;timers=[];unsubscribe;claiming=!1;closed=!1;alive=!0;channels=new Map;constructor(e,n,t,a){super(),this.environmentId=e,this.generation=n,this.ws=t,this.token=a}start(){const{ws:e}=this;e.on("message",n=>{this.onMessage(n).catch(t=>this.fault("daemon.machine_link.frame_failed",t))}),e.on("pong",()=>{this.alive=!0}),e.on("close",()=>{this.teardown().catch(n=>this.fault("daemon.machine_link.teardown_failed",n))}),e.on("error",()=>{}),this.timers.push(setInterval(()=>{this.renew().catch(n=>this.fault("daemon.machine_link.renew_failed",n))},B)),this.timers.push(setInterval(()=>{if(!this.alive){e.terminate();return}this.alive=!1;try{e.ping()}catch{}},K)),this.timers.push(setInterval(()=>{this.claim().catch(n=>this.fault("daemon.machine_link.claim_failed",n))},V)),U.subscribe(n=>{n===this.environmentId&&this.claim().catch(t=>this.fault("daemon.machine_link.claim_failed",t))},{kinds:["machine"],onListenStart:s(()=>{this.claim().catch(n=>this.fault("daemon.machine_link.claim_failed",n))},"onListenStart")}).then(n=>{this.closed?n():this.unsubscribe=n})}fault(e,n){h({level:"error",event:e,fields:{environment:this.environmentId},error:n})}send(e){return this.ws.readyState!==b.OPEN?!1:(this.ws.send(JSON.stringify(e)),!0)}async renew(){if(this.closed)return;const e=await r(),n=u();if((await e.prepare("UPDATE machine_links SET lease_expires_at = ? WHERE environment = ? AND generation = ?").run(n,this.environmentId,this.generation)).changes===0){this.ws.close(v,"superseded");return}await e.prepare("UPDATE machine_calls SET lease_expires_at = ? WHERE environment = ? AND state = 'sent' AND claimed_generation = ?").run(n,this.environmentId,this.generation),await e.prepare("UPDATE environments SET last_seen_at = ? WHERE object = ?").run(new Date().toISOString(),this.environmentId),await this.credentialValid()||this.ws.close(W,"revoked")}async credentialValid(){return await w(this.environmentId,this.token)}async claim(){if(!(this.closed||this.claiming)){this.claiming=!0;try{for(;;){const e=await(await r()).prepare(`UPDATE machine_calls SET state = 'sent', claimed_generation = ?, lease_expires_at = ?
|
|
2
2
|
WHERE call_id IN (SELECT call_id FROM machine_calls WHERE environment = ? AND state = 'pending'
|
|
3
3
|
AND EXISTS (SELECT 1 FROM machine_links WHERE environment = ? AND generation = ?)
|
|
4
|
-
ORDER BY created_at FOR UPDATE SKIP LOCKED LIMIT ${
|
|
5
|
-
RETURNING call_id, op, args_json`).all(this.generation,u(),this.environmentId,this.environmentId,this.generation),n=!this.closed&&await this.isCurrentGeneration();for(const t of e)n?this.send({type:"call",call_id:t.call_id,op:t.op,args:JSON.parse(t.args_json)})||await this.failCall(t.call_id,"machine_offline","link closed before the call was sent",!1):await this.release(t.call_id);if(e.length<
|
|
4
|
+
ORDER BY created_at FOR UPDATE SKIP LOCKED LIMIT ${S})
|
|
5
|
+
RETURNING call_id, op, args_json`).all(this.generation,u(),this.environmentId,this.environmentId,this.generation),n=!this.closed&&await this.isCurrentGeneration();for(const t of e)n?this.send({type:"call",call_id:t.call_id,op:t.op,args:JSON.parse(t.args_json)})||await this.failCall(t.call_id,"machine_offline","link closed before the call was sent",!1):await this.release(t.call_id);if(e.length<S)return}}finally{this.claiming=!1}}}async failCall(e,n,t,a){await this.settle(e,"failed",{code:n,message:t,sent:a},!1)}async isCurrentGeneration(){return await(await r()).prepare("SELECT 1 AS live FROM machine_links WHERE environment = ? AND generation = ?").get(this.environmentId,this.generation)!==void 0}async release(e){await(await r()).prepare("UPDATE machine_calls SET state = 'pending', claimed_generation = NULL, lease_expires_at = NULL WHERE call_id = ? AND state = 'sent' AND claimed_generation = ?").run(e,this.generation)}async settle(e,n,t,a){await Y(e,n,t,this.environmentId,this.generation,a)}async onMessage(e){const n=F(e);if(n!==null)switch(n.type){case"result":n.ok?await this.settle(n.call_id,"done",n.value??null,!0):await this.settle(n.call_id,"failed",{code:"machine_call_failed",message:n.error},!0);return;case"exit":await q(this.environmentId,n);return;case"job.report":await this.storeJobReport(n);return;case"view.ready":this.channels.get(n.channel)?.emit("connect");return;case"view.data":this.channels.get(n.channel)?.emit("data",Buffer.from(n.bytes,"base64"));return;case"view.close":this.channels.get(n.channel)?.finish(n.error);return;default:return}}async storeJobReport(e){try{if(await p(e.node)!==this.environmentId)throw new E(404,"unknown_node",`node ${e.node} does not run in this machine environment`);await M(e.node,e.job,e.request),this.send({type:"job.reported",id:e.id})}catch(n){const t=n instanceof E;t||this.fault("daemon.machine_link.job_report_failed",n),this.send({type:"job.reported",id:e.id,error:{status:t?n.status:500,code:t?n.code:"internal_error",message:n.message}})}}async teardown(){if(this.closed)return;this.closed=!0;for(const t of this.timers)clearInterval(t);this.unsubscribe?.(),c.get(this.environmentId)===this&&c.delete(this.environmentId);for(const t of[...this.channels.values()])t.finish("machine link closed");const e=await r(),n=await e.prepare("SELECT call_id FROM machine_calls WHERE environment = ? AND state = 'sent' AND claimed_generation = ?").all(this.environmentId,this.generation);for(const{call_id:t}of n)await this.failCall(t,"machine_offline","link dropped before the result",!0);await e.prepare("DELETE FROM machine_links WHERE environment = ? AND generation = ?").run(this.environmentId,this.generation)}}async function Y(i,e,n,t,a,o){const l=await r();(await l.prepare(`UPDATE machine_calls SET state = ?, result_json = ?, finished_at = ?, args_json = '{}'
|
|
6
6
|
WHERE call_id = ? AND environment = ? AND claimed_generation = ? AND state = 'sent'
|
|
7
|
-
${o?"AND EXISTS (SELECT 1 FROM machine_links WHERE environment = ? AND generation = ?)":""}`).run(e,JSON.stringify(n),new Date().toISOString(),i,t,a,...o?[t,a]:[])).changes>0&&await l.prepare("SELECT pg_notify(?, ?)").get("crtr_signal",`machine_call:${i}`)}s(
|
|
7
|
+
${o?"AND EXISTS (SELECT 1 FROM machine_links WHERE environment = ? AND generation = ?)":""}`).run(e,JSON.stringify(n),new Date().toISOString(),i,t,a,...o?[t,a]:[])).changes>0&&await l.prepare("SELECT pg_notify(?, ?)").get("crtr_signal",`machine_call:${i}`)}s(Y,"withNotify");async function q(i,e){const n=await r(),t=await n.prepare("SELECT stop_requested_at, stop_reason FROM executions WHERE execution_id = ? AND node_id = ? AND runner = 'machine' AND state != 'exited'").get(e.execution,e.node);return t===void 0||await p(e.node)!==i||(await T()).has(e.node)||(await C(e.execution,{code:e.code,signal:e.signal}),!await x(e.execution,{reason:"exited"}))?!1:(t.stop_requested_at===null&&t.stop_reason===null&&await n.prepare("SELECT pg_notify(?, ?)").get("crtr_signal",`execution_exit:${e.node}`),h({level:"info",event:"broker.exit.reported",node_id:e.node,fields:{environment:i,code:e.code,signal:e.signal}}),!0)}s(q,"recordMachineBrokerExit");class Ee extends f{static{s(this,"MachineViewLink")}link;ended=!1;failed=!1;channel=L();constructor(e,n){super(),this.link=e,e.channels.set(this.channel,this);const t=performance.now();this.once("connect",()=>h({level:"info",event:"daemon.timing.machine_view_ready",fields:{channel:this.channel,node:n,open_to_ready_ms:Math.round((performance.now()-t)*10)/10}})),e.send({type:"view.open",channel:this.channel,node:n})||queueMicrotask(()=>this.finish("machine link closed"))}get destroyed(){return this.ended}write(e){return!this.ended&&this.link.send({type:"view.data",channel:this.channel,bytes:Buffer.from(e).toString("base64")})}destroy(){return this.ended||(this.link.send({type:"view.close",channel:this.channel}),this.finish(void 0)),this}finish(e){this.ended||(this.ended=!0,this.link.channels.delete(this.channel),e!==void 0&&!this.failed&&(this.failed=!0,this.emit("error",Object.assign(new Error(e),{code:"ECONNRESET"}))),this.emit("close",this.failed))}}const we=s(i=>c.get(i)??null,"heldLinkOf"),Z=/^\/v1\/machines\/([A-Za-z0-9_-]+)\/link$/;function ge(i){const e=Z.exec(new URL(i.url??"/","http://runtime.local").pathname);return e===null?null:e[1]}s(ge,"machineLinkEnvironment");async function ve(i,e,n,t){const a=i.headers.authorization,o=/^Bearer (\S+)$/.exec(Array.isArray(a)?a[0]??"":a??"")?.[1];if(o===void 0||!await w(t,o))return{status:401,text:"Unauthorized",code:"unauthorized",message:"machine credential refused"};if(H(String(i.headers[P.toLowerCase()]??""),g())<0)return{status:426,text:"Upgrade Required",code:"machine_release_behind",message:g()};const l=new Date().toISOString(),d=await r(),A=await d.prepare(`INSERT INTO machine_links (environment, generation, api_address, connected_at, lease_expires_at) VALUES (?, 1, ?, ?, ?)
|
|
8
8
|
ON CONFLICT (environment) DO UPDATE SET generation = machine_links.generation + 1, api_address = EXCLUDED.api_address, connected_at = EXCLUDED.connected_at, lease_expires_at = EXCLUDED.lease_expires_at
|
|
9
|
-
RETURNING generation`).get(t,
|
|
9
|
+
RETURNING generation`).get(t,G(),l,u());await d.prepare("UPDATE environments SET last_seen_at = ? WHERE object = ?").run(l,t);const _=Number(A.generation);return e.destroyed?(await d.prepare("DELETE FROM machine_links WHERE environment = ? AND generation = ?").run(t,_),null):(X.handleUpgrade(i,e,n,N=>{const m=new z(t,_,N,o),R=c.get(t);c.set(t,m),R?.ws.close(v,"superseded"),m.start(),m.claim().catch(k=>h({level:"error",event:"daemon.machine_link.claim_failed",fields:{environment:t},error:k}))}),null)}s(ve,"handleMachineLinkUpgrade");export{z as HeldLink,$ as LINK_LEASE_MS,K as LINK_PING_MS,B as LINK_RENEW_MS,Ee as MachineViewLink,J as UNROUTABLE_PREFIX,G as apiAddress,ve as handleMachineLinkUpgrade,we as heldLinkOf,ge as machineLinkEnvironment,q as recordMachineBrokerExit,pe as setApiAddress};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/** Ends each `running` machine execution whose machine reports no broker for it. The rows are read before the call, so a broker that
|
|
2
2
|
* started after the scan is never judged by it (its execution was not yet `running`). An environment whose call fails (offline, lost)
|
|
3
|
-
* is left as it is. A
|
|
3
|
+
* is left as it is. A node held by an
|
|
4
4
|
* import is left to the import. Returns the nodes whose execution this call ended, so the caller can re-read their rows. */
|
|
5
5
|
export declare function endGoneMachineExecutions(): Promise<ReadonlySet<string>>;
|