@lensmcp/cluster 1.25.55 → 1.25.57
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/devserver-notifier.d.ts +37 -1
- package/devserver-notifier.js +1 -1
- 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
package/devserver-notifier.d.ts
CHANGED
|
@@ -31,7 +31,18 @@ export declare class DevserverNotifier {
|
|
|
31
31
|
private building;
|
|
32
32
|
/** The pod generation this build's tree was started as — said on every notice (notice-generation.ts). */
|
|
33
33
|
private readonly generation;
|
|
34
|
-
|
|
34
|
+
/**
|
|
35
|
+
* The testimony is OWED to the parent until this time: a notice that carried it did not reach this tree's parent
|
|
36
|
+
* ({@link owe}). 0: nothing is owed.
|
|
37
|
+
*/
|
|
38
|
+
private owedUntil;
|
|
39
|
+
private owedTimer;
|
|
40
|
+
private readonly owedPollMs;
|
|
41
|
+
private readonly owedForMs;
|
|
42
|
+
constructor(port: number, secure?: boolean, controlSock?: string, managed?: boolean, generation?: number | undefined, owed?: {
|
|
43
|
+
pollMs?: number;
|
|
44
|
+
forMs?: number;
|
|
45
|
+
});
|
|
35
46
|
/**
|
|
36
47
|
* Deliver to the parent's CONTROL SOCKET first (`$TMPDIR[/<wsKey>]/<service>-devserver/parent.sock`), then
|
|
37
48
|
* the TCP port. The socket path is bind-STOLEN by whichever parent generation started last, so during a
|
|
@@ -43,6 +54,31 @@ export declare class DevserverNotifier {
|
|
|
43
54
|
* — it rejects with {@link NotThisGeneration} and is never retried on the port, which is the same other parent's.
|
|
44
55
|
*/
|
|
45
56
|
private post;
|
|
57
|
+
/**
|
|
58
|
+
* A notice that carries the testimony — `/webpack/watching`, or `/webpack/reload` with it in its body. One that does
|
|
59
|
+
* not reach this tree's parent leaves the testimony owed ({@link owe}); one that does pays what was owed.
|
|
60
|
+
*/
|
|
61
|
+
private tell;
|
|
62
|
+
/**
|
|
63
|
+
* The testimony did not reach this tree's parent, so it is sent again once the parent answers on the control socket
|
|
64
|
+
* (issues/closed/overseer-16). Two ways it is missed, every time:
|
|
65
|
+
* - A FIRST build ends before its parent exists: the serve executor forks the devserver parent only after the first
|
|
66
|
+
* good build, so that build's `watchRun` and `built` find no control socket.
|
|
67
|
+
* - A rolling recycle's STANDBY builds while the generation it replaces still holds the socket: that parent answers
|
|
68
|
+
* 409 (not this generation) until the standby's own parent starts and takes the socket over.
|
|
69
|
+
* Either way the parent started with no testimony, so its pods answered `/__lensmcp/alive` with no `watcher` until
|
|
70
|
+
* their watcher next woke — which a file the bundle does not import never does. At the next source-set change the
|
|
71
|
+
* gateway read them as unverifiable and recycled them (`LENSMCP_POD_WATCHER_UNVERIFIED=recycle`): one file added under
|
|
72
|
+
* FoodGuard's shared/contracts recycled seven pods in one sweep. Sent again, the testimony makes them read «silent»,
|
|
73
|
+
* which the gateway keeps (`LENSMCP_POD_WATCHER_SILENT=keep`).
|
|
74
|
+
*
|
|
75
|
+
* Only the testimony is sent again — never a reload: a parent that starts after a build loads that build. Bounded:
|
|
76
|
+
* {@link OWED_FOR_MS} after the last miss, it is let go. Not for a frozen service (`LENSMCP_FREEZE=1`): it compiles
|
|
77
|
+
* once and has no watcher, and its testimony would read as one that will see a change.
|
|
78
|
+
*/
|
|
79
|
+
private owe;
|
|
80
|
+
private paid;
|
|
81
|
+
private payOwed;
|
|
46
82
|
/** The current testimony snapshot (the wire shape the parent receives). */
|
|
47
83
|
snapshot(): PodWatcherTestimonyWire;
|
|
48
84
|
/** The watcher started a run for these changed paths. */
|
package/devserver-notifier.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var v=Object.defineProperty;var g=(a,t)=>v(a,"name",{value:t,configurable:!0});var m=Object.defineProperty,h=g((a,t)=>m(a,"name",{value:t,configurable:!0}),"h");Object.defineProperty(exports,"__esModule",{value:!0}),exports.DevserverNotifier=void 0,exports.devserverControlSock=devserverControlSock;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")),notice_generation_1=require("./notice-generation");class DevserverNotifier{static{g(this,"DevserverNotifier")}static{h(this,"DevserverNotifier")}static{this.RECENT_PATH_CAP=32}static{this.BUILD_PATH_CAP=50}constructor(t,e=!1,i,o=Number(process.env.LENSMCP_GATEWAY_PID??0)>0,c=(0,notice_generation_1.generationFromEnv)(),l={}){this.testimony={schemaVersion:1,lastWatchRunAt:0,lastBuildAt:0,buildsSinceSpawn:0,degraded:!1,recentPaths:[]},this.owedUntil=0,this.managed=o,this.owedPollMs=l.pollMs??OWED_POLL_MS,this.owedForMs=l.forMs??OWED_FOR_MS,this.secure=e,this.base=`${e?"https":"http"}://localhost:${t}`,this.controlSock=i,this.generation=c}post(t,e){const i=JSON.stringify(e),o={"content-type":"application/json",...this.generation!==void 0?{[notice_generation_1.NOTICE_GENERATION_HEADER]:String(this.generation)}:{}},c=h((s,n,r)=>{if(s.statusCode!==409||this.generation===void 0){s.resume(),s.on("end",n);return}let d="";s.setEncoding("utf8"),s.on("data",u=>{d+=u}),s.on("end",()=>{let u;try{u=JSON.parse(d).generation}catch{}r(new notice_generation_1.NotThisGeneration(this.generation,u))})},"answered"),l=h(()=>new Promise((s,n)=>{const r=(this.secure?require("node:https"):require("node:http")).request(`${this.base}${t}`,{method:"POST",headers:o,rejectUnauthorized:!1},d=>c(d,s,n));r.on("error",n),r.end(i)}),"viaTcp"),w=this.controlSock;return!w||!fs.existsSync(w)?this.managed?Promise.reject(new Error("the devserver control socket is not up yet")):l():new Promise((s,n)=>{const r=require("node:http").request({socketPath:w,path:t,method:"POST",headers:o},d=>c(d,s,n));r.on("error",n),r.end(i)}).catch(s=>{if(this.managed||s instanceof notice_generation_1.NotThisGeneration)throw s;return l()})}tell(t,e){return this.post(t,e).then(()=>{this.paid()},i=>{throw this.managed&&this.owe(),i})}owe(){process.env.LENSMCP_FREEZE==="1"||!this.controlSock||(this.owedUntil=Date.now()+this.owedForMs,!this.owedTimer&&(this.owedTimer=setTimeout(()=>this.payOwed(),this.owedPollMs),this.owedTimer.unref?.()))}paid(){this.owedUntil=0,this.owedTimer&&clearTimeout(this.owedTimer),this.owedTimer=void 0}payOwed(){if(this.owedTimer=void 0,!this.owedUntil)return;const t=h(()=>{if(Date.now()>=this.owedUntil){this.owedUntil=0;return}this.owedTimer=setTimeout(()=>this.payOwed(),this.owedPollMs),this.owedTimer.unref?.()},"again");if(!this.controlSock||!fs.existsSync(this.controlSock)){t();return}this.post("/webpack/watching",this.snapshot()).then(()=>{this.owedUntil&&(this.paid(),console.log("[DevServerReloadPlugin] the devserver is up \u2014 sent it the watcher testimony it missed while it was starting"))},t)}snapshot(){return{...this.testimony,recentPaths:[...this.testimony.recentPaths]}}watchRun(t){if(this.testimony.lastWatchRunAt=Date.now(),t.length){const e=[...this.testimony.recentPaths,...t];this.testimony.recentPaths=e.slice(-DevserverNotifier.RECENT_PATH_CAP)}this.building??={startedAt:this.testimony.lastWatchRunAt,changed:new Set,more:0};for(const e of t)this.building.changed.has(e)||(this.building.changed.size>=DevserverNotifier.BUILD_PATH_CAP?this.building.more+=1:this.building.changed.add(e));this.testimony.building=this.buildAccount(),this.tellWatching()}buildAccount(){if(this.building)return{startedAt:this.building.startedAt,changedFiles:[...this.building.changed],...this.building.more>0?{moreChanged:this.building.more}:{}}}failed(t){const e=Date.now(),i=this.buildAccount()??(t!==void 0?{startedAt:e,changedFiles:[]}:void 0);this.building=void 0,delete this.testimony.building,this.testimony.lastFailedAt=e;const o=i?{...i,endedAt:e,...t?{error:t.slice(0,FAILURE_TEXT_CAP)}:{}}:void 0;this.tell("/webpack/watching",{...this.testimony,...o?{failed:o}:{}}).catch(()=>{})}degrade(t){this.testimony.degraded=t,this.tellWatching()}tellWatching(){this.tell("/webpack/watching",this.testimony).catch(()=>{})}async built(t=!0){this.testimony.lastBuildAt=Date.now(),this.testimony.buildsSinceSpawn+=1;const e=this.buildAccount();if(this.building=void 0,delete this.testimony.building,!t){const i=e?{...e,endedAt:this.testimony.lastBuildAt}:void 0;this.tell("/webpack/watching",{...this.testimony,...i?{unchanged:i}:{}}).catch(()=>{});return}try{await this.tell("/webpack/reload",{watcher:this.testimony,...e?{build:{...e,endedAt:this.testimony.lastBuildAt}}:{}}),console.log("[DevServerReloadPlugin] notified devserver to reload")}catch(i){i instanceof notice_generation_1.NotThisGeneration?console.log(`[DevServerReloadPlugin] not this generation's devserver (${i.message}) \u2014 not reloaded; this generation's devserver loads the build when it starts`):console.log("[DevServerReloadPlugin] devserver not running yet")}}}exports.DevserverNotifier=DevserverNotifier;const FAILURE_TEXT_CAP=500,OWED_POLL_MS=500,OWED_FOR_MS=3*6e4;function devserverControlSock(a,t=process.env){const e=t.LENSMCP_SOCK_NS||t.LENSMCP_WS_KEY||"",i=e?path.join(os.tmpdir(),e,`${a}-devserver`):path.join(os.tmpdir(),`${a}-devserver`);return path.join(i,"parent.sock")}g(devserverControlSock,"devserverControlSock"),h(devserverControlSock,"devserverControlSock");
|
|
@@ -20,9 +20,21 @@ export declare function isLoopbackRequest(req: Pick<http.IncomingMessage, 'socke
|
|
|
20
20
|
* Home-relative, last two segments: `/Users/dana/work/acme/web` → `~/…/acme/web`.
|
|
21
21
|
*/
|
|
22
22
|
export declare function displayRoot(root: string, home?: string): string;
|
|
23
|
+
/** A parked on-demand worktree whose dashboard this daemon keeps (parked-dashboards.ts) — never in the registry file,
|
|
24
|
+
* which says what the daemon SERVES. */
|
|
25
|
+
export interface ParkedChooserEntry {
|
|
26
|
+
key: string;
|
|
27
|
+
root: string;
|
|
28
|
+
/** Its dashboard's path under the lens host (`/foodguard-gate1`). */
|
|
29
|
+
base: string;
|
|
30
|
+
name: string;
|
|
31
|
+
baseKey: string;
|
|
32
|
+
apex: string;
|
|
33
|
+
}
|
|
23
34
|
/** Render the chooser HTML from the registry entries (+ which key is running in THIS gateway). A worktree instance
|
|
24
|
-
* (`entry.instance`) is listed UNDER its project, not beside it.
|
|
25
|
-
|
|
35
|
+
* (`entry.instance`) is listed UNDER its project, not beside it. A `parked` worktree takes the place of a stale entry of
|
|
36
|
+
* its own key (a daemon that died with it registered) and opens its dashboard like a live one. */
|
|
37
|
+
export declare function renderChooserPage(entries: WorkspaceEntry[], currentKey: string, parked?: readonly ParkedChooserEntry[]): string;
|
|
26
38
|
/**
|
|
27
39
|
* Serve the chooser at the dashboard-host root. Reads the registry fresh so live status is current.
|
|
28
40
|
*
|
|
@@ -32,4 +44,4 @@ export declare function renderChooserPage(entries: WorkspaceEntry[], currentKey:
|
|
|
32
44
|
* (issues/closed/codex-security-26). A caller from elsewhere gets the same 404 any other unrouted path
|
|
33
45
|
* gets: a landing page that announces itself to the network is not a 404 page.
|
|
34
46
|
*/
|
|
35
|
-
export declare function serveChooser(res: http.ServerResponse, currentKey: string, req?: Pick<http.IncomingMessage, 'socket'
|
|
47
|
+
export declare function serveChooser(res: http.ServerResponse, currentKey: string, req?: Pick<http.IncomingMessage, 'socket'>, parked?: readonly ParkedChooserEntry[]): void;
|
|
@@ -1,16 +1,16 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`);return`
|
|
3
|
-
<div class="worktrees"><div class="wt-head">Worktrees \xB7 ${
|
|
4
|
-
${
|
|
5
|
-
</div>`},"worktreeList"),
|
|
6
|
-
<div class="key">${esc(e.key)} ${
|
|
7
|
-
<div class="root">${esc(displayRoot(e.root))}</div>${
|
|
1
|
+
"use strict";var w=Object.defineProperty;var l=(t,a)=>w(t,"name",{value:a,configurable:!0});var y=Object.defineProperty,r=l((t,a)=>y(t,"name",{value:a,configurable:!0}),"r");Object.defineProperty(exports,"__esModule",{value:!0}),exports.isLoopbackRequest=isLoopbackRequest,exports.displayRoot=displayRoot,exports.renderChooserPage=renderChooserPage,exports.serveChooser=serveChooser;const node_os_1=require("node:os"),workspace_registry_1=require("./workspace-registry"),esc=r(t=>t.replace(/[&<>"']/g,a=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[a]),"esc");function isLoopbackRequest(t){const a=t.socket?.remoteAddress;if(!a)return!1;const o=a.startsWith("::ffff:")?a.slice(7):a;return o==="::1"||o==="127.0.0.1"||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(o)}l(isLoopbackRequest,"isLoopbackRequest"),r(isLoopbackRequest,"isLoopbackRequest");function displayRoot(t,a=(0,node_os_1.homedir)()){const o=t.replace(/\/+$/,"").split("/").filter(Boolean),p=o.slice(-2).join("/");if(!p)return"/";const n=a!==""&&(t===a||t.startsWith(`${a}/`)),c=o.length>2;return n?c?`~/\u2026/${p}`:`~/${p}`:c?`\u2026/${p}`:`/${p}`}l(displayRoot,"displayRoot"),r(displayRoot,"displayRoot");function renderChooserPage(t,a,o=[]){const p=new Set(o.map(e=>e.key)),n=[...t.filter(e=>!p.has(e.key)).map(e=>({...e,live:e.key===a||(0,workspace_registry_1.isWorkspaceLive)(e),parked:!1})),...o.map(e=>({key:e.key,root:e.root,base:e.base,pid:0,updatedAt:"",instance:{name:e.name,baseKey:e.baseKey,apex:e.apex},live:!1,parked:!0}))].sort((e,s)=>Number(s.live)-Number(e.live)||e.key.localeCompare(s.key)),c=r(e=>e.live||e.parked,"opens"),h=new Set(n.map(e=>e.key)),u=r(e=>!!e.instance&&h.has(e.instance.baseKey),"nested"),d=n.filter(e=>!u(e)),k=r(e=>n.filter(s=>s.instance?.baseKey===e),"worktreesOf"),x=r(e=>e.key===a?'<span class="badge here">running here</span>':e.live?'<span class="badge live">live</span>':e.parked?'<span class="badge parked">parked</span>':'<span class="badge off">offline</span>',"badgeOf"),m=r(e=>{const s=k(e);if(s.length===0)return"";const g=s.map(i=>{const b=`<span class="wt-name">${esc(i.instance?.name??i.key)}</span> ${x(i)}<span class="wt-apex">${esc(i.instance?.apex??"")}</span>`;return c(i)?`<a class="wt is-live" href="${esc(i.base)}/">${b}<span class="open">Open \u2192</span></a>`:`<div class="wt is-off">${b}</div>`}).join(`
|
|
2
|
+
`),f=s.filter(i=>i.parked).length;return`
|
|
3
|
+
<div class="worktrees"><div class="wt-head">Worktrees \xB7 ${s.filter(i=>i.live).length} running${f?` \xB7 ${f} parked`:""}</div>
|
|
4
|
+
${g}
|
|
5
|
+
</div>`},"worktreeList"),v=d.length===0?'<p class="empty">No workspaces registered yet. Start a gateway in a workspace (<code>lensmcp gateway start</code>) and it will appear here.</p>':d.map(e=>{const s=c(e)?'<span class="open">Open dashboard \u2192</span>':'<span class="hint">start its gateway to open</span>',g=e.instance?`<div class="root">worktree <b>${esc(e.instance.name)}</b> of ${esc(e.instance.baseKey)} \xB7 ${esc(e.instance.apex)}</div>`:"",f=`<div class="card-main">
|
|
6
|
+
<div class="key">${esc(e.key)} ${x(e)}</div>
|
|
7
|
+
<div class="root">${esc(displayRoot(e.root))}</div>${g}
|
|
8
8
|
</div>
|
|
9
|
-
<div class="card-action">${
|
|
10
|
-
${
|
|
9
|
+
<div class="card-action">${s}</div>`;return`<div class="group">${c(e)?`<a class="card is-live" href="${esc(e.base)}/">
|
|
10
|
+
${f}
|
|
11
11
|
</a>`:`<div class="card is-off">
|
|
12
|
-
${
|
|
13
|
-
</div>`}${
|
|
12
|
+
${f}
|
|
13
|
+
</div>`}${m(e.key)}</div>`}).join(`
|
|
14
14
|
`);return`<!doctype html>
|
|
15
15
|
<html lang="en"><head>
|
|
16
16
|
<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
|
|
@@ -36,6 +36,7 @@
|
|
|
36
36
|
.badge.here { background: rgba(51,85,255,.16); color: #8aa8ff; }
|
|
37
37
|
.badge.live { background: rgba(38,190,120,.15); color: #4fd699; }
|
|
38
38
|
.badge.off { background: rgba(139,147,163,.14); color: #9aa1b0; }
|
|
39
|
+
.badge.parked { background: rgba(214,170,60,.14); color: #d9b55a; }
|
|
39
40
|
.card-action { flex-shrink: 0; }
|
|
40
41
|
.open { color: #8aa8ff; font-weight: 600; font-size: 13.5px; text-decoration: none; }
|
|
41
42
|
.hint { color: #6b7280; font-size: 12.5px; }
|
|
@@ -55,10 +56,10 @@
|
|
|
55
56
|
<body><div class="wrap">
|
|
56
57
|
<header>
|
|
57
58
|
<h1>LensMCP workspaces</h1>
|
|
58
|
-
<p class="sub">Pick a workspace to open its dashboard. ${
|
|
59
|
+
<p class="sub">Pick a workspace to open its dashboard. ${d.filter(e=>e.live).length} live \xB7 ${d.length} known${n.length>d.length?` \xB7 ${n.length-d.length} worktree${n.length-d.length===1?"":"s"}`:""}.</p>
|
|
59
60
|
</header>
|
|
60
61
|
<div class="list">
|
|
61
|
-
${
|
|
62
|
+
${v}
|
|
62
63
|
</div>
|
|
63
64
|
<footer>Served by the gateway on <code>lensmcp.local</code>. This list updates as gateways start and stop.</footer>
|
|
64
|
-
</div></body></html>`}l(renderChooserPage,"renderChooserPage"),
|
|
65
|
+
</div></body></html>`}l(renderChooserPage,"renderChooserPage"),r(renderChooserPage,"renderChooserPage");function serveChooser(t,a,o,p=[]){if(o&&!isLoopbackRequest(o)){t.writeHead(404,{"content-type":"text/plain; charset=utf-8","cache-control":"no-store"}),t.end("not found");return}const n=renderChooserPage((0,workspace_registry_1.readWorkspaces)(),a,p);t.writeHead(200,{"content-type":"text/html; charset=utf-8","cache-control":"no-store"}),t.end(n)}l(serveChooser,"serveChooser"),r(serveChooser,"serveChooser");
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use strict";var M=Object.defineProperty;var m=(d,r)=>M(d,"name",{value:r,configurable:!0});var W=Object.defineProperty,f=m((d,r)=>W(d,"name",{value:r,configurable:!0}),"f");Object.defineProperty(exports,"__esModule",{value:!0}),exports.clusterVersion=void 0,exports.instanceSummary=instanceSummary,exports.controlSocketPath=controlSocketPath,exports.versionAtLoad=versionAtLoad,exports.readClusterVersion=readClusterVersion,exports.ensureOwnerOnlyDir=ensureOwnerOnlyDir,exports.startControlServer=startControlServer;const tslib_1=require("tslib"),fs=tslib_1.__importStar(require("node:fs")),http=tslib_1.__importStar(require("node:http")),os=tslib_1.__importStar(require("node:os")),path=tslib_1.__importStar(require("node:path")),discovery_1=require("./discovery"),guest_graph_1=require("./guest-graph"),guest_replay_1=require("./guest-replay"),on_demand_1=require("./on-demand"),registration_guards_1=require("./registration-guards"),scope_1=require("./scope"),awake_1=require("./awake"),warm_start_1=require("./warm-start"),service_keys_1=require("./service-keys"),workspace_log_1=require("./workspace-log"),workspace_middleware_1=require("./workspace-middleware");function instanceSummary(d){const r=d?.instance;return r?{instance:r.name,baseKey:r.baseKey,apex:r.apex,baseApex:r.baseApex,...r.frozen?{frozen:!0}:{}}:{}}m(instanceSummary,"instanceSummary"),f(instanceSummary,"instanceSummary");function controlSocketPath(){const d=process.env.LENSMCP_HOME||os.homedir();return path.join(d,".lensmcp","control.sock")}m(controlSocketPath,"controlSocketPath"),f(controlSocketPath,"controlSocketPath");const CONTROL_BODY_BYTES=1e6;class BodyTooLarge extends Error{static{m(this,"BodyTooLarge")}static{f(this,"BodyTooLarge")}constructor(r){super(`body too large (over ${r} bytes)`),this.limit=r}}exports.clusterVersion=versionAtLoad(()=>readClusterVersion(__dirname));function versionAtLoad(d){const r=d();return()=>r}m(versionAtLoad,"versionAtLoad"),f(versionAtLoad,"versionAtLoad");function readClusterVersion(d){let r=d;for(let g=0;g<6;g++){const h=path.join(r,"package.json");if(fs.existsSync(h))try{const c=JSON.parse(fs.readFileSync(h,"utf8"));if(c.name==="@lensmcp/cluster"&&typeof c.version=="string")return c.version}catch{}const S=path.dirname(r);if(S===r)break;r=S}}m(readClusterVersion,"readClusterVersion"),f(readClusterVersion,"readClusterVersion");function readJsonBody(d,r=CONTROL_BODY_BYTES){return new Promise((g,h)=>{const S=[];let c=0,j=!1;d.on("data",$=>{if(!j){if(c+=$.length,c>r){j=!0,S.length=0,h(new BodyTooLarge(r));return}S.push($)}}),d.on("end",()=>{if(j)return;const $=Buffer.concat(S).toString("utf8");try{g({value:$?JSON.parse($):{},bytes:c})}catch(D){h(D)}}),d.on("error",h)})}m(readJsonBody,"readJsonBody"),f(readJsonBody,"readJsonBody");function graphShare(d,r){return r-Buffer.byteLength(JSON.stringify({...d,projectGraph:null}))}m(graphShare,"graphShare"),f(graphShare,"graphShare");function graphVerdict(d){return d?d.refused===void 0?{forwarded:!0,accepted:!0}:{forwarded:!0,accepted:!1,reason:d.refused}:{forwarded:!1,accepted:!1}}m(graphVerdict,"graphVerdict"),f(graphVerdict,"graphVerdict");function ensureOwnerOnlyDir(d){try{fs.mkdirSync(d,{recursive:!0,mode:448})}catch{}try{const r=fs.lstatSync(d);return r.isDirectory()?((r.mode&63)!==0&&fs.chmodSync(d,448),!0):!1}catch{return!1}}m(ensureOwnerOnlyDir,"ensureOwnerOnlyDir"),f(ensureOwnerOnlyDir,"ensureOwnerOnlyDir");function startControlServer(d){const{rt:r}=d,g=d.env??process.env,h=controlSocketPath(),S=path.dirname(h);ensureOwnerOnlyDir(S)||console.warn(`[gateway] control home ${S} is not a usable owner-only directory \u2014 refusing to expose the control plane there.`);try{fs.unlinkSync(h)}catch{}const c=f((e,t,u)=>{e.writeHead(t,{"content-type":"application/json"}),e.end(JSON.stringify(u))},"send"),j=f(async(e,t,u=!1)=>{if(!e.wsKey||!e.root)return{status:400,json:{error:"wsKey and root are required"}};const s=e.projects??{},o=(0,discovery_1.projectSourceRoots)(e.root,s,e.projectDependencies),n=(0,scope_1.readLensScope)(e.root),a=n.key===e.wsKey,l=a&&n.sockNs!==e.wsKey?n.sockNs:void 0,{routes:y,services:i,instance:w}=(0,discovery_1.discoverRoutes)(e.root,s,void 0,e.wsKey,o,l,a?n.instance:void 0),v=(0,workspace_middleware_1.findGatewayMiddleware)(e.root,s),k={wsKey:e.wsKey,...l?{sockNs:l}:{},root:e.root,routes:y,services:i,...w?{instance:w}:{},...v?{middleware:v}:{}},p=(0,registration_guards_1.refuseRegistration)(r.registry,k);if(p)return console.warn(`[gateway] refused to register '${e.wsKey}' from ${e.root}: ${p.error}`),{status:409,json:p};if(u)return w?{status:200,json:{wsKey:e.wsKey,root:e.root,...instanceSummary(k),env:w.env}}:{status:400,json:{error:`'${e.wsKey}' has no resolvable instance configuration`}};const _=(0,on_demand_1.runCapRefusal)(r.registry,k,g);if(_)return console.warn(`[gateway] refused to register '${e.wsKey}' from ${e.root}: ${_.error}`),{status:409,json:_};w?.onDemand&&(k.lastUseAt=Date.now());try{const K=(0,service_keys_1.adoptServiceKeys)(r,e.root,i,e.wsKey);K.added.length>0&&console.log(`[gateway] adopted east-west keys for ${e.wsKey}: ${K.added.join(", ")}`),K.regenerated.length>0&&console.warn(`[gateway] ${e.root} carried another workspace's east-west keys (a copied key file) \u2014 new keys for ${e.wsKey}: ${K.regenerated.join(", ")}`)}catch(K){console.error(`[gateway] could not adopt east-west keys for ${e.wsKey}: ${K.message}`)}try{(0,workspace_log_1.workspaceLogWriter)(e.root)?.(`[gateway] ${new Date().toISOString()} this workspace ('${e.wsKey}') is served by the daemon at ${r.root} (pid ${process.pid}); its gateway-level log is ${path.join(r.root,".lensmcp","gateway.log")}. Pod output for this workspace follows here. Attach live with \`lensmcp logs <service>\`.
|
|
2
|
-
`)}catch{}let O;if(r.graphStores){const K={root:e.root,daemonRoot:r.root,otherRoots:r.registry.keys().filter(P=>P!==e.wsKey).flatMap(P=>r.registry.get(P)?.root??[])};O=e.projectGraph===void 0?void 0:(0,guest_graph_1.admitForwardedGraph)(e.projectGraph,{...K,bytes:graphShare(e,t)}),O?.refused!==void 0&&console.warn(`[gateway] refused the project graph '${e.wsKey}' forwarded from ${e.root}: ${O.refused} \u2014 its services start through \`nx run\` until the gateway computes it`),(0,registration_guards_1.sameRoot)(e.root,r.root)||r.graphStores.set((0,guest_graph_1.createGuestGraphStore)({wsKey:e.wsKey,root:e.root,...O?{admission:O}:{},context:K}))}return r.registry.register(k),await d.onRegister?.(k),r.rebuildRoutes(),r.root&&!(0,registration_guards_1.sameRoot)(e.root,r.root)&&(0,guest_replay_1.recordGuest)({wsKey:e.wsKey,root:e.root,projects:s,...e.projectDependencies?{projectDependencies:e.projectDependencies}:{},daemonRoot:r.root,registeredAt:new Date().toISOString(),...w?.onDemand?{onDemand:!0}:{}}),w?.onDemand&&console.log(`[gateway] registered on-demand worktree '${w.name}' (${e.wsKey}) \u2014 nothing starts until its run asks (POST /awake); parked after ${(0,on_demand_1.worktreeRunIdleSec)(g)}s unused (${on_demand_1.WORKTREE_RUN_IDLE_ENV})`),{status:200,json:{ok:!0,wsKey:e.wsKey,routes:y.length,services:i.length,workspaces:r.registry.keys(),...r.graphStores?{projectGraph:graphVerdict(O)}:{},...(0,on_demand_1.runSummary)(k,g)}}},"register"),$=f(e=>{const t=r.registry.unregister(e);if(t){for(const u of t.services){const s=(0,service_keys_1.serviceKeyId)(u.wsKey??e,u.project),o=r.serviceKeys[s];o&&(delete r.serviceKeys[s],r.keyToProject.delete(o),r.keyToWorkspace?.delete(o))}for(const u of t.services)d.killService(u,"workspace unregistered");return r.graphStores?.delete(t.root),(0,guest_replay_1.forgetGuest)(e),d.onUnregister?.(t),t}},"unregisterWorkspace"),D=f((e,t,u={})=>{try{fs.rmSync(path.join(e.root,".lensmcp","registered.json"),{force:!0})}catch{}const s=e.instance?.name??e.wsKey,o=(0,on_demand_1.worktreeRunIdleSec)(g);console.log(`[gateway] ${new Date().toISOString()} parked on-demand worktree '${s}' (${e.wsKey}): ${t==="idle"?`no request and no hold for ${o}s (${on_demand_1.WORKTREE_RUN_IDLE_ENV})`:"asked"} \u2014 its services, frontends, capture, dashboard and build host are stopped; its data is kept.`),d.emitWorkspace?.(e,"info",`worktree parked: ${s} (${t==="idle"?`unused for ${o}s`:"asked"})`,"cluster-worktree:parked",{kind:"worktree-parked",wsKey:e.wsKey,name:s,why:t,...t==="idle"?{idleSec:o}:{},...u})},"announceParked"),G=f(e=>t=>(t&&(0,on_demand_1.touchStart)(r.registry,e),t),"touchedStart"),E=f((e,t)=>{const u=r.registry.get(e);if(!u)return{error:`no workspace '${e}' is registered`,workspaces:r.registry.keys()};const s=u.services.find(o=>o.project===t);return s?{svc:s}:{error:`'${e}' has no service '${t}'`,services:u.services.map(o=>o.project)}},"findService"),b=f(e=>{let t=(e.stoppingUntil??0)>Date.now();if(e.stoppingPid)try{process.kill(e.stoppingPid,0),t=!0}catch{e.stoppingPid=void 0}return{service:e.project,state:e.state,stopped:e.manualStopped===!0&&!t,ready:!e.manualStopped&&e.state==="up"&&e.pool.socks.length>0,busy:t||e.actionStarting===!0||!!e.rolling||!!(e.restart&&!e.restart.done),failure:e.actionFailure??(!e.manualStopped&&e.restart?.done?.ok===!1?e.restart.done.error:void 0)}},"serviceView"),U=f((e,t)=>(e.manualStopped=!1,e.actionFailure=void 0,e.restart=void 0,e.actionStarting=!0,t(e).then(u=>(!u&&!e.manualStopped&&(e.actionFailure="Service did not become ready"),u),u=>(e.actionFailure=String(u).slice(0,500),!1)).finally(()=>{e.actionStarting=!1})),"startService"),R=f((e,t)=>({project:e.project,wsKey:e.wsKey,host:e.decl.host,state:e.state,...e.generation!==void 0?{generation:e.generation}:{},...e.restart?{restart:e.restart}:{},...(0,awake_1.idleFields)(e,(0,warm_start_1.serviceIdleSec)(r,e,g),t),...e.lastStartError?{error:e.lastStartError}:{}}),"statusRow");let q=Promise.resolve();const L=d.startTurn??(e=>{const t=q.then(e);return q=t.catch(()=>{}),t}),T=f(e=>({wsKey:e.wsKey,service:e.project,state:e.state,...e.generation!==void 0?{generation:e.generation}:{},...e.restart?{restart:e.restart}:{}}),"restartView"),x=f((e,t,u,s,o)=>{const n=o+Math.round(u*1e3),a=[],l=f((i,w)=>({at:o,outcome:i,...w?{reason:w}:{}}),"asked");for(const i of t)i.awakeUntil=Math.max(i.awakeUntil??0,n),i.state==="up"?i.wake=l("up"):b(i).busy?i.wake=l("skipped","a stop, start or restart of it is under way \u2014 `lensmcp instance status` shows how it ends"):i.manualStopped&&!s?i.wake=l("skipped","stopped by hand \u2014 name it to start it"):d.ensureService?(i.manualStopped=!1,i.wake=l("queued"),a.push({svc:i,wake:i.wake})):i.wake=l("failed","this gateway cannot start services"),d.emitService?.(i,"info",`awake until ${new Date(i.awakeUntil).toISOString()}: ${i.project}`,{kind:"service-awake",project:i.project,until:i.awakeUntil,forSec:u,wake:i.wake.outcome});const y=d.ensureService;return a.length>0&&y&&L(()=>(0,awake_1.wakeServices)(a,{start:f(i=>U(i,y).then(G(i)),"start"),available:d.available??(()=>(0,warm_start_1.availableMemory)()),minFreeBytes:d.minFreeBytes??(0,warm_start_1.warmMinFreeBytes)(),current:f(i=>!r.stopped?.()&&!!r.registry.get(i.wsKey)?.services.includes(i),"current"),busy:f(i=>b(i).busy,"busy"),emit:f((i,w,v,k)=>d.emitService?.(i,w,v,k),"emit"),log:f(i=>console.log(i),"log")})).catch(i=>console.error(`[gateway] wake of ${e.wsKey} failed:`,i)),n},"holdAndWake"),A=f(e=>{(0,on_demand_1.isOnDemand)(e)&&r.registry.get(e.wsKey)===e&&(0,guest_replay_1.updateGuest)(e.wsKey,{runUntil:(0,on_demand_1.holdEnd)(e)})},"heldRun"),N=http.createServer((e,t)=>{(async()=>{try{const u=(e.url??"").split("?")[0];if(e.method==="GET"&&u==="/list")return c(t,200,{workspaces:r.registry.keys().map(s=>{const o=r.registry.get(s);return{key:s,root:o?.root,routes:o?.routes.length??0,services:o?.services.length??0,...instanceSummary(o),...(0,on_demand_1.runSummary)(o,g)}})});if(e.method==="GET"&&u==="/status"){const s=(0,exports.clusterVersion)();return c(t,200,{daemon:{pid:process.pid,wsKey:r.wsKey,...s?{version:s}:{}},workspaces:r.registry.keys().map(o=>{const n=r.registry.get(o);return{key:o,root:n?.root,routes:n?.routes.length??0,services:n?.services.length??0,isDaemon:o===r.wsKey,...instanceSummary(n),...(0,on_demand_1.runSummary)(n,g)}}),services:r.registry.allServices().map(o=>R(o,Date.now()))})}if(e.method==="GET"&&u==="/instance-env"){const s=new URL(e.url??"/","http://control").searchParams.get("wsKey")??"",o=r.registry.get(s);return o?o.instance?c(t,200,{wsKey:s,root:o.root,...instanceSummary(o),env:o.instance.env}):c(t,404,{error:`'${s}' is not an instance`}):c(t,404,{error:`no workspace '${s}' is registered`})}if(e.method==="POST"&&u==="/instance-env"){const{value:s,bytes:o}=await readJsonBody(e,CONTROL_BODY_BYTES+guest_graph_1.MAX_FORWARDED_GRAPH_BYTES),n=await j(s,o,!0);return c(t,n.status,n.json)}if(u==="/service"&&(e.method==="GET"||e.method==="POST")){const s=e.method==="GET"?Object.fromEntries(new URL(e.url??"/","http://control").searchParams):(await readJsonBody(e)).value??{};if(typeof s.wsKey!="string"||typeof s.service!="string")return c(t,400,{error:"wsKey and service are required"});const o=E(s.wsKey,s.service);if("error"in o)return c(t,404,o);const n=o.svc,a=f(()=>b(n),"view");if(e.method==="GET")return c(t,200,a());const l=s.action;if(!["start","stop","restart"].includes(String(l)))return c(t,400,{error:"action must be start, stop or restart"});if(a().busy&&!(l==="stop"&&n.actionStarting&&!n.rolling))return c(t,409,{error:"A service lifecycle operation is already in progress"});if(l==="stop")return!n.proc&&n.pool.socks.length&&!n.manualStopped?c(t,409,{error:"This gateway does not own the adopted service process; stop it with its owner"}):(n.manualStopped=!0,n.stoppingPid=n.proc?.pid,n.stoppingUntil=Date.now()+(n.proc?1600:0),d.killService(n,"workspace action stop"),n.state="down",c(t,202,a()));if(l==="restart"){if(!d.restartService)return c(t,501,{error:"This gateway cannot restart services"});(0,on_demand_1.touchStart)(r.registry,n);const i=d.restartService(n,{hard:s.hard===!0,reason:"workspace action restart"});return"refused"in i?c(t,409,{error:i.refused}):c(t,202,{...a(),restart:i.restart})}if(!d.ensureService)return c(t,501,{error:"This gateway cannot start services"});const y=n.state!=="up"&&!n.proc;return(0,on_demand_1.touchStart)(r.registry,n),U(n,d.ensureService).then(G(n)),c(t,202,{...a(),started:y})}if(e.method==="POST"&&u==="/awake"){const s=(await readJsonBody(e)).value??{},o=typeof s.wsKey=="string"?s.wsKey:"";if(!o)return c(t,400,{error:"wsKey is required"});const n=typeof s.forSec=="number"?s.forSec:NaN;if(!Number.isFinite(n)||n<0)return c(t,400,{error:"forSec is required: the seconds to hold them awake, 0 to release the hold"});if(n>awake_1.MAX_AWAKE_SEC)return c(t,400,{error:`forSec ${n} is over the ${awake_1.MAX_AWAKE_SEC} s (4 h) a hold may last \u2014 ask again before it ends to keep them longer`,maxSec:awake_1.MAX_AWAKE_SEC});const a=s.services;if(a!==void 0&&(!Array.isArray(a)||a.length===0||!a.every(p=>typeof p=="string"&&p.length>0)))return c(t,400,{error:"services, when given, names one service or more"});const l=r.registry.get(o);if(!l)return c(t,404,{error:`no workspace '${o}' is registered`,workspaces:r.registry.keys()});const y=[];for(const p of a??[]){const _=E(o,p);if("error"in _)return c(t,404,_);y.includes(_.svc)||y.push(_.svc)}const i=y.length>0,w=!i&&s.warmOnly===!0;i||y.push(...w?l.services.filter(p=>p.decl.eager):l.services);const v=Date.now();if(n===0){for(const p of y)(p.awakeUntil??0)<=v||(p.awakeUntil=v,d.emitService?.(p,"info",`awake hold released: ${p.project}`,{kind:"service-awake",project:p.project,until:null,released:!0}));return A(l),c(t,202,{ok:!0,wsKey:o,forSec:0,released:!0,...w?{warmOnly:!0}:{},services:y.map(p=>R(p,v)),...(0,on_demand_1.runSummary)(l,g)})}const k=x(l,y,n,i,v);return(0,on_demand_1.isOnDemand)(l)&&(l.lastUseAt=v),A(l),c(t,202,{ok:!0,wsKey:o,forSec:n,until:k,...w?{warmOnly:!0}:{},services:y.map(p=>R(p,v)),...(0,on_demand_1.runSummary)(l,g)})}if(u==="/restart"&&(e.method==="POST"||e.method==="GET")){const s=e.method==="GET"?Object.fromEntries(new URL(e.url??"/","http://control").searchParams):(await readJsonBody(e)).value??{},o=typeof s.wsKey=="string"?s.wsKey:"",n=typeof s.service=="string"?s.service:"";if(!o||!n)return c(t,400,{error:"wsKey and service are required"});const a=E(o,n);if("error"in a)return c(t,404,a);const l=a.svc;if(e.method==="GET")return c(t,200,T(l));if(!d.restartService)return c(t,501,{error:"this gateway cannot restart a service"});(0,on_demand_1.touchStart)(r.registry,l);const y=typeof s.reason=="string"&&s.reason.trim()?s.reason.trim().slice(0,200):"asked for",i=d.restartService(l,{hard:s.hard===!0,reason:y});return"refused"in i?c(t,409,{error:i.refused,...T(l)}):c(t,202,{ok:!0,already:i.already,...T(l)})}if(e.method==="GET"&&u==="/identities"||e.method==="POST"&&u==="/act"){const s=e.method==="GET"?Object.fromEntries(new URL(e.url??"/","http://control").searchParams):(await readJsonBody(e)).value??{},o=typeof s.wsKey=="string"?s.wsKey:"";if(!o)return c(t,400,{error:"wsKey is required"});if(!r.registry.get(o)&&o!==r.wsKey)return c(t,404,{error:`no workspace '${o}' is registered`,workspaces:r.registry.keys()});if(!d.act)return c(t,501,{error:"acting as a signed-in user is turned off on this gateway (LENSMCP_GW_ACT=0)"});if(e.method==="GET")return c(t,200,{wsKey:o,identities:d.act.list(o)});const n=f(i=>typeof s[i]=="string"&&s[i].trim()?s[i].trim().slice(0,256):void 0,"pick"),a=n("user"),l=n("tenant"),y=d.act.mint(o,{...a?{user:a}:{},...l?{tenant:l}:{}});return"error"in y?c(t,404,{wsKey:o,...y}):c(t,200,{wsKey:o,...y})}if(e.method==="POST"&&u==="/register"){const{value:s,bytes:o}=await readJsonBody(e,CONTROL_BODY_BYTES+guest_graph_1.MAX_FORWARDED_GRAPH_BYTES),n=await j(s,o);return c(t,n.status,n.json)}if(e.method==="POST"&&u==="/unregister"){const s=(await readJsonBody(e)).value;if(!s.wsKey)return c(t,400,{error:"wsKey is required"});const o=(0,registration_guards_1.refuseUnregistration)(r.registry,{wsKey:s.wsKey,...s.root?{root:s.root}:{}},r.wsKey);if(o)return console.warn(`[gateway] refused to unregister '${s.wsKey}'${s.root?` for ${s.root}`:""}: ${o.error}`),c(t,409,o);const n=$(s.wsKey);return n&&(0,on_demand_1.isOnDemand)(n)&&D(n,"asked"),r.rebuildRoutes(),c(t,200,{ok:!0,removed:!!n,workspaces:r.registry.keys(),...n&&(0,on_demand_1.isOnDemand)(n)?{parked:!0}:{}})}c(t,404,{error:"not found"})}catch(u){if(u instanceof BodyTooLarge)return e.resume(),c(t,413,{error:u.message});c(t,500,{error:u.message})}})()});return N.listen(h,()=>{try{fs.chmodSync(h,384)}catch(e){console.warn(`[gateway] could not restrict ${h} to 0600:`,e.message)}}),{socketPath:h,async replay(){const e=Date.now(),{replay:t,gone:u,parked:s}=(0,guest_replay_1.guestsToReplay)(r.root,(0,guest_replay_1.readGuests)(),e),o={replayed:[],refused:[],gone:u.map(a=>a.wsKey),parked:s.map(a=>a.wsKey)};for(const a of u)(0,guest_replay_1.forgetGuest)(a.wsKey),console.log(`[gateway] not re-hosting '${a.wsKey}': ${a.root} is no longer a workspace \u2014 forgotten`);const n=f((a,l)=>{(0,guest_replay_1.forgetGuest)(a.wsKey);try{fs.rmSync(path.join(a.root,".lensmcp","registered.json"),{force:!0})}catch{}console.log(`[gateway] not re-hosting on-demand worktree '${a.wsKey}': ${l} \u2014 it stays parked (\`lensmcp instance run\` runs it)`)},"leaveParked");for(const a of s)n(a,a.runUntil?`its run ended at ${new Date(a.runUntil).toISOString()}`:"no run held it");for(const a of t)if(!r.registry.has(a.wsKey))try{const l=await j({wsKey:a.wsKey,root:a.root,projects:a.projects,...a.projectDependencies?{projectDependencies:a.projectDependencies}:{}},0);if(l.status===200){o.replayed.push(a.wsKey),console.log(`[gateway] re-hosted '${a.wsKey}' (${a.root}) \u2014 registered before this daemon restarted`);const y=r.registry.get(a.wsKey),i=(a.runUntil??0)-Date.now();a.onDemand&&y&&(0,on_demand_1.isOnDemand)(y)&&i>0&&(x(y,y.services.filter(w=>w.decl.eager),i/1e3,!1,Date.now()),A(y))}else a.onDemand&&l.json.code==="run-cap"?(o.parked.push(a.wsKey),n(a,`${l.json.max??"?"} on-demand worktrees already run (LENSMCP_WORKTREE_RUN_MAX)`)):(o.refused.push(a.wsKey),console.warn(`[gateway] could not re-host '${a.wsKey}' (${a.root}): ${JSON.stringify(l.json)} \u2014 \`lensmcp gateway start\` there`))}catch(l){o.refused.push(a.wsKey),console.warn(`[gateway] could not re-host '${a.wsKey}' (${a.root}): ${l.message}`)}return o},parkIdle(e=Date.now()){if(r.stopped?.())return[];const t=[];for(const u of r.registry.keys()){if(u===r.wsKey)continue;const s=r.registry.get(u);if(!s||!(0,on_demand_1.isOnDemand)(s))continue;const o=(0,on_demand_1.parkVerdict)(s,e,g);if(!o.ok)continue;const n=s.lastUseAt;$(u)&&(t.push(u),D(s,"idle",{parkAt:o.parkAt,...n!==void 0?{lastUseAt:n}:{}}))}return t.length>0&&r.rebuildRoutes(),t},close:f(()=>{N.close();try{fs.unlinkSync(h)}catch{}},"close")}}m(startControlServer,"startControlServer"),f(startControlServer,"startControlServer");
|
|
2
|
+
`)}catch{}let O;if(r.graphStores){const K={root:e.root,daemonRoot:r.root,otherRoots:r.registry.keys().filter(P=>P!==e.wsKey).flatMap(P=>r.registry.get(P)?.root??[])};O=e.projectGraph===void 0?void 0:(0,guest_graph_1.admitForwardedGraph)(e.projectGraph,{...K,bytes:graphShare(e,t)}),O?.refused!==void 0&&console.warn(`[gateway] refused the project graph '${e.wsKey}' forwarded from ${e.root}: ${O.refused} \u2014 its services start through \`nx run\` until the gateway computes it`),(0,registration_guards_1.sameRoot)(e.root,r.root)||r.graphStores.set((0,guest_graph_1.createGuestGraphStore)({wsKey:e.wsKey,root:e.root,...O?{admission:O}:{},context:K}))}return r.registry.register(k),await d.onRegister?.(k),r.rebuildRoutes(),r.root&&!(0,registration_guards_1.sameRoot)(e.root,r.root)&&(0,guest_replay_1.recordGuest)({wsKey:e.wsKey,root:e.root,projects:s,...e.projectDependencies?{projectDependencies:e.projectDependencies}:{},daemonRoot:r.root,registeredAt:new Date().toISOString(),...w?.onDemand?{onDemand:!0}:{}}),w?.onDemand&&console.log(`[gateway] registered on-demand worktree '${w.name}' (${e.wsKey}) \u2014 nothing starts until its run asks (POST /awake); parked after ${(0,on_demand_1.worktreeRunIdleSec)(g)}s unused (${on_demand_1.WORKTREE_RUN_IDLE_ENV})`),{status:200,json:{ok:!0,wsKey:e.wsKey,routes:y.length,services:i.length,workspaces:r.registry.keys(),...r.graphStores?{projectGraph:graphVerdict(O)}:{},...(0,on_demand_1.runSummary)(k,g)}}},"register"),$=f(e=>{const t=r.registry.unregister(e);if(t){for(const u of t.services){const s=(0,service_keys_1.serviceKeyId)(u.wsKey??e,u.project),o=r.serviceKeys[s];o&&(delete r.serviceKeys[s],r.keyToProject.delete(o),r.keyToWorkspace?.delete(o))}for(const u of t.services)d.killService(u,"workspace unregistered");return r.graphStores?.delete(t.root),(0,guest_replay_1.forgetGuest)(e),d.onUnregister?.(t),t}},"unregisterWorkspace"),D=f((e,t,u={})=>{try{fs.rmSync(path.join(e.root,".lensmcp","registered.json"),{force:!0})}catch{}const s=e.instance?.name??e.wsKey,o=(0,on_demand_1.worktreeRunIdleSec)(g);console.log(`[gateway] ${new Date().toISOString()} parked on-demand worktree '${s}' (${e.wsKey}): ${t==="idle"?`no request and no hold for ${o}s (${on_demand_1.WORKTREE_RUN_IDLE_ENV})`:"asked"} \u2014 its services, frontends, capture, dashboard and build host are stopped; its data is kept.`),d.emitWorkspace?.(e,"info",`worktree parked: ${s} (${t==="idle"?`unused for ${o}s`:"asked"})`,"cluster-worktree:parked",{kind:"worktree-parked",wsKey:e.wsKey,name:s,why:t,...t==="idle"?{idleSec:o}:{},...u})},"announceParked"),G=f(e=>t=>(t&&(0,on_demand_1.touchStart)(r.registry,e),t),"touchedStart"),b=f((e,t)=>{const u=r.registry.get(e);if(!u)return{error:`no workspace '${e}' is registered`,workspaces:r.registry.keys()};const s=u.services.find(o=>o.project===t);return s?{svc:s}:{error:`'${e}' has no service '${t}'`,services:u.services.map(o=>o.project)}},"findService"),E=f(e=>{let t=(e.stoppingUntil??0)>Date.now();if(e.stoppingPid)try{process.kill(e.stoppingPid,0),t=!0}catch{e.stoppingPid=void 0}return{service:e.project,state:e.state,stopped:e.manualStopped===!0&&!t,ready:!e.manualStopped&&e.state==="up"&&e.pool.socks.length>0,busy:t||e.actionStarting===!0||!!e.rolling||!!(e.restart&&!e.restart.done),failure:e.actionFailure??(!e.manualStopped&&e.restart?.done?.ok===!1?e.restart.done.error:void 0)}},"serviceView"),U=f((e,t)=>(e.manualStopped=!1,e.actionFailure=void 0,e.restart=void 0,e.actionStarting=!0,t(e).then(u=>(!u&&!e.manualStopped&&(e.actionFailure="Service did not become ready"),u),u=>(e.actionFailure=String(u).slice(0,500),!1)).finally(()=>{e.actionStarting=!1})),"startService"),R=f((e,t)=>({project:e.project,wsKey:e.wsKey,host:e.decl.host,state:e.state,...e.generation!==void 0?{generation:e.generation}:{},...e.restart?{restart:e.restart}:{},...(0,awake_1.idleFields)(e,(0,warm_start_1.serviceIdleSec)(r,e,g),t),...e.lastStartError?{error:e.lastStartError}:{}}),"statusRow");let q=Promise.resolve();const L=d.startTurn??(e=>{const t=q.then(e);return q=t.catch(()=>{}),t}),T=f(e=>({wsKey:e.wsKey,service:e.project,state:e.state,...e.generation!==void 0?{generation:e.generation}:{},...e.restart?{restart:e.restart}:{}}),"restartView"),x=f((e,t,u,s,o)=>{const n=o+Math.round(u*1e3),a=[],l=f((i,w)=>({at:o,outcome:i,...w?{reason:w}:{}}),"asked");for(const i of t)i.awakeUntil=Math.max(i.awakeUntil??0,n),i.state==="up"?i.wake=l("up"):E(i).busy?i.wake=l("skipped","a stop, start or restart of it is under way \u2014 `lensmcp instance status` shows how it ends"):i.manualStopped&&!s?i.wake=l("skipped","stopped by hand \u2014 name it to start it"):d.ensureService?(i.manualStopped=!1,i.wake=l("queued"),a.push({svc:i,wake:i.wake})):i.wake=l("failed","this gateway cannot start services"),d.emitService?.(i,"info",`awake until ${new Date(i.awakeUntil).toISOString()}: ${i.project}`,{kind:"service-awake",project:i.project,until:i.awakeUntil,forSec:u,wake:i.wake.outcome});const y=d.ensureService;return a.length>0&&y&&L(()=>(0,awake_1.wakeServices)(a,{start:f(i=>U(i,y).then(G(i)),"start"),available:d.available??(()=>(0,warm_start_1.availableMemory)()),minFreeBytes:d.minFreeBytes??(0,warm_start_1.warmMinFreeBytes)(),current:f(i=>!r.stopped?.()&&!!r.registry.get(i.wsKey)?.services.includes(i),"current"),busy:f(i=>E(i).busy,"busy"),emit:f((i,w,v,k)=>d.emitService?.(i,w,v,k),"emit"),log:f(i=>console.log(i),"log")})).catch(i=>console.error(`[gateway] wake of ${e.wsKey} failed:`,i)),n},"holdAndWake"),A=f(e=>{(0,on_demand_1.isOnDemand)(e)&&r.registry.get(e.wsKey)===e&&(0,guest_replay_1.updateGuest)(e.wsKey,{runUntil:(0,on_demand_1.holdEnd)(e)})},"heldRun"),N=http.createServer((e,t)=>{(async()=>{try{const u=(e.url??"").split("?")[0];if(e.method==="GET"&&u==="/list")return c(t,200,{workspaces:r.registry.keys().map(s=>{const o=r.registry.get(s);return{key:s,root:o?.root,routes:o?.routes.length??0,services:o?.services.length??0,...instanceSummary(o),...(0,on_demand_1.runSummary)(o,g)}})});if(e.method==="GET"&&u==="/status"){const s=(0,exports.clusterVersion)();return c(t,200,{daemon:{pid:process.pid,wsKey:r.wsKey,...s?{version:s}:{}},capabilities:{candidateRuntimeProof:1},workspaces:r.registry.keys().map(o=>{const n=r.registry.get(o);return{key:o,root:n?.root,routes:n?.routes.length??0,services:n?.services.length??0,isDaemon:o===r.wsKey,...instanceSummary(n),...(0,on_demand_1.runSummary)(n,g)}}),services:r.registry.allServices().map(o=>R(o,Date.now()))})}if(e.method==="GET"&&u==="/instance-env"){const s=new URL(e.url??"/","http://control").searchParams.get("wsKey")??"",o=r.registry.get(s);return o?o.instance?c(t,200,{wsKey:s,root:o.root,...instanceSummary(o),env:o.instance.env}):c(t,404,{error:`'${s}' is not an instance`}):c(t,404,{error:`no workspace '${s}' is registered`})}if(e.method==="POST"&&u==="/instance-env"){const{value:s,bytes:o}=await readJsonBody(e,CONTROL_BODY_BYTES+guest_graph_1.MAX_FORWARDED_GRAPH_BYTES),n=await j(s,o,!0);return c(t,n.status,n.json)}if(u==="/service"&&(e.method==="GET"||e.method==="POST")){const s=e.method==="GET"?Object.fromEntries(new URL(e.url??"/","http://control").searchParams):(await readJsonBody(e)).value??{};if(typeof s.wsKey!="string"||typeof s.service!="string")return c(t,400,{error:"wsKey and service are required"});const o=b(s.wsKey,s.service);if("error"in o)return c(t,404,o);const n=o.svc,a=f(()=>E(n),"view");if(e.method==="GET")return c(t,200,a());const l=s.action;if(!["start","stop","restart"].includes(String(l)))return c(t,400,{error:"action must be start, stop or restart"});if(a().busy&&!(l==="stop"&&n.actionStarting&&!n.rolling))return c(t,409,{error:"A service lifecycle operation is already in progress"});if(l==="stop")return!n.proc&&n.pool.socks.length&&!n.manualStopped?c(t,409,{error:"This gateway does not own the adopted service process; stop it with its owner"}):(n.manualStopped=!0,n.stoppingPid=n.proc?.pid,n.stoppingUntil=Date.now()+(n.proc?1600:0),d.killService(n,"workspace action stop"),n.state="down",c(t,202,a()));if(l==="restart"){if(!d.restartService)return c(t,501,{error:"This gateway cannot restart services"});(0,on_demand_1.touchStart)(r.registry,n);const i=d.restartService(n,{hard:s.hard===!0,reason:"workspace action restart"});return"refused"in i?c(t,409,{error:i.refused}):c(t,202,{...a(),restart:i.restart})}if(!d.ensureService)return c(t,501,{error:"This gateway cannot start services"});const y=n.state!=="up"&&!n.proc;return(0,on_demand_1.touchStart)(r.registry,n),U(n,d.ensureService).then(G(n)),c(t,202,{...a(),started:y})}if(e.method==="POST"&&u==="/awake"){const s=(await readJsonBody(e)).value??{},o=typeof s.wsKey=="string"?s.wsKey:"";if(!o)return c(t,400,{error:"wsKey is required"});const n=typeof s.forSec=="number"?s.forSec:NaN;if(!Number.isFinite(n)||n<0)return c(t,400,{error:"forSec is required: the seconds to hold them awake, 0 to release the hold"});if(n>awake_1.MAX_AWAKE_SEC)return c(t,400,{error:`forSec ${n} is over the ${awake_1.MAX_AWAKE_SEC} s (4 h) a hold may last \u2014 ask again before it ends to keep them longer`,maxSec:awake_1.MAX_AWAKE_SEC});const a=s.services;if(a!==void 0&&(!Array.isArray(a)||a.length===0||!a.every(p=>typeof p=="string"&&p.length>0)))return c(t,400,{error:"services, when given, names one service or more"});const l=r.registry.get(o);if(!l)return c(t,404,{error:`no workspace '${o}' is registered`,workspaces:r.registry.keys()});const y=[];for(const p of a??[]){const _=b(o,p);if("error"in _)return c(t,404,_);y.includes(_.svc)||y.push(_.svc)}const i=y.length>0,w=!i&&s.warmOnly===!0;i||y.push(...w?l.services.filter(p=>p.decl.eager):l.services);const v=Date.now();if(n===0){for(const p of y)(p.awakeUntil??0)<=v||(p.awakeUntil=v,d.emitService?.(p,"info",`awake hold released: ${p.project}`,{kind:"service-awake",project:p.project,until:null,released:!0}));return A(l),c(t,202,{ok:!0,wsKey:o,forSec:0,released:!0,...w?{warmOnly:!0}:{},services:y.map(p=>R(p,v)),...(0,on_demand_1.runSummary)(l,g)})}const k=x(l,y,n,i,v);return(0,on_demand_1.isOnDemand)(l)&&(l.lastUseAt=v),A(l),c(t,202,{ok:!0,wsKey:o,forSec:n,until:k,...w?{warmOnly:!0}:{},services:y.map(p=>R(p,v)),...(0,on_demand_1.runSummary)(l,g)})}if(u==="/restart"&&(e.method==="POST"||e.method==="GET")){const s=e.method==="GET"?Object.fromEntries(new URL(e.url??"/","http://control").searchParams):(await readJsonBody(e)).value??{},o=typeof s.wsKey=="string"?s.wsKey:"",n=typeof s.service=="string"?s.service:"";if(!o||!n)return c(t,400,{error:"wsKey and service are required"});const a=b(o,n);if("error"in a)return c(t,404,a);const l=a.svc;if(e.method==="GET")return c(t,200,T(l));if(!d.restartService)return c(t,501,{error:"this gateway cannot restart a service"});(0,on_demand_1.touchStart)(r.registry,l);const y=typeof s.reason=="string"&&s.reason.trim()?s.reason.trim().slice(0,200):"asked for",i=d.restartService(l,{hard:s.hard===!0,reason:y});return"refused"in i?c(t,409,{error:i.refused,...T(l)}):c(t,202,{ok:!0,already:i.already,...T(l)})}if(e.method==="GET"&&u==="/identities"||e.method==="POST"&&u==="/act"){const s=e.method==="GET"?Object.fromEntries(new URL(e.url??"/","http://control").searchParams):(await readJsonBody(e)).value??{},o=typeof s.wsKey=="string"?s.wsKey:"";if(!o)return c(t,400,{error:"wsKey is required"});if(!r.registry.get(o)&&o!==r.wsKey)return c(t,404,{error:`no workspace '${o}' is registered`,workspaces:r.registry.keys()});if(!d.act)return c(t,501,{error:"acting as a signed-in user is turned off on this gateway (LENSMCP_GW_ACT=0)"});if(e.method==="GET")return c(t,200,{wsKey:o,identities:d.act.list(o)});const n=f(i=>typeof s[i]=="string"&&s[i].trim()?s[i].trim().slice(0,256):void 0,"pick"),a=n("user"),l=n("tenant"),y=d.act.mint(o,{...a?{user:a}:{},...l?{tenant:l}:{}});return"error"in y?c(t,404,{wsKey:o,...y}):c(t,200,{wsKey:o,...y})}if(e.method==="POST"&&u==="/register"){const{value:s,bytes:o}=await readJsonBody(e,CONTROL_BODY_BYTES+guest_graph_1.MAX_FORWARDED_GRAPH_BYTES),n=await j(s,o);return c(t,n.status,n.json)}if(e.method==="POST"&&u==="/unregister"){const s=(await readJsonBody(e)).value;if(!s.wsKey)return c(t,400,{error:"wsKey is required"});const o=(0,registration_guards_1.refuseUnregistration)(r.registry,{wsKey:s.wsKey,...s.root?{root:s.root}:{}},r.wsKey);if(o)return console.warn(`[gateway] refused to unregister '${s.wsKey}'${s.root?` for ${s.root}`:""}: ${o.error}`),c(t,409,o);const n=$(s.wsKey);return n&&(0,on_demand_1.isOnDemand)(n)&&D(n,"asked"),r.rebuildRoutes(),c(t,200,{ok:!0,removed:!!n,workspaces:r.registry.keys(),...n&&(0,on_demand_1.isOnDemand)(n)?{parked:!0}:{}})}c(t,404,{error:"not found"})}catch(u){if(u instanceof BodyTooLarge)return e.resume(),c(t,413,{error:u.message});c(t,500,{error:u.message})}})()});return N.listen(h,()=>{try{fs.chmodSync(h,384)}catch(e){console.warn(`[gateway] could not restrict ${h} to 0600:`,e.message)}}),{socketPath:h,async replay(){const e=Date.now(),{replay:t,gone:u,parked:s}=(0,guest_replay_1.guestsToReplay)(r.root,(0,guest_replay_1.readGuests)(),e),o={replayed:[],refused:[],gone:u.map(a=>a.wsKey),parked:s.map(a=>a.wsKey)};for(const a of u)(0,guest_replay_1.forgetGuest)(a.wsKey),console.log(`[gateway] not re-hosting '${a.wsKey}': ${a.root} is no longer a workspace \u2014 forgotten`);const n=f((a,l)=>{(0,guest_replay_1.forgetGuest)(a.wsKey);try{fs.rmSync(path.join(a.root,".lensmcp","registered.json"),{force:!0})}catch{}console.log(`[gateway] not re-hosting on-demand worktree '${a.wsKey}': ${l} \u2014 it stays parked (\`lensmcp instance run\` runs it)`)},"leaveParked");for(const a of s)n(a,a.runUntil?`its run ended at ${new Date(a.runUntil).toISOString()}`:"no run held it");for(const a of t)if(!r.registry.has(a.wsKey))try{const l=await j({wsKey:a.wsKey,root:a.root,projects:a.projects,...a.projectDependencies?{projectDependencies:a.projectDependencies}:{}},0);if(l.status===200){o.replayed.push(a.wsKey),console.log(`[gateway] re-hosted '${a.wsKey}' (${a.root}) \u2014 registered before this daemon restarted`);const y=r.registry.get(a.wsKey),i=(a.runUntil??0)-Date.now();a.onDemand&&y&&(0,on_demand_1.isOnDemand)(y)&&i>0&&(x(y,y.services.filter(w=>w.decl.eager),i/1e3,!1,Date.now()),A(y))}else a.onDemand&&l.json.code==="run-cap"?(o.parked.push(a.wsKey),n(a,`${l.json.max??"?"} on-demand worktrees already run (LENSMCP_WORKTREE_RUN_MAX)`)):(o.refused.push(a.wsKey),console.warn(`[gateway] could not re-host '${a.wsKey}' (${a.root}): ${JSON.stringify(l.json)} \u2014 \`lensmcp gateway start\` there`))}catch(l){o.refused.push(a.wsKey),console.warn(`[gateway] could not re-host '${a.wsKey}' (${a.root}): ${l.message}`)}return o},parkIdle(e=Date.now()){if(r.stopped?.())return[];const t=[];for(const u of r.registry.keys()){if(u===r.wsKey)continue;const s=r.registry.get(u);if(!s||!(0,on_demand_1.isOnDemand)(s))continue;const o=(0,on_demand_1.parkVerdict)(s,e,g);if(!o.ok)continue;const n=s.lastUseAt;$(u)&&(t.push(u),D(s,"idle",{parkAt:o.parkAt,...n!==void 0?{lastUseAt:n}:{}}))}return t.length>0&&r.rebuildRoutes(),t},close:f(()=>{N.close();try{fs.unlinkSync(h)}catch{}},"close")}}m(startControlServer,"startControlServer"),f(startControlServer,"startControlServer");
|
|
@@ -93,6 +93,18 @@ export interface ChildGraphOutput {
|
|
|
93
93
|
* for the admission to refuse.
|
|
94
94
|
*/
|
|
95
95
|
export declare function forwardedGraphInChild(root: string, env: NodeJS.ProcessEnv, script?: RunnerScript | undefined): Promise<ChildGraphOutput>;
|
|
96
|
+
/**
|
|
97
|
+
* The gateway's OWN workspace's graph, computed in a fresh child process: `graph-snapshot.js` in the same environment a
|
|
98
|
+
* guest's is computed in ({@link forwardedGraphInChild}, {@link guestGraphEnv} — no nx daemon, plugins in-process). The
|
|
99
|
+
* store falls back to it once a computation in the gateway's own process has failed (project-graph-store.ts
|
|
100
|
+
* `setFallback`): nx's state in a long-lived process can stay broken after one failure, and FoodGuard's did for four
|
|
101
|
+
* hours, until a restart (issues/closed/overseer-16). A fresh process starts clean every time.
|
|
102
|
+
*
|
|
103
|
+
* The admission a guest's graph passes refuses this root (the gateway reads its own graph itself), so the checks it
|
|
104
|
+
* still needs are made here: the size, the format, that it describes this root, and its shape. The store fingerprints
|
|
105
|
+
* the declaring files itself, by its own rule.
|
|
106
|
+
*/
|
|
107
|
+
export declare function ownGraphInFreshProcess(root: string, env?: NodeJS.ProcessEnv, run?: (root: string, env: NodeJS.ProcessEnv) => Promise<ChildGraphOutput>): Promise<ComputedProjectGraph>;
|
|
96
108
|
export interface GuestGraphStoreParams {
|
|
97
109
|
/** The registered workspace's key — for the log lines. */
|
|
98
110
|
wsKey: string;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`).pop();
|
|
1
|
+
"use strict";var R=Object.defineProperty;var f=(e,r)=>R(e,"name",{value:r,configurable:!0});var _=Object.defineProperty,d=f((e,r)=>_(e,"name",{value:r,configurable:!0}),"d");Object.defineProperty(exports,"__esModule",{value:!0}),exports.GUEST_GRAPH_RETRY_MS=exports.MAX_FORWARDED_PROJECTS=exports.MAX_FORWARDED_GRAPH_BYTES=exports.FORWARDED_GRAPH_FORMAT=void 0,exports.ownedByThisUser=ownedByThisUser,exports.admitForwardedGraph=admitForwardedGraph,exports.compactSourceMaps=compactSourceMaps,exports.projectsOnly=projectsOnly,exports.snapshotWorkspaceGraph=snapshotWorkspaceGraph,exports.graphSnapshotScript=graphSnapshotScript,exports.guestGraphEnv=guestGraphEnv,exports.forwardedGraphInChild=forwardedGraphInChild,exports.ownGraphInFreshProcess=ownGraphInFreshProcess,exports.createGuestGraphStore=createGuestGraphStore;const tslib_1=require("tslib"),node_child_process_1=require("node:child_process"),fs=tslib_1.__importStar(require("node:fs")),os=tslib_1.__importStar(require("node:os")),path=tslib_1.__importStar(require("node:path")),pod_env_1=require("./pod-env"),project_graph_store_1=require("./project-graph-store"),registration_guards_1=require("./registration-guards");exports.FORWARDED_GRAPH_FORMAT=1,exports.MAX_FORWARDED_GRAPH_BYTES=8*1024*1024,exports.MAX_FORWARDED_PROJECTS=2e4,exports.GUEST_GRAPH_RETRY_MS=6e4;const GUEST_GRAPH_TIMEOUT_MS=12e4,SIGNATURE=/^(?:-|\?|\d+(?:\.\d+)?:\d+:\d+)$/;function megabytes(e){return`${(e/(1024*1024)).toFixed(1)} MB`}f(megabytes,"megabytes"),d(megabytes,"megabytes");const isRecord=d(e=>!!e&&typeof e=="object"&&!Array.isArray(e),"isRecord");function insideWorkspace(e){return e===""||path.isAbsolute(e)||/^[a-zA-Z]:/.test(e)?!1:!path.posix.normalize(e.replace(/\\/g,"/")).split("/").includes("..")}f(insideWorkspace,"insideWorkspace"),d(insideWorkspace,"insideWorkspace");function ownedByThisUser(e){const r=fs.statSync(e,{throwIfNoEntry:!1});if(!r?.isDirectory())return!1;if(typeof process.getuid!="function")return!0;const o=process.getuid();return r.uid===o||o===0&&r.uid===Number(process.env.SUDO_UID)}f(ownedByThisUser,"ownedByThisUser"),d(ownedByThisUser,"ownedByThisUser");function relativeDeclaringFiles(e,r){return(0,project_graph_store_1.declaringFiles)(e,r).map(o=>path.relative(e,o).split(path.sep).join("/"))}f(relativeDeclaringFiles,"relativeDeclaringFiles"),d(relativeDeclaringFiles,"relativeDeclaringFiles");function shapeProblem(e){if(!isRecord(e)||!isRecord(e.nodes)||!isRecord(e.dependencies))return"it has no `nodes` and `dependencies`";const r=e.nodes,o=Object.keys(r);if(o.length>exports.MAX_FORWARDED_PROJECTS)return`it names ${o.length} projects (at most ${exports.MAX_FORWARDED_PROJECTS})`;for(const t of o){const s=r[t];if(!isRecord(s)||s.name!==t||typeof s.type!="string"||!isRecord(s.data))return`project '${t}' is not a project node`;const n=s.data.root;if(typeof n!="string"||!insideWorkspace(n))return`project '${t}' has a root outside the workspace (${String(n)})`;const a=s.data.targets;if(a!==void 0&&(!isRecord(a)||!Object.values(a).every(isRecord)))return`project '${t}' has malformed targets`}for(const[t,s]of Object.entries(e.dependencies)){if(!(t in r)||!Array.isArray(s))return`the dependencies of '${t}' are not a known project's`;for(const n of s)if(!isRecord(n)||n.source!==t||typeof n.target!="string"||!(n.target in r)||typeof n.type!="string")return`a dependency of '${t}' is malformed`}}f(shapeProblem,"shapeProblem"),d(shapeProblem,"shapeProblem");function sourceMapsProblem(e){if(e!==void 0){if(!isRecord(e))return"its source maps are not a map";for(const[r,o]of Object.entries(e)){if(!isRecord(o))return`the source map of ${r} is malformed`;for(const t of Object.values(o))if(!Array.isArray(t)||t.length!==2||t[0]!==null&&typeof t[0]!="string"||typeof t[1]!="string")return`the source map of ${r} is malformed`}}}f(sourceMapsProblem,"sourceMapsProblem"),d(sourceMapsProblem,"sourceMapsProblem");function admitForwardedGraph(e,r){const o=d(p=>({refused:p}),"refuse");if(r.bytes>exports.MAX_FORWARDED_GRAPH_BYTES)return o(`${megabytes(r.bytes)} is over the ${megabytes(exports.MAX_FORWARDED_GRAPH_BYTES)} limit`);if(!isRecord(e))return o("it is not a project graph");if(e.format!==exports.FORWARDED_GRAPH_FORMAT)return o(`its format is ${String(e.format)}, and this gateway reads ${exports.FORWARDED_GRAPH_FORMAT}`);const t=e.root;if(typeof t!="string"||!path.isAbsolute(t))return o("it does not say which workspace it describes");if(!(0,registration_guards_1.sameRoot)(t,r.root))return o(`it describes ${t}, not the registering workspace ${r.root}`);if((0,registration_guards_1.sameRoot)(r.root,r.daemonRoot))return o(`${r.root} is the gateway's own workspace \u2014 the gateway reads that graph itself`);if(r.otherRoots.some(p=>(0,registration_guards_1.sameRoot)(p,r.root)))return o(`${r.root} is registered under another key`);if(!ownedByThisUser(r.root))return o(`${r.root} is not a directory this user owns`);const s=e.startedAt;if(typeof s!="number"||!Number.isFinite(s))return o("it does not say when it was computed");const n=shapeProblem(e.projectGraph)??sourceMapsProblem(e.sourceMaps);if(n)return o(n);const a=e.projectGraph,i=e.files;if(!isRecord(i))return o("it carries no fingerprint of its declaring files");const c=(0,registration_guards_1.canonicalRoot)(r.root),h=relativeDeclaringFiles(c,a),u=Object.keys(i),l=h.filter(p=>!(p in i));return l.length>0||u.length!==h.length?o(`its fingerprint does not cover exactly the files that declare it${l.length>0?` (no ${l[0]})`:""}`):Object.values(i).every(p=>typeof p=="string"&&SIGNATURE.test(p))?{snapshot:{root:c,startedAt:s,files:new Map(h.map(p=>[path.join(c,p),i[p]])),projectGraph:{nodes:a.nodes,dependencies:a.dependencies,externalNodes:{}},...e.sourceMaps!==void 0?{sourceMaps:e.sourceMaps}:{}}}:o("its fingerprint is malformed")}f(admitForwardedGraph,"admitForwardedGraph"),d(admitForwardedGraph,"admitForwardedGraph");function compactSourceMaps(e,r){const o={};for(const t of Object.values(e.nodes)){const s=r[t.data.root];if(!s)continue;const n=new Set;for(const i of Object.keys(t.data.targets??{})){const c=`targets.${i}`,h=new Set;for(const[u,l]of Object.entries(s)){if(u!==c&&!u.startsWith(`${c}.`))continue;const p=JSON.stringify(l);h.has(p)||(h.add(p),n.add(u))}}const a={};for(const[i,c]of Object.entries(s))n.has(i)&&(a[i]=c);o[t.data.root]=a}return o}f(compactSourceMaps,"compactSourceMaps"),d(compactSourceMaps,"compactSourceMaps");function projectsOnly(e){const r={};for(const[o,t]of Object.entries(e.dependencies))o in e.nodes&&(r[o]=t.filter(s=>s.target in e.nodes));return{nodes:e.nodes,dependencies:r}}f(projectsOnly,"projectsOnly"),d(projectsOnly,"projectsOnly");async function snapshotWorkspaceGraph(e,r=()=>(0,project_graph_store_1.computeProjectGraphInProcess)(e)){const o=Date.now(),t=(0,project_graph_store_1.filesystemNow)(),s=await r(),n=projectsOnly(s.projectGraph),a={};for(const i of(0,project_graph_store_1.declaringFiles)(e,s.projectGraph)){const c=fs.statSync(i,{throwIfNoEntry:!1});a[path.relative(e,i).split(path.sep).join("/")]=c&&c.mtimeMs>t?"?":(0,project_graph_store_1.statSignature)(i)}return{format:exports.FORWARDED_GRAPH_FORMAT,root:e,startedAt:o,projectGraph:n,...s.sourceMaps?{sourceMaps:compactSourceMaps(n,s.sourceMaps)}:{},files:a}}f(snapshotWorkspaceGraph,"snapshotWorkspaceGraph"),d(snapshotWorkspaceGraph,"snapshotWorkspaceGraph");function graphSnapshotScript(e=path.join(__dirname,"../../..")){const r=path.join(e,"graph-snapshot.js");if(fs.existsSync(r))return{path:r,execArgv:[]};const o=path.join(e,"graph-snapshot.ts");if(fs.existsSync(o))try{return{path:o,execArgv:["--require",require.resolve("@swc-node/register")]}}catch{return}}f(graphSnapshotScript,"graphSnapshotScript"),d(graphSnapshotScript,"graphSnapshotScript");function guestGraphEnv(e,r,o){const t={...(0,pod_env_1.podBaseEnv)(e,r,o)};for(const s of Object.keys(t))(s.startsWith("NX_TASK_")||["NX_WORKSPACE_ROOT","NX_WORKSPACE_ROOT_PATH","NX_WORKSPACE_DATA_DIRECTORY","NX_PROJECT_GRAPH_CACHE_DIRECTORY"].includes(s))&&delete t[s];return t.NX_DAEMON="false",t.NX_ISOLATE_PLUGINS="false",t}f(guestGraphEnv,"guestGraphEnv"),d(guestGraphEnv,"guestGraphEnv");function forwardedGraphInChild(e,r,o=graphSnapshotScript()){if(!o)return Promise.reject(new Error("graph-snapshot.js is missing from @lensmcp/cluster"));const t=fs.mkdtempSync(path.join(os.tmpdir(),"lensmcp-graph-")),s=path.join(t,"graph.json");return new Promise((n,a)=>{let i="";const c=(0,node_child_process_1.spawn)(process.execPath,[...o.execArgv,o.path,s],{cwd:e,env:r,stdio:["ignore","ignore","pipe"]});c.stderr?.on("data",u=>{i.length<4096&&(i+=u.toString())});const h=setTimeout(()=>c.kill("SIGKILL"),GUEST_GRAPH_TIMEOUT_MS);h.unref(),c.on("error",u=>{clearTimeout(h),a(u)}),c.on("exit",(u,l)=>{if(clearTimeout(h),u!==0){const p=i.trim().split(`
|
|
2
|
+
`).pop();a(new Error(`the graph computation in ${e} exited ${l??u}${p?` \u2014 ${p}`:""}`));return}try{const p=fs.statSync(s).size;n({bytes:p,graph:p>exports.MAX_FORWARDED_GRAPH_BYTES?void 0:JSON.parse(fs.readFileSync(s,"utf8"))})}catch(p){a(p)}})}).finally(()=>fs.rmSync(t,{recursive:!0,force:!0}))}f(forwardedGraphInChild,"forwardedGraphInChild"),d(forwardedGraphInChild,"forwardedGraphInChild");async function ownGraphInFreshProcess(e,r=process.env,o=(t,s)=>forwardedGraphInChild(t,s)){const{graph:t,bytes:s}=await o(e,guestGraphEnv(r,e,e)),n=d(h=>new Error(`the project graph computed in a fresh process was refused: ${h}`),"refused");if(s>exports.MAX_FORWARDED_GRAPH_BYTES)throw n(`${megabytes(s)} is over the ${megabytes(exports.MAX_FORWARDED_GRAPH_BYTES)} limit`);if(!isRecord(t))throw n("it is not a project graph");if(t.format!==exports.FORWARDED_GRAPH_FORMAT)throw n(`its format is ${String(t.format)}, and this gateway reads ${exports.FORWARDED_GRAPH_FORMAT}`);const a=t.root;if(typeof a!="string"||!(0,registration_guards_1.sameRoot)(a,e))throw n(`it describes ${String(a)}, not ${e}`);const i=shapeProblem(t.projectGraph)??sourceMapsProblem(t.sourceMaps);if(i)throw n(i);const c=t.projectGraph;return{projectGraph:{nodes:c.nodes,dependencies:c.dependencies,externalNodes:{}},...t.sourceMaps!==void 0?{sourceMaps:t.sourceMaps}:{}}}f(ownGraphInFreshProcess,"ownGraphInFreshProcess"),d(ownGraphInFreshProcess,"ownGraphInFreshProcess");function createGuestGraphStore(e,r=process.env){const{wsKey:o,admission:t,context:s}=e,n=(0,registration_guards_1.canonicalRoot)(e.root),a=e.compute??(()=>forwardedGraphInChild(n,guestGraphEnv(r,s.daemonRoot,n))),i=t===void 0?"its registration forwarded none":t.refused!==void 0?`the project graph its registration forwarded was refused: ${t.refused}`:void 0;return(0,project_graph_store_1.createProjectGraphStore)(n,async()=>{const{graph:c,bytes:h}=await a(),u=admitForwardedGraph(c,{...s,bytes:h});if(u.refused!==void 0)throw new Error(`the computed project graph was refused: ${u.refused}`);return{projectGraph:u.snapshot.projectGraph,...u.snapshot.sourceMaps?{sourceMaps:u.snapshot.sourceMaps}:{}}},{...t?.snapshot?{seed:t.snapshot}:{},...i?{error:i}:{},retryAfterFailureMs:exports.GUEST_GRAPH_RETRY_MS,onRefreshed:d(c=>console.log(`[gateway] project graph of '${o}' (${n}) refreshed \u2014 ${Object.keys(c.projectGraph.nodes).length} projects; its services start through the serve runner again`),"onRefreshed")})}f(createGuestGraphStore,"createGuestGraphStore"),d(createGuestGraphStore,"createGuestGraphStore");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var q=Object.defineProperty;var m=(u,n)=>q(u,"name",{value:n,configurable:!0});var T=Object.defineProperty,l=m((u,n)=>T(u,"name",{value:n,configurable:!0}),"l");Object.defineProperty(exports,"__esModule",{value:!0}),exports.mayBeParkedHost=mayBeParkedHost,exports.createHandler=createHandler;const manifest_1=require("../manifest"),service_keys_1=require("./service-keys"),gateway_errors_1=require("../gateway-errors"),discovery_1=require("./discovery"),edge_1=require("./edge"),observability_1=require("./observability"),chooser_1=require("./chooser"),on_demand_1=require("./on-demand");function mayBeParkedHost(u){return!u||!u.host||u.host.startsWith("*.")}m(mayBeParkedHost,"mayBeParkedHost"),l(mayBeParkedHost,"mayBeParkedHost");function createHandler(u){const{rt:n,obs:p,auth:g,proxy:H,hooks:c}=u,E=u.parkedHosts??(0,on_demand_1.createParkedHostLookup)({registry:l(()=>n.registry,"registry")}),k=l(e=>(e.headers.host||"").split(":")[0],"hostOf"),S=l(()=>(n.parkedDashboards?.list()??[]).flatMap(e=>e.base?[{key:e.key,root:e.root,base:e.base,name:e.name,baseKey:e.baseKey,apex:e.apex??""}]:[]),"parkedChooserEntries"),R=l((e,r)=>{const t=n.parkedDashboards?.list().find(s=>s.key===r);if(!t?.host||!t.base)return;const h=(e.headers.host||"").split(":")[1];return`${n.https?"https":"http"}://${t.host}${h?`:${h}`:""}${t.base}/`},"parkedDashboardUrl"),x=l((e,r)=>{if((0,edge_1.cors)(e,r,n.routes),e.method==="OPTIONS"){r.writeHead(204,{"access-control-allow-methods":edge_1.PREFLIGHT_METHODS_NOROUTE,"access-control-allow-headers":String(e.headers["access-control-request-headers"]??"*"),"access-control-max-age":edge_1.PREFLIGHT_MAX_AGE}),r.end();return}const t=(e.headers.host||"").split(":")[0],h=n.routes.filter(o=>o.host&&(0,manifest_1.hostMatches)(o.host,t)&&o.prefix),s=(e.url??"/").split("?")[0];if((s==="/"||s==="/index.html"||s==="")&&n.routes.some(o=>o.host&&(0,manifest_1.hostMatches)(o.host,t)&&o.project===observability_1.LENS_DASHBOARD_PROJECT)){(0,chooser_1.serveChooser)(r,n.wsKey,e,S());return}if(h.length>0&&(s==="/health"||s==="/healthz")){const o=h.map(d=>({project:d.project,prefix:d.prefix,pods:d.pool?((0,discovery_1.pickSock)(d.pool,0),d.pool.socks.length):void 0,state:d.svc?.state??(d.target?"up":"unknown")})),f=o.every(d=>d.state!=="down"||!0);r.writeHead(f?200:503,{"content-type":"application/json"}),r.end(JSON.stringify({status:"ok",host:t,services:o},null,2));return}if(h.length>0&&s==="/.well-known/services"){r.writeHead(200,{"content-type":"application/json"}),r.end(JSON.stringify({host:t,services:h.map(o=>({prefix:o.prefix,project:o.project,internal:!!o.internal}))},null,2));return}(0,edge_1.sendError)(r,e,404,"not_found",h.length>0?`No service mounted at ${s}. Mounted on ${t}: ${[...new Set(h.map(o=>o.prefix))].join(", ")} (+ /health, /.well-known/services)`:"No gateway route for this hostname.")},"handleNoRoute"),O=l(async(e,r)=>{if(!e.headers.host){const o=e.authority??e.headers[":authority"];o&&(e.headers.host=o)}(0,edge_1.stripOwnedHeaders)(e);let t=p.beginTrace(e);const h=Date.now();(0,gateway_errors_1.ensureRequestId)(e),t&&(p.traceStep(t,"received",{host:t.host,method:t.method,url:t.url}),e.__lensmcpTrace=t);const s=c.httpContext(e,r,t);try{const o=e.url??"/",f=(0,edge_1.canonicalize)(o);if(f===void 0){p.traceStep(t,"bad-path",{}),p.finishTrace(t,"gateway",400),(0,edge_1.sendError)(r,e,400,"bad_request","Bad Request");return}const d=f.policy,_=f.path+f.query;if(_!==o&&(0,edge_1.rememberRawTarget)(e,o),e.url=_,(0,edge_1.resolveClientIp)(n,e),c.has("onRequest")&&(await c.run("onRequest",s),s.responded()))return;const a=(0,manifest_1.matchRoute)(n.routes,k(e),d+f.query);if(mayBeParkedHost(a)){const i=E.match(k(e));if(i){const w=(0,on_demand_1.parkedAnswer)(i,String(e.headers.accept??""),R(e,i.key));p.traceStep(t,"worktree-parked",{worktree:i.name}),p.finishTrace(t,"gateway",w.status),r.writeHead(w.status,w.headers),r.end(w.body);return}}if(!a){x(e,r);return}s.route=a,(0,on_demand_1.touchRun)(n.registry,a,r);const y=p.startHeadlessFlow(e,a,t,h);if(y!==t&&(t=y,s.trace=y,e.__lensmcpTrace=y),p.traceStep(t,"route-match",{project:a.project,...a.prefix?{prefix:a.prefix}:{},...a.host?{routeHost:a.host}:{},...a.internal?{internal:!0}:{}}),e.method==="OPTIONS"){(0,edge_1.cors)(e,r,n.routes),r.writeHead(204,{"access-control-allow-methods":edge_1.PREFLIGHT_METHODS_ROUTED,"access-control-allow-headers":String(e.headers["access-control-request-headers"]??"*"),"access-control-max-age":edge_1.PREFLIGHT_MAX_AGE}),r.end();return}if((0,edge_1.cors)(e,r,n.routes),c.has("beforeAuth")&&(await c.run("beforeAuth",s),s.responded()))return;if(a.internal){const i=g.internal(e,a,t);if(!i.ok){p.finishTrace(t,a.project,i.status,void 0,a),(0,edge_1.sendError)(r,e,i.status,i.reason,i.detail);return}s.caller=i.caller}else{const i=g.public(e,a,t,d);if(!i.ok){p.finishTrace(t,a.project,i.status,void 0,a),(0,edge_1.sendError)(r,e,i.status,i.reason,i.detail);return}if(s.claims=i.claims,c.has("afterAuth")&&(await c.run("afterAuth",s),s.responded()))return}const v=a.pool?n.serviceKeys[(0,service_keys_1.serviceKeyId)(a.svc?.wsKey,a.project)]:void 0;if(v&&(e.headers["x-internal-token"]=v),(0,edge_1.stampForwardingHeaders)(n,e),c.has("beforeForward")&&(await c.run("beforeForward",s),s.responded()))return;c.has("onResponse")&&r.on("close",()=>{s.status=r.statusCode??0,c.run("onResponse",s)});const b=a.project===observability_1.LENS_DASHBOARD_PROJECT&&a.target?n.hostedDashboards?.get(a.target):void 0;b&&await b.serve(r),H.forward(a,e,r)}catch(o){s.error=o,console.error(`[gateway] ${new Date().toISOString()} pipeline error traceId=${(0,gateway_errors_1.ensureRequestId)(e)}: ${o?.stack??String(o)}`),c.has("onError")&&await c.run("onError",s),s.responded()||(0,edge_1.sendError)(r,e,500,"internal","Internal gateway error.")}},"runPipeline");return(e,r)=>{O(e,r)}}m(createHandler,"createHandler"),l(createHandler,"createHandler");
|
|
@@ -69,6 +69,19 @@ export interface LensChildren {
|
|
|
69
69
|
* distinct port, append its `lensmcp.local/<key>` route to its fragment. Returns a reaper (kills the
|
|
70
70
|
* child WITHOUT auto-heal respawn) for the daemon to call on unregister — or undefined if no bundle. */
|
|
71
71
|
hostWorkspaceDashboard(fragment: WorkspaceFragment): Promise<(() => void) | undefined>;
|
|
72
|
+
/** Host a PARKED on-demand worktree's dashboard (parked-dashboards.ts): a standalone `lensmcp.local/<key>` route, its
|
|
73
|
+
* dashboard started only by a request for it, in the worktree's root and on its bus. Where it answers and a reaper —
|
|
74
|
+
* or undefined: no bundle, `dashboard: false`, or a root whose config is not that instance's. */
|
|
75
|
+
hostParkedDashboard(w: {
|
|
76
|
+
key: string;
|
|
77
|
+
name: string;
|
|
78
|
+
baseKey: string;
|
|
79
|
+
root: string;
|
|
80
|
+
}): Promise<{
|
|
81
|
+
host: string;
|
|
82
|
+
base: string;
|
|
83
|
+
reap: () => void;
|
|
84
|
+
} | undefined>;
|
|
72
85
|
/** Host a REGISTERED workspace's `lens:true` FRONTEND apps (completes model-A "the daemon hosts
|
|
73
86
|
* everything"): spawn each app's vite (+ capture) in the workspace's OWN root + event bus, on a
|
|
74
87
|
* collision-safe port, and point its route target at that port. Returns a reaper for unregister. */
|