@lensmcp/cluster 1.25.55 → 1.25.56
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/executors/gateway/runtime/chooser.d.ts +15 -3
- package/executors/gateway/runtime/chooser.js +15 -14
- package/executors/gateway/runtime/control.js +1 -1
- package/executors/gateway/runtime/guest-graph.d.ts +12 -0
- package/executors/gateway/runtime/guest-graph.js +2 -2
- package/executors/gateway/runtime/handler.js +1 -1
- package/executors/gateway/runtime/lens-children.d.ts +13 -0
- package/executors/gateway/runtime/lens-children.js +1 -1
- package/executors/gateway/runtime/lifecycle.js +3 -3
- package/executors/gateway/runtime/on-demand.d.ts +26 -9
- package/executors/gateway/runtime/on-demand.js +10 -9
- package/executors/gateway/runtime/parked-dashboards.d.ts +62 -0
- package/executors/gateway/runtime/parked-dashboards.js +1 -0
- package/executors/gateway/runtime/project-graph-store.d.ts +39 -3
- package/executors/gateway/runtime/project-graph-store.js +1 -1
- package/executors/gateway/runtime/route-registry.d.ts +12 -1
- package/executors/gateway/runtime/route-registry.js +1 -1
- package/executors/gateway/runtime/server.js +2 -2
- package/executors/gateway/runtime/types.d.ts +8 -0
- package/package.json +4 -4
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`)}m(startErrorText,"startErrorText"),s(startErrorText,"startErrorText");function scaleTarget(t,i=fs.existsSync){if(t.decl.adminUrl)return{url:t.decl.adminUrl};const l=path.join(t.pool.dir,"parent.sock");return i(l)?{socketPath:l}:t.decl.port?{url:`http://localhost:${t.decl.port}`}:void 0}m(scaleTarget,"scaleTarget"),s(scaleTarget,"scaleTarget");function isLoopbackHostname(t){const i=t.toLowerCase().replace(/^\[(.*)\]$/,"$1").replace(/\.$/,"");return i==="localhost"||i.endsWith(".localhost")?!0:net.isIPv4(i)?i.split(".")[0]==="127":net.isIPv6(i)&&new URL(`http://[${i}]/`).hostname==="[::1]"}m(isLoopbackHostname,"isLoopbackHostname"),s(isLoopbackHostname,"isLoopbackHostname");function postScale(t,i,l){let p;if("socketPath"in t)p=http.request({socketPath:t.socketPath,path:"/webpack/scale",method:"POST",headers:{"content-type":"application/json"}},y=>y.resume());else{const y=t.url.startsWith("https"),M=y?require("node:https"):http,j={method:"POST"};y&&isLoopbackHostname(new URL(t.url).hostname)&&(j.rejectUnauthorized=!1),l&&(j.lookup=l),p=M.request(`${t.url}/webpack/scale`,j,A=>A.resume())}return p.on("error",()=>{}),p.end(JSON.stringify({pods:i})),p}m(postScale,"postScale"),s(postScale,"postScale");function isOwnRunnerCommand(t,i){return(0,serve_launch_1.isServeRunnerCommand)(t)?(0,serve_launch_1.isServeRunnerCommandOf)(t,i):t.includes("/node_modules/nx/")?t.includes(`${i.replace(/\/+$/,"")}/node_modules/nx/`):!0}m(isOwnRunnerCommand,"isOwnRunnerCommand"),s(isOwnRunnerCommand,"isOwnRunnerCommand");function isRunnerOf(t,i,l){const p=i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return!new RegExp(`(^|\\s)run ${p}(:|\\s|$)`).test(t)||!(0,serve_launch_1.isServeRunnerCommand)(t)&&!/\bnx(\.js)?\b/.test(t)?!1:isOwnRunnerCommand(t,l)}m(isRunnerOf,"isRunnerOf"),s(isRunnerOf,"isRunnerOf");const TEST_FILE_RE=/\.(spec|test|e2e|e2e-spec|stories)\.[cm]?[jt]sx?$/,TEST_DIR_SEGMENTS=new Set(["__tests__","__mocks__","__snapshots__"]);function isTestSourcePath(t){const i=t.split("/"),l=i[i.length-1]??"";if(TEST_FILE_RE.test(l))return!0;for(let p=0;p<i.length-1;p+=1)if(TEST_DIR_SEGMENTS.has(i[p]))return!0;return!1}m(isTestSourcePath,"isTestSourcePath"),s(isTestSourcePath,"isTestSourcePath");function sourceScanPass(t,i,l){const p=l?.ignoreTests??!0;let y;const M=new Map,j=`tree:${path.resolve(t)}`,A=s(E=>path.relative(t,E).split(path.sep).join("/"),"rel"),C=s(async(E,_)=>{const R=await(y??=gitIgnoredPaths(t)),D=[],F=new Set;let b=!1;const
|
|
1
|
+
"use strict";var dt=Object.defineProperty;var m=(t,i)=>dt(t,"name",{value:i,configurable:!0});var lt=Object.defineProperty,s=m((t,i)=>lt(t,"name",{value:i,configurable:!0}),"s");Object.defineProperty(exports,"__esModule",{value:!0}),exports.startErrorText=startErrorText,exports.scaleTarget=scaleTarget,exports.isLoopbackHostname=isLoopbackHostname,exports.isOwnRunnerCommand=isOwnRunnerCommand,exports.isRunnerOf=isRunnerOf,exports.isTestSourcePath=isTestSourcePath,exports.sourceScanPass=sourceScanPass,exports.sourceSetSnapshot=sourceSetSnapshot,exports.sourceSetSignature=sourceSetSignature,exports.diffSourceSets=diffSourceSets,exports.sourceChangeWindowMs=sourceChangeWindowMs,exports.sourceScopeDirs=sourceScopeDirs,exports.podRecycleReason=podRecycleReason,exports.lensFrontendStale=lensFrontendStale,exports.lensWatcherVerdict=lensWatcherVerdict,exports.podWatcherVerdict=podWatcherVerdict,exports.lensChildWedged=lensChildWedged,exports.isPortConflictExit=isPortConflictExit,exports.podChangeClock=podChangeClock,exports.createServiceLayer=createServiceLayer,exports.chooseStalePodKillTarget=chooseStalePodKillTarget;const tslib_1=require("tslib"),node_child_process_1=require("node:child_process"),node_crypto_1=require("node:crypto"),fs=tslib_1.__importStar(require("node:fs")),http=tslib_1.__importStar(require("node:http")),net=tslib_1.__importStar(require("node:net")),path=tslib_1.__importStar(require("node:path")),node_util_1=require("node:util"),discovery_1=require("./discovery"),instance_1=require("./instance"),pod_sock_1=require("../../../pod-sock"),scope_1=require("./scope"),pod_env_1=require("./pod-env"),pod_probe_1=require("./pod-probe"),service_keys_1=require("./service-keys"),workspace_log_1=require("./workspace-log"),own_log_1=require("./own-log"),inspector_secret_1=require("../../../inspector-secret"),pod_output_1=require("./pod-output"),serve_launch_1=require("./serve-launch"),shared_build_1=require("./shared-build"),awake_1=require("./awake"),warm_start_1=require("./warm-start"),protocol_1=require("../../../shared-build/protocol"),types_1=require("./types"),exit_reason_1=require("../../../exit-reason"),handoff_retire_1=require("../../../handoff-retire"),process_name_1=require("../../../process-name"),orphan_reaper_1=require("./orphan-reaper");function eastWestEnv(t,i){const l={},p=t.serviceKeys[(0,service_keys_1.serviceKeyId)(i.wsKey,i.project)];if(p&&(l.LENSMCP_SERVICE_KEY=p),t.https){const y=require("../../../basic-ssl").caCertPath();fs.existsSync(y)&&(l.NODE_EXTRA_CA_CERTS=y)}return l}m(eastWestEnv,"eastWestEnv"),s(eastWestEnv,"eastWestEnv");const sleep=s(t=>new Promise(i=>setTimeout(i,t)),"sleep"),SRC_EXCLUDE=new Set(["node_modules","dist","tmp","coverage","build","out","target"]),SRC_EXT=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".css",".scss",".sass",".less",".json",".html",".htm",".vue",".svelte",".mdx"]),SCAN_FILE_CAP=1e5;function fnv1a(t){let i=2166136261;for(let l=0;l<t.length;l+=1)i^=t.charCodeAt(l),i=Math.imul(i,16777619);return i>>>0}m(fnv1a,"fnv1a"),s(fnv1a,"fnv1a");const execFileP=(0,node_util_1.promisify)(node_child_process_1.execFile);async function gitIgnoredPaths(t){try{const{stdout:i}=await execFileP("git",["ls-files","--others","--directory","--ignored","--exclude-standard","-z"],{cwd:t,maxBuffer:33554432,timeout:1e4,windowsHide:!0});return new Set(i.split("\0").filter(Boolean))}catch{return new Set}}m(gitIgnoredPaths,"gitIgnoredPaths"),s(gitIgnoredPaths,"gitIgnoredPaths");function startErrorText(t,i){return[t,...(i??[]).slice(-(types_1.START_ERROR_LINES-1))].join(`
|
|
2
|
+
`)}m(startErrorText,"startErrorText"),s(startErrorText,"startErrorText");function scaleTarget(t,i=fs.existsSync){if(t.decl.adminUrl)return{url:t.decl.adminUrl};const l=path.join(t.pool.dir,"parent.sock");return i(l)?{socketPath:l}:t.decl.port?{url:`http://localhost:${t.decl.port}`}:void 0}m(scaleTarget,"scaleTarget"),s(scaleTarget,"scaleTarget");function isLoopbackHostname(t){const i=t.toLowerCase().replace(/^\[(.*)\]$/,"$1").replace(/\.$/,"");return i==="localhost"||i.endsWith(".localhost")?!0:net.isIPv4(i)?i.split(".")[0]==="127":net.isIPv6(i)&&new URL(`http://[${i}]/`).hostname==="[::1]"}m(isLoopbackHostname,"isLoopbackHostname"),s(isLoopbackHostname,"isLoopbackHostname");function postScale(t,i,l){let p;if("socketPath"in t)p=http.request({socketPath:t.socketPath,path:"/webpack/scale",method:"POST",headers:{"content-type":"application/json"}},y=>y.resume());else{const y=t.url.startsWith("https"),M=y?require("node:https"):http,j={method:"POST"};y&&isLoopbackHostname(new URL(t.url).hostname)&&(j.rejectUnauthorized=!1),l&&(j.lookup=l),p=M.request(`${t.url}/webpack/scale`,j,A=>A.resume())}return p.on("error",()=>{}),p.end(JSON.stringify({pods:i})),p}m(postScale,"postScale"),s(postScale,"postScale");function isOwnRunnerCommand(t,i){return(0,serve_launch_1.isServeRunnerCommand)(t)?(0,serve_launch_1.isServeRunnerCommandOf)(t,i):t.includes("/node_modules/nx/")?t.includes(`${i.replace(/\/+$/,"")}/node_modules/nx/`):!0}m(isOwnRunnerCommand,"isOwnRunnerCommand"),s(isOwnRunnerCommand,"isOwnRunnerCommand");function isRunnerOf(t,i,l){const p=i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return!new RegExp(`(^|\\s)run ${p}(:|\\s|$)`).test(t)||!(0,serve_launch_1.isServeRunnerCommand)(t)&&!/\bnx(\.js)?\b/.test(t)?!1:isOwnRunnerCommand(t,l)}m(isRunnerOf,"isRunnerOf"),s(isRunnerOf,"isRunnerOf");const TEST_FILE_RE=/\.(spec|test|e2e|e2e-spec|stories)\.[cm]?[jt]sx?$/,TEST_DIR_SEGMENTS=new Set(["__tests__","__mocks__","__snapshots__"]);function isTestSourcePath(t){const i=t.split("/"),l=i[i.length-1]??"";if(TEST_FILE_RE.test(l))return!0;for(let p=0;p<i.length-1;p+=1)if(TEST_DIR_SEGMENTS.has(i[p]))return!0;return!1}m(isTestSourcePath,"isTestSourcePath"),s(isTestSourcePath,"isTestSourcePath");function sourceScanPass(t,i,l){const p=l?.ignoreTests??!0;let y;const M=new Map,j=`tree:${path.resolve(t)}`,A=s(E=>path.relative(t,E).split(path.sep).join("/"),"rel"),C=s(async(E,_)=>{const R=await(y??=gitIgnoredPaths(t)),D=[],F=new Set;let b=!1;const X=s(async(te,v)=>{if(D.length>=SCAN_FILE_CAP){b=!0;return}let O;try{O=await fs.promises.readdir(te,{withFileTypes:!0})}catch{return}v&&F.add(A(te));for(const z of O){if(D.length>=SCAN_FILE_CAP){b=!0;return}const W=z.name,re=path.join(te,W);if(z.isDirectory()){if(!v||W.startsWith(".")||SRC_EXCLUDE.has(W)||i?.has(W)||W.endsWith("-devserver")||R.has(`${A(re)}/`))continue;await X(re,!0)}else if(z.isFile()){const oe=W.lastIndexOf(".");if(oe<=0||!SRC_EXT.has(W.slice(oe)))continue;const J=A(re);if(R.has(J)||p&&isTestSourcePath(J))continue;D.push(J)}}},"walk");return await X(E,_),{paths:D,entered:F,truncated:b}},"walkDir"),L=s((E,_)=>{let R=M.get(E);return R||(R=_(),M.set(E,R)),R},"memo"),ce=s(async()=>{const E=M.get(j);if(!E)return;const _=await E;return _.truncated?void 0:_},"wideWalk"),H=new Set,le=s(()=>L(`files:${path.resolve(t)}`,async()=>{const E=await ce();return E?{paths:E.paths.filter(_=>!_.includes("/")),entered:H,truncated:!1}:C(t,!1)}),"rootFiles"),de=s(E=>L(`tree:${path.resolve(E)}`,async()=>{const _=await ce(),R=A(E);if(_?.entered.has(R)){const D=`${R}/`;return{paths:R===""?_.paths:_.paths.filter(F=>F.startsWith(D)),entered:H,truncated:!1}}return C(E,!0)}),"subtree"),V=s(E=>{const _=new Set;let R=0,D=E.some(b=>b.truncated);const F=s(b=>_.has(b)?!0:_.size>=SCAN_FILE_CAP?(D=!0,!1):(_.add(b),R^=fnv1a(b),!0),"add");for(const b of E)if(!b.paths.every(F))break;return{signature:`${_.size}:${(R>>>0).toString(36)}`,paths:_,truncated:D}},"compose");return{async snapshot(E){if(!E||E.length===0)return V([await L(j,()=>C(t,!0))]);const _=[await le()];for(const R of E)_.push(await de(R));return V(_)}}}m(sourceScanPass,"sourceScanPass"),s(sourceScanPass,"sourceScanPass");async function sourceSetSnapshot(t,i,l,p){return sourceScanPass(t,l,p).snapshot(i)}m(sourceSetSnapshot,"sourceSetSnapshot"),s(sourceSetSnapshot,"sourceSetSnapshot");async function sourceSetSignature(t,i,l,p){return(await sourceSetSnapshot(t,i,l,p)).signature}m(sourceSetSignature,"sourceSetSignature"),s(sourceSetSignature,"sourceSetSignature");const SOURCE_DIFF_PATH_CAP=128;function diffSourceSets(t,i,l,p){if(t.paths.size===i.paths.size){let A=!0;for(const C of t.paths)if(!i.paths.has(C)){A=!1;break}if(A)return null}const y=[],M=[];let j=t.truncated||i.truncated;for(const A of i.paths)t.paths.has(A)||(y.length+M.length<SOURCE_DIFF_PATH_CAP?y.push(A):j=!0);for(const A of t.paths)i.paths.has(A)||(y.length+M.length<SOURCE_DIFF_PATH_CAP?M.push(A):j=!0);return{changedAt:l,added:y,removed:M,truncated:j,...p!==void 0?{windowMs:p}:{}}}m(diffSourceSets,"diffSourceSets"),s(diffSourceSets,"diffSourceSets");function sourceChangeWindowMs(t,i,l,p){const y=i&&i>0?t-i:l;return Math.max(y,l)+p}m(sourceChangeWindowMs,"sourceChangeWindowMs"),s(sourceChangeWindowMs,"sourceChangeWindowMs");function sourceScopeDirs(t,i,l,p,y){const M=s(C=>{const L=path.relative(t,C).split(path.sep).filter(Boolean);return L.length===0||L[0].startsWith("..")?"":L[0]},"bucketOf")(i);if(!M)return[];const j=new Set(l.filter(Boolean)),A=new Set([M]);for(const C of p)C.startsWith(".")||SRC_EXCLUDE.has(C)||y?.has(C)||C.endsWith("-devserver")||j.has(C)||A.add(C);return[...A].sort().map(C=>path.join(t,C))}m(sourceScopeDirs,"sourceScopeDirs"),s(sourceScopeDirs,"sourceScopeDirs");function podRecycleReason(t,i,l,p){return!t.proc||t.state!=="up"||t.spawnAt==null||t.inflight>0||(t.activeWork??0)>0||i-t.lastUsed<p.settleMs||t.lastStaleRecycleAt!=null&&i-t.lastStaleRecycleAt<p.cooldownMs?null:l>0&&l-t.spawnAt>p.graceMs?"stale-source-set":p.maxAgeMs>0&&i-t.spawnAt>p.maxAgeMs?"max-age":null}m(podRecycleReason,"podRecycleReason"),s(podRecycleReason,"podRecycleReason");function lensFrontendStale(t,i,l,p,y){return!(p-i<y.cooldownMs||l<=0||l-t<=y.graceMs||p-l<y.settleMs)}m(lensFrontendStale,"lensFrontendStale"),s(lensFrontendStale,"lensFrontendStale");function lensWatcherVerdict(t,i,l,p=[]){if(!t)return"unknown";if("schemaVersion"in t&&t.schemaVersion>=2&&p.length>0){const y=i-l,M=new Set(t.recentEvents.filter(j=>j.at>=y).map(j=>path.resolve(j.path)));return p.every(j=>M.has(path.resolve(j)))?"heard":"missed"}return t.lastFsSetEventAt>=i-l?"heard":"missed"}m(lensWatcherVerdict,"lensWatcherVerdict"),s(lensWatcherVerdict,"lensWatcherVerdict");function podWatcherVerdict(t,i,l){if(!t)return"unknown";if(t.degraded)return"degraded";const p=i-l;return t.lastWatchRunAt>=p||t.lastBuildAt>=p?"heard":"silent"}m(podWatcherVerdict,"podWatcherVerdict"),s(podWatcherVerdict,"podWatcherVerdict");function lensChildWedged(t,i,l,p){const y=t.hasListened?p.graceMs:Math.max(p.graceMs,p.neverListenedGraceMs);return l-t.spawnedAt<y||l-i<p.cooldownMs||t.probeFails<Math.max(2,p.failureThreshold)?null:"wedged-no-listener"}m(lensChildWedged,"lensChildWedged"),s(lensChildWedged,"lensChildWedged");function isPortConflictExit(t,i){return t.signal||t.code===null||t.code===0||t.ranMs>i.fastFailMs?!1:t.portHeld}m(isPortConflictExit,"isPortConflictExit"),s(isPortConflictExit,"isPortConflictExit");function podChangeClock(t,i){const l=t.sourceSetChangedFor?.get(i);if(l!==void 0){const p=t.sourceSetChangesFor?.get(i);return{at:l,...p?{change:p}:{},scope:"project"}}return t.sourceSetScoped?.has(i)?{at:0,scope:"none"}:{at:t.sourceSetChangedAt??0,...t.sourceSetChange?{change:t.sourceSetChange}:{},scope:"workspace"}}m(podChangeClock,"podChangeClock"),s(podChangeClock,"podChangeClock");const changeEvidence=s(t=>{if(!t)return"no path evidence";const i=[...t.added.map(l=>`+${l}`),...t.removed.map(l=>`-${l}`)];return i.length?`${i.slice(0,3).join(", ")}${i.length>3?` (+${i.length-3} more)`:""}`:"no path evidence"},"changeEvidence");function createServiceLayer(t,i,l={}){const p=l.spawnProcess??node_child_process_1.spawn,y=l.probeAlive??pod_probe_1.probePodAlive,M=l.killTree??((e,r="SIGTERM")=>{try{process.kill(-e.pid,r)}catch{try{e.kill(r)}catch{}}}),j=l.sharedBuild??(0,shared_build_1.createSharedBuildRelay)(t),A=s((e,r="SIGTERM")=>{j.detach(e),M(e,r)},"killTree"),C=l.handoffDrainMs??(0,handoff_retire_1.handoffDrainBoundMs)(),L=l.treeAlive??(e=>{if(!e.pid||!(e instanceof node_child_process_1.ChildProcess))return!1;try{return process.kill(-e.pid,0),!0}catch(r){return r.code==="EPERM"}}),ce=l.retirePollMs??1e3,H=l.rollReadyMs??types_1.POD_ROLL_READY_MS,le=l.rollPollMs??750,de=l.maxConcurrentRolls??types_1.POD_MAX_CONCURRENT_ROLLS,V=de>0?de:Number.POSITIVE_INFINITY,E=l.maxConcurrentColdStarts??types_1.MAX_COLD_STARTS,_=E>0?E:Number.POSITIVE_INFINITY;let R=0;const D=[],F=s(()=>R<_?(R+=1,Promise.resolve()):new Promise(e=>{D.push(()=>{R+=1,e()})}),"acquireColdSlot"),b=s(()=>{R-=1,D.shift()?.()},"releaseColdSlot"),{emit:X}=i,te=s(e=>e.wsKey===t.wsKey?void 0:path.join(e.root,".lensmcp","events.jsonl"),"serviceBus"),v=s((e,r,o,n,d)=>X(r,o,n,{wsKey:e.wsKey,...d},void 0,te(e)),"emitSvc"),O=s(e=>(e.scannedAt=0,(0,discovery_1.pickSock)(e,t.scanTtlMs)?e.socks.length:0),"scanNow"),z=s((e,r)=>{let o;try{o=(0,node_child_process_1.execFileSync)("ps",["ax","-ww","-o","pid=,pgid=,command="],{encoding:"utf8",timeout:5e3})}catch{return 0}const n=e.proc?.pid;let d=0;for(const a of o.split(`
|
|
3
3
|
`)){const c=a.match(/^\s*(\d+)\s+(\d+)\s+(.*)$/);if(!c)continue;const u=Number(c[1]),f=Number(c[2]);if(isRunnerOf(c[3],r,e.root)&&!(u===process.pid||u===n)&&!(n!==void 0&&f===n)){try{process.kill(-f,"SIGKILL")}catch{try{process.kill(u,"SIGKILL")}catch{}}d+=1}}return d>0&&(console.log(`[gateway] ${r}: reaped ${d} stale runner tree(s) \u2014 a foreign generation of this service (holding nx's task lock, or its pool)`),v(e,"warning",`stale-runner reap: ${e.project} (${d} foreign tree(s))`,`cluster-service:${e.project}`,{kind:"stale-runner-reap",project:e.project,reaped:d})),d},"reapForeignRunners"),W=s((e,r)=>({...(0,pod_env_1.podBaseEnv)(process.env,t.root,e.root),...e.instanceEnv?{...e.instanceEnv,LENSMCP_SOCKET_ONLY:"1"}:{},...e.frozen?{LENSMCP_FREEZE:"1",LENSMCP_TYPECHECK:"off"}:{},NX_DAEMON:"false",NX_ISOLATE_PLUGINS:"false",...e.wsKey?{LENSMCP_WS_KEY:e.wsKey}:{},...e.sockNs?{LENSMCP_SOCK_NS:e.sockNs}:{},LENSMCP_EVENT_FILE:e.wsKey===t.wsKey?t.eventFile:path.join(e.root,".lensmcp","events.jsonl"),LENSMCP_GATEWAY_PID:String(process.pid),LENSMCP_POD_GENERATION:String(r),...eastWestEnv(t,e)}),"serviceEnv"),re=s((e,r,o,n)=>{const d=W(e,r),a=e.wsKey||path.basename(e.root),c=(0,serve_launch_1.planServeLaunch)({stores:t.graphStores,root:e.root,project:e.project,target:e.decl.serveTarget??"serve-hmr",childCount:n,baseEnv:d});if(c.kind==="runner"){const $=j.offeredTo(e),h=p((0,process_name_1.namedExecPath)((0,process_name_1.processName)(a,e.project,serve_launch_1.SERVE_RUNNER_ROLE)),[...c.script.execArgv,c.script.path,...(0,serve_launch_1.serveRunnerArgs)(o,n,e.root)],{cwd:e.root,detached:!0,env:$?{...c.env,[protocol_1.SHARED_BUILD_ENV]:"1"}:c.env,stdio:["ignore","pipe","pipe","ipc"]});return $&&j.attach(e,r,h),h.send?.(c.message,k=>{k&&console.error(`[gateway] ${o}: could not hand the task to its runner (${k.message})`)}),{proc:h,launcher:"runner"}}console.log(`[gateway] ${o}: starting through nx run \u2014 ${c.reason}`);const u=path.join(e.root,"node_modules","nx","dist","bin","nx.js"),f=(0,process_name_1.namedExecPath)((0,process_name_1.processName)(a,e.project,"nx")),[g,w]=fs.existsSync(u)?[f,[u,"run",o,`--childCount=${n}`]]:["yarn",["nx","run",o,`--childCount=${n}`]];return{proc:p(g,w,{cwd:e.root,detached:!0,env:d,stdio:["ignore","pipe","pipe"]}),launcher:"nx"}},"startServiceTree"),oe=new WeakMap,J=s((e,r,o)=>{const n=`${e.project}:${e.decl.serveTarget??"serve-hmr"}`,d=Math.max(1,e.decl.minPods??1),{proc:a,launcher:c}=re(e,r,n,d);oe.set(a,c),o==="active"&&(e.launcher=c),o==="active"&&(e.lastErrors=[],e.buildFailed=!1,e.faults=new pod_output_1.PodFaults,e.outputTail=[]);const u=s(w=>{const $=w.toString();for(const h of $.split(`
|
|
4
|
-
`)){const k=(0,pod_output_1.classifyPodLine)(h),{clean:T,broken:G,healthy:se}=k,S=T;if(o==="active"&&e.outputTail&&T.trim()&&(e.outputTail.push(T.trimEnd().slice(0,400)),e.outputTail.length>types_1.OUTPUT_TAIL_LINES&&e.outputTail.shift()),G){e.lastErrors.push(T),e.lastErrors.length>12&&e.lastErrors.shift(),e.buildFailed=!0;const x=Date.now();(T!==e.lastErrorEmitSig||x-(e.lastErrorEmitAt??0)>=types_1.SERVICE_ERROR_THROTTLE_MS)&&(e.lastErrorEmitSig=T,e.lastErrorEmitAt=x,v(e,"error",`service error: ${e.project}`,`cluster-service:${e.project}`,{kind:"service-error",project:e.project,line:T,fault:k.fault}))}se&&(e.buildFailed=!1);const P=(e.faults??=new pod_output_1.PodFaults).observe(k);if(P){e.lastErrorEmitSig=void 0;const x=P.open.length===0;v(e,"info",`${x?"service recovered":`${P.closed.join(" + ")} recovered`}: ${e.project}`,`cluster-service:${e.project}`,{kind:x?"service-recovered":"service-fault-closed",project:e.project,line:T,closed:P.closed,open:P.open})}!e.lockBlockedAt&&/Waiting for .+ in another nx process/.test(S)&&(e.lockBlockedAt=Date.now(),console.log(`[gateway] ${n}: spawn blocked by a stale nx runner \u2014 breaking the lock + respawning`),v(e,"warning",`nx task lock: ${e.project} blocked by a stale runner \u2014 auto-breaking`,`cluster-service:${e.project}`,{kind:"nx-lock-break",project:e.project}),setTimeout(()=>{t.stopped()||!e.lockBlockedAt||(V(e,"parked on a foreign nx task lock \u2014 recycling",{announce:!1}),z(e,n),setTimeout(()=>{!t.stopped()&&!e.proc&&e.state==="down"&&Y(e)},1500).unref?.())},250).unref?.())}},"sniff"),f=e.wsKey&&e.wsKey!==t.wsKey&&e.root?(0,workspace_log_1.workspaceLogWriter)(e.root):void 0,g=s(w=>{const $=(0,own_log_1.linePrefixer)(e.project);return h=>{if(t.stopped())return;const k=(0,inspector_secret_1.redactInspectorUrls)(h.toString());u(k);const T=$(k);w.write(T),f?.(T)}},"relay");return a.stdout?.on("data",g(process.stdout)),a.stderr?.on("data",g(process.stderr)),a.on("exit",(w,$)=>{if(e.proc!==a||(e.proc=void 0,e.state="down",t.stopped()))return;const h=(0,exit_reason_1.describeExit)(w,$);if(console.log(`[gateway] ${n} exited (${w??"no code"}${$?`, ${$}`:""}${e.inflight?`, ${e.inflight} request(s) in flight`:""})${h?` \u2014 ${h}`:""}`),v(e,w===0?"info":"warning",`service down: ${e.project} (exit ${w})`,`cluster-service:${e.project}`,{kind:"service-down",project:e.project,code:w,...$?{signal:$}:{}}),w===0||e.buildFailed)return;const k=Date.now();if(e.restarts=(e.restarts??[]).filter(G=>k-G<types_1.SERVICE_RESTART_WINDOW_MS),e.restarts.length>=types_1.SERVICE_MAX_RESTARTS){v(e,"error",`service crash-looping: ${e.project} \u2014 ${types_1.SERVICE_MAX_RESTARTS}+ restarts/min, not auto-respawning (the next request retries)`,`cluster-service:${e.project}`,{kind:"service-crash-loop",project:e.project});return}e.restarts.push(k);const T=Math.min(8e3,500*2**(e.restarts.length-1));setTimeout(()=>{t.stopped()||e.proc||e.state!=="down"||(console.log(`[gateway] self-heal: respawning ${e.project} (restart ${e.restarts.length}/${types_1.SERVICE_MAX_RESTARTS})`),v(e,"info",`self-heal: respawning ${e.project}`,`cluster-service:${e.project}`,{kind:"service-respawn",project:e.project,attempt:e.restarts.length}),Y(e))},T)}),a},"launchServiceProcess"),Y=s(e=>{if(t.stopped()||e.manualStopped)return;const r=`${e.project}:${e.decl.serveTarget??"serve-hmr"}`,o=Math.max(1,e.decl.minPods??1);l.reapForeign!==!1&&z(e,r),e.lockBlockedAt=void 0,console.log(`[gateway] starting ${r} (pods=${o})\u2026`),v(e,"info",`service starting: ${e.project} (${o} pod${o>1?"s":""})`,`cluster-service:${e.project}`,{kind:"service-starting",project:e.project,pods:o}),e.state="starting",e.spawnAt=Date.now(),e.generation=(e.generation??0)+1,e.proc=J(e,e.generation,"active")},"spawnService"),De=s(async e=>{const r=e.pool.socks[0];if(!r)return;const o=await(0,pod_probe_1.probePodAlive)(r,void 0,t.serviceKeys[(0,service_keys_1.serviceKeyId)(e.wsKey,e.project)]);o&&(e.activeWork=o.activeWork,o.watcher&&(e.watcher=o.watcher))},"refreshActiveWork"),Le=s(e=>{try{const r=Number(fs.readFileSync(`${e}.owner`,"utf8").trim());return Number.isInteger(r)&&r>1?r:void 0}catch{return}},"readOwnerSidecar"),Ie=s(async e=>{const r=t.serviceKeys[(0,service_keys_1.serviceKeyId)(e.wsKey,e.project)];if(!r)return[];const o=(0,node_crypto_1.createHash)("sha256").update(r).digest("hex").slice(0,8),n=[];for(const d of e.pool.socks){const a=await(0,pod_probe_1.probePodAlive)(d,void 0,r);a&&(!a.keyFingerprint||a.keyFingerprint!==o)&&n.push({sock:d,pid:a.pid})}return n},"staleAdoptedSocks"),Oe=s((e,r)=>{const o=r.map(n=>n.sock);for(const{sock:n,pid:d}of r){const a=chooseStalePodKillTarget(d,Le(n),process.pid);if(a!==void 0)try{process.kill(a,"SIGTERM")}catch{}try{fs.unlinkSync(n)}catch{}try{fs.unlinkSync(`${n}.owner`)}catch{}}e.pool.socks=e.pool.socks.filter(n=>!o.includes(n)),e.pool.idx=-1,e.pool.scannedAt=0},"evictStaleAdopted"),pe=s((e,r)=>{if(e.state==="up")return!1;e.state="up",e.lastStartError=void 0,e.wedgeRecycles=0;const o=e.pool.socks.length;return v(e,"info",`service up: ${e.project} (${o} pods, ${r})`,`cluster-service:${e.project}`,{kind:"service-up",project:e.project,pods:o,adopted:r==="adopted"}),!0},"markUp"),ve=s(async e=>{if(e.manualStopped)return!1;if(O(e.pool)>0){const n=await Ie(e);if(e.manualStopped)return!1;if(n.length>0&&(console.error(`[gateway] ${e.project}: ${n.length} adopted pod(s) hold a foreign east-west key \u2014 evicting instead of adopting.`),v(e,"warning",`stale adoption: ${e.project} (foreign east-west key)`,`cluster-service:${e.project}`,{kind:"pod-recycle",project:e.project,reason:"stale-adoption",pods:n.length}),e.proc&&V(e,"stale adoption (foreign east-west key)"),Oe(e,n)),e.pool.socks.length>0)return pe(e,"adopted"),!0}if(t.stopped())return!1;let r=!1;const o=s(()=>e.state!=="starting"&&!e.proc,"notStarted");if(o())if(e.coldWait)await e.coldWait;else{R>=_&&(console.log(`[gateway] cold start queued: ${e.project}${e.wsKey&&e.wsKey!==t.wsKey?` (${e.wsKey})`:""} \u2014 ${R} starting, ${D.length} ahead (LENSMCP_MAX_COLD_STARTS=${_}).`),v(e,"info",`cold start queued: ${e.project}`,`cluster-service:${e.project}`,{kind:"cold-start-queued",project:e.project,inFlight:R,ahead:D.length}));const n=F();if(e.coldWait=n,await n,e.coldWait=void 0,r=!0,t.stopped()||e.manualStopped)return b(),!1;o()&&Y(e)}try{const n=await Ne(e);return n?e.lastStartError=void 0:!t.stopped()&&!e.manualStopped&&(e.lastStartError=startErrorText(fe(e),e.outputTail)),n}finally{r&&b()}},"ensureUp"),Ne=s(async e=>{const r=Date.now()+t.startupTimeoutMs,o=Date.now()+12e3;for(;!t.stopped()&&!e.manualStopped&&Date.now()<r;){if(await sleep(Math.min(700,t.startupTimeoutMs/4)),e.manualStopped||e.buildFailed&&Date.now()>o)return!1;if(O(e.pool)>0){e.state="up",e.buildFailed=!1;const n=e.spawnAt?Date.now()-e.spawnAt:void 0;return console.log(`[gateway] ${e.project} up (${e.pool.socks.length} pods${n?`, cold start ${n}ms`:""})`),v(e,"info",`cold start: ${e.project} (${e.pool.socks.length} pods, ${n??"?"}ms)`,`cluster-service:${e.project}`,{kind:"cold-start",project:e.project,pods:e.pool.socks.length,durationMs:n}),!0}if(e.state==="down")return!1}return!1},"waitForPods"),Ke=s(e=>{const r=e.decl.maxPods??e.decl.minPods??1,o=e.pool.socks.length,n=scaleTarget(e);!n||o===0||o>=r||e.inflight<=o||Date.now()-e.lastScaleAt<5e3||(e.lastScaleAt=Date.now(),postScale(n,o+1,l.scaleLookup),console.log(`[gateway] autoscale ${e.project}: ${o} \u2192 ${o+1} pods (inflight ${e.inflight})`),v(e,"info",`autoscale: ${e.project} ${o} \u2192 ${o+1} pods`,`cluster-service:${e.project}`,{kind:"autoscale",project:e.project,from:o,to:o+1,inflight:e.inflight}))},"scaleUp"),ue=l.killGraceMs??types_1.TREE_KILL_GRACE_MS,N=new Map,Ae=s(e=>{const r=N.get(e);if(!r||(N.delete(e),clearTimeout(r.timer),!L(e)))return;const{svc:o,why:n}=r;console.log(`[gateway] ${o.project}: its tree (pid ${e.pid}) was still running ${Math.round(ue/1e3)}s after it was told to stop (${n}) \u2014 killing it (SIGKILL).`),v(o,"warning",`tree force-killed: ${o.project} (it ignored SIGTERM)`,`cluster-service:${o.project}`,{kind:"tree-force-killed",project:o.project,why:n,pid:e.pid,graceMs:ue}),M(e,"SIGKILL")},"settleDyingTree"),Se=s((e,r,o)=>{if(A(r,"SIGTERM"),ue<=0||N.has(r))return;const n=setTimeout(()=>Ae(r),ue);n.unref?.(),N.set(r,{svc:e,why:o,timer:n})},"stopTree"),Fe=s(async(e=3e3)=>{const r=Date.now()+e;for(;N.size>0;){for(const[o,n]of[...N])L(o)||(clearTimeout(n.timer),N.delete(o));if(N.size===0||Date.now()>=r)break;await sleep(100)}for(const o of[...N.keys()])Ae(o)},"finishDyingTrees"),V=s((e,r,o)=>{if(!e.proc)return;console.log(`[gateway] ${e.project} ${r} \u2014 scaling to zero.`),o?.announce!==!1&&v(e,"info",`idle kill: ${e.project} (${r})`,`cluster-service:${e.project}`,{kind:"idle-kill",project:e.project,why:r});const n=e.proc;try{n.stdout?.removeAllListeners("data"),n.stderr?.removeAllListeners("data"),n.removeAllListeners("exit")}catch{}(0,discovery_1.stopRoutingTo)(e.pool),Se(e,n,r),e.proc=void 0,e.state="down",setTimeout(()=>{ge(e),e.pool.socks=[],e.pool.scannedAt=0},1200).unref?.()},"killSpawned"),ge=s(e=>{try{for(const r of fs.readdirSync(e.pool.dir)){if(!r.endsWith(".sock"))continue;const o=path.join(e.pool.dir,r);try{const n=Number(fs.readFileSync(`${o}.owner`,"utf8").trim());if(Number.isFinite(n)&&n>0)try{process.kill(n,0);continue}catch{}}catch{}try{fs.unlinkSync(o)}catch{}try{fs.unlinkSync(`${o}.owner`)}catch{}}}catch{}},"sweepDeadOwnerSocks");let Q=0;const ye=[],We=s(()=>Q<X?(Q+=1,Promise.resolve()):new Promise(e=>{ye.push(()=>{Q+=1,e()})}),"acquireRollSlot"),Ge=s(()=>{Q-=1,ye.shift()?.()},"releaseRollSlot"),$e=s(async(e,r,o)=>{O(e.pool);for(const n of e.pool.socks){const d=await y(n,void 0,o);if(d&&r(d.podGeneration))return!0}return!1},"anyPodAnswers"),he=new Map,qe=s((e,r,o)=>{const n=C>0&&(0,handoff_retire_1.requestHandoffRetire)(e.pool.dir,o);if(A(r,"SIGTERM"),!n)return;const d=e.wsKey&&e.wsKey!==t.wsKey&&e.root?(0,workspace_log_1.workspaceLogWriter)(e.root):void 0,a=s(se=>S=>{if(t.stopped())return;const P=(0,inspector_secret_1.redactInspectorUrls)(S.toString()).replace(/^(?=.)/gm,`[${e.project} g${o} retiring] `);se.write(P),d?.(P)},"say"),c=a(process.stdout),u=a(process.stderr);r.stdout?.on("data",c),r.stderr?.on("data",u);let f,g=!1;const w=s(()=>{g=!0,clearTimeout(f),r.stdout?.removeListener("data",c),r.stderr?.removeListener("data",u),r.removeListener("close",w)},"releaseLogs");r.once("close",w);let $=!1;const h=s(()=>{$||($=!0,clearTimeout(k),clearInterval(G),t.stopped()?w():g||(f=setTimeout(w,1e3),f.unref?.()),he.delete(r),(0,handoff_retire_1.clearHandoffRetire)(e.pool.dir,o),ge(e),e.pool.scannedAt=0)},"end"),k=setTimeout(()=>{console.error(`[gateway] pod handoff: ${e.project} g${o} was still running ${C}ms after it was retired \u2014 killing it.`),M(r,"SIGKILL"),h()},C);k.unref?.();const T=s(()=>{if(!$){if(t.stopped()){h();return}L(r)||(console.log(`[gateway] pod handoff: ${e.project} g${o} finished its in-flight work and exited.`),h())}},"look"),G=setInterval(T,ce);G.unref?.(),r.once("exit",T),he.set(r,()=>{h(),Se(e,r,"the gateway is stopping")})},"retireReplacedTree"),Ve=l.standbyGraceMs??3e4,I=new Map,Ue=s((e,r,o,n,d)=>{const a=d+B+Ve,c=setTimeout(()=>Me(r),Math.max(0,a-Date.now()));c.unref?.(),I.set(r,{svc:e,generation:o,reason:n,beganAt:d,deadlineAt:a,timer:c})},"holdStandby"),Be=s(e=>{const r=I.get(e);r&&(clearTimeout(r.timer),I.delete(e))},"releaseStandby"),Z=s((e,r)=>{const o=I.get(e);if(!o)return!1;clearTimeout(o.timer),I.delete(e);const{svc:n,generation:d}=o;try{e.stdout?.removeAllListeners("data"),e.stderr?.removeAllListeners("data")}catch{}return(0,discovery_1.stopRoutingTo)(n.pool,a=>(0,pod_sock_1.podSockGeneration)(a)===d),Se(n,e,`standby g${d}: ${r}`),setTimeout(()=>ge(n),1200).unref?.(),!0},"endStandby"),Ce=s((e,r)=>{const o=r.oldServing?`old generation g${r.fromGen} kept serving`:`and the old generation g${r.fromGen} is NOT serving (${r.oldGone?"its tree is gone":"none of its pods answers"}) \u2014 the service is down until it recovers`;console.error(`[gateway] pod handoff failed: ${e.project} g${r.generation}: ${r.why} \u2014 ${o}.`),e.rollFailure=`${r.why} \u2014 ${o}`,v(e,r.oldServing?"warning":"error",`pod handoff failed: ${e.project}`,`cluster-service:${e.project}`,{kind:"pod-handoff-failed",project:e.project,reason:r.reason,generation:r.generation,error:r.why,durationMs:Date.now()-r.beganAt,oldServing:r.oldServing})},"reportStandbyFailed"),Me=s(e=>{const r=I.get(e);if(!r)return;const{svc:o,generation:n,reason:d,beganAt:a}=r,c=`the standby outlived its roll (${Math.round((Date.now()-a)/1e3)}s; a roll waits ${Math.round(B/1e3)}s for it)`;Z(e,c);const u=o.proc,f=t.serviceKeys[(0,service_keys_1.serviceKeyId)(o.wsKey,o.project)];(async()=>{const g=!u||u.exitCode!==null||u.signalCode!==null,w=g?!1:await Promise.race([$e(o,h=>h!==n,f).catch(()=>!1),sleep(2e3).then(()=>{})]),$=!t.stopped()&&!g&&(w??O(o.pool)>0);Ce(o,{reason:d,generation:n,fromGen:o.generation??n-1,why:c,beganAt:a,oldServing:$,oldGone:g})})()},"outlivedRoll"),He=s(()=>{for(const[e,r]of[...I])Date.now()>=r.deadlineAt?Me(e):!r.svc.rolling&&r.svc.proc!==e&&(console.error(`[gateway] pod handoff: ${r.svc.project} g${r.generation} is a standby whose roll is over \u2014 stopping it.`),Z(e,"its roll is over"))},"sweepStandbys"),Ye=s(()=>{for(const e of[...he.values()])e();for(const e of[...I.keys()])Z(e,"the gateway is stopping")},"stopRetiringTrees"),me=s((e,r)=>{if(e.rolling)return e.rolling;const o=e.proc;if(!o||t.stopped())return Promise.resolve(!1);if(e.launcher==="nx")return console.log(`[gateway] pod handoff skipped: ${e.project} runs through nx run, which starts one instance of a target at a time \u2014 no standby can overlap it (reason=${r}).`),Promise.resolve(!1);Q>=X&&console.log(`[gateway] pod handoff queued: ${e.project} reason=${r} \u2014 ${Q} roll(s) in flight, ${ye.length} ahead (LENSMCP_POD_MAX_CONCURRENT_ROLLS=${X}).`);const n=(async()=>{await We();try{return await Xe(e,o,r)}finally{Ge()}})().finally(()=>{e.rolling=void 0});return e.rolling=n,n},"rollPod"),Xe=s(async(e,r,o)=>{const n=e.proc;if(n!==r||t.stopped())return!1;const d=e.generation??0,a=d+1,c=Date.now();e.lastStaleRecycleAt=c,console.log(`[gateway] pod handoff start: ${e.project} g${d}\u2192g${a} reason=${o} \u2014 standby spawning, old generation keeps serving.`),v(e,"info",`pod handoff starting: ${e.project} (${o})`,`cluster-service:${e.project}`,{kind:"pod-handoff-start",project:e.project,reason:o,generation:a,fromGeneration:d});const u=J(e,a,"standby"),f=t.serviceKeys[(0,service_keys_1.serviceKeyId)(e.wsKey,e.project)];Ue(e,u,a,o,c);let g=!1;try{const w=c+B;let $;for(;!t.stopped()&&Date.now()<w&&I.has(u)&&!(u.exitCode!==null||u.signalCode!==null);){O(e.pool);for(const h of e.pool.socks)if((await y(h,void 0,f))?.podGeneration===a){$=h;break}if($)break;await sleep(le)}if(!I.has(u))return!1;if(!$||t.stopped()){const h=t.stopped()?"gateway stopping":u.exitCode!==null||u.signalCode!==null?`standby exited (${u.exitCode??u.signalCode})`:`standby not ready within ${Math.round(B/1e3)}s`;Z(u,h);const k=!t.stopped()&&e.proc===n&&n.exitCode===null&&n.signalCode===null&&await $e(e,T=>T!==a,f);return Ce(e,{reason:o,generation:a,fromGen:d,why:h,beganAt:c,oldServing:k,oldGone:e.proc!==n||n.exitCode!==null||n.signalCode!==null}),!1}if(e.proc!==n)return Z(u,"the service was replaced underneath the roll"),!1;Be(u),g=!0,e.proc=u,e.launcher=oe.get(u),e.generation=a,e.spawnAt=c,e.state="up",e.watcher=void 0,e.staleVerifiedAt=void 0,e.staleKeptAt=void 0,e.buildFailed=!1,e.lastErrors=[];try{n.stdout?.removeAllListeners("data"),n.stderr?.removeAllListeners("data"),n.removeAllListeners("exit")}catch{}return(0,discovery_1.stopRoutingTo)(e.pool,h=>(0,pod_sock_1.podSockGeneration)(h)!==a&&path.join(e.pool.dir,h)!==$),qe(e,n,d),setTimeout(()=>{ge(e),e.pool.scannedAt=0},1200).unref?.(),console.log(`[gateway] pod handoff ready: ${e.project} g${a} answered on ${path.basename($)} in ${Date.now()-c}ms; retiring g${d}.`),v(e,"info",`pod handoff complete: ${e.project}`,`cluster-service:${e.project}`,{kind:"pod-handoff-complete",project:e.project,reason:o,generation:a,fromGeneration:d,durationMs:Date.now()-c}),!0}finally{g||Z(u,"its roll ended without it")}},"runRoll"),ze=s((e,r)=>{if(t.stopped())return{refused:"the gateway is stopping"};const o=e.restart&&!e.restart.done?e.restart:void 0,n=o?void 0:Je(e);if(n&&"refused"in n)return console.error(`[gateway] restart refused: ${e.project}${e.wsKey!==t.wsKey?` (${e.wsKey})`:""} \u2014 ${n.refused}`),v(e,"warning",`restart refused: ${e.project}`,`cluster-service:${e.project}`,{kind:"service-restart",phase:"refused",project:e.project,reason:r.reason,error:n.refused}),{refused:n.refused};const d=n&&"applied"in n?n:void 0;if(e.manualStopped=!1,e.actionFailure=void 0,o)return{restart:o,already:!0};if(!e.proc&&e.state!=="down")return{refused:`${e.project} is served by pods this gateway adopted from an earlier one \u2014 it has no tree of its own to replace. \`lensmcp gateway restart\` starts every service under this gateway.`};const a=e.proc?r.hard||e.launcher==="nx"||e.state!=="up"?"hard":"rolling":"start",c={how:a,reason:r.reason,startedAt:Date.now(),...e.proc&&e.generation!==void 0?{fromGeneration:e.generation}:{},...d?{env:d.applied}:{}};d&&(e.instanceEnv=d.env),e.restart=c,e.lastUsed=c.startedAt;const u=c.env?{envFingerprint:c.env.fingerprint,envChanged:c.env.changed}:{},f=c.env?` Instance variables ${c.env.fingerprint}: ${c.env.changed.length?`changed ${c.env.changed.join(", ")}`:"unchanged"}.`:"";return console.log(`[gateway] restart asked: ${e.project}${e.wsKey!==t.wsKey?` (${e.wsKey})`:""} \u2014 ${a} (${r.reason}).${f}`),v(e,"info",`restart asked: ${e.project} (${a})`,`cluster-service:${e.project}`,{kind:"service-restart",phase:"started",project:e.project,how:a,reason:r.reason,...c.fromGeneration!==void 0?{fromGeneration:c.fromGeneration}:{},...u}),s(async()=>{if(a==="start")return await ve(e)?{ok:!0}:{ok:!1,error:fe(e)};if(a==="rolling")return e.rolling&&await e.rolling,e.proc?(e.rollFailure=void 0,await me(e,r.reason)?{ok:!0}:{ok:!1,error:e.rollFailure??"the new tree did not take over"}):await ve(e)?{ok:!0}:{ok:!1,error:fe(e)};if(V(e,`restart asked (${r.reason})`,{announce:!1}),await sleep(1500),t.stopped())return{ok:!1,error:"the gateway is stopping"};let g=!1;e.proc||(await F(),g=!0,!e.proc&&e.state!=="starting"&&Y(e));try{const w=e.proc,$=e.generation,h=t.serviceKeys[(0,service_keys_1.serviceKeyId)(e.wsKey,e.project)],k=Date.now()+t.startupTimeoutMs;for(;!t.stopped()&&Date.now()<k;){if(!w||e.proc!==w||w.exitCode!==null||w.signalCode!==null)return{ok:!1,error:fe(e)};if(await $e(e,T=>T===$,h))return pe(e,"observed"),e.buildFailed=!1,{ok:!0};await sleep(le)}return{ok:!1,error:t.stopped()?"the gateway is stopping":`no pod of the new tree answered within ${Math.round(t.startupTimeoutMs/1e3)}s`}}finally{g&&b()}},"run")().catch(g=>({ok:!1,error:g.message})).then(g=>{c.done={ok:g.ok,at:Date.now(),...e.generation!==void 0?{generation:e.generation}:{},...g.error?{error:g.error}:{}},g.ok&&(e.lastUsed=c.done.at);const w=Math.round((c.done.at-c.startedAt)/100)/10;g.ok?console.log(`[gateway] restarted: ${e.project} \u2014 g${c.done.generation??"?"} serving after ${w}s (${a}).`):console.error(`[gateway] restart failed: ${e.project} \u2014 ${g.error} (${a}, after ${w}s).`),v(e,g.ok?"info":"error",g.ok?`restarted: ${e.project}`:`restart failed: ${e.project}`,`cluster-service:${e.project}`,{kind:"service-restart",phase:g.ok?"done":"failed",project:e.project,how:a,reason:r.reason,...c.fromGeneration!==void 0?{fromGeneration:c.fromGeneration}:{},...c.done.generation!==void 0?{generation:c.done.generation}:{},durationMs:c.done.at-c.startedAt,...g.error?{error:g.error}:{},...u})}),{restart:c,already:!1}},"restartService"),Je=s(e=>{if(!e.instanceBuiltins)return;const r=(0,instance_1.readInstanceEnvStrict)(e.root,e.instanceBuiltins);if("reason"in r)return{refused:`the instance variables of ${e.project} could not be read again \u2014 ${r.reason}. Nothing was restarted: the running tree keeps what it has. Fix the file, then restart it again.`};const o=e.instanceEnv??{};return{env:r.env,applied:{fingerprint:(0,instance_1.instanceEnvFingerprint)(r.env),fromFingerprint:(0,instance_1.instanceEnvFingerprint)(o),changed:(0,instance_1.changedInstanceEnvNames)(o,r.env)}}},"restartEnv"),fe=s(e=>e.buildFailed?`its build failed${e.lastErrors?.length?`: ${e.lastErrors[e.lastErrors.length-1]}`:""}`:e.proc&&(e.proc.exitCode!==null||e.proc.signalCode!==null)?`its tree exited (${e.proc.exitCode??e.proc.signalCode})`:!e.proc&&e.state==="down"?"its tree exited before a pod answered":`no pod answered within ${Math.round(t.startupTimeoutMs/1e3)}s`,"startFailure"),xe=s(e=>{const r=Date.now();e.restarts=(e.restarts??[]).filter(n=>r-n<types_1.SERVICE_RESTART_WINDOW_MS);const o=(e.wedgeRecycles??0)+1;if(e.restarts.length>=types_1.SERVICE_MAX_RESTARTS||o>types_1.SERVICE_MAX_RESTARTS){const n=e.restarts.length>=types_1.SERVICE_MAX_RESTARTS?`wedged ${types_1.SERVICE_MAX_RESTARTS}+\xD7/min`:`recycled ${types_1.SERVICE_MAX_RESTARTS}\xD7 in a row and no pod came up`;v(e,"error",`service crash-looping: ${e.project} \u2014 ${n}, not auto-recycling (the next request retries)`,`cluster-service:${e.project}`,{kind:"service-crash-loop",project:e.project,recycles:o-1}),V(e,"wedged (crash-loop cap) \u2014 leaving down for the next request",{announce:!1});return}e.wedgeRecycles=o,e.restarts.push(r),console.log(`[gateway] self-heal: recycling WEDGED ${e.project} (live parent, 0 live pods; attempt ${o}/${types_1.SERVICE_MAX_RESTARTS} with no pod up since the first, ${e.restarts.length} in the last minute; ${e.inflight??0} request(s) in flight \u2014 jobs held by the dead pod keep their locks until they expire)`),v(e,"warning",`self-heal: recycling wedged ${e.project} (0 live pods)`,`cluster-service:${e.project}`,{kind:"service-recycle",project:e.project,attempt:o,inWindow:e.restarts.length}),V(e,"wedged: 0 live pods \u2014 recycling",{announce:!1}),setTimeout(()=>{!t.stopped()&&!e.proc&&e.state==="down"&&Y(e)},1500).unref?.()},"recycleWedged"),Qe={maxAgeMs:types_1.POD_MAX_AGE_MS,graceMs:types_1.POD_STALE_GRACE_MS,settleMs:types_1.POD_RECYCLE_SETTLE_MS,cooldownMs:types_1.POD_STALE_RECYCLE_COOLDOWN_MS};let Ee;const ne=new Map,_e=new Map;let ke=!1,je=0,we=0;const Ze=s(()=>{const e=t.projectRoots??{},r=new Set(t.services.map(n=>n.project));for(const n of t.routes)n.lens&&r.add(n.lens.project);const o=new Set;for(const n of r){const d=e[n];if(!d)continue;const a=path.relative(t.root,d).split(path.sep).filter(Boolean)[0];a&&!a.startsWith("..")&&o.add(a)}return[...o]},"managedBuckets"),et=s((e,r,o,n)=>{const d=t.projectSourceRoots?.[e];if(d?.length)return d;const a=t.projectRoots?.[e];if(!a)return;const c=sourceScopeDirs(t.root,a,o,r,n);return c.length>0?c:void 0},"scopeFor"),tt=s(()=>{if(ke||Date.now()-je<types_1.POD_STALE_SCAN_MS)return;ke=!0,je=Date.now();const e=je;(async()=>{const r=(0,scope_1.readSourceSetOptions)(t.root),o=r.exclude,n={ignoreTests:r.ignoreTests},d=sourceScanPass(t.root,o,n),a=await d.snapshot(),c=Date.now(),u=sourceChangeWindowMs(c,we,types_1.POD_STALE_SCAN_MS,types_1.POD_RECYCLE_SETTLE_MS),f=Ee?diffSourceSets(Ee,a,c,u):null;if(f&&(t.sourceSetChangedAt=c,t.sourceSetChange=f,H("info","source file set changed \u2014 stale pods recycle when idle","cluster-gateway",{kind:"source-set-changed",added:f.added,removed:f.removed,truncated:f.truncated})),Ee=a,!t.projectRoots){we=e;return}let g;try{g=(await fs.promises.readdir(t.root,{withFileTypes:!0})).filter(S=>S.isDirectory()).map(S=>S.name)}catch{return}const w=Ze(),$=new Set(t.services.map(S=>S.project));for(const S of t.routes)S.lens&&$.add(S.lens.project);const h=new Map;for(const S of $){const P=et(S,g,w,o);if(!P)continue;const x=P.join("|"),q=h.get(x)??{dirs:P,projects:[]};q.projects.push(S),h.set(x,q)}const k=Date.now(),T=sourceChangeWindowMs(k,we,types_1.POD_STALE_SCAN_MS,types_1.POD_RECYCLE_SETTLE_MS);we=e;const G=s((S,P,x)=>{t.sourceSetChangedFor??=new Map,t.sourceSetChangesFor??=new Map;for(const q of S)t.sourceSetChangedFor.set(q,P),t.sourceSetChangesFor.set(q,x)},"stampScoped"),se=new Set([...h.values()].flatMap(S=>S.projects));for(const S of[...t.sourceSetScoped??[]])se.has(S)||t.sourceSetScoped.delete(S);for(const[S,{dirs:P,projects:x}]of h){const q=await d.snapshot(P),Re=ne.get(S);if(Re||x.some(K=>_e.has(K))){t.sourceSetScoped??=new Set;for(const K of x)t.sourceSetScoped.add(K)}ne.set(S,q);const Te=new Map;for(const K of x){const U=_e.get(K);if(U===void 0||U===S)continue;const ee=Te.get(U)??[];ee.push(K),Te.set(U,ee)}for(const K of x)_e.set(K,S);for(const[K,U]of Te){const ee=ne.get(K),ie=ee?diffSourceSets(ee,q,k,T):f;ie&&(G(U,ee?k:c,ie),H("info",`source file set changed \u2014 ${U.join(", ")}'s watch scope was re-keyed`,"cluster-gateway",{kind:"source-set-changed",scoped:!0,rescoped:!0,projects:U,added:ie.added,removed:ie.removed,truncated:ie.truncated}))}if(!Re)continue;const ae=diffSourceSets(Re,q,k,T);ae&&(G(x,k,ae),H("info",`source file set changed in ${x.join(", ")}'s scope`,"cluster-gateway",{kind:"source-set-changed",scoped:!0,projects:x,added:ae.added,removed:ae.removed,truncated:ae.truncated}))}for(const S of[...ne.keys()])h.has(S)||ne.delete(S)})().catch(()=>{}).finally(()=>{ke=!1})},"maybeScanSourceSet"),rt=s((e,r)=>{const o=podChangeClock(t,e.project),n=o.change,d=`${o.scope==="project"?"in its scope":"in the workspace (its scope is not known)"}: ${changeEvidence(n)}`,a=n?.windowMs??types_1.POD_STALE_SCAN_MS+types_1.POD_RECYCLE_SETTLE_MS,c=podWatcherVerdict(e.watcher,r,a),u=s(g=>(e.staleKeptAt!==r&&(e.staleKeptAt=r,console.log(`[gateway] stale source set: pod ${e.project} ${g} \u2014 no recycle.`)),!1),"keep");if(c==="heard")return e.staleVerifiedAt=r,v(e,"info",`stale check: ${e.project} watcher confirmed \u2014 no recycle`,`cluster-service:${e.project}`,{kind:"pod-stale-verified",project:e.project,watcher:c}),u(`watcher CONFIRMED alive across the change (last build ${new Date(e.watcher?.lastBuildAt??0).toISOString()})`);if(c==="degraded")return console.log(`[gateway] stale source set: pod ${e.project} watcher DEGRADED (${e.watcher?.degraded}) \u2014 recycling.`),!0;const f=s(g=>(e.staleKeptAt!==r&&(e.staleKeptAt=r,console.log(`[gateway] stale source set: pod ${e.project} ${g}; the change ${d} \u2014 recycling.`)),!0),"recycling");return c==="silent"?types_1.POD_WATCHER_SILENT==="keep"?u("watcher alive but quiet across the change \u2014 keeping it (LENSMCP_POD_WATCHER_SILENT=keep; a live watcher cannot miss an add it will need)"):f("watcher alive but quiet across the change"):types_1.POD_WATCHER_UNVERIFIED==="keep"?u("unverifiable (no watcher testimony \u2014 older devserver bundle?) \u2014 keeping it (LENSMCP_POD_WATCHER_UNVERIFIED=keep)"):f("watcher unverifiable (no testimony yet \u2014 a pod that never rebuilt, or an older devserver bundle)")},"podStaleRecycleAllowed"),ot=s((e,r)=>{if(e.lastStaleRecycleAt=Date.now(),types_1.POD_RECYCLE_MODE==="rolling"&&e.proc&&e.launcher!=="nx"){me(e,r);return}console.log(`[gateway] zombie recycle: ${e.project} (${r}) \u2014 stale fs view; fresh pod incoming`),v(e,"warning",`zombie recycle: ${e.project} (${r})`,`cluster-service:${e.project}`,{kind:"pod-recycle",project:e.project,reason:r});const o=!!e.decl.eager;V(e,`${r} \u2014 recycling stale pod`,{announce:!1}),o&&setTimeout(()=>{!t.stopped()&&!e.proc&&e.state==="down"&&Y(e)},1500).unref?.()},"recyclePod"),nt=s(e=>{const r=setInterval(()=>{if(e&&!t.stopped())try{e()}catch(o){console.error("[gateway] park sweep error:",o)}ct().catch(o=>console.error("[gateway] sweep error:",o))},t.sweepMs);return r.unref(),r},"startSweeper"),st=l.listProcesses??(()=>{try{return(0,orphan_reaper_1.parsePsRows)((0,node_child_process_1.execFileSync)("ps",orphan_reaper_1.PS_ROW_ARGS,{encoding:"utf8",timeout:5e3}))}catch{return[]}}),Pe=l.signalProcess??((e,r)=>{process.kill(e,r)});let be=0;const at=s(()=>{if(typeof process.getuid!="function")return 0;const e=t.registry?t.registry.allServices():t.services;if(e.length===0)return 0;const r=e.map(a=>({label:a.wsKey||path.basename(a.root),project:a.project,root:a.root,svc:a})),o=new Set;for(const a of e)a.proc?.pid&&o.add(a.proc.pid);for(const a of[...he.keys(),...N.keys(),...I.keys()])a.pid&&o.add(a.pid);const n=[...new Set((0,process_name_1.defaultLinkDirs)().flatMap(a=>{try{return[a,fs.realpathSync(a)]}catch{return[a]}}))];let d=0;for(const a of(0,orphan_reaper_1.findOrphanExecutors)(st(),r,{linkDirs:n,uid:process.getuid(),selfPid:process.pid,ownGroups:o})){const{row:c}=a;try{Pe(a.group?-c.pgid:c.pid,"SIGKILL")}catch(f){if(f.code!=="ESRCH"||!a.group)continue;try{Pe(c.pid,"SIGKILL")}catch{continue}}d+=1;const u=a.owner.svc;console.log(`[gateway] reaped an orphaned executor of ${u.project} (${a.role}, pid ${c.pid}${a.group?`, group ${c.pgid}`:""}, parent gone) \u2014 a stopped tree it outlived: ${c.command.slice(0,160)}`),v(u,"warning",`orphan reap: ${u.project} (pid ${c.pid})`,`cluster-service:${u.project}`,{kind:"orphan-executor-reap",project:u.project,pid:c.pid,pgid:c.pgid,role:a.role,group:a.group})}return d},"reapOrphanExecutors"),ct=s(async()=>{{if(t.stopped())return;He(),l.reapForeign!==!1&&types_1.ORPHAN_REAP_EVERY_MS>0&&Date.now()-be>=types_1.ORPHAN_REAP_EVERY_MS&&(be=Date.now(),at());for(const e of t.graphStores?.all()??[])e.refreshIfStale();types_1.POD_RECYCLE_ENABLED&&tt();for(const e of t.registry?t.registry.allServices():t.services){if(t.stopped()||!e.proc){e.wedgedSince=void 0;continue}const r=path.resolve(e.root)===path.resolve(t.root),o=(0,warm_start_1.serviceIdleSec)(t,e),n=(0,awake_1.idleStopAt)(e,o);if(n!==void 0&&e.state==="up"&&(!e.restart||e.restart.done)&&e.inflight===0&&Date.now()>n){e.lastIdleStop={at:Date.now(),why:`no request for ${o}s${(e.awakeUntil??0)>e.lastUsed?" after its hold ended":""}`},V(e,`idle ${o}s`),e.wedgedSince=void 0;continue}const d=e.state==="starting"&&e.spawnAt!==void 0&&Date.now()-e.spawnAt<t.startupTimeoutMs,a=O(e.pool)>0;if(a||d){if(e.wedgedSince=void 0,a&&pe(e,"observed"),a&&!d&&types_1.POD_RECYCLE_ENABLED&&r){const c=podChangeClock(t,e.project).at;await De(e);const u=(e.staleVerifiedAt??0)>=c&&c>0,f=podRecycleReason(e,Date.now(),u?0:c,Qe);if(f==="stale-source-set"&&!rt(e,c))continue;f&&ot(e,f)}continue}e.wedgedSince??=Date.now(),Date.now()-e.wedgedSince>types_1.WEDGE_RECYCLE_GRACE_MS&&(e.wedgedSince=void 0,xe(e))}}},"sweepOnce");return{scanNow:O,spawnService:Y,ensureUp:ve,scaleUp:Ke,killSpawned:V,markUp:pe,emitSvc:v,startSweeper:nt,rollPod:me,restartService:ze,recycleWedged:xe,stopRetiringTrees:Ye,finishDyingTrees:Fe,stopBuildHost:s(e=>e===void 0?j.stop():j.release(e),"stopBuildHost")}}m(createServiceLayer,"createServiceLayer"),s(createServiceLayer,"createServiceLayer");function chooseStalePodKillTarget(t,i,l){if(!(t===void 0||!Number.isInteger(t)||t<=1)&&!(i!==void 0&&i!==t)&&t!==l)return t}m(chooseStalePodKillTarget,"chooseStalePodKillTarget"),s(chooseStalePodKillTarget,"chooseStalePodKillTarget");
|
|
4
|
+
`)){const k=(0,pod_output_1.classifyPodLine)(h),{clean:T,broken:G,healthy:se}=k,S=T;if(o==="active"&&e.outputTail&&T.trim()&&(e.outputTail.push(T.trimEnd().slice(0,400)),e.outputTail.length>types_1.OUTPUT_TAIL_LINES&&e.outputTail.shift()),G){e.lastErrors.push(T),e.lastErrors.length>12&&e.lastErrors.shift(),e.buildFailed=!0;const x=Date.now();(T!==e.lastErrorEmitSig||x-(e.lastErrorEmitAt??0)>=types_1.SERVICE_ERROR_THROTTLE_MS)&&(e.lastErrorEmitSig=T,e.lastErrorEmitAt=x,v(e,"error",`service error: ${e.project}`,`cluster-service:${e.project}`,{kind:"service-error",project:e.project,line:T,fault:k.fault}))}se&&(e.buildFailed=!1);const P=(e.faults??=new pod_output_1.PodFaults).observe(k);if(P){e.lastErrorEmitSig=void 0;const x=P.open.length===0;v(e,"info",`${x?"service recovered":`${P.closed.join(" + ")} recovered`}: ${e.project}`,`cluster-service:${e.project}`,{kind:x?"service-recovered":"service-fault-closed",project:e.project,line:T,closed:P.closed,open:P.open})}!e.lockBlockedAt&&/Waiting for .+ in another nx process/.test(S)&&(e.lockBlockedAt=Date.now(),console.log(`[gateway] ${n}: spawn blocked by a stale nx runner \u2014 breaking the lock + respawning`),v(e,"warning",`nx task lock: ${e.project} blocked by a stale runner \u2014 auto-breaking`,`cluster-service:${e.project}`,{kind:"nx-lock-break",project:e.project}),setTimeout(()=>{t.stopped()||!e.lockBlockedAt||(U(e,"parked on a foreign nx task lock \u2014 recycling",{announce:!1}),z(e,n),setTimeout(()=>{!t.stopped()&&!e.proc&&e.state==="down"&&Y(e)},1500).unref?.())},250).unref?.())}},"sniff"),f=e.wsKey&&e.wsKey!==t.wsKey&&e.root?(0,workspace_log_1.workspaceLogWriter)(e.root):void 0,g=s(w=>{const $=(0,own_log_1.linePrefixer)(e.project);return h=>{if(t.stopped())return;const k=(0,inspector_secret_1.redactInspectorUrls)(h.toString());u(k);const T=$(k);w.write(T),f?.(T)}},"relay");return a.stdout?.on("data",g(process.stdout)),a.stderr?.on("data",g(process.stderr)),a.on("exit",(w,$)=>{if(e.proc!==a||(e.proc=void 0,e.state="down",t.stopped()))return;const h=(0,exit_reason_1.describeExit)(w,$);if(console.log(`[gateway] ${n} exited (${w??"no code"}${$?`, ${$}`:""}${e.inflight?`, ${e.inflight} request(s) in flight`:""})${h?` \u2014 ${h}`:""}`),v(e,w===0?"info":"warning",`service down: ${e.project} (exit ${w})`,`cluster-service:${e.project}`,{kind:"service-down",project:e.project,code:w,...$?{signal:$}:{}}),w===0||e.buildFailed)return;const k=Date.now();if(e.restarts=(e.restarts??[]).filter(G=>k-G<types_1.SERVICE_RESTART_WINDOW_MS),e.restarts.length>=types_1.SERVICE_MAX_RESTARTS){v(e,"error",`service crash-looping: ${e.project} \u2014 ${types_1.SERVICE_MAX_RESTARTS}+ restarts/min, not auto-respawning (the next request retries)`,`cluster-service:${e.project}`,{kind:"service-crash-loop",project:e.project});return}e.restarts.push(k);const T=Math.min(8e3,500*2**(e.restarts.length-1));setTimeout(()=>{t.stopped()||e.proc||e.state!=="down"||(console.log(`[gateway] self-heal: respawning ${e.project} (restart ${e.restarts.length}/${types_1.SERVICE_MAX_RESTARTS})`),v(e,"info",`self-heal: respawning ${e.project}`,`cluster-service:${e.project}`,{kind:"service-respawn",project:e.project,attempt:e.restarts.length}),Y(e))},T)}),a},"launchServiceProcess"),Y=s(e=>{if(t.stopped()||e.manualStopped)return;const r=`${e.project}:${e.decl.serveTarget??"serve-hmr"}`,o=Math.max(1,e.decl.minPods??1);l.reapForeign!==!1&&z(e,r),e.lockBlockedAt=void 0,console.log(`[gateway] starting ${r} (pods=${o})\u2026`),v(e,"info",`service starting: ${e.project} (${o} pod${o>1?"s":""})`,`cluster-service:${e.project}`,{kind:"service-starting",project:e.project,pods:o}),e.state="starting",e.spawnAt=Date.now(),e.generation=(e.generation??0)+1,e.proc=J(e,e.generation,"active")},"spawnService"),Le=s(async e=>{const r=e.pool.socks[0];if(!r)return;const o=await(0,pod_probe_1.probePodAlive)(r,void 0,t.serviceKeys[(0,service_keys_1.serviceKeyId)(e.wsKey,e.project)]);o&&(e.activeWork=o.activeWork,o.watcher&&(e.watcher=o.watcher))},"refreshActiveWork"),Ie=s(e=>{try{const r=Number(fs.readFileSync(`${e}.owner`,"utf8").trim());return Number.isInteger(r)&&r>1?r:void 0}catch{return}},"readOwnerSidecar"),Oe=s(async e=>{const r=t.serviceKeys[(0,service_keys_1.serviceKeyId)(e.wsKey,e.project)];if(!r)return[];const o=(0,node_crypto_1.createHash)("sha256").update(r).digest("hex").slice(0,8),n=[];for(const d of e.pool.socks){const a=await(0,pod_probe_1.probePodAlive)(d,void 0,r);a&&(!a.keyFingerprint||a.keyFingerprint!==o)&&n.push({sock:d,pid:a.pid})}return n},"staleAdoptedSocks"),Ne=s((e,r)=>{const o=r.map(n=>n.sock);for(const{sock:n,pid:d}of r){const a=chooseStalePodKillTarget(d,Ie(n),process.pid);if(a!==void 0)try{process.kill(a,"SIGTERM")}catch{}try{fs.unlinkSync(n)}catch{}try{fs.unlinkSync(`${n}.owner`)}catch{}}e.pool.socks=e.pool.socks.filter(n=>!o.includes(n)),e.pool.idx=-1,e.pool.scannedAt=0},"evictStaleAdopted"),pe=s((e,r)=>{if(e.state==="up")return!1;e.state="up",e.lastStartError=void 0,e.wedgeRecycles=0;const o=e.pool.socks.length;return v(e,"info",`service up: ${e.project} (${o} pods, ${r})`,`cluster-service:${e.project}`,{kind:"service-up",project:e.project,pods:o,adopted:r==="adopted"}),!0},"markUp"),ve=s(async e=>{if(e.manualStopped)return!1;if(O(e.pool)>0){const n=await Oe(e);if(e.manualStopped)return!1;if(n.length>0&&(console.error(`[gateway] ${e.project}: ${n.length} adopted pod(s) hold a foreign east-west key \u2014 evicting instead of adopting.`),v(e,"warning",`stale adoption: ${e.project} (foreign east-west key)`,`cluster-service:${e.project}`,{kind:"pod-recycle",project:e.project,reason:"stale-adoption",pods:n.length}),e.proc&&U(e,"stale adoption (foreign east-west key)"),Ne(e,n)),e.pool.socks.length>0)return pe(e,"adopted"),!0}if(t.stopped())return!1;let r=!1;const o=s(()=>e.state!=="starting"&&!e.proc,"notStarted");if(o())if(e.coldWait)await e.coldWait;else{R>=_&&(console.log(`[gateway] cold start queued: ${e.project}${e.wsKey&&e.wsKey!==t.wsKey?` (${e.wsKey})`:""} \u2014 ${R} starting, ${D.length} ahead (LENSMCP_MAX_COLD_STARTS=${_}).`),v(e,"info",`cold start queued: ${e.project}`,`cluster-service:${e.project}`,{kind:"cold-start-queued",project:e.project,inFlight:R,ahead:D.length}));const n=F();if(e.coldWait=n,await n,e.coldWait=void 0,r=!0,t.stopped()||e.manualStopped)return b(),!1;o()&&Y(e)}try{const n=await Ke(e);return n?e.lastStartError=void 0:!t.stopped()&&!e.manualStopped&&(e.lastStartError=startErrorText(fe(e),e.outputTail)),n}finally{r&&b()}},"ensureUp"),Ke=s(async e=>{const r=Date.now()+t.startupTimeoutMs,o=Date.now()+12e3;for(;!t.stopped()&&!e.manualStopped&&Date.now()<r;){if(await sleep(Math.min(700,t.startupTimeoutMs/4)),e.manualStopped||e.buildFailed&&Date.now()>o)return!1;if(O(e.pool)>0){e.state="up",e.buildFailed=!1;const n=e.spawnAt?Date.now()-e.spawnAt:void 0;return console.log(`[gateway] ${e.project} up (${e.pool.socks.length} pods${n?`, cold start ${n}ms`:""})`),v(e,"info",`cold start: ${e.project} (${e.pool.socks.length} pods, ${n??"?"}ms)`,`cluster-service:${e.project}`,{kind:"cold-start",project:e.project,pods:e.pool.socks.length,durationMs:n}),!0}if(e.state==="down")return!1}return!1},"waitForPods"),Fe=s(e=>{const r=e.decl.maxPods??e.decl.minPods??1,o=e.pool.socks.length,n=scaleTarget(e);!n||o===0||o>=r||e.inflight<=o||Date.now()-e.lastScaleAt<5e3||(e.lastScaleAt=Date.now(),postScale(n,o+1,l.scaleLookup),console.log(`[gateway] autoscale ${e.project}: ${o} \u2192 ${o+1} pods (inflight ${e.inflight})`),v(e,"info",`autoscale: ${e.project} ${o} \u2192 ${o+1} pods`,`cluster-service:${e.project}`,{kind:"autoscale",project:e.project,from:o,to:o+1,inflight:e.inflight}))},"scaleUp"),ue=l.killGraceMs??types_1.TREE_KILL_GRACE_MS,N=new Map,Ae=s(e=>{const r=N.get(e);if(!r||(N.delete(e),clearTimeout(r.timer),!L(e)))return;const{svc:o,why:n}=r;console.log(`[gateway] ${o.project}: its tree (pid ${e.pid}) was still running ${Math.round(ue/1e3)}s after it was told to stop (${n}) \u2014 killing it (SIGKILL).`),v(o,"warning",`tree force-killed: ${o.project} (it ignored SIGTERM)`,`cluster-service:${o.project}`,{kind:"tree-force-killed",project:o.project,why:n,pid:e.pid,graceMs:ue}),M(e,"SIGKILL")},"settleDyingTree"),Se=s((e,r,o)=>{if(A(r,"SIGTERM"),ue<=0||N.has(r))return;const n=setTimeout(()=>Ae(r),ue);n.unref?.(),N.set(r,{svc:e,why:o,timer:n})},"stopTree"),We=s(async(e=3e3)=>{const r=Date.now()+e;for(;N.size>0;){for(const[o,n]of[...N])L(o)||(clearTimeout(n.timer),N.delete(o));if(N.size===0||Date.now()>=r)break;await sleep(100)}for(const o of[...N.keys()])Ae(o)},"finishDyingTrees"),U=s((e,r,o)=>{if(!e.proc)return;console.log(`[gateway] ${e.project} ${r} \u2014 scaling to zero.`),o?.announce!==!1&&v(e,"info",`idle kill: ${e.project} (${r})`,`cluster-service:${e.project}`,{kind:"idle-kill",project:e.project,why:r});const n=e.proc;try{n.stdout?.removeAllListeners("data"),n.stderr?.removeAllListeners("data"),n.removeAllListeners("exit")}catch{}(0,discovery_1.stopRoutingTo)(e.pool),Se(e,n,r),e.proc=void 0,e.state="down",setTimeout(()=>{ge(e),e.pool.socks=[],e.pool.scannedAt=0},1200).unref?.()},"killSpawned"),ge=s(e=>{try{for(const r of fs.readdirSync(e.pool.dir)){if(!r.endsWith(".sock"))continue;const o=path.join(e.pool.dir,r);try{const n=Number(fs.readFileSync(`${o}.owner`,"utf8").trim());if(Number.isFinite(n)&&n>0)try{process.kill(n,0);continue}catch{}}catch{}try{fs.unlinkSync(o)}catch{}try{fs.unlinkSync(`${o}.owner`)}catch{}}}catch{}},"sweepDeadOwnerSocks");let Q=0;const ye=[],Ge=s(()=>Q<V?(Q+=1,Promise.resolve()):new Promise(e=>{ye.push(()=>{Q+=1,e()})}),"acquireRollSlot"),qe=s(()=>{Q-=1,ye.shift()?.()},"releaseRollSlot"),$e=s(async(e,r,o)=>{O(e.pool);for(const n of e.pool.socks){const d=await y(n,void 0,o);if(d&&r(d.podGeneration))return!0}return!1},"anyPodAnswers"),he=new Map,Ve=s((e,r,o)=>{const n=C>0&&(0,handoff_retire_1.requestHandoffRetire)(e.pool.dir,o);if(A(r,"SIGTERM"),!n)return;const d=e.wsKey&&e.wsKey!==t.wsKey&&e.root?(0,workspace_log_1.workspaceLogWriter)(e.root):void 0,a=s(se=>S=>{if(t.stopped())return;const P=(0,inspector_secret_1.redactInspectorUrls)(S.toString()).replace(/^(?=.)/gm,`[${e.project} g${o} retiring] `);se.write(P),d?.(P)},"say"),c=a(process.stdout),u=a(process.stderr);r.stdout?.on("data",c),r.stderr?.on("data",u);let f,g=!1;const w=s(()=>{g=!0,clearTimeout(f),r.stdout?.removeListener("data",c),r.stderr?.removeListener("data",u),r.removeListener("close",w)},"releaseLogs");r.once("close",w);let $=!1;const h=s(()=>{$||($=!0,clearTimeout(k),clearInterval(G),t.stopped()?w():g||(f=setTimeout(w,1e3),f.unref?.()),he.delete(r),(0,handoff_retire_1.clearHandoffRetire)(e.pool.dir,o),ge(e),e.pool.scannedAt=0)},"end"),k=setTimeout(()=>{console.error(`[gateway] pod handoff: ${e.project} g${o} was still running ${C}ms after it was retired \u2014 killing it.`),M(r,"SIGKILL"),h()},C);k.unref?.();const T=s(()=>{if(!$){if(t.stopped()){h();return}L(r)||(console.log(`[gateway] pod handoff: ${e.project} g${o} finished its in-flight work and exited.`),h())}},"look"),G=setInterval(T,ce);G.unref?.(),r.once("exit",T),he.set(r,()=>{h(),Se(e,r,"the gateway is stopping")})},"retireReplacedTree"),Ue=l.standbyGraceMs??3e4,I=new Map,Be=s((e,r,o,n,d)=>{const a=d+H+Ue,c=setTimeout(()=>Me(r),Math.max(0,a-Date.now()));c.unref?.(),I.set(r,{svc:e,generation:o,reason:n,beganAt:d,deadlineAt:a,timer:c})},"holdStandby"),He=s(e=>{const r=I.get(e);r&&(clearTimeout(r.timer),I.delete(e))},"releaseStandby"),Z=s((e,r)=>{const o=I.get(e);if(!o)return!1;clearTimeout(o.timer),I.delete(e);const{svc:n,generation:d}=o;try{e.stdout?.removeAllListeners("data"),e.stderr?.removeAllListeners("data")}catch{}return(0,discovery_1.stopRoutingTo)(n.pool,a=>(0,pod_sock_1.podSockGeneration)(a)===d),Se(n,e,`standby g${d}: ${r}`),setTimeout(()=>ge(n),1200).unref?.(),!0},"endStandby"),Ce=s((e,r)=>{const o=r.oldServing?`old generation g${r.fromGen} kept serving`:`and the old generation g${r.fromGen} is NOT serving (${r.oldGone?"its tree is gone":"none of its pods answers"}) \u2014 the service is down until it recovers`;console.error(`[gateway] pod handoff failed: ${e.project} g${r.generation}: ${r.why} \u2014 ${o}.`),e.rollFailure=`${r.why} \u2014 ${o}`,v(e,r.oldServing?"warning":"error",`pod handoff failed: ${e.project}`,`cluster-service:${e.project}`,{kind:"pod-handoff-failed",project:e.project,reason:r.reason,generation:r.generation,error:r.why,durationMs:Date.now()-r.beganAt,oldServing:r.oldServing})},"reportStandbyFailed"),Me=s(e=>{const r=I.get(e);if(!r)return;const{svc:o,generation:n,reason:d,beganAt:a}=r,c=`the standby outlived its roll (${Math.round((Date.now()-a)/1e3)}s; a roll waits ${Math.round(H/1e3)}s for it)`;Z(e,c);const u=o.proc,f=t.serviceKeys[(0,service_keys_1.serviceKeyId)(o.wsKey,o.project)];(async()=>{const g=!u||u.exitCode!==null||u.signalCode!==null,w=g?!1:await Promise.race([$e(o,h=>h!==n,f).catch(()=>!1),sleep(2e3).then(()=>{})]),$=!t.stopped()&&!g&&(w??O(o.pool)>0);Ce(o,{reason:d,generation:n,fromGen:o.generation??n-1,why:c,beganAt:a,oldServing:$,oldGone:g})})()},"outlivedRoll"),Xe=s(()=>{for(const[e,r]of[...I])Date.now()>=r.deadlineAt?Me(e):!r.svc.rolling&&r.svc.proc!==e&&(console.error(`[gateway] pod handoff: ${r.svc.project} g${r.generation} is a standby whose roll is over \u2014 stopping it.`),Z(e,"its roll is over"))},"sweepStandbys"),Ye=s(()=>{for(const e of[...he.values()])e();for(const e of[...I.keys()])Z(e,"the gateway is stopping")},"stopRetiringTrees"),me=s((e,r)=>{if(e.rolling)return e.rolling;const o=e.proc;if(!o||t.stopped())return Promise.resolve(!1);if(e.launcher==="nx")return console.log(`[gateway] pod handoff skipped: ${e.project} runs through nx run, which starts one instance of a target at a time \u2014 no standby can overlap it (reason=${r}).`),Promise.resolve(!1);Q>=V&&console.log(`[gateway] pod handoff queued: ${e.project} reason=${r} \u2014 ${Q} roll(s) in flight, ${ye.length} ahead (LENSMCP_POD_MAX_CONCURRENT_ROLLS=${V}).`);const n=(async()=>{await Ge();try{return await ze(e,o,r)}finally{qe()}})().finally(()=>{e.rolling=void 0});return e.rolling=n,n},"rollPod"),ze=s(async(e,r,o)=>{const n=e.proc;if(n!==r||t.stopped())return!1;const d=e.generation??0,a=d+1,c=Date.now();e.lastStaleRecycleAt=c,console.log(`[gateway] pod handoff start: ${e.project} g${d}\u2192g${a} reason=${o} \u2014 standby spawning, old generation keeps serving.`),v(e,"info",`pod handoff starting: ${e.project} (${o})`,`cluster-service:${e.project}`,{kind:"pod-handoff-start",project:e.project,reason:o,generation:a,fromGeneration:d});const u=J(e,a,"standby"),f=t.serviceKeys[(0,service_keys_1.serviceKeyId)(e.wsKey,e.project)];Be(e,u,a,o,c);let g=!1;try{const w=c+H;let $;for(;!t.stopped()&&Date.now()<w&&I.has(u)&&!(u.exitCode!==null||u.signalCode!==null);){O(e.pool);for(const h of e.pool.socks)if((await y(h,void 0,f))?.podGeneration===a){$=h;break}if($)break;await sleep(le)}if(!I.has(u))return!1;if(!$||t.stopped()){const h=t.stopped()?"gateway stopping":u.exitCode!==null||u.signalCode!==null?`standby exited (${u.exitCode??u.signalCode})`:`standby not ready within ${Math.round(H/1e3)}s`;Z(u,h);const k=!t.stopped()&&e.proc===n&&n.exitCode===null&&n.signalCode===null&&await $e(e,T=>T!==a,f);return Ce(e,{reason:o,generation:a,fromGen:d,why:h,beganAt:c,oldServing:k,oldGone:e.proc!==n||n.exitCode!==null||n.signalCode!==null}),!1}if(e.proc!==n)return Z(u,"the service was replaced underneath the roll"),!1;He(u),g=!0,e.proc=u,e.launcher=oe.get(u),e.generation=a,e.spawnAt=c,e.state="up",e.watcher=void 0,e.staleVerifiedAt=void 0,e.staleKeptAt=void 0,e.buildFailed=!1,e.lastErrors=[];try{n.stdout?.removeAllListeners("data"),n.stderr?.removeAllListeners("data"),n.removeAllListeners("exit")}catch{}return(0,discovery_1.stopRoutingTo)(e.pool,h=>(0,pod_sock_1.podSockGeneration)(h)!==a&&path.join(e.pool.dir,h)!==$),Ve(e,n,d),setTimeout(()=>{ge(e),e.pool.scannedAt=0},1200).unref?.(),console.log(`[gateway] pod handoff ready: ${e.project} g${a} answered on ${path.basename($)} in ${Date.now()-c}ms; retiring g${d}.`),v(e,"info",`pod handoff complete: ${e.project}`,`cluster-service:${e.project}`,{kind:"pod-handoff-complete",project:e.project,reason:o,generation:a,fromGeneration:d,durationMs:Date.now()-c}),!0}finally{g||Z(u,"its roll ended without it")}},"runRoll"),Je=s((e,r)=>{if(t.stopped())return{refused:"the gateway is stopping"};const o=e.restart&&!e.restart.done?e.restart:void 0,n=o?void 0:Qe(e);if(n&&"refused"in n)return console.error(`[gateway] restart refused: ${e.project}${e.wsKey!==t.wsKey?` (${e.wsKey})`:""} \u2014 ${n.refused}`),v(e,"warning",`restart refused: ${e.project}`,`cluster-service:${e.project}`,{kind:"service-restart",phase:"refused",project:e.project,reason:r.reason,error:n.refused}),{refused:n.refused};const d=n&&"applied"in n?n:void 0;if(e.manualStopped=!1,e.actionFailure=void 0,o)return{restart:o,already:!0};if(!e.proc&&e.state!=="down")return{refused:`${e.project} is served by pods this gateway adopted from an earlier one \u2014 it has no tree of its own to replace. \`lensmcp gateway restart\` starts every service under this gateway.`};const a=e.proc?r.hard||e.launcher==="nx"||e.state!=="up"?"hard":"rolling":"start",c={how:a,reason:r.reason,startedAt:Date.now(),...e.proc&&e.generation!==void 0?{fromGeneration:e.generation}:{},...d?{env:d.applied}:{}};d&&(e.instanceEnv=d.env),e.restart=c,e.lastUsed=c.startedAt;const u=c.env?{envFingerprint:c.env.fingerprint,envChanged:c.env.changed}:{},f=c.env?` Instance variables ${c.env.fingerprint}: ${c.env.changed.length?`changed ${c.env.changed.join(", ")}`:"unchanged"}.`:"";return console.log(`[gateway] restart asked: ${e.project}${e.wsKey!==t.wsKey?` (${e.wsKey})`:""} \u2014 ${a} (${r.reason}).${f}`),v(e,"info",`restart asked: ${e.project} (${a})`,`cluster-service:${e.project}`,{kind:"service-restart",phase:"started",project:e.project,how:a,reason:r.reason,...c.fromGeneration!==void 0?{fromGeneration:c.fromGeneration}:{},...u}),s(async()=>{if(a==="start")return await ve(e)?{ok:!0}:{ok:!1,error:fe(e)};if(a==="rolling")return e.rolling&&await e.rolling,e.proc?(e.rollFailure=void 0,await me(e,r.reason)?{ok:!0}:{ok:!1,error:e.rollFailure??"the new tree did not take over"}):await ve(e)?{ok:!0}:{ok:!1,error:fe(e)};if(U(e,`restart asked (${r.reason})`,{announce:!1}),await sleep(1500),t.stopped())return{ok:!1,error:"the gateway is stopping"};let g=!1;e.proc||(await F(),g=!0,!e.proc&&e.state!=="starting"&&Y(e));try{const w=e.proc,$=e.generation,h=t.serviceKeys[(0,service_keys_1.serviceKeyId)(e.wsKey,e.project)],k=Date.now()+t.startupTimeoutMs;for(;!t.stopped()&&Date.now()<k;){if(!w||e.proc!==w||w.exitCode!==null||w.signalCode!==null)return{ok:!1,error:fe(e)};if(await $e(e,T=>T===$,h))return pe(e,"observed"),e.buildFailed=!1,{ok:!0};await sleep(le)}return{ok:!1,error:t.stopped()?"the gateway is stopping":`no pod of the new tree answered within ${Math.round(t.startupTimeoutMs/1e3)}s`}}finally{g&&b()}},"run")().catch(g=>({ok:!1,error:g.message})).then(g=>{c.done={ok:g.ok,at:Date.now(),...e.generation!==void 0?{generation:e.generation}:{},...g.error?{error:g.error}:{}},g.ok&&(e.lastUsed=c.done.at);const w=Math.round((c.done.at-c.startedAt)/100)/10;g.ok?console.log(`[gateway] restarted: ${e.project} \u2014 g${c.done.generation??"?"} serving after ${w}s (${a}).`):console.error(`[gateway] restart failed: ${e.project} \u2014 ${g.error} (${a}, after ${w}s).`),v(e,g.ok?"info":"error",g.ok?`restarted: ${e.project}`:`restart failed: ${e.project}`,`cluster-service:${e.project}`,{kind:"service-restart",phase:g.ok?"done":"failed",project:e.project,how:a,reason:r.reason,...c.fromGeneration!==void 0?{fromGeneration:c.fromGeneration}:{},...c.done.generation!==void 0?{generation:c.done.generation}:{},durationMs:c.done.at-c.startedAt,...g.error?{error:g.error}:{},...u})}),{restart:c,already:!1}},"restartService"),Qe=s(e=>{if(!e.instanceBuiltins)return;const r=(0,instance_1.readInstanceEnvStrict)(e.root,e.instanceBuiltins);if("reason"in r)return{refused:`the instance variables of ${e.project} could not be read again \u2014 ${r.reason}. Nothing was restarted: the running tree keeps what it has. Fix the file, then restart it again.`};const o=e.instanceEnv??{};return{env:r.env,applied:{fingerprint:(0,instance_1.instanceEnvFingerprint)(r.env),fromFingerprint:(0,instance_1.instanceEnvFingerprint)(o),changed:(0,instance_1.changedInstanceEnvNames)(o,r.env)}}},"restartEnv"),fe=s(e=>e.buildFailed?`its build failed${e.lastErrors?.length?`: ${e.lastErrors[e.lastErrors.length-1]}`:""}`:e.proc&&(e.proc.exitCode!==null||e.proc.signalCode!==null)?`its tree exited (${e.proc.exitCode??e.proc.signalCode})`:!e.proc&&e.state==="down"?"its tree exited before a pod answered":`no pod answered within ${Math.round(t.startupTimeoutMs/1e3)}s`,"startFailure"),xe=s(e=>{const r=Date.now();e.restarts=(e.restarts??[]).filter(n=>r-n<types_1.SERVICE_RESTART_WINDOW_MS);const o=(e.wedgeRecycles??0)+1;if(e.restarts.length>=types_1.SERVICE_MAX_RESTARTS||o>types_1.SERVICE_MAX_RESTARTS){const n=e.restarts.length>=types_1.SERVICE_MAX_RESTARTS?`wedged ${types_1.SERVICE_MAX_RESTARTS}+\xD7/min`:`recycled ${types_1.SERVICE_MAX_RESTARTS}\xD7 in a row and no pod came up`;v(e,"error",`service crash-looping: ${e.project} \u2014 ${n}, not auto-recycling (the next request retries)`,`cluster-service:${e.project}`,{kind:"service-crash-loop",project:e.project,recycles:o-1}),U(e,"wedged (crash-loop cap) \u2014 leaving down for the next request",{announce:!1});return}e.wedgeRecycles=o,e.restarts.push(r),console.log(`[gateway] self-heal: recycling WEDGED ${e.project} (live parent, 0 live pods; attempt ${o}/${types_1.SERVICE_MAX_RESTARTS} with no pod up since the first, ${e.restarts.length} in the last minute; ${e.inflight??0} request(s) in flight \u2014 jobs held by the dead pod keep their locks until they expire)`),v(e,"warning",`self-heal: recycling wedged ${e.project} (0 live pods)`,`cluster-service:${e.project}`,{kind:"service-recycle",project:e.project,attempt:o,inWindow:e.restarts.length}),U(e,"wedged: 0 live pods \u2014 recycling",{announce:!1}),setTimeout(()=>{!t.stopped()&&!e.proc&&e.state==="down"&&Y(e)},1500).unref?.()},"recycleWedged"),Ze={maxAgeMs:types_1.POD_MAX_AGE_MS,graceMs:types_1.POD_STALE_GRACE_MS,settleMs:types_1.POD_RECYCLE_SETTLE_MS,cooldownMs:types_1.POD_STALE_RECYCLE_COOLDOWN_MS};let Ee;const ne=new Map,_e=new Map;let ke=!1,je=0,we=0;const et=s(()=>{const e=t.projectRoots??{},r=new Set(t.services.map(n=>n.project));for(const n of t.routes)n.lens&&r.add(n.lens.project);const o=new Set;for(const n of r){const d=e[n];if(!d)continue;const a=path.relative(t.root,d).split(path.sep).filter(Boolean)[0];a&&!a.startsWith("..")&&o.add(a)}return[...o]},"managedBuckets"),tt=s((e,r,o,n)=>{const d=t.projectSourceRoots?.[e];if(d?.length)return d;const a=t.projectRoots?.[e];if(!a)return;const c=sourceScopeDirs(t.root,a,o,r,n);return c.length>0?c:void 0},"scopeFor"),rt=s(()=>{if(ke||Date.now()-je<types_1.POD_STALE_SCAN_MS)return;ke=!0,je=Date.now();const e=je;(async()=>{const r=(0,scope_1.readSourceSetOptions)(t.root),o=r.exclude,n={ignoreTests:r.ignoreTests},d=sourceScanPass(t.root,o,n),a=await d.snapshot(),c=Date.now(),u=sourceChangeWindowMs(c,we,types_1.POD_STALE_SCAN_MS,types_1.POD_RECYCLE_SETTLE_MS),f=Ee?diffSourceSets(Ee,a,c,u):null;if(f&&(t.sourceSetChangedAt=c,t.sourceSetChange=f,X("info","source file set changed \u2014 stale pods recycle when idle","cluster-gateway",{kind:"source-set-changed",added:f.added,removed:f.removed,truncated:f.truncated})),Ee=a,!t.projectRoots){we=e;return}let g;try{g=(await fs.promises.readdir(t.root,{withFileTypes:!0})).filter(S=>S.isDirectory()).map(S=>S.name)}catch{return}const w=et(),$=new Set(t.services.map(S=>S.project));for(const S of t.routes)S.lens&&$.add(S.lens.project);const h=new Map;for(const S of $){const P=tt(S,g,w,o);if(!P)continue;const x=P.join("|"),q=h.get(x)??{dirs:P,projects:[]};q.projects.push(S),h.set(x,q)}const k=Date.now(),T=sourceChangeWindowMs(k,we,types_1.POD_STALE_SCAN_MS,types_1.POD_RECYCLE_SETTLE_MS);we=e;const G=s((S,P,x)=>{t.sourceSetChangedFor??=new Map,t.sourceSetChangesFor??=new Map;for(const q of S)t.sourceSetChangedFor.set(q,P),t.sourceSetChangesFor.set(q,x)},"stampScoped"),se=new Set([...h.values()].flatMap(S=>S.projects));for(const S of[...t.sourceSetScoped??[]])se.has(S)||t.sourceSetScoped.delete(S);for(const[S,{dirs:P,projects:x}]of h){const q=await d.snapshot(P),Re=ne.get(S);if(Re||x.some(K=>_e.has(K))){t.sourceSetScoped??=new Set;for(const K of x)t.sourceSetScoped.add(K)}ne.set(S,q);const Te=new Map;for(const K of x){const B=_e.get(K);if(B===void 0||B===S)continue;const ee=Te.get(B)??[];ee.push(K),Te.set(B,ee)}for(const K of x)_e.set(K,S);for(const[K,B]of Te){const ee=ne.get(K),ie=ee?diffSourceSets(ee,q,k,T):f;ie&&(G(B,ee?k:c,ie),X("info",`source file set changed \u2014 ${B.join(", ")}'s watch scope was re-keyed`,"cluster-gateway",{kind:"source-set-changed",scoped:!0,rescoped:!0,projects:B,added:ie.added,removed:ie.removed,truncated:ie.truncated}))}if(!Re)continue;const ae=diffSourceSets(Re,q,k,T);ae&&(G(x,k,ae),X("info",`source file set changed in ${x.join(", ")}'s scope`,"cluster-gateway",{kind:"source-set-changed",scoped:!0,projects:x,added:ae.added,removed:ae.removed,truncated:ae.truncated}))}for(const S of[...ne.keys()])h.has(S)||ne.delete(S)})().catch(()=>{}).finally(()=>{ke=!1})},"maybeScanSourceSet"),ot=s((e,r)=>{const o=podChangeClock(t,e.project),n=o.change,d=`${o.scope==="project"?"in its scope":"in the workspace (its scope is not known)"}: ${changeEvidence(n)}`,a=n?.windowMs??types_1.POD_STALE_SCAN_MS+types_1.POD_RECYCLE_SETTLE_MS,c=podWatcherVerdict(e.watcher,r,a),u=s(g=>(e.staleKeptAt!==r&&(e.staleKeptAt=r,console.log(`[gateway] stale source set: pod ${e.project} ${g} \u2014 no recycle.`)),!1),"keep");if(c==="heard")return e.staleVerifiedAt=r,v(e,"info",`stale check: ${e.project} watcher confirmed \u2014 no recycle`,`cluster-service:${e.project}`,{kind:"pod-stale-verified",project:e.project,watcher:c}),u(`watcher CONFIRMED alive across the change (last build ${new Date(e.watcher?.lastBuildAt??0).toISOString()})`);if(c==="degraded")return console.log(`[gateway] stale source set: pod ${e.project} watcher DEGRADED (${e.watcher?.degraded}) \u2014 recycling.`),!0;const f=s(g=>(e.staleKeptAt!==r&&(e.staleKeptAt=r,console.log(`[gateway] stale source set: pod ${e.project} ${g}; the change ${d} \u2014 recycling.`)),!0),"recycling");return c==="silent"?types_1.POD_WATCHER_SILENT==="keep"?u("watcher alive but quiet across the change \u2014 keeping it (LENSMCP_POD_WATCHER_SILENT=keep; a live watcher cannot miss an add it will need)"):f("watcher alive but quiet across the change"):types_1.POD_WATCHER_UNVERIFIED==="keep"?u("unverifiable (no watcher testimony \u2014 older devserver bundle?) \u2014 keeping it (LENSMCP_POD_WATCHER_UNVERIFIED=keep)"):f("watcher unverifiable (no testimony yet \u2014 a pod that never rebuilt, or an older devserver bundle)")},"podStaleRecycleAllowed"),Pe=s(e=>types_1.POD_RECYCLE_MODE==="rolling"&&!!e.proc&&e.launcher!=="nx","recycleRolls"),nt=s((e,r)=>{if(e.lastStaleRecycleAt=Date.now(),Pe(e)){me(e,r);return}console.log(`[gateway] zombie recycle: ${e.project} (${r}) \u2014 stale fs view; fresh pod incoming`);const o=!!e.decl.eager;v(e,"warning",`zombie recycle: ${e.project} (${r})`,`cluster-service:${e.project}`,{kind:"pod-recycle",project:e.project,reason:r,respawn:o}),U(e,`${r} \u2014 recycling stale pod`,{announce:!1}),o&&setTimeout(()=>{!t.stopped()&&!e.proc&&e.state==="down"&&Y(e)},1500).unref?.()},"recyclePod"),st=s(e=>{const r=setInterval(()=>{if(e&&!t.stopped())try{e()}catch(o){console.error("[gateway] park sweep error:",o)}ct().catch(o=>console.error("[gateway] sweep error:",o))},t.sweepMs);return r.unref(),r},"startSweeper"),at=l.listProcesses??(()=>{try{return(0,orphan_reaper_1.parsePsRows)((0,node_child_process_1.execFileSync)("ps",orphan_reaper_1.PS_ROW_ARGS,{encoding:"utf8",timeout:5e3}))}catch{return[]}}),be=l.signalProcess??((e,r)=>{process.kill(e,r)});let De=0;const it=s(()=>{if(typeof process.getuid!="function")return 0;const e=t.registry?t.registry.allServices():t.services;if(e.length===0)return 0;const r=e.map(a=>({label:a.wsKey||path.basename(a.root),project:a.project,root:a.root,svc:a})),o=new Set;for(const a of e)a.proc?.pid&&o.add(a.proc.pid);for(const a of[...he.keys(),...N.keys(),...I.keys()])a.pid&&o.add(a.pid);const n=[...new Set((0,process_name_1.defaultLinkDirs)().flatMap(a=>{try{return[a,fs.realpathSync(a)]}catch{return[a]}}))];let d=0;for(const a of(0,orphan_reaper_1.findOrphanExecutors)(at(),r,{linkDirs:n,uid:process.getuid(),selfPid:process.pid,ownGroups:o})){const{row:c}=a;try{be(a.group?-c.pgid:c.pid,"SIGKILL")}catch(f){if(f.code!=="ESRCH"||!a.group)continue;try{be(c.pid,"SIGKILL")}catch{continue}}d+=1;const u=a.owner.svc;console.log(`[gateway] reaped an orphaned executor of ${u.project} (${a.role}, pid ${c.pid}${a.group?`, group ${c.pgid}`:""}, parent gone) \u2014 a stopped tree it outlived: ${c.command.slice(0,160)}`),v(u,"warning",`orphan reap: ${u.project} (pid ${c.pid})`,`cluster-service:${u.project}`,{kind:"orphan-executor-reap",project:u.project,pid:c.pid,pgid:c.pgid,role:a.role,group:a.group})}return d},"reapOrphanExecutors"),ct=s(async()=>{{if(t.stopped())return;Xe(),l.reapForeign!==!1&&types_1.ORPHAN_REAP_EVERY_MS>0&&Date.now()-De>=types_1.ORPHAN_REAP_EVERY_MS&&(De=Date.now(),it());for(const r of t.graphStores?.all()??[])r.refreshIfStale();types_1.POD_RECYCLE_ENABLED&&rt();let e=0;for(const r of t.registry?t.registry.allServices():t.services){if(t.stopped()||!r.proc){r.wedgedSince=void 0;continue}const o=path.resolve(r.root)===path.resolve(t.root),n=(0,warm_start_1.serviceIdleSec)(t,r),d=(0,awake_1.idleStopAt)(r,n);if(d!==void 0&&r.state==="up"&&(!r.restart||r.restart.done)&&r.inflight===0&&Date.now()>d){r.lastIdleStop={at:Date.now(),why:`no request for ${n}s${(r.awakeUntil??0)>r.lastUsed?" after its hold ended":""}`},U(r,`idle ${n}s`),r.wedgedSince=void 0;continue}const a=r.state==="starting"&&r.spawnAt!==void 0&&Date.now()-r.spawnAt<t.startupTimeoutMs,c=O(r.pool)>0;if(c||a){if(r.wedgedSince=void 0,c&&pe(r,"observed"),c&&!a&&types_1.POD_RECYCLE_ENABLED&&o){const u=podChangeClock(t,r.project).at;await Le(r);const f=(r.staleVerifiedAt??0)>=u&&u>0,g=podRecycleReason(r,Date.now(),f?0:u,Ze);if(g==="stale-source-set"&&!ot(r,u)||!g)continue;if(!Pe(r)){if(e>=V){console.log(`[gateway] zombie recycle deferred: ${r.project} (${g}) \u2014 ${e} pod(s) already recycled kill-first this sweep (LENSMCP_POD_MAX_CONCURRENT_ROLLS=${V}); it goes on a later sweep.`);continue}e+=1}nt(r,g)}continue}r.wedgedSince??=Date.now(),Date.now()-r.wedgedSince>types_1.WEDGE_RECYCLE_GRACE_MS&&(r.wedgedSince=void 0,xe(r))}}},"sweepOnce");return{scanNow:O,spawnService:Y,ensureUp:ve,scaleUp:Fe,killSpawned:U,markUp:pe,emitSvc:v,startSweeper:st,rollPod:me,restartService:Je,recycleWedged:xe,stopRetiringTrees:Ye,finishDyingTrees:We,stopBuildHost:s(e=>e===void 0?j.stop():j.release(e),"stopBuildHost")}}m(createServiceLayer,"createServiceLayer"),s(createServiceLayer,"createServiceLayer");function chooseStalePodKillTarget(t,i,l){if(!(t===void 0||!Number.isInteger(t)||t<=1)&&!(i!==void 0&&i!==t)&&t!==l)return t}m(chooseStalePodKillTarget,"chooseStalePodKillTarget"),s(chooseStalePodKillTarget,"chooseStalePodKillTarget");
|
|
@@ -68,28 +68,44 @@ export declare function touchRun(registry: Pick<RouteRegistry, 'get'> | undefine
|
|
|
68
68
|
export declare function touchStart(registry: Pick<RouteRegistry, 'get'> | undefined, svc: Pick<ServiceCtl, 'wsKey'>): void;
|
|
69
69
|
/** `~/.lensmcp/instances.json` — the CLI's registry of worktree instances (libs/cli instance-registry.ts). */
|
|
70
70
|
export declare function instancesFile(env?: NodeJS.ProcessEnv): string;
|
|
71
|
-
/** An on-demand worktree on the CLI's record: what a parked host names. */
|
|
71
|
+
/** An on-demand worktree on the CLI's record: what a parked host names, and where its checkout is. */
|
|
72
72
|
export interface ParkedWorktree {
|
|
73
73
|
key: string;
|
|
74
74
|
name: string;
|
|
75
75
|
baseKey: string;
|
|
76
76
|
/** The base apex its own config pins (`instance.apex`), when it does. */
|
|
77
77
|
apex?: string;
|
|
78
|
+
/** Its checkout, as the record has it: where its parked dashboard runs (parked-dashboards.ts). */
|
|
79
|
+
root?: string;
|
|
80
|
+
/** The record also says it is a checkout only (`checkoutOnly: true`): no lens of its own, so no dashboard either. */
|
|
81
|
+
checkoutOnly?: true;
|
|
78
82
|
}
|
|
79
83
|
/** The on-demand records of an `instances.json` text (`services: 'on-demand'`); anything unreadable is none. */
|
|
80
84
|
export declare function onDemandRecords(text: string, readConfig?: (root: string) => string | undefined): ParkedWorktree[];
|
|
81
|
-
export interface
|
|
82
|
-
/** The parked on-demand worktree `host` names — on record, of a workspace this daemon serves, not registered. */
|
|
83
|
-
match(host: string): ParkedWorktree | undefined;
|
|
84
|
-
}
|
|
85
|
-
export interface ParkedHostLookupDeps {
|
|
86
|
-
registry: () => Pick<RouteRegistry, 'get' | 'has'> | undefined;
|
|
85
|
+
export interface OnDemandRecordsReaderDeps {
|
|
87
86
|
/** `instances.json`'s path — resolved at each refresh ({@link instancesFile}). */
|
|
88
87
|
file?: () => string;
|
|
89
88
|
/** At most this often is the file looked at (a stat; it is read again only when it changed). Default 2 s. */
|
|
90
89
|
ttlMs?: number;
|
|
91
90
|
now?: () => number;
|
|
92
91
|
}
|
|
92
|
+
/**
|
|
93
|
+
* The on-demand records on file now, CHEAP: `instances.json` is looked at at most once per
|
|
94
|
+
* {@link OnDemandRecordsReaderDeps.ttlMs} — a stat, and a parse only when the file changed. What the parked-host check
|
|
95
|
+
* and the parked worktrees' dashboards (parked-dashboards.ts) both read.
|
|
96
|
+
*/
|
|
97
|
+
export declare function createOnDemandRecordsReader(deps?: OnDemandRecordsReaderDeps): () => ParkedWorktree[];
|
|
98
|
+
export interface ParkedHostLookup {
|
|
99
|
+
/** The parked on-demand worktree `host` names — on record, of a workspace this daemon serves, not registered. */
|
|
100
|
+
match(host: string): ParkedWorktree | undefined;
|
|
101
|
+
}
|
|
102
|
+
export interface ParkedHostLookupDeps extends OnDemandRecordsReaderDeps {
|
|
103
|
+
registry: () => Pick<RouteRegistry, 'get' | 'has'> | undefined;
|
|
104
|
+
/** The records to match against — one reader shared with the parked dashboards; else a reader of its own. */
|
|
105
|
+
records?: () => readonly ParkedWorktree[];
|
|
106
|
+
}
|
|
107
|
+
/** The apex the parked worktree `r` is named under: its own config's pin, else its base's ({@link baseApexOf}). */
|
|
108
|
+
export declare function parkedApexOf(r: Pick<ParkedWorktree, 'apex'>, base: WorkspaceFragment, cache?: WeakMap<WorkspaceFragment, string | null>): string | undefined;
|
|
93
109
|
/**
|
|
94
110
|
* The parked-host check, CHEAP: the handler asks it only for a host no exact route claims (one that would fall to a
|
|
95
111
|
* catch-all or a wildcard), and it reads `instances.json` at most once per {@link ParkedHostLookupDeps.ttlMs} — a stat,
|
|
@@ -100,9 +116,10 @@ export declare function createParkedHostLookup(deps: ParkedHostLookupDeps): Park
|
|
|
100
116
|
export declare function runHint(name: string): string;
|
|
101
117
|
/**
|
|
102
118
|
* The answer to a request for a parked worktree's host (OD-D4): a page for a browser (`Accept: text/html`), else JSON
|
|
103
|
-
* `{ error, code: 'worktree-parked', name, run }`. Always 503: nothing starts on its own.
|
|
119
|
+
* `{ error, code: 'worktree-parked', name, run }`. Always 503: nothing starts on its own. `dashboard`: the URL its
|
|
120
|
+
* parked dashboard answers at (parked-dashboards.ts) — the page links it.
|
|
104
121
|
*/
|
|
105
|
-
export declare function parkedAnswer(w: Pick<ParkedWorktree, 'name' | 'key'>, accept: string | undefined): {
|
|
122
|
+
export declare function parkedAnswer(w: Pick<ParkedWorktree, 'name' | 'key'>, accept: string | undefined, dashboard?: string): {
|
|
106
123
|
status: 503;
|
|
107
124
|
headers: Record<string, string>;
|
|
108
125
|
body: string;
|
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var m=Object.defineProperty;var i=(t,e)=>m(t,"name",{value:e,configurable:!0});var f=Object.defineProperty,a=i((t,e)=>f(t,"name",{value:e,configurable:!0}),"a");Object.defineProperty(exports,"__esModule",{value:!0}),exports.DEFAULT_WORKTREE_RUN_MAX=exports.WORKTREE_RUN_MAX_ENV=exports.MIN_WORKTREE_RUN_IDLE_SEC=exports.DEFAULT_WORKTREE_RUN_IDLE_SEC=exports.WORKTREE_RUN_IDLE_ENV=void 0,exports.worktreeRunIdleSec=worktreeRunIdleSec,exports.worktreeRunMax=worktreeRunMax,exports.isOnDemand=isOnDemand,exports.holdEnd=holdEnd,exports.parkAt=parkAt,exports.runSummary=runSummary,exports.runUnderWay=runUnderWay,exports.parkVerdict=parkVerdict,exports.runCapRefusal=runCapRefusal,exports.runOf=runOf,exports.touchRun=touchRun,exports.touchStart=touchStart,exports.instancesFile=instancesFile,exports.onDemandRecords=onDemandRecords,exports.createOnDemandRecordsReader=createOnDemandRecordsReader,exports.parkedApexOf=parkedApexOf,exports.createParkedHostLookup=createParkedHostLookup,exports.runHint=runHint,exports.parkedAnswer=parkedAnswer;const tslib_1=require("tslib"),fs=tslib_1.__importStar(require("node:fs")),os=tslib_1.__importStar(require("node:os")),path=tslib_1.__importStar(require("node:path")),instance_1=require("./instance"),observability_1=require("./observability");exports.WORKTREE_RUN_IDLE_ENV="LENSMCP_WORKTREE_RUN_IDLE_SEC",exports.DEFAULT_WORKTREE_RUN_IDLE_SEC=900,exports.MIN_WORKTREE_RUN_IDLE_SEC=60,exports.WORKTREE_RUN_MAX_ENV="LENSMCP_WORKTREE_RUN_MAX",exports.DEFAULT_WORKTREE_RUN_MAX=2;function worktreeRunIdleSec(t=process.env){const e=Number(t[exports.WORKTREE_RUN_IDLE_ENV]?.trim()||NaN);return Number.isFinite(e)&&e>=exports.MIN_WORKTREE_RUN_IDLE_SEC?e:exports.DEFAULT_WORKTREE_RUN_IDLE_SEC}i(worktreeRunIdleSec,"worktreeRunIdleSec"),a(worktreeRunIdleSec,"worktreeRunIdleSec");function worktreeRunMax(t=process.env){const e=Number(t[exports.WORKTREE_RUN_MAX_ENV]?.trim()||NaN);if(!Number.isFinite(e)||e<0)return exports.DEFAULT_WORKTREE_RUN_MAX;const r=Math.floor(e);return r===0?void 0:r}i(worktreeRunMax,"worktreeRunMax"),a(worktreeRunMax,"worktreeRunMax");function isOnDemand(t){return!!t?.instance?.onDemand}i(isOnDemand,"isOnDemand"),a(isOnDemand,"isOnDemand");function holdEnd(t){let e=0;for(const r of t.services)e=Math.max(e,r.awakeUntil??0);return e}i(holdEnd,"holdEnd"),a(holdEnd,"holdEnd");function parkAt(t,e=process.env){if(isOnDemand(t))return Math.max((t.lastUseAt??0)+worktreeRunIdleSec(e)*1e3,holdEnd(t))}i(parkAt,"parkAt"),a(parkAt,"parkAt");function runSummary(t,e=process.env){return!t||!isOnDemand(t)?{}:{onDemand:!0,parkAt:parkAt(t,e),...t.lastUseAt!==void 0?{lastUseAt:t.lastUseAt}:{}}}i(runSummary,"runSummary"),a(runSummary,"runSummary");function runUnderWay(t){for(const e of t.services){if(e.inflight>0)return`${e.project} has ${e.inflight} request(s) in flight`;if(e.state==="starting"||e.actionStarting)return`${e.project} is starting`;if(e.rolling||e.restart&&!e.restart.done)return`${e.project} is restarting`;if(e.wake&&(e.wake.outcome==="queued"||e.wake.outcome==="starting"))return`${e.project} is waiting its turn to start`}}i(runUnderWay,"runUnderWay"),a(runUnderWay,"runUnderWay");function parkVerdict(t,e,r=process.env){const n=parkAt(t,r);if(n===void 0||e<n)return{ok:!1,...n!==void 0?{parkAt:n}:{}};const c=runUnderWay(t);return c?{ok:!1,parkAt:n,busy:c}:{ok:!0,parkAt:n}}i(parkVerdict,"parkVerdict"),a(parkVerdict,"parkVerdict");function runCapRefusal(t,e,r=process.env){if(!isOnDemand(e))return;const n=worktreeRunMax(r);if(n===void 0)return;const c=t.keys().filter(s=>s!==e.wsKey).map(s=>t.get(s)).filter(s=>!!s&&isOnDemand(s));if(c.length<n)return;const u=c.map(s=>({wsKey:s.wsKey,name:s.instance?.name??s.wsKey,parkAt:parkAt(s,r)})),o=u.map(s=>`${s.name}${s.parkAt?` (parks ${new Date(s.parkAt).toISOString()} unless used)`:""}`).join(", ");return{error:`${c.length} on-demand worktree(s) already run on this machine, the most ${exports.WORKTREE_RUN_MAX_ENV} allows (${n}): ${o}. Park one (worktree_park, \`lensmcp instance park <name>\`) or run again once one has parked.`,code:"run-cap",max:n,running:u}}i(runCapRefusal,"runCapRefusal"),a(runCapRefusal,"runCapRefusal");function runOf(t,e){if(!t||!e||e.internal||e.project===observability_1.LENS_DASHBOARD_PROJECT)return;const r=e.wsKey?t.get(e.wsKey):void 0;return r&&isOnDemand(r)?r:void 0}i(runOf,"runOf"),a(runOf,"runOf");function touchRun(t,e,r){const n=runOf(t,e);n&&(n.lastUseAt=Date.now(),r?.once("close",()=>{n.lastUseAt=Date.now()}))}i(touchRun,"touchRun"),a(touchRun,"touchRun");function touchStart(t,e){const r=t?.get(e.wsKey);r&&isOnDemand(r)&&(r.lastUseAt=Date.now())}i(touchStart,"touchStart"),a(touchStart,"touchStart");function instancesFile(t=process.env){return path.join(t.LENSMCP_HOME||os.homedir(),".lensmcp","instances.json")}i(instancesFile,"instancesFile"),a(instancesFile,"instancesFile");function onDemandRecords(t,e){let r;try{r=JSON.parse(t)}catch{return[]}const n=r?.instances;if(!n||typeof n!="object")return[];const c=[];for(const u of Object.values(n)){const o=u;if(!o||o.services!=="on-demand"||typeof o.key!="string"||typeof o.name!="string"||typeof o.baseKey!="string"||!o.name)continue;let s;if(e&&typeof o.root=="string")try{const p=JSON.parse(e(o.root)??"null");typeof p?.instance?.apex=="string"&&p.instance.apex&&(s=p.instance.apex.toLowerCase())}catch{}c.push({key:o.key,name:o.name.toLowerCase(),baseKey:o.baseKey,...s?{apex:s}:{},...typeof o.root=="string"&&o.root?{root:o.root}:{},...o.checkoutOnly===!0?{checkoutOnly:!0}:{}})}return c}i(onDemandRecords,"onDemandRecords"),a(onDemandRecords,"onDemandRecords");function createOnDemandRecordsReader(t={}){const e=t.ttlMs??2e3,r=t.now??Date.now,n=t.file??(()=>instancesFile());let c=-1/0,u="",o=[];return()=>{const s=r();if(s-c<e)return o;c=s;const p=n();let l="";try{const d=fs.statSync(p);l=`${p}:${d.mtimeMs}:${d.size}`}catch{return u="",o=[],o}if(l===u)return o;u=l;try{o=onDemandRecords(fs.readFileSync(p,"utf8"),d=>{try{return fs.readFileSync(path.join(d,".lensmcp","config.json"),"utf8")}catch{return}})}catch{o=[]}return o}}i(createOnDemandRecordsReader,"createOnDemandRecordsReader"),a(createOnDemandRecordsReader,"createOnDemandRecordsReader");function baseApexOf(t){return(0,instance_1.commonApex)(t.routes.filter(e=>!!e.host&&e.project!==observability_1.LENS_DASHBOARD_PROJECT).map(e=>e.host))}i(baseApexOf,"baseApexOf"),a(baseApexOf,"baseApexOf");function parkedApexOf(t,e,r){if(t.apex)return t.apex;let n=r?.get(e);return n===void 0&&(n=baseApexOf(e)??null,r?.set(e,n)),n??void 0}i(parkedApexOf,"parkedApexOf"),a(parkedApexOf,"parkedApexOf");function createParkedHostLookup(t){const e=t.records??createOnDemandRecordsReader(t),r=new WeakMap;return{match(n){const c=t.registry();if(!c||!n)return;const u=e();if(u.length===0)return;const o=n.toLowerCase();for(const s of u){if(c.has(s.key))continue;const p=c.get(s.baseKey);if(!p||p.instance)continue;const l=parkedApexOf(s,p,r);if(!l)continue;const d=`${s.name}.${l}`;if(o===d||o.endsWith(`.${d}`))return s}}}}i(createParkedHostLookup,"createParkedHostLookup"),a(createParkedHostLookup,"createParkedHostLookup");const escapeHtml=a(t=>t.replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e]),"escapeHtml");function runHint(t){return`worktree_run { name: "${t}" } \xB7 lensmcp instance run ${t}`}i(runHint,"runHint"),a(runHint,"runHint");function parkedAnswer(t,e,r){const n={"cache-control":"no-store","x-lensmcp-worktree":"parked"};if(/\btext\/html\b/i.test(e??"")){const c=escapeHtml(t.name),u=r?`<p>What its last run recorded \u2014 flows, errors, logs, reviews \u2014 is on <a href="${escapeHtml(r)}">its dashboard</a>, which opens without running it.</p>
|
|
2
|
+
`:"",o=`<!doctype html>
|
|
2
3
|
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
|
|
3
|
-
<title>${
|
|
4
|
+
<title>${c} is parked</title>
|
|
4
5
|
<style>
|
|
5
6
|
:root{--bg:#f7f7f5;--fg:#1d1d1b;--muted:#6b6b66;--card:#fff;--line:#e3e3de;--code:#f0f0ec}
|
|
6
7
|
@media (prefers-color-scheme: dark){:root{--bg:#141413;--fg:#ecece8;--muted:#9a9a93;--card:#1d1d1b;--line:#30302d;--code:#262624}}
|
|
@@ -9,16 +10,16 @@ main{max-width:560px;margin:12vh auto;padding:0 16px}
|
|
|
9
10
|
.card{background:var(--card);border:1px solid var(--line);border-radius:10px;padding:24px}
|
|
10
11
|
h1{font-size:20px;margin:0 0 8px}p{margin:8px 0;color:var(--muted)}
|
|
11
12
|
code{background:var(--code);border-radius:4px;padding:2px 6px;font:13px ui-monospace,SFMono-Regular,Menlo,monospace;color:var(--fg)}
|
|
12
|
-
ul{padding-left:18px;margin:12px 0 0}li{margin:6px 0}
|
|
13
|
+
ul{padding-left:18px;margin:12px 0 0}li{margin:6px 0}a{color:var(--fg)}
|
|
13
14
|
</style></head>
|
|
14
15
|
<body><main><div class="card">
|
|
15
|
-
<h1>The worktree <code>${
|
|
16
|
-
<p>Its services
|
|
17
|
-
<p>Run it, then reload this page:</p>
|
|
16
|
+
<h1>The worktree <code>${c}</code> is parked</h1>
|
|
17
|
+
<p>Its services and frontends are stopped to give the machine its memory back. Its data is kept, and nothing starts on its own.</p>
|
|
18
|
+
${u}<p>Run it, then reload this page:</p>
|
|
18
19
|
<ul>
|
|
19
|
-
<li>an agent: <code>worktree_run { name: "${
|
|
20
|
-
<li>a terminal: <code>lensmcp instance run ${
|
|
20
|
+
<li>an agent: <code>worktree_run { name: "${c}" }</code></li>
|
|
21
|
+
<li>a terminal: <code>lensmcp instance run ${c}</code></li>
|
|
21
22
|
<li>the dashboard: <strong>Run</strong> on its worktree</li>
|
|
22
23
|
</ul>
|
|
23
24
|
</div></main></body></html>
|
|
24
|
-
`;return{status:503,headers:{...
|
|
25
|
+
`;return{status:503,headers:{...n,"content-type":"text/html; charset=utf-8"},body:o}}return{status:503,headers:{...n,"content-type":"application/json"},body:JSON.stringify({error:`the worktree '${t.name}' is parked \u2014 nothing of it runs until it is run`,code:"worktree-parked",name:t.name,run:runHint(t.name)})}}i(parkedAnswer,"parkedAnswer"),a(parkedAnswer,"parkedAnswer");
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { type ParkedWorktree } from './on-demand';
|
|
2
|
+
import type { RouteRegistry } from './route-registry';
|
|
3
|
+
/** One parked worktree the daemon keeps a dashboard for. */
|
|
4
|
+
export interface ParkedDashboard {
|
|
5
|
+
key: string;
|
|
6
|
+
name: string;
|
|
7
|
+
baseKey: string;
|
|
8
|
+
root: string;
|
|
9
|
+
/** Its own apex (`gate1.foodguard.localhost`), when its base's hosts name one. */
|
|
10
|
+
apex?: string;
|
|
11
|
+
/** Where its dashboard answers (`lensmcp.local` + `/<key>`) — absent when this gateway hosts no dashboards. */
|
|
12
|
+
host?: string;
|
|
13
|
+
base?: string;
|
|
14
|
+
}
|
|
15
|
+
/** What hosting one parked worktree's dashboard gave: where it answers, and how to take it away. */
|
|
16
|
+
export interface HostedParked {
|
|
17
|
+
host: string;
|
|
18
|
+
base: string;
|
|
19
|
+
reap: () => void;
|
|
20
|
+
}
|
|
21
|
+
/** The record a parked dashboard is hosted from. */
|
|
22
|
+
export type ParkedRecord = Required<Pick<ParkedWorktree, 'key' | 'name' | 'baseKey' | 'root'>>;
|
|
23
|
+
export interface ParkedDashboardsDeps {
|
|
24
|
+
registry: () => Pick<RouteRegistry, 'has' | 'get'>;
|
|
25
|
+
/** The on-demand records on file now — cheap (on-demand.ts `createOnDemandRecordsReader`). */
|
|
26
|
+
records: () => readonly ParkedWorktree[];
|
|
27
|
+
/** Host its dashboard (lens-children.ts `hostParkedDashboard`); none when this gateway hosts no dashboards. */
|
|
28
|
+
host: (w: ParkedRecord) => Promise<HostedParked | undefined>;
|
|
29
|
+
/** The route table changed: rebuild it (and the cert). */
|
|
30
|
+
rebuild: () => void;
|
|
31
|
+
/** Is `root` still the checkout of instance `key`? Default: its `.lensmcp/config.json` says so. */
|
|
32
|
+
isCheckoutOf?: (root: string, key: string) => boolean;
|
|
33
|
+
/** The teardown flag — a getter (the daemon is stopping: nothing is hosted any more). */
|
|
34
|
+
stopped?: () => boolean;
|
|
35
|
+
log?: (line: string) => void;
|
|
36
|
+
}
|
|
37
|
+
export interface ParkedDashboards {
|
|
38
|
+
/** Host the dashboards of the parked worktrees not hosted yet; drop those no longer parked. Calls coalesce. */
|
|
39
|
+
sync(): Promise<{
|
|
40
|
+
hosted: string[];
|
|
41
|
+
dropped: string[];
|
|
42
|
+
}>;
|
|
43
|
+
/**
|
|
44
|
+
* A run registers `wsKey`: its parked dashboard goes first (after a sync under way, which may be hosting it). Whether
|
|
45
|
+
* there was one. The caller rebuilds the routes, as a registration does anyway.
|
|
46
|
+
*/
|
|
47
|
+
drop(wsKey: string): Promise<boolean>;
|
|
48
|
+
/** The parked worktrees and where each one's dashboard answers — what the chooser at `lensmcp.local/` lists. */
|
|
49
|
+
list(): ParkedDashboard[];
|
|
50
|
+
/** The daemon stops: every parked dashboard goes. */
|
|
51
|
+
close(): void;
|
|
52
|
+
}
|
|
53
|
+
/** Is `root` the checkout of instance `key` — its own `.lensmcp/config.json` names that key? */
|
|
54
|
+
export declare function isCheckoutOf(root: string, key: string): boolean;
|
|
55
|
+
/**
|
|
56
|
+
* The hosts the parked worktrees of the workspaces `registry` serves would run under — each of its base's route hosts
|
|
57
|
+
* moved under its name, as instance.ts `rewriteHost` moves them for a run. The cert's SANs: with them a browser reaches
|
|
58
|
+
* a parked host's page (OD-D4) instead of a certificate error, and the set is the same parked or running. Synchronous
|
|
59
|
+
* and cheap (the records are cached), so the cert is minted with it at once.
|
|
60
|
+
*/
|
|
61
|
+
export declare function parkedHosts(registry: Pick<RouteRegistry, 'has' | 'get'>, records: readonly ParkedWorktree[]): string[];
|
|
62
|
+
export declare function createParkedDashboards(deps: ParkedDashboardsDeps): ParkedDashboards;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var x=Object.defineProperty;var b=(o,s)=>x(o,"name",{value:s,configurable:!0});var w=Object.defineProperty,p=b((o,s)=>w(o,"name",{value:s,configurable:!0}),"p");Object.defineProperty(exports,"__esModule",{value:!0}),exports.isCheckoutOf=isCheckoutOf,exports.parkedHosts=parkedHosts,exports.createParkedDashboards=createParkedDashboards;const tslib_1=require("tslib"),fs=tslib_1.__importStar(require("node:fs")),path=tslib_1.__importStar(require("node:path")),instance_1=require("./instance"),observability_1=require("./observability"),on_demand_1=require("./on-demand");function isCheckoutOf(o,s){try{return JSON.parse(fs.readFileSync(path.join(o,".lensmcp","config.json"),"utf8"))?.key===s}catch{return!1}}b(isCheckoutOf,"isCheckoutOf"),p(isCheckoutOf,"isCheckoutOf");function parkedRecords(o,s){const y=[],a=new Set;for(const d of s){if(a.has(d.key)||o.has(d.key))continue;const c=o.get(d.baseKey);!c||c.instance||(a.add(d.key),y.push({record:d,base:c}))}return y}b(parkedRecords,"parkedRecords"),p(parkedRecords,"parkedRecords");function parkedHosts(o,s){const y=new Set,a=new WeakMap;for(const{record:d,base:c}of parkedRecords(o,s)){const i=(0,on_demand_1.parkedApexOf)(d,c,a);if(i)for(const k of c.routes){if(!k.host||k.project===observability_1.LENS_DASHBOARD_PROJECT)continue;const l=(0,instance_1.rewriteHost)(k.host,i,d.name);l&&y.add(l)}}return[...y].sort()}b(parkedHosts,"parkedHosts"),p(parkedHosts,"parkedHosts");function createParkedDashboards(o){const s=o.log??(t=>console.log(t)),y=o.isCheckoutOf??isCheckoutOf,a=new Map;let d=!1;const c=p(()=>d||!!o.stopped?.(),"stopped");let i,k=!1;const l=p((t,u)=>{const r=a.get(t);if(!r)return!1;a.delete(t);try{r.reap?.()}catch(f){s(`[gateway] could not fully take away the dashboard of parked worktree '${t}': ${f.message}`)}return r.reap&&s(`[gateway] the dashboard of parked worktree '${t}' is no longer hosted (${u})`),!0},"take"),g=p(async()=>{const t={hosted:[],dropped:[]};if(c())return t;const u=o.registry(),r=new Map;for(const{record:e}of parkedRecords(u,o.records())){if(!e.root||e.checkoutOnly)continue;const n=a.get(e.key);(n&&n.root===e.root?fs.existsSync(path.join(e.root,".lensmcp","config.json")):y(e.root,e.key))&&r.set(e.key,{...e,root:e.root})}let f=!1;for(const[e,n]of[...a]){const h=r.get(e);h&&h.root===n.root||(l(e,u.has(e)?"it is registered":"it is no longer a parked on-demand worktree on record"),t.dropped.push(e),f=!0)}for(const[e,n]of r){if(a.has(e))continue;if(c())break;let h;try{h=await o.host({key:e,name:n.name,baseKey:n.baseKey,root:n.root})}catch(m){s(`[gateway] could not host the dashboard of parked worktree '${e}': ${m.message}`)}if(c()||o.registry().has(e)){h?.reap();continue}a.set(e,{key:e,name:n.name,baseKey:n.baseKey,root:n.root,...n.apex?{pinnedApex:n.apex}:{},...h?{host:h.host,base:h.base,reap:h.reap}:{}}),t.hosted.push(e),f=!0}return f&&!c()&&o.rebuild(),t},"once");return{sync:p(()=>i?(k=!0,i):(i=(async()=>{const t={hosted:[],dropped:[]};try{do{k=!1;const u=await g();t.hosted.push(...u.hosted),t.dropped.push(...u.dropped)}while(k&&!c())}finally{i=void 0}return t})(),i),"sync"),async drop(t){return i&&await i.catch(()=>{}),l(t,"a run registers it")},list(){const t=o.registry(),u=new WeakMap;return[...a.values()].map(r=>{const f=t.get(r.baseKey),e=f?(0,on_demand_1.parkedApexOf)({...r.pinnedApex?{apex:r.pinnedApex}:{}},f,u):void 0;return{key:r.key,name:r.name,baseKey:r.baseKey,root:r.root,...e?{apex:`${r.name}.${e}`}:{},...r.host&&r.base?{host:r.host,base:r.base}:{}}})},close(){d=!0;for(const t of[...a.keys()])l(t,"the daemon stops")}}}b(createParkedDashboards,"createParkedDashboards"),p(createParkedDashboards,"createParkedDashboards");
|
|
@@ -25,21 +25,43 @@ export interface ProjectGraphStore {
|
|
|
25
25
|
staleReason(): string | undefined;
|
|
26
26
|
/** Recompute now. Concurrent callers share one computation; a failure keeps the previous snapshot. */
|
|
27
27
|
refresh(): Promise<ProjectGraphSnapshot | undefined>;
|
|
28
|
-
/** Kick a refresh when the snapshot is stale. Never awaits, never throws — the sweeper calls it every tick.
|
|
28
|
+
/** Kick a refresh when the snapshot is stale. Never awaits, never throws — the sweeper calls it every tick. After a
|
|
29
|
+
* failure it waits ({@link ProjectGraphStoreOptions.retryAfterFailureMs}, doubling), unless a declaring file changed. */
|
|
29
30
|
refreshIfStale(): void;
|
|
30
31
|
/** The last computation's error message, until one succeeds. */
|
|
31
32
|
lastError(): string | undefined;
|
|
33
|
+
/**
|
|
34
|
+
* The computation to use once the store's own has failed: the graph in a FRESH process. The gateway's own store is
|
|
35
|
+
* made by the executor (gateway.impl.ts), which computes in its own long-lived process, and nx's state there can stay
|
|
36
|
+
* broken after one failure (issues/open/overseer-16); the gateway hands it this when it starts (server.ts).
|
|
37
|
+
*/
|
|
38
|
+
setFallback?(compute: ComputeProjectGraph): void;
|
|
32
39
|
}
|
|
40
|
+
/** After a failed computation the first retry waits this long; each failure after it doubles the wait. */
|
|
41
|
+
export declare const GRAPH_RETRY_BASE_MS = 10000;
|
|
42
|
+
/** …up to this. */
|
|
43
|
+
export declare const GRAPH_RETRY_MAX_MS: number;
|
|
44
|
+
/** A computation that has not finished by now has failed: one that hangs must not stop every later one. */
|
|
45
|
+
export declare const GRAPH_COMPUTE_TIMEOUT_MS: number;
|
|
33
46
|
export interface ProjectGraphStoreOptions {
|
|
34
47
|
/** A snapshot computed somewhere else, with its own fingerprint — what a registering workspace forwards. */
|
|
35
48
|
seed?: ProjectGraphSnapshot;
|
|
36
49
|
/** Why there is no snapshot yet (`lastError`), until a computation succeeds. */
|
|
37
50
|
error?: string;
|
|
38
|
-
/**
|
|
39
|
-
*
|
|
51
|
+
/**
|
|
52
|
+
* After a failed computation, `refreshIfStale` waits this long before computing again, and twice as long after each
|
|
53
|
+
* failure in a row, up to `maxRetryAfterFailureMs` — or only this long when a declaring file changed since the attempt
|
|
54
|
+
* that failed (that edit may be its fix). An explicit `refresh` is never held back. Default {@link GRAPH_RETRY_BASE_MS}.
|
|
55
|
+
*/
|
|
40
56
|
retryAfterFailureMs?: number;
|
|
57
|
+
/** The longest wait between automatic retries. Default {@link GRAPH_RETRY_MAX_MS} (never less than the first wait). */
|
|
58
|
+
maxRetryAfterFailureMs?: number;
|
|
59
|
+
/** How long one computation may run before it counts as failed. Default {@link GRAPH_COMPUTE_TIMEOUT_MS}; `0`: forever. */
|
|
60
|
+
computeTimeoutMs?: number;
|
|
41
61
|
/** Called after every computation that succeeded. */
|
|
42
62
|
onRefreshed?: (snapshot: ProjectGraphSnapshot) => void;
|
|
63
|
+
/** The clock the retry waits are measured on (tests). Default `Date.now`. */
|
|
64
|
+
now?: () => number;
|
|
43
65
|
}
|
|
44
66
|
/** The gateway's project graphs, one store per workspace root it serves — its own and each registered one's. */
|
|
45
67
|
export interface ProjectGraphStores {
|
|
@@ -71,4 +93,18 @@ export declare function declaringFiles(root: string, graph: ProjectGraph): strin
|
|
|
71
93
|
* the executor reads.
|
|
72
94
|
*/
|
|
73
95
|
export declare function computeProjectGraphInProcess(root: string): Promise<ComputedProjectGraph>;
|
|
96
|
+
/**
|
|
97
|
+
* A FAILED refresh is retried (issues/open/overseer-16). It always was — every sweep tick, in the same process, and a
|
|
98
|
+
* repeat said nothing — and on FoodGuard that was not enough: once nx in the gateway's process had failed (its daemon
|
|
99
|
+
* disabled, «Failed to load 7 Nx plugin(s): The "path" argument must be of type string»), every computation there
|
|
100
|
+
* failed the same way for four hours, until the gateway restarted. The snapshot stayed the one from before nx.json
|
|
101
|
+
* changed, every service started through `nx run`, and every recycle was kill-first. So:
|
|
102
|
+
* - the waits grow: {@link ProjectGraphStoreOptions.retryAfterFailureMs}, doubling to `maxRetryAfterFailureMs`, and
|
|
103
|
+
* back to the first wait as soon as a declaring file changes after the attempt that failed;
|
|
104
|
+
* - with a fallback ({@link ProjectGraphStore.setFallback}), every attempt after the first failure runs in a fresh
|
|
105
|
+
* process. Once that has worked where this process did not, it stays the way the graph is read: this process's nx
|
|
106
|
+
* is not trusted with it again before the gateway restarts;
|
|
107
|
+
* - a computation that hangs fails after `computeTimeoutMs` — `inFlight` used to hold every later one off for good;
|
|
108
|
+
* - each failure says so, and so does the first success after them.
|
|
109
|
+
*/
|
|
74
110
|
export declare function createProjectGraphStore(root: string, compute: ComputeProjectGraph, options?: ProjectGraphStoreOptions): ProjectGraphStore;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var v=Object.defineProperty;var a=(e,t)=>v(e,"name",{value:t,configurable:!0});var E=Object.defineProperty,o=a((e,t)=>E(e,"name",{value:t,configurable:!0}),"o");Object.defineProperty(exports,"__esModule",{value:!0}),exports.GRAPH_COMPUTE_TIMEOUT_MS=exports.GRAPH_RETRY_MAX_MS=exports.GRAPH_RETRY_BASE_MS=void 0,exports.createProjectGraphStores=createProjectGraphStores,exports.statSignature=statSignature,exports.filesystemNow=filesystemNow,exports.declaringFiles=declaringFiles,exports.computeProjectGraphInProcess=computeProjectGraphInProcess,exports.createProjectGraphStore=createProjectGraphStore;const tslib_1=require("tslib"),fs=tslib_1.__importStar(require("node:fs")),node_module_1=require("node:module"),os=tslib_1.__importStar(require("node:os")),path=tslib_1.__importStar(require("node:path")),registration_guards_1=require("./registration-guards");exports.GRAPH_RETRY_BASE_MS=1e4,exports.GRAPH_RETRY_MAX_MS=5*6e4,exports.GRAPH_COMPUTE_TIMEOUT_MS=3*6e4;function createProjectGraphStores(...e){const t=new Map,s=o(r=>{t.set((0,registration_guards_1.canonicalRoot)(r.root),r)},"set");for(const r of e)s(r);return{get:o(r=>t.get((0,registration_guards_1.canonicalRoot)(r)),"get"),all:o(()=>[...t.values()],"all"),set:s,delete:o(r=>{t.delete((0,registration_guards_1.canonicalRoot)(r))},"delete")}}a(createProjectGraphStores,"createProjectGraphStores"),o(createProjectGraphStores,"createProjectGraphStores");function statSignature(e){const t=fs.statSync(e,{throwIfNoEntry:!1});return t?`${t.mtimeMs}:${t.size}:${t.ino}`:"-"}a(statSignature,"statSignature"),o(statSignature,"statSignature");const CHANGED_DURING_COMPUTE="?";function filesystemNow(){const e=path.join(os.tmpdir(),`lensmcp-graph-clock-${process.pid}`);try{fs.writeFileSync(e,"");const t=fs.statSync(e).mtimeMs;return fs.unlinkSync(e),t}catch{return Date.now()}}a(filesystemNow,"filesystemNow"),o(filesystemNow,"filesystemNow");function modifiedAfter(e,t){const s=fs.statSync(e,{throwIfNoEntry:!1});return!!s&&s.mtimeMs>t}a(modifiedAfter,"modifiedAfter"),o(modifiedAfter,"modifiedAfter");function declaringFiles(e,t){const s=[path.join(e,"nx.json")];for(const r of Object.values(t.nodes)){const n=path.join(e,r.data.root);s.push(path.join(n,"project.json"),path.join(n,"package.json"))}return[...new Set(s)]}a(declaringFiles,"declaringFiles"),o(declaringFiles,"declaringFiles");async function computeProjectGraphInProcess(e){const t=(0,node_module_1.createRequire)(path.join(e,"package.json"))("nx/src/project-graph/project-graph");return t.createProjectGraphAndSourceMapsAsync?t.createProjectGraphAndSourceMapsAsync():{projectGraph:await t.createProjectGraphAsync()}}a(computeProjectGraphInProcess,"computeProjectGraphInProcess"),o(computeProjectGraphInProcess,"computeProjectGraphInProcess");function within(e,t,s){return t>0?new Promise((r,n)=>{const c=setTimeout(()=>n(new Error(`${s} did not finish in ${Math.round(t/1e3)} s`)),t);c.unref?.(),e.then(p=>{clearTimeout(c),r(p)},p=>{clearTimeout(c),n(p)})}):e}a(within,"within"),o(within,"within");const seconds=o(e=>`${Math.round(e/1e3)} s`,"seconds");function createProjectGraphStore(e,t,s={}){let r=s.seed,n,c=s.seed?void 0:s.error;const p=s.now??Date.now,g=Math.max(0,s.retryAfterFailureMs??exports.GRAPH_RETRY_BASE_MS),x=Math.max(g,s.maxRetryAfterFailureMs??exports.GRAPH_RETRY_MAX_MS),$=s.computeTimeoutMs??exports.GRAPH_COMPUTE_TIMEOUT_MS;let _,j=!1,u=0,m=0,M,S=0;const R=o(()=>{if(!r)return"no project graph yet";for(const[l,P]of r.files)if(statSignature(l)!==P)return`${path.relative(e,l)} changed since the gateway read the project graph`},"staleReason"),y=o(()=>(r?[...r.files.keys()]:[path.join(e,"nx.json")]).map(statSignature).join("|"),"declaringState"),w=o(()=>(n??=(async()=>{const l=Date.now(),P=filesystemNow(),A=new Map;if(r)for(const i of r.files.keys())A.set(i,statSignature(i));const T=y(),h=j&&_!==void 0;try{const i=await within((h?_:t)(),$,"the project graph computation"),d=new Map;for(const f of declaringFiles(e,i.projectGraph))d.set(f,A.get(f)??(modifiedAfter(f,P)?CHANGED_DURING_COMPUTE:statSignature(f)));r={root:e,startedAt:l,files:d,...i},u>0&&console.log(`[gateway] project graph of ${e} read again${h?" in a fresh process":""} after ${u} failed attempt${u===1?"":"s"} \u2014 its services start through the serve runner again${h?"; this gateway reads it in a fresh process from now on":""}.`),c=void 0,u=0,S=0,M=void 0,s.onRefreshed?.(r)}catch(i){const d=i?.message??String(i);h||(j=!0),u+=1,m=p(),M=T;const f=Math.min(x,g*2**Math.min(u-1,30));S=m+f;const G=`tried again in ${seconds(f)}${j&&_?" in a fresh process":""}, or ${seconds(g)} after nx.json or a project file changes`;d!==c?console.warn(`[gateway] project graph refresh failed for ${e}${h?" in a fresh process":""} (its services start through \`nx run\` until it succeeds; ${G}): ${d}`):console.log(`[gateway] project graph refresh failed again for ${e}${h?" in a fresh process":""} (attempt ${u}; ${G}) \u2014 the same error.`),c=d}return r})().finally(()=>{n=void 0}),n),"refresh");return{root:e,current:o(()=>r,"current"),staleReason:R,refresh:w,refreshIfStale:o(()=>{n||!R()||p()<S&&(p()<m+g||y()===M)||w()},"refreshIfStale"),lastError:o(()=>c,"lastError"),setFallback:o(l=>{_=l},"setFallback")}}a(createProjectGraphStore,"createProjectGraphStore"),o(createProjectGraphStore,"createProjectGraphStore");
|
|
@@ -26,6 +26,12 @@ export interface WorkspaceFragment {
|
|
|
26
26
|
/** A live map of `wsKey → fragment`; `merged()` is the flat table the pipeline matches against. */
|
|
27
27
|
export declare class RouteRegistry {
|
|
28
28
|
private readonly fragments;
|
|
29
|
+
/**
|
|
30
|
+
* Routes that belong to NO registered workspace, by an id: a parked on-demand worktree's `lensmcp.local/<key>/`
|
|
31
|
+
* dashboard route (parked-dashboards.ts). Only `merged()` sees them — a parked worktree stays unregistered to
|
|
32
|
+
* everything else (`has`, `keys`, `/list`, the run cap, the parked-host check).
|
|
33
|
+
*/
|
|
34
|
+
private readonly standalone;
|
|
29
35
|
/** Register (or REPLACE) a workspace's fragment. Idempotent by `wsKey`. */
|
|
30
36
|
register(fragment: WorkspaceFragment): void;
|
|
31
37
|
/** Drop a workspace's fragment; returns it (so the caller can reap its services/dashboard). */
|
|
@@ -39,9 +45,14 @@ export declare class RouteRegistry {
|
|
|
39
45
|
appendRoutes(wsKey: string, routes: Route[]): void;
|
|
40
46
|
/** Every registered workspace's pod-service controllers, flattened (the daemon's full lifecycle set). */
|
|
41
47
|
allServices(): ServiceCtl[];
|
|
48
|
+
/** Set (or REPLACE) the standalone routes under `id` — routes no registered workspace owns. */
|
|
49
|
+
setStandalone(id: string, routes: Route[]): void;
|
|
50
|
+
/** Drop the standalone routes under `id` — only `routes` when given, so a stale reaper never drops a newer set. */
|
|
51
|
+
dropStandalone(id: string, routes?: Route[]): boolean;
|
|
52
|
+
standaloneIds(): string[];
|
|
42
53
|
/** The merged, specificity-sorted route table (host+path ▸ host ▸ per-apex catch-all). A NEW array each
|
|
43
54
|
* call — the caller rebuilds `rt.routes` in place from it so the pipeline (which reads `rt.routes` fresh
|
|
44
|
-
* per request) picks the change up atomically. */
|
|
55
|
+
* per request) picks the change up atomically. The standalone routes join it. */
|
|
45
56
|
merged(): Route[];
|
|
46
57
|
}
|
|
47
58
|
/** Rebuild `routes` IN PLACE from the registry (mutate the SAME array the request pipeline holds, so a
|