@lensmcp/cluster 1.25.54 → 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.d.ts +14 -0
- package/executors/gateway/runtime/control.js +2 -2
- package/executors/gateway/runtime/discovery.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/guest-replay.d.ts +12 -2
- package/executors/gateway/runtime/guest-replay.js +2 -2
- package/executors/gateway/runtime/handler.d.ts +9 -1
- package/executors/gateway/runtime/handler.js +1 -1
- package/executors/gateway/runtime/instance.d.ts +9 -0
- package/executors/gateway/runtime/instance.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.d.ts +11 -2
- package/executors/gateway/runtime/lifecycle.js +4 -3
- package/executors/gateway/runtime/on-demand.d.ts +127 -0
- package/executors/gateway/runtime/on-demand.js +25 -0
- 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 +18 -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 +18 -0
- package/executors/gateway/runtime/types.js +1 -1
- package/executors/gateway/runtime/upgrade.d.ts +3 -0
- package/executors/gateway/runtime/upgrade.js +1 -1
- package/executors/gateway/runtime/warm-start.d.ts +19 -5
- package/executors/gateway/runtime/warm-start.js +1 -1
- package/package.json +4 -4
|
@@ -0,0 +1,25 @@
|
|
|
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>
|
|
3
|
+
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
|
|
4
|
+
<title>${c} is parked</title>
|
|
5
|
+
<style>
|
|
6
|
+
:root{--bg:#f7f7f5;--fg:#1d1d1b;--muted:#6b6b66;--card:#fff;--line:#e3e3de;--code:#f0f0ec}
|
|
7
|
+
@media (prefers-color-scheme: dark){:root{--bg:#141413;--fg:#ecece8;--muted:#9a9a93;--card:#1d1d1b;--line:#30302d;--code:#262624}}
|
|
8
|
+
body{margin:0;background:var(--bg);color:var(--fg);font:15px/1.55 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}
|
|
9
|
+
main{max-width:560px;margin:12vh auto;padding:0 16px}
|
|
10
|
+
.card{background:var(--card);border:1px solid var(--line);border-radius:10px;padding:24px}
|
|
11
|
+
h1{font-size:20px;margin:0 0 8px}p{margin:8px 0;color:var(--muted)}
|
|
12
|
+
code{background:var(--code);border-radius:4px;padding:2px 6px;font:13px ui-monospace,SFMono-Regular,Menlo,monospace;color:var(--fg)}
|
|
13
|
+
ul{padding-left:18px;margin:12px 0 0}li{margin:6px 0}a{color:var(--fg)}
|
|
14
|
+
</style></head>
|
|
15
|
+
<body><main><div class="card">
|
|
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>
|
|
19
|
+
<ul>
|
|
20
|
+
<li>an agent: <code>worktree_run { name: "${c}" }</code></li>
|
|
21
|
+
<li>a terminal: <code>lensmcp instance run ${c}</code></li>
|
|
22
|
+
<li>the dashboard: <strong>Run</strong> on its worktree</li>
|
|
23
|
+
</ul>
|
|
24
|
+
</div></main></body></html>
|
|
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");
|
|
@@ -16,10 +16,22 @@ export interface WorkspaceFragment {
|
|
|
16
16
|
instance?: InstanceRouting;
|
|
17
17
|
/** Its own gateway target's `middleware` (relative to `root`), run on its routes (workspace-middleware.ts). */
|
|
18
18
|
middleware?: string;
|
|
19
|
+
/**
|
|
20
|
+
* An ON-DEMAND instance's last use (ms, on-demand.ts): its registration, a request to one of its app's own hosts (a
|
|
21
|
+
* pod, a frontend Vite, a TCP route — not its hosted dashboard, not an `internal.*` hop) and a start of one of its
|
|
22
|
+
* services. The park clock counts from it.
|
|
23
|
+
*/
|
|
24
|
+
lastUseAt?: number;
|
|
19
25
|
}
|
|
20
26
|
/** A live map of `wsKey → fragment`; `merged()` is the flat table the pipeline matches against. */
|
|
21
27
|
export declare class RouteRegistry {
|
|
22
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;
|
|
23
35
|
/** Register (or REPLACE) a workspace's fragment. Idempotent by `wsKey`. */
|
|
24
36
|
register(fragment: WorkspaceFragment): void;
|
|
25
37
|
/** Drop a workspace's fragment; returns it (so the caller can reap its services/dashboard). */
|
|
@@ -33,9 +45,14 @@ export declare class RouteRegistry {
|
|
|
33
45
|
appendRoutes(wsKey: string, routes: Route[]): void;
|
|
34
46
|
/** Every registered workspace's pod-service controllers, flattened (the daemon's full lifecycle set). */
|
|
35
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[];
|
|
36
53
|
/** The merged, specificity-sorted route table (host+path ▸ host ▸ per-apex catch-all). A NEW array each
|
|
37
54
|
* call — the caller rebuilds `rt.routes` in place from it so the pipeline (which reads `rt.routes` fresh
|
|
38
|
-
* per request) picks the change up atomically. */
|
|
55
|
+
* per request) picks the change up atomically. The standalone routes join it. */
|
|
39
56
|
merged(): Route[];
|
|
40
57
|
}
|
|
41
58
|
/** Rebuild `routes` IN PLACE from the registry (mutate the SAME array the request pipeline holds, so a
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var o=Object.defineProperty;var n=(s,e)=>o(s,"name",{value:e,configurable:!0});var a=Object.defineProperty,r=n((s,e)=>a(s,"name",{value:e,configurable:!0}),"r");Object.defineProperty(exports,"__esModule",{value:!0}),exports.RouteRegistry=void 0,exports.rebuildRoutesInPlace=rebuildRoutesInPlace;const manifest_1=require("../manifest");class RouteRegistry{static{n(this,"RouteRegistry")}static{r(this,"RouteRegistry")}constructor(){this.fragments=new Map,this.standalone=new Map}register(e){this.fragments.set(e.wsKey,e)}unregister(e){const t=this.fragments.get(e);return this.fragments.delete(e),t}has(e){return this.fragments.has(e)}get(e){return this.fragments.get(e)}keys(){return[...this.fragments.keys()]}size(){return this.fragments.size}appendRoutes(e,t){const i=this.fragments.get(e);i&&i.routes.push(...t)}allServices(){return[...this.fragments.values()].flatMap(e=>e.services)}setStandalone(e,t){this.standalone.set(e,t)}dropStandalone(e,t){return t&&this.standalone.get(e)!==t?!1:this.standalone.delete(e)}standaloneIds(){return[...this.standalone.keys()]}merged(){const e=[...[...this.fragments.values()].flatMap(t=>t.routes),...[...this.standalone.values()].flat()];return(0,manifest_1.sortBySpecificity)(e),e}}exports.RouteRegistry=RouteRegistry;function rebuildRoutesInPlace(s,e){const t=e.merged();s.length=0,s.push(...t)}n(rebuildRoutesInPlace,"rebuildRoutesInPlace"),r(rebuildRoutesInPlace,"rebuildRoutesInPlace");
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
"use strict";var Te=Object.defineProperty;var T=(r,t)=>Te(r,"name",{value:t,configurable:!0});var Ae=Object.defineProperty,n=T((r,t)=>Ae(r,"name",{value:t,configurable:!0}),"n");Object.defineProperty(exports,"__esModule",{value:!0}),exports.GATEWAY_H2_IDLE_SESSION_MS_DEFAULT=exports.GATEWAY_MAX_H2_STREAMS_DEFAULT=exports.GATEWAY_MAX_H2_SESSIONS_DEFAULT=exports.GATEWAY_MAX_CONNECTIONS_DEFAULT=exports.BENIGN_SOCKET_ERRNOS=void 0,exports.buildEdgeVerifierPool=buildEdgeVerifierPool,exports.edgeKeyWait=edgeKeyWait,exports.withBuiltinHooks=withBuiltinHooks,exports.classifyClientError=classifyClientError,exports.createClientErrorLogGate=createClientErrorLogGate,exports.retirePreviousWorkspace=retirePreviousWorkspace,exports.resolveMaxConnections=resolveMaxConnections,exports.h2BudgetFromEnv=h2BudgetFromEnv,exports.createH2Governor=createH2Governor,exports.startGateway=startGateway;const tslib_1=require("tslib"),http=tslib_1.__importStar(require("node:http")),path=tslib_1.__importStar(require("node:path")),discovery_1=require("./discovery"),scope_1=require("./scope"),route_registry_1=require("./route-registry"),act_1=require("./act"),control_1=require("./control"),workspace_middleware_1=require("./workspace-middleware"),workspace_registry_1=require("./workspace-registry"),service_keys_1=require("./service-keys"),source_poller_1=require("./source-poller"),client_ip_1=require("../client-ip"),workspace_log_1=require("./workspace-log"),own_log_1=require("./own-log"),observability_1=require("./observability"),lifecycle_1=require("./lifecycle"),process_names_1=require("./process-names"),project_graph_store_1=require("./project-graph-store"),serve_launch_1=require("./serve-launch"),process_name_1=require("../../../process-name"),protocol_1=require("../../../shared-build/protocol"),lens_children_1=require("./lens-children"),proxy_1=require("./proxy"),auth_1=require("./auth"),hooks_1=require("./hooks"),handler_1=require("./handler"),upgrade_1=require("./upgrade"),jwks_verify_1=require("../jwks-verify"),gateway_errors_1=require("../gateway-errors"),workspace_auth_1=require("../workspace-auth"),manifest_1=require("../manifest"),edge_1=require("./edge"),warm_start_1=require("./warm-start"),types_1=require("./types");function insecureLocalFetch(r,t){return new Promise((l,i)=>{const a=(r.startsWith("https:")?require("node:https"):require("node:http")).request(r,{method:"GET",headers:t?.headers,rejectUnauthorized:!1},h=>{const y=[];h.on("data",g=>y.push(g)),h.on("error",i),h.on("end",()=>{const g=h.statusCode??0,A=Buffer.concat(y).toString("utf8");l({ok:g>=200&&g<300,status:g,json:n(async()=>JSON.parse(A),"json")})})});a.on("error",i),t?.signal?.addEventListener("abort",()=>a.destroy(new Error(`JWKS ${r} \u2192 aborted`)),{once:!0}),a.end()})}T(insecureLocalFetch,"insecureLocalFetch"),n(insecureLocalFetch,"insecureLocalFetch");function buildEdgeVerifierPool(r,t={}){const l=process.env.LENSMCP_GW_JWKS_URL,i=process.env.LENSMCP_GW_JWT_ISS,a=new Map;let h,y=!1;const g=n((o,u)=>{console.log(`[gateway] edge JWT: verifying via JWKS ${o}${u}`);const p=(0,jwks_verify_1.createJwksVerifier)({jwksUrl:o,...i?{issuer:i}:{},fetchImpl:t.fetchImpl??insecureLocalFetch});let w=!1;return p.warm({...t.warm,onError:n((M,b,x)=>{w=!0,b===1&&x!==void 0&&console.warn(`[gateway] edge JWKS ${o} not loaded yet (${M.message}) \u2014 retrying in the background`),x===void 0&&console.warn(`[gateway] edge JWKS ${o} still not loaded after ${b} attempts (${M.message}) \u2014 the first token that needs it fetches it`)},"onError")}).then(M=>{M&&w&&console.log(`[gateway] edge JWKS ${o} loaded`)}),p},"make"),A=n(o=>{let u=a.get(o);return u||(u=g(`https://auth.${o}/jwks.json`,` (auto-derived for apex ${o})`),a.set(o,u)),u},"forApex");return{for(o){if(l)return h??=g(l,"");const u=o.split(":")[0].toLowerCase();let p;for(const w of idpApexes(r()))(u===w||u.endsWith(`.${w}`))&&(!p||w.length>p.length)&&(p=w);return p?A(p):void 0},warm(){if(!y){if(l){h??=g(l,"");return}for(const o of idpApexes(r()))A(o)}},stop(){y=!0,h?.stop();for(const o of a.values())o.stop()}}}T(buildEdgeVerifierPool,"buildEdgeVerifierPool"),n(buildEdgeVerifierPool,"buildEdgeVerifierPool");function idpApexes(r){const t=new Set;for(const l of r){const i=l.host;typeof i!="string"||!/^auth\./.test(i)||i.startsWith("internal.")||t.add(i.slice(5))}return t}T(idpApexes,"idpApexes"),n(idpApexes,"idpApexes");function edgeKeyWait(r){return async t=>{const l=t.route;if(!l?.auth||l.internal)return;const{req:i}=t,a=Array.isArray(i.headers.authorization)?i.headers.authorization[0]:i.headers.authorization,h=String(a??""),y=(0,workspace_auth_1.requestToken)(i)??(h.startsWith("Bearer ")?h.slice(7):void 0);if(!y)return;const g=i.url??"/";if((0,manifest_1.authRuleFor)(l.auth,(0,edge_1.canonicalPath)(g)??g.split("?")[0],(i.method??"GET").toUpperCase()).mode!=="jwt")return;const A=String(i.headers.host??"").split(":")[0].toLowerCase();await r.for(A)?.awaitKey(y)}}T(edgeKeyWait,"edgeKeyWait"),n(edgeKeyWait,"edgeKeyWait");function withBuiltinHooks(r,t){return{...r,beforeAuth:[...r.beforeAuth??[],...t.preAuth?[t.preAuth]:[],t.keyWait],afterAuth:[t.middleware,...r.afterAuth??[]],beforeForward:[...t.beforeForward?[t.beforeForward]:[],...r.beforeForward??[]]}}T(withBuiltinHooks,"withBuiltinHooks"),n(withBuiltinHooks,"withBuiltinHooks"),exports.BENIGN_SOCKET_ERRNOS=new Set(["ECONNRESET","EPIPE","ETIMEDOUT","ECONNABORTED","ECANCELED"]);function classifyClientError(r,t){return r&&exports.BENIGN_SOCKET_ERRNOS.has(r)?{status:null,report:!1,cause:"client-abort"}:r==="HPE_INVALID_EOF_STATE"?{status:null,report:!1,cause:"truncated-at-eof"}:r==="ERR_HTTP_REQUEST_TIMEOUT"?{status:408,report:!0,cause:"request-timeout"}:r==="HPE_HEADER_OVERFLOW"?{status:431,report:!0,cause:"header-overflow"}:r?.startsWith("HPE_")?{status:400,report:!0,cause:"parse-error"}:{status:400,report:!0,cause:r??t??"unknown"}}T(classifyClientError,"classifyClientError"),n(classifyClientError,"classifyClientError");const CLIENT_ERROR_REASON={400:"Bad Request",408:"Request Timeout",431:"Request Header Fields Too Large"};function createClientErrorLogGate(r=1e4){const t=new Map;return l=>{const i=Date.now(),a=t.get(l)??0;return i-a<r?!1:(t.set(l,i),!0)}}T(createClientErrorLogGate,"createClientErrorLogGate"),n(createClientErrorLogGate,"createClientErrorLogGate");function guardInboundSocket(r){r.on("error",t=>{exports.BENIGN_SOCKET_ERRNOS.has(t.code??"")||console.warn(`[gateway] inbound socket error (${t.code??t.message}) \u2014 dropping this connection only`),r.destroy()})}T(guardInboundSocket,"guardInboundSocket"),n(guardInboundSocket,"guardInboundSocket");function retirePreviousWorkspace(r,t,l){const i=r.get(t);if(!i)return!1;r.delete(t),l==="re-registered"&&console.log(`[gateway] workspace '${t}' re-registered \u2014 retiring the children of its previous registration first.`);try{i()}catch(a){console.warn(`[gateway] could not fully retire the previous registration of '${t}' (${l}): ${a.message}`)}return!0}T(retirePreviousWorkspace,"retirePreviousWorkspace"),n(retirePreviousWorkspace,"retirePreviousWorkspace"),exports.GATEWAY_MAX_CONNECTIONS_DEFAULT=512,exports.GATEWAY_MAX_H2_SESSIONS_DEFAULT=64,exports.GATEWAY_MAX_H2_STREAMS_DEFAULT=4096,exports.GATEWAY_H2_IDLE_SESSION_MS_DEFAULT=3e5;function parseBudget(r,t){if(r===void 0||r.trim()==="")return t;const l=Number(r);return!Number.isFinite(l)||l<0?t:Math.floor(l)}T(parseBudget,"parseBudget"),n(parseBudget,"parseBudget");function resolveMaxConnections(r){return parseBudget(r,exports.GATEWAY_MAX_CONNECTIONS_DEFAULT)}T(resolveMaxConnections,"resolveMaxConnections"),n(resolveMaxConnections,"resolveMaxConnections");function h2BudgetFromEnv(r=process.env){return{maxSessions:parseBudget(r.LENSMCP_MAX_H2_SESSIONS,exports.GATEWAY_MAX_H2_SESSIONS_DEFAULT),maxStreams:parseBudget(r.LENSMCP_MAX_H2_STREAMS,exports.GATEWAY_MAX_H2_STREAMS_DEFAULT),idleSessionMs:parseBudget(r.LENSMCP_H2_IDLE_MS,exports.GATEWAY_H2_IDLE_SESSION_MS_DEFAULT)}}T(h2BudgetFromEnv,"h2BudgetFromEnv"),n(h2BudgetFromEnv,"h2BudgetFromEnv");function createH2Governor(r,t){const{NGHTTP2_ENHANCE_YOUR_CALM:l,NGHTTP2_REFUSED_STREAM:i}=require("node:http2").constants,a=new Map;let h=0;const y=n(o=>{o.idle&&(clearTimeout(o.idle),o.idle=void 0)},"disarm"),g=n((o,u)=>{y(u),!(r.idleSessionMs<=0||u.open>0)&&(u.idle=setTimeout(()=>{o.destroyed||o.closed||(t("session-reclaimed",{idleMs:r.idleSessionMs,sessions:a.size}),a.delete(o),o.close())},r.idleSessionMs),u.idle.unref?.())},"arm"),A=n(()=>{for(const[o,u]of a)if(!(u.open>0||o.destroyed))return y(u),a.delete(o),t("session-reclaimed",{reason:"cap",sessions:a.size+1,maxSessions:r.maxSessions}),o.close(),!0;return!1},"reclaimOldestIdle");return{admitSession(o){if(r.maxSessions>0&&a.size>=r.maxSessions&&!A()){t("session-refused",{sessions:a.size,maxSessions:r.maxSessions,streams:h});try{o.goaway(l)}catch{}try{o.close()}catch{}return!1}const u={open:0};return a.set(o,u),g(o,u),o.once("close",()=>{y(u),a.delete(o)}),!0},admitStream(o,u){const p=a.get(o);if(!p)return!0;if(r.maxStreams>0&&h>=r.maxStreams){t("stream-refused",{streams:h,maxStreams:r.maxStreams,sessions:a.size});try{u.close(i)}catch{}return!1}return h+=1,p.open+=1,y(p),u.once("close",()=>{h=Math.max(0,h-1),p.open=Math.max(0,p.open-1),p.open===0&&a.has(o)&&g(o,p)}),!0},dispose(){for(const o of a.values())y(o);a.clear()}}}T(createH2Governor,"createH2Governor"),n(createH2Governor,"createH2Governor");async function startGateway(r,t){const l=r.https!==!1,i=r.ports?.length?r.ports:[443],a=r.scanTtlMs??1500,h=r.startupTimeoutMs??12e4,y=r.sweepMs??1e4,g=r.trafficFlushMs??5e3;let A=!1;const o=process.env.LENSMCP_EVENT_FILE??path.join(t.root,".lensmcp","events.jsonl"),u=(0,own_log_1.startOwnLogRotation)(t.root),p=(0,scope_1.readLensScope)(t.root),w=p.key,M=p.sockNs!==w?p.sockNs:void 0,b=t.projectsConfigurations?.projects??{},x=(0,discovery_1.projectSourceRoots)(t.root,b,t.projectDependencies),{routes:G,services:R,instance:ee}=(0,discovery_1.discoverRoutes)(t.root,b,void 0,w,x,M,p.instance);if(G.length===0)throw new Error("[gateway] no project declares a `cluster` field \u2014 nothing to route.");const K=new route_registry_1.RouteRegistry;K.register({wsKey:w,...M?{sockNs:M}:{},root:t.root,routes:G,services:R,...ee?{instance:ee}:{}});const P=[];let re=n(()=>{},"refreshCert"),F=n(()=>{},"warmEdgeVerifiers");const te=n(()=>{(0,route_registry_1.rebuildRoutesInPlace)(P,K),re(),F()},"rebuildRoutes");te();const{serviceKeys:pe,keyToProject:_e,keyToWorkspace:Se}=(0,service_keys_1.loadServiceKeys)(t.root,R,w),he=(0,client_ip_1.createClientIpResolver)({...(0,client_ip_1.clientIpOptionsFromEnv)(),...r.trustProxyHops!==void 0?{trustProxyHops:r.trustProxyHops}:{},...r.clientIpHeader?{clientIpHeader:r.clientIpHeader}:{},...r.clientIpTrustedProxies?{clientIpTrustedProxies:r.clientIpTrustedProxies}:{}}),E={root:t.root,wsKey:w,...M?{sockNs:M}:{},eventFile:o,routes:P,registry:K,rebuildRoutes:te,services:R,serviceKeys:pe,keyToProject:_e,keyToWorkspace:Se,clientIp:he,bodyStallMs:r.bodyStallMs??types_1.BODY_STALL_MS,scanTtlMs:a,startupTimeoutMs:h,sweepMs:y,trafficFlushMs:g,https:l,projectRoots:Object.fromEntries(Object.entries(t.projectsConfigurations?.projects??{}).map(([e,s])=>[e,path.resolve(t.root,s.root)])),projectSourceRoots:x,...t.projectGraphStore?{graphStores:(0,project_graph_store_1.createProjectGraphStores)(t.projectGraphStore)}:{},...r.sharedCompiler!==void 0?{sharedCompiler:r.sharedCompiler}:{},stopped:n(()=>A,"stopped")};(0,process_name_1.prelinkProcessNames)((0,process_names_1.gatewayProcessNames)(R,{runner:(0,serve_launch_1.serveRunnerEnabled)()&&!!t.projectGraphStore,sharedBuild:(0,protocol_1.sharedCompilerEnabled)(process.env,r.sharedCompiler),label:w||path.basename(t.root),lens:{key:w,dashboard:r.dashboard!==!1,mcp:r.mcp!==!1&&G.some(e=>!!e.lens)}}));const m=(0,observability_1.createObservability)(o,{trafficFlushMs:g}),ge=createClientErrorLogGate(),L=h2BudgetFromEnv(),Ee=createClientErrorLogGate(3e4),D=createH2Governor(L,(e,s)=>{Ee(e)&&console.warn(`[gateway] h2 aggregate budget: ${e} (${JSON.stringify(s)}). These are the FRONT DOOR's ceilings, not an upstream's \u2014 raise/disable with LENSMCP_MAX_H2_SESSIONS / LENSMCP_MAX_H2_STREAMS / LENSMCP_H2_IDLE_MS / LENSMCP_MAX_CONNECTIONS (0 = unbounded).`),m.emit(e==="session-reclaimed"?"info":"warning",`h2 aggregate budget: ${e}`,`gateway-h2-budget:${e}`,{kind:"h2-aggregate-budget",event:e,project:"gateway",...s})}),v=(0,lifecycle_1.createServiceLayer)(E,m),O=(0,lens_children_1.createLensChildren)(E,m,r),U=new Map;let se=n(()=>{},"ownBooted");const we=new Promise(e=>se=e),B=(0,warm_start_1.createWorktreeWarmer)({rt:E,obs:m,ready:we,ensureUp:n(e=>v.ensureUp(e),"ensureUp")});let Y;if(r.middleware){const e=require(path.resolve(t.root,r.middleware));Y=(0,workspace_auth_1.validateMiddleware)(e.default??e)}const X=(0,workspace_middleware_1.createWorkspaceMiddleware)({ownerKey:w,...Y?{owner:Y}:{},policy:(0,workspace_middleware_1.guestMiddlewarePolicy)()}),$=process.env.LENSMCP_GW_ACT==="0"?void 0:(0,act_1.createActStore)({dir:path.join(path.dirname((0,control_1.controlSocketPath)()),"identities")});let I;try{I=(0,control_1.startControlServer)({rt:E,killService:n((e,s)=>v.killSpawned(e,s),"killService"),restartService:n((e,s)=>v.restartService(e,s),"restartService"),ensureService:n(e=>v.ensureUp(e),"ensureService"),startTurn:n(e=>B.take(e),"startTurn"),emitService:n((e,s,_,d)=>v.emitSvc(e,s,_,`cluster-service:${e.project}`,d),"emitService"),...$?{act:$}:{},onRegister:n(async e=>{retirePreviousWorkspace(U,e.wsKey,"re-registered"),X.set(e.wsKey,e.root,e.middleware);const s=await O.hostWorkspaceDashboard(e),_=await O.hostWorkspaceApps(e);U.set(e.wsKey,()=>{try{s?.()}finally{_()}}),B.onRegister(e)},"onRegister"),onUnregister:n(e=>{B.onUnregister(e.wsKey),retirePreviousWorkspace(U,e.wsKey,"unregistered"),X.drop(e.wsKey),v.stopBuildHost(e.root)},"onUnregister")})}catch(e){console.warn("[gateway] control plane failed to start (multi-workspace register disabled):",e.message)}const H=(0,proxy_1.createProxy)(E,m,v),q=buildEdgeVerifierPool(()=>E.routes),oe=(0,auth_1.createEdgeAuth)(E,m,q,$),J=n(e=>async s=>{const _=s.route;if(!_||_.internal||_.project===observability_1.LENS_DASHBOARD_PROJECT)return;const d=_.wsKey,S=X.for(d);if(S)try{const c=d?E.registry.get(d):void 0;await(0,workspace_auth_1.dispatchMiddleware)(S,e,s.req,{...d?{wsKey:d}:{},...c?{root:c.root}:{},env:c?.instance?.env??{},...s.claims?{claims:s.claims}:{}})}catch(c){console.warn(`[gateway] ${new Date().toISOString()} middleware refused a request at ${e} traceId=${(0,gateway_errors_1.ensureRequestId)(s.req)}: ${c?.message??String(c)}`),m.traceStep(s.trace,"auth",{mode:"middleware",ok:!1,reason:`refused at ${e}`}),m.finishTrace(s.trace,_.project,401),s.sendError(401,"unauthorized","Gateway middleware rejected the request")}},"middlewareStep"),ne=J("preAuth"),ae=J("beforeForward"),ie=(0,hooks_1.createHooks)(withBuiltinHooks(r.hooks??{},{keyWait:edgeKeyWait(q),middleware:J("afterAuth"),preAuth:ne,beforeForward:ae})),ce=(0,handler_1.createHandler)({rt:E,obs:m,auth:oe,proxy:H,hooks:ie}),le=(0,upgrade_1.createUpgrade)({rt:E,auth:oe,proxy:H,hooks:ie,obs:m,middleware:{preAuth:ne,beforeForward:ae}}),ye=m.startEdgeFlusher(),me=v.startSweeper(),ue=(0,source_poller_1.createSourcePoller)({services:n(()=>E.registry.allServices(),"services"),serviceKey:n(e=>E.serviceKeys[(0,service_keys_1.serviceKeyId)(e.wsKey,e.project)],"serviceKey"),emit:n((e,s,_,d,S)=>m.emit(s,_,d,{wsKey:e.wsKey,...S},void 0,e.wsKey===E.wsKey?void 0:path.join(e.root,".lensmcp","events.jsonl")),"emit"),scanTtlMs:a,stopped:n(()=>A,"stopped")});(0,source_poller_1.sourcesEnabled)()&&ue.start(),await O.bootSingletonsAndApps();const de=R.filter(e=>e.decl.eager).map(e=>v.ensureUp(e));Promise.allSettled(de).then(()=>setTimeout(se,de.length?2e4:0).unref());let k,z,W;if(l){const e=require("../../../basic-ssl"),s=(0,service_keys_1.gatewayCacheDir)(t.root);W=n(()=>e.getCertificateSync(s,"gateway",E.routes.map(_=>_.host).filter(_=>!!_)),"mintCert"),k=W(),z=e.caCertPath()}const V=[],j=[],Q=r.maxConnections??resolveMaxConnections(process.env.LENSMCP_MAX_CONNECTIONS);for(const e of i){const s=k?require("node:http2").createSecureServer({key:k,cert:k,allowHTTP1:!0,maxSessionMemory:512,settings:{maxConcurrentStreams:512},peerMaxConcurrentStreams:512,streamResetBurst:r.h2ResetBurst??types_1.GATEWAY_H2_RESET_BURST,streamResetRate:r.h2ResetRate??types_1.GATEWAY_H2_RESET_RATE},(d,S)=>ce(d,S)):http.createServer(ce);s.on("upgrade",le),s.on("error",d=>console.error(`[gateway] port ${e}: ${d.code}`)),s.on("connection",guardInboundSocket),s.on("secureConnection",guardInboundSocket),s.on("tlsClientError",(d,S)=>S.destroy()),s.on("clientError",(d,S)=>{const c=d,f=classifyClientError(c.code,c.message);if(f.report&&ge(f.cause)){const N=S.remoteAddress??"unknown",C=f.status===null?"dropped":String(f.status);console.warn(`[gateway] inbound H1 clientError from ${N}: ${f.cause} (${c.code??c.message}${c.bytesParsed!==void 0?`, bytesParsed=${c.bytesParsed}`:""}) \u2192 ${C}. This status is the GATEWAY's, not the upstream service's.`),m.emit("warning",`inbound clientError: ${f.cause} \u2192 ${C}`,`gateway-client-error:${f.cause}`,{kind:"gateway-client-error",cause:f.cause,code:c.code??null,status:f.status,peer:N,bytesParsed:c.bytesParsed??null})}f.status!==null&&S.writable&&S.end(`HTTP/1.1 ${f.status} ${CLIENT_ERROR_REASON[f.status]}\r
|
|
1
|
+
"use strict";var ke=Object.defineProperty;var T=(r,t)=>ke(r,"name",{value:t,configurable:!0});var Me=Object.defineProperty,s=T((r,t)=>Me(r,"name",{value:t,configurable:!0}),"s");Object.defineProperty(exports,"__esModule",{value:!0}),exports.GATEWAY_H2_IDLE_SESSION_MS_DEFAULT=exports.GATEWAY_MAX_H2_STREAMS_DEFAULT=exports.GATEWAY_MAX_H2_SESSIONS_DEFAULT=exports.GATEWAY_MAX_CONNECTIONS_DEFAULT=exports.BENIGN_SOCKET_ERRNOS=void 0,exports.buildEdgeVerifierPool=buildEdgeVerifierPool,exports.edgeKeyWait=edgeKeyWait,exports.withBuiltinHooks=withBuiltinHooks,exports.classifyClientError=classifyClientError,exports.createClientErrorLogGate=createClientErrorLogGate,exports.retirePreviousWorkspace=retirePreviousWorkspace,exports.resolveMaxConnections=resolveMaxConnections,exports.h2BudgetFromEnv=h2BudgetFromEnv,exports.createH2Governor=createH2Governor,exports.startGateway=startGateway;const tslib_1=require("tslib"),http=tslib_1.__importStar(require("node:http")),path=tslib_1.__importStar(require("node:path")),discovery_1=require("./discovery"),scope_1=require("./scope"),route_registry_1=require("./route-registry"),act_1=require("./act"),control_1=require("./control"),workspace_middleware_1=require("./workspace-middleware"),workspace_registry_1=require("./workspace-registry"),service_keys_1=require("./service-keys"),source_poller_1=require("./source-poller"),client_ip_1=require("../client-ip"),workspace_log_1=require("./workspace-log"),own_log_1=require("./own-log"),observability_1=require("./observability"),lifecycle_1=require("./lifecycle"),process_names_1=require("./process-names"),project_graph_store_1=require("./project-graph-store"),guest_graph_1=require("./guest-graph"),serve_launch_1=require("./serve-launch"),process_name_1=require("../../../process-name"),protocol_1=require("../../../shared-build/protocol"),lens_children_1=require("./lens-children"),proxy_1=require("./proxy"),auth_1=require("./auth"),hooks_1=require("./hooks"),handler_1=require("./handler"),upgrade_1=require("./upgrade"),jwks_verify_1=require("../jwks-verify"),gateway_errors_1=require("../gateway-errors"),workspace_auth_1=require("../workspace-auth"),manifest_1=require("../manifest"),edge_1=require("./edge"),warm_start_1=require("./warm-start"),on_demand_1=require("./on-demand"),parked_dashboards_1=require("./parked-dashboards"),types_1=require("./types");function insecureLocalFetch(r,t){return new Promise((l,i)=>{const n=(r.startsWith("https:")?require("node:https"):require("node:http")).request(r,{method:"GET",headers:t?.headers,rejectUnauthorized:!1},S=>{const m=[];S.on("data",w=>m.push(w)),S.on("error",i),S.on("end",()=>{const w=S.statusCode??0,A=Buffer.concat(m).toString("utf8");l({ok:w>=200&&w<300,status:w,json:s(async()=>JSON.parse(A),"json")})})});n.on("error",i),t?.signal?.addEventListener("abort",()=>n.destroy(new Error(`JWKS ${r} \u2192 aborted`)),{once:!0}),n.end()})}T(insecureLocalFetch,"insecureLocalFetch"),s(insecureLocalFetch,"insecureLocalFetch");function buildEdgeVerifierPool(r,t={}){const l=process.env.LENSMCP_GW_JWKS_URL,i=process.env.LENSMCP_GW_JWT_ISS,n=new Map;let S,m=!1;const w=s((a,d)=>{console.log(`[gateway] edge JWT: verifying via JWKS ${a}${d}`);const _=(0,jwks_verify_1.createJwksVerifier)({jwksUrl:a,...i?{issuer:i}:{},fetchImpl:t.fetchImpl??insecureLocalFetch});let y=!1;return _.warm({...t.warm,onError:s((M,P,x)=>{y=!0,P===1&&x!==void 0&&console.warn(`[gateway] edge JWKS ${a} not loaded yet (${M.message}) \u2014 retrying in the background`),x===void 0&&console.warn(`[gateway] edge JWKS ${a} still not loaded after ${P} attempts (${M.message}) \u2014 the first token that needs it fetches it`)},"onError")}).then(M=>{M&&y&&console.log(`[gateway] edge JWKS ${a} loaded`)}),_},"make"),A=s(a=>{let d=n.get(a);return d||(d=w(`https://auth.${a}/jwks.json`,` (auto-derived for apex ${a})`),n.set(a,d)),d},"forApex");return{for(a){if(l)return S??=w(l,"");const d=a.split(":")[0].toLowerCase();let _;for(const y of idpApexes(r()))(d===y||d.endsWith(`.${y}`))&&(!_||y.length>_.length)&&(_=y);return _?A(_):void 0},warm(){if(!m){if(l){S??=w(l,"");return}for(const a of idpApexes(r()))A(a)}},stop(){m=!0,S?.stop();for(const a of n.values())a.stop()}}}T(buildEdgeVerifierPool,"buildEdgeVerifierPool"),s(buildEdgeVerifierPool,"buildEdgeVerifierPool");function idpApexes(r){const t=new Set;for(const l of r){const i=l.host;typeof i!="string"||!/^auth\./.test(i)||i.startsWith("internal.")||t.add(i.slice(5))}return t}T(idpApexes,"idpApexes"),s(idpApexes,"idpApexes");function edgeKeyWait(r){return async t=>{const l=t.route;if(!l?.auth||l.internal)return;const{req:i}=t,n=Array.isArray(i.headers.authorization)?i.headers.authorization[0]:i.headers.authorization,S=String(n??""),m=(0,workspace_auth_1.requestToken)(i)??(S.startsWith("Bearer ")?S.slice(7):void 0);if(!m)return;const w=i.url??"/";if((0,manifest_1.authRuleFor)(l.auth,(0,edge_1.canonicalPath)(w)??w.split("?")[0],(i.method??"GET").toUpperCase()).mode!=="jwt")return;const A=String(i.headers.host??"").split(":")[0].toLowerCase();await r.for(A)?.awaitKey(m)}}T(edgeKeyWait,"edgeKeyWait"),s(edgeKeyWait,"edgeKeyWait");function withBuiltinHooks(r,t){return{...r,beforeAuth:[...r.beforeAuth??[],...t.preAuth?[t.preAuth]:[],t.keyWait],afterAuth:[t.middleware,...r.afterAuth??[]],beforeForward:[...t.beforeForward?[t.beforeForward]:[],...r.beforeForward??[]]}}T(withBuiltinHooks,"withBuiltinHooks"),s(withBuiltinHooks,"withBuiltinHooks"),exports.BENIGN_SOCKET_ERRNOS=new Set(["ECONNRESET","EPIPE","ETIMEDOUT","ECONNABORTED","ECANCELED"]);function classifyClientError(r,t){return r&&exports.BENIGN_SOCKET_ERRNOS.has(r)?{status:null,report:!1,cause:"client-abort"}:r==="HPE_INVALID_EOF_STATE"?{status:null,report:!1,cause:"truncated-at-eof"}:r==="ERR_HTTP_REQUEST_TIMEOUT"?{status:408,report:!0,cause:"request-timeout"}:r==="HPE_HEADER_OVERFLOW"?{status:431,report:!0,cause:"header-overflow"}:r?.startsWith("HPE_")?{status:400,report:!0,cause:"parse-error"}:{status:400,report:!0,cause:r??t??"unknown"}}T(classifyClientError,"classifyClientError"),s(classifyClientError,"classifyClientError");const CLIENT_ERROR_REASON={400:"Bad Request",408:"Request Timeout",431:"Request Header Fields Too Large"};function createClientErrorLogGate(r=1e4){const t=new Map;return l=>{const i=Date.now(),n=t.get(l)??0;return i-n<r?!1:(t.set(l,i),!0)}}T(createClientErrorLogGate,"createClientErrorLogGate"),s(createClientErrorLogGate,"createClientErrorLogGate");function guardInboundSocket(r){r.on("error",t=>{exports.BENIGN_SOCKET_ERRNOS.has(t.code??"")||console.warn(`[gateway] inbound socket error (${t.code??t.message}) \u2014 dropping this connection only`),r.destroy()})}T(guardInboundSocket,"guardInboundSocket"),s(guardInboundSocket,"guardInboundSocket");function retirePreviousWorkspace(r,t,l){const i=r.get(t);if(!i)return!1;r.delete(t),l==="re-registered"&&console.log(`[gateway] workspace '${t}' re-registered \u2014 retiring the children of its previous registration first.`);try{i()}catch(n){console.warn(`[gateway] could not fully retire the previous registration of '${t}' (${l}): ${n.message}`)}return!0}T(retirePreviousWorkspace,"retirePreviousWorkspace"),s(retirePreviousWorkspace,"retirePreviousWorkspace"),exports.GATEWAY_MAX_CONNECTIONS_DEFAULT=512,exports.GATEWAY_MAX_H2_SESSIONS_DEFAULT=64,exports.GATEWAY_MAX_H2_STREAMS_DEFAULT=4096,exports.GATEWAY_H2_IDLE_SESSION_MS_DEFAULT=3e5;function parseBudget(r,t){if(r===void 0||r.trim()==="")return t;const l=Number(r);return!Number.isFinite(l)||l<0?t:Math.floor(l)}T(parseBudget,"parseBudget"),s(parseBudget,"parseBudget");function resolveMaxConnections(r){return parseBudget(r,exports.GATEWAY_MAX_CONNECTIONS_DEFAULT)}T(resolveMaxConnections,"resolveMaxConnections"),s(resolveMaxConnections,"resolveMaxConnections");function h2BudgetFromEnv(r=process.env){return{maxSessions:parseBudget(r.LENSMCP_MAX_H2_SESSIONS,exports.GATEWAY_MAX_H2_SESSIONS_DEFAULT),maxStreams:parseBudget(r.LENSMCP_MAX_H2_STREAMS,exports.GATEWAY_MAX_H2_STREAMS_DEFAULT),idleSessionMs:parseBudget(r.LENSMCP_H2_IDLE_MS,exports.GATEWAY_H2_IDLE_SESSION_MS_DEFAULT)}}T(h2BudgetFromEnv,"h2BudgetFromEnv"),s(h2BudgetFromEnv,"h2BudgetFromEnv");function createH2Governor(r,t){const{NGHTTP2_ENHANCE_YOUR_CALM:l,NGHTTP2_REFUSED_STREAM:i}=require("node:http2").constants,n=new Map;let S=0;const m=s(a=>{a.idle&&(clearTimeout(a.idle),a.idle=void 0)},"disarm"),w=s((a,d)=>{m(d),!(r.idleSessionMs<=0||d.open>0)&&(d.idle=setTimeout(()=>{a.destroyed||a.closed||(t("session-reclaimed",{idleMs:r.idleSessionMs,sessions:n.size}),n.delete(a),a.close())},r.idleSessionMs),d.idle.unref?.())},"arm"),A=s(()=>{for(const[a,d]of n)if(!(d.open>0||a.destroyed))return m(d),n.delete(a),t("session-reclaimed",{reason:"cap",sessions:n.size+1,maxSessions:r.maxSessions}),a.close(),!0;return!1},"reclaimOldestIdle");return{admitSession(a){if(r.maxSessions>0&&n.size>=r.maxSessions&&!A()){t("session-refused",{sessions:n.size,maxSessions:r.maxSessions,streams:S});try{a.goaway(l)}catch{}try{a.close()}catch{}return!1}const d={open:0};return n.set(a,d),w(a,d),a.once("close",()=>{m(d),n.delete(a)}),!0},admitStream(a,d){const _=n.get(a);if(!_)return!0;if(r.maxStreams>0&&S>=r.maxStreams){t("stream-refused",{streams:S,maxStreams:r.maxStreams,sessions:n.size});try{d.close(i)}catch{}return!1}return S+=1,_.open+=1,m(_),d.once("close",()=>{S=Math.max(0,S-1),_.open=Math.max(0,_.open-1),_.open===0&&n.has(a)&&w(a,_)}),!0},dispose(){for(const a of n.values())m(a);n.clear()}}}T(createH2Governor,"createH2Governor"),s(createH2Governor,"createH2Governor");async function startGateway(r,t){const l=r.https!==!1,i=r.ports?.length?r.ports:[443],n=r.scanTtlMs??1500,S=r.startupTimeoutMs??12e4,m=r.sweepMs??1e4,w=r.trafficFlushMs??5e3;let A=!1;const a=process.env.LENSMCP_EVENT_FILE??path.join(t.root,".lensmcp","events.jsonl"),d=(0,own_log_1.startOwnLogRotation)(t.root),_=(0,scope_1.readLensScope)(t.root),y=_.key,M=_.sockNs!==y?_.sockNs:void 0,P=t.projectsConfigurations?.projects??{},x=(0,discovery_1.projectSourceRoots)(t.root,P,t.projectDependencies),{routes:D,services:C,instance:se}=(0,discovery_1.discoverRoutes)(t.root,P,void 0,y,x,M,_.instance);if(D.length===0)throw new Error("[gateway] no project declares a `cluster` field \u2014 nothing to route.");const U=new route_registry_1.RouteRegistry;U.register({wsKey:y,...M?{sockNs:M}:{},root:t.root,routes:D,services:C,...se?{instance:se}:{}});const R=[];let oe=s(()=>{},"refreshCert"),B=s(()=>{},"warmEdgeVerifiers");const ae=s(()=>{(0,route_registry_1.rebuildRoutesInPlace)(R,U),oe(),B()},"rebuildRoutes");ae();const{serviceKeys:_e,keyToProject:Se,keyToWorkspace:we}=(0,service_keys_1.loadServiceKeys)(t.root,C,y),ye=(0,client_ip_1.createClientIpResolver)({...(0,client_ip_1.clientIpOptionsFromEnv)(),...r.trustProxyHops!==void 0?{trustProxyHops:r.trustProxyHops}:{},...r.clientIpHeader?{clientIpHeader:r.clientIpHeader}:{},...r.clientIpTrustedProxies?{clientIpTrustedProxies:r.clientIpTrustedProxies}:{}});t.projectGraphStore?.setFallback?.(()=>(0,guest_graph_1.ownGraphInFreshProcess)(t.root));const p={root:t.root,wsKey:y,...M?{sockNs:M}:{},eventFile:a,routes:R,registry:U,rebuildRoutes:ae,services:C,serviceKeys:_e,keyToProject:Se,keyToWorkspace:we,clientIp:ye,bodyStallMs:r.bodyStallMs??types_1.BODY_STALL_MS,scanTtlMs:n,startupTimeoutMs:S,sweepMs:m,trafficFlushMs:w,https:l,projectRoots:Object.fromEntries(Object.entries(t.projectsConfigurations?.projects??{}).map(([e,o])=>[e,path.resolve(t.root,o.root)])),projectSourceRoots:x,...t.projectGraphStore?{graphStores:(0,project_graph_store_1.createProjectGraphStores)(t.projectGraphStore)}:{},...r.sharedCompiler!==void 0?{sharedCompiler:r.sharedCompiler}:{},stopped:s(()=>A,"stopped")};(0,process_name_1.prelinkProcessNames)((0,process_names_1.gatewayProcessNames)(C,{runner:(0,serve_launch_1.serveRunnerEnabled)()&&!!t.projectGraphStore,sharedBuild:(0,protocol_1.sharedCompilerEnabled)(process.env,r.sharedCompiler),label:y||path.basename(t.root),lens:{key:y,dashboard:r.dashboard!==!1,mcp:r.mcp!==!1&&D.some(e=>!!e.lens)}}));const E=(0,observability_1.createObservability)(a,{trafficFlushMs:w}),Ee=createClientErrorLogGate(),O=h2BudgetFromEnv(),me=createClientErrorLogGate(3e4),Y=createH2Governor(O,(e,o)=>{me(e)&&console.warn(`[gateway] h2 aggregate budget: ${e} (${JSON.stringify(o)}). These are the FRONT DOOR's ceilings, not an upstream's \u2014 raise/disable with LENSMCP_MAX_H2_SESSIONS / LENSMCP_MAX_H2_STREAMS / LENSMCP_H2_IDLE_MS / LENSMCP_MAX_CONNECTIONS (0 = unbounded).`),E.emit(e==="session-reclaimed"?"info":"warning",`h2 aggregate budget: ${e}`,`gateway-h2-budget:${e}`,{kind:"h2-aggregate-budget",event:e,project:"gateway",...o})}),v=(0,lifecycle_1.createServiceLayer)(p,E),L=(0,lens_children_1.createLensChildren)(p,E,r),X=(0,on_demand_1.createOnDemandRecordsReader)(),$=(0,parked_dashboards_1.createParkedDashboards)({registry:s(()=>p.registry,"registry"),records:X,host:s(e=>L.hostParkedDashboard(e),"host"),rebuild:s(()=>p.rebuildRoutes(),"rebuild"),stopped:s(()=>A,"stopped")});p.parkedDashboards=$;const H=s(()=>{$.sync().catch(e=>console.warn("[gateway] parked worktree dashboards:",e.message))},"syncParked"),J=new Map;let ne=s(()=>{},"ownBooted");const fe=new Promise(e=>ne=e),q=(0,warm_start_1.createWorktreeWarmer)({rt:p,obs:E,ready:fe,ensureUp:s(e=>v.ensureUp(e),"ensureUp")});(0,warm_start_1.mainAlwaysUp)()&&q.warmOwn(C);let z;if(r.middleware){const e=require(path.resolve(t.root,r.middleware));z=(0,workspace_auth_1.validateMiddleware)(e.default??e)}const V=(0,workspace_middleware_1.createWorkspaceMiddleware)({ownerKey:y,...z?{owner:z}:{},policy:(0,workspace_middleware_1.guestMiddlewarePolicy)()}),W=process.env.LENSMCP_GW_ACT==="0"?void 0:(0,act_1.createActStore)({dir:path.join(path.dirname((0,control_1.controlSocketPath)()),"identities")});let I;try{I=(0,control_1.startControlServer)({rt:p,killService:s((e,o)=>v.killSpawned(e,o),"killService"),restartService:s((e,o)=>v.restartService(e,o),"restartService"),ensureService:s(e=>v.ensureUp(e),"ensureService"),startTurn:s(e=>q.take(e),"startTurn"),emitService:s((e,o,h,u)=>v.emitSvc(e,o,h,`cluster-service:${e.project}`,u),"emitService"),emitWorkspace:s((e,o,h,u,g)=>E.emit(o,h,u,{wsKey:e.wsKey,...g},void 0,e.wsKey===y?void 0:path.join(e.root,".lensmcp","events.jsonl")),"emitWorkspace"),...W?{act:W}:{},onRegister:s(async e=>{retirePreviousWorkspace(J,e.wsKey,"re-registered"),await $.drop(e.wsKey),V.set(e.wsKey,e.root,e.middleware);const o=await L.hostWorkspaceDashboard(e),h=await L.hostWorkspaceApps(e);J.set(e.wsKey,()=>{try{o?.()}finally{h()}}),q.onRegister(e)},"onRegister"),onUnregister:s(e=>{q.onUnregister(e.wsKey),retirePreviousWorkspace(J,e.wsKey,"unregistered"),V.drop(e.wsKey),v.stopBuildHost(e.root),H()},"onUnregister")})}catch(e){console.warn("[gateway] control plane failed to start (multi-workspace register disabled):",e.message)}const j=(0,proxy_1.createProxy)(p,E,v),G=buildEdgeVerifierPool(()=>p.routes),ie=(0,auth_1.createEdgeAuth)(p,E,G,W),Q=s(e=>async o=>{const h=o.route;if(!h||h.internal||h.project===observability_1.LENS_DASHBOARD_PROJECT)return;const u=h.wsKey,g=V.for(u);if(g)try{const c=u?p.registry.get(u):void 0;await(0,workspace_auth_1.dispatchMiddleware)(g,e,o.req,{...u?{wsKey:u}:{},...c?{root:c.root}:{},env:c?.instance?.env??{},...o.claims?{claims:o.claims}:{}})}catch(c){console.warn(`[gateway] ${new Date().toISOString()} middleware refused a request at ${e} traceId=${(0,gateway_errors_1.ensureRequestId)(o.req)}: ${c?.message??String(c)}`),E.traceStep(o.trace,"auth",{mode:"middleware",ok:!1,reason:`refused at ${e}`}),E.finishTrace(o.trace,h.project,401),o.sendError(401,"unauthorized","Gateway middleware rejected the request")}},"middlewareStep"),ce=Q("preAuth"),le=Q("beforeForward"),de=(0,hooks_1.createHooks)(withBuiltinHooks(r.hooks??{},{keyWait:edgeKeyWait(G),middleware:Q("afterAuth"),preAuth:ce,beforeForward:le})),ue=(0,handler_1.createHandler)({rt:p,obs:E,auth:ie,proxy:j,hooks:de,parkedHosts:(0,on_demand_1.createParkedHostLookup)({registry:s(()=>p.registry,"registry"),records:X})}),pe=(0,upgrade_1.createUpgrade)({rt:p,auth:ie,proxy:j,hooks:de,obs:E,middleware:{preAuth:ce,beforeForward:le}}),Te=E.startEdgeFlusher(),Ae=v.startSweeper(()=>{I?.parkIdle(),H()}),he=(0,source_poller_1.createSourcePoller)({services:s(()=>p.registry.allServices(),"services"),serviceKey:s(e=>p.serviceKeys[(0,service_keys_1.serviceKeyId)(e.wsKey,e.project)],"serviceKey"),emit:s((e,o,h,u,g)=>E.emit(o,h,u,{wsKey:e.wsKey,...g},void 0,e.wsKey===p.wsKey?void 0:path.join(e.root,".lensmcp","events.jsonl")),"emit"),scanTtlMs:n,stopped:s(()=>A,"stopped")});(0,source_poller_1.sourcesEnabled)()&&he.start(),await L.bootSingletonsAndApps();const ge=C.filter(e=>e.decl.eager).map(e=>v.ensureUp(e));Promise.allSettled(ge).then(()=>setTimeout(ne,ge.length?2e4:0).unref());let b,Z,K;if(l){const e=require("../../../basic-ssl"),o=(0,service_keys_1.gatewayCacheDir)(t.root);K=s(()=>e.getCertificateSync(o,"gateway",[...new Set([...p.routes.map(h=>h.host).filter(h=>!!h),...(0,parked_dashboards_1.parkedHosts)(p.registry,X())])]),"mintCert"),b=K(),Z=e.caCertPath()}const ee=[],F=[],re=r.maxConnections??resolveMaxConnections(process.env.LENSMCP_MAX_CONNECTIONS);for(const e of i){const o=b?require("node:http2").createSecureServer({key:b,cert:b,allowHTTP1:!0,maxSessionMemory:512,settings:{maxConcurrentStreams:512},peerMaxConcurrentStreams:512,streamResetBurst:r.h2ResetBurst??types_1.GATEWAY_H2_RESET_BURST,streamResetRate:r.h2ResetRate??types_1.GATEWAY_H2_RESET_RATE},(u,g)=>ue(u,g)):http.createServer(ue);o.on("upgrade",pe),o.on("error",u=>console.error(`[gateway] port ${e}: ${u.code}`)),o.on("connection",guardInboundSocket),o.on("secureConnection",guardInboundSocket),o.on("tlsClientError",(u,g)=>g.destroy()),o.on("clientError",(u,g)=>{const c=u,f=classifyClientError(c.code,c.message);if(f.report&&Ee(f.cause)){const N=g.remoteAddress??"unknown",k=f.status===null?"dropped":String(f.status);console.warn(`[gateway] inbound H1 clientError from ${N}: ${f.cause} (${c.code??c.message}${c.bytesParsed!==void 0?`, bytesParsed=${c.bytesParsed}`:""}) \u2192 ${k}. This status is the GATEWAY's, not the upstream service's.`),E.emit("warning",`inbound clientError: ${f.cause} \u2192 ${k}`,`gateway-client-error:${f.cause}`,{kind:"gateway-client-error",cause:f.cause,code:c.code??null,status:f.status,peer:N,bytesParsed:c.bytesParsed??null})}f.status!==null&&g.writable&&g.end(`HTTP/1.1 ${f.status} ${CLIENT_ERROR_REASON[f.status]}\r
|
|
2
2
|
\r
|
|
3
|
-
`),
|
|
3
|
+
`),g.destroy()}),o.keepAliveTimeout=types_1.GATEWAY_KEEPALIVE_TIMEOUT_MS,o.headersTimeout=r.headersTimeoutMs??types_1.GATEWAY_HEADERS_TIMEOUT_MS,re>0&&(o.maxConnections=re);const h=r.connectionsCheckingIntervalMs??types_1.GATEWAY_CONN_CHECK_MS;if(h>0&&(o.connectionsCheckingInterval=h),b!=null){const u=o,{NGHTTP2_CANCEL:g}=require("node:http2").constants;u.on("session",c=>{if(!Y.admitSession(c)){c.on("error",()=>{});return}let f=0,N=0;c.on("stream",k=>{Y.admitStream(c,k)&&k.once("close",()=>{c.destroyed?N+=1:k.rstCode===g&&(f+=1)})}),c.once("close",()=>{N!==0&&(console.warn(`[gateway] h2 session closed with ${N} stream(s) in flight after ${f} client reset(s) \u2014 every in-flight fetch on that connection failed at once (ERR_HTTP2_PROTOCOL_ERROR in the browser). Reset budget: LENSMCP_H2_RESET_BURST/LENSMCP_H2_RESET_RATE (issues/closed/foodguard-14).`),E.emit("warning",`h2 session lost with ${N} stream(s) in flight`,"gateway-h2-session-lost",{kind:"h2-session-lost",project:"gateway",inflight:N,clientResets:f}))}),c.on("error",k=>{const ve=k.code??k.message;console.warn(`[gateway] h2 session error (${ve}) \u2014 dropping this session only`),c.destroyed||c.destroy()})}),u.on("sessionError",c=>{console.warn(`[gateway] h2 sessionError: ${c.code??c.message}`)})}await new Promise(u=>{o.listen(e,()=>{const g=o.address()?.port??e;F.push(g),console.log(`[gateway] Listening on ${b?"https":"http"}://localhost:${g}`),u()})}),ee.push(o)}K&&(oe=s(()=>{const e=K();for(const o of ee)o.setSecureContext?.({key:e,cert:e})},"refreshCert")),console.log("[gateway] Routes:");for(const e of R){const o=e.pool?`pods@${e.pool.dir}`:e.target;console.log(`[gateway] ${e.host??"(default)"} \u2192 ${o}${e.prependPrefix?` (+${e.prependPrefix})`:""}${e.internal?" [internal: no middleware]":""} [${e.project}]`)}Z&&console.log(`[gateway] CA: ${Z} \u2014 one-time setup via the trust executor.`),B=s(()=>G.warm(),"warmEdgeVerifiers"),B();const te=s(e=>e>0?String(e):"unbounded","unbounded");return console.log(`[gateway] front-door budget: \u2264${te(re)} connections, \u2264${te(O.maxSessions)} h2 sessions (each \u2264512 MB session memory, \u2264512 streams), \u2264${te(O.maxStreams)} open streams in total, idle h2 session reclaimed after ${O.idleSessionMs>0?`${Math.round(O.idleSessionMs/1e3)}s`:"never"}. Override: LENSMCP_MAX_CONNECTIONS / LENSMCP_MAX_H2_SESSIONS / LENSMCP_MAX_H2_STREAMS / LENSMCP_H2_IDLE_MS (0 = unbounded).`),E.emit("info",`gateway up: ${R.length} routes on ${F.join("/")}`,"cluster-gateway",{kind:"gateway-up",project:"gateway",ports:F,routes:R.map(e=>({host:e.host??"(default)",project:e.project,mode:e.pool?"pods":"tcp",internal:!!e.internal,prependPrefix:e.prependPrefix}))}),I&&process.env.LENSMCP_GUEST_REPLAY!=="0"?I.replay().catch(e=>console.warn("[gateway] guest replay failed:",e.message)).finally(H):H(),{ports:F,routes:R,services:C,stop:s(async()=>{if(!A){A=!0,clearInterval(Te),clearInterval(Ae),he.stop(),E.emit("info","gateway down","cluster-gateway",{kind:"gateway-down",project:"gateway"}),G.stop(),I?.close(),W?.flush(),(0,workspace_registry_1.unregisterWorkspace)(y);for(const e of C)v.killSpawned(e,"gateway shutdown");v.stopRetiringTrees(),await v.stopBuildHost(),await v.finishDyingTrees(),$.close(),await L.reapAll(),pe.closeTunnels(),await Promise.all(ee.map(e=>new Promise(o=>{let h=!1;const u=s(()=>{h||(h=!0,o())},"done"),g=e;e.close(()=>u());try{g.closeIdleConnections?.()}catch{}setTimeout(()=>{try{g.closeAllConnections?.()}catch{}u()},types_1.GATEWAY_STOP_GRACE_MS).unref?.()}))),j.closeProxy(),j.destroyAgents(),Y.dispose(),(0,workspace_log_1.closeWorkspaceLogs)(),d()}},"stop"),...p.lensSupervisor?{lensSupervisor:p.lensSupervisor}:{},...p.graphStores?{graphStores:p.graphStores}:{}}}T(startGateway,"startGateway"),s(startGateway,"startGateway");
|
|
@@ -16,6 +16,7 @@ import type { RouteRegistry } from './route-registry';
|
|
|
16
16
|
import type { PodFaults } from './pod-output';
|
|
17
17
|
import type { ProjectGraphStore, ProjectGraphStores } from './project-graph-store';
|
|
18
18
|
import type { HostedDashboard } from './hosted-dashboard';
|
|
19
|
+
import type { ParkedDashboards } from './parked-dashboards';
|
|
19
20
|
export type { Attrs };
|
|
20
21
|
export interface GatewayContext {
|
|
21
22
|
root: string;
|
|
@@ -392,6 +393,12 @@ export interface ServiceCtl {
|
|
|
392
393
|
spawnAt?: number;
|
|
393
394
|
lastErrors?: string[];
|
|
394
395
|
buildFailed?: boolean;
|
|
396
|
+
/** The last lines its current tree printed, de-coloured (lifecycle.ts, at most {@link OUTPUT_TAIL_LINES}): what a failed
|
|
397
|
+
* start is told with. */
|
|
398
|
+
outputTail?: string[];
|
|
399
|
+
/** Why its last start failed — the reason, then the last lines its tree printed (at most {@link START_ERROR_LINES} lines
|
|
400
|
+
* in all). Cleared once it comes up. `/status` says it as the service row's `error` (planning/team/21). */
|
|
401
|
+
lastStartError?: string;
|
|
395
402
|
/** The faults REPORTED to the lens and not yet taken back — what decides when `service-recovered` is
|
|
396
403
|
* announced. Not `buildFailed`, which is the gateway's own control flag (pod-output.ts). */
|
|
397
404
|
faults?: PodFaults;
|
|
@@ -606,6 +613,10 @@ export declare const POD_ROLL_READY_MS: number;
|
|
|
606
613
|
* in the same sweep: uncapped, that doubled the fleet (twelve concurrent cold compiles for foodguard's six
|
|
607
614
|
* eager services). The rest queue and roll as slots free. Override `LENSMCP_POD_MAX_CONCURRENT_ROLLS`;
|
|
608
615
|
* `0` removes the cap. Default 2.
|
|
616
|
+
*
|
|
617
|
+
* The same number bounds the recycles that cannot roll — a tree started through `nx run`, or
|
|
618
|
+
* `LENSMCP_POD_RECYCLE_MODE=in-place`: no more of them go kill-first in one sweep, and the rest go on the
|
|
619
|
+
* next sweeps (issues/open/overseer-16 — one file added under foodguard's shared/contracts killed seven).
|
|
609
620
|
*/
|
|
610
621
|
export declare const POD_MAX_CONCURRENT_ROLLS: number;
|
|
611
622
|
/**
|
|
@@ -913,6 +924,9 @@ export interface GatewayRuntime {
|
|
|
913
924
|
/** Registered workspaces' dashboards, by their route's `target` (hosted-dashboard.ts): the pipeline starts a parked
|
|
914
925
|
* one before it forwards to it, and holds it awake while the response is open. Installed by lens-children. */
|
|
915
926
|
hostedDashboards?: Map<string, HostedDashboard>;
|
|
927
|
+
/** The parked on-demand worktrees whose dashboards this daemon keeps at `lensmcp.local/<key>/` (parked-dashboards.ts):
|
|
928
|
+
* the chooser lists them, the parked host page links them. Installed by server.ts. */
|
|
929
|
+
parkedDashboards?: Pick<ParkedDashboards, 'list'>;
|
|
916
930
|
/** Teardown flag — a GETTER, never a captured boolean, so every layer reads
|
|
917
931
|
* the LIVE value (an in-flight cold start / auto-heal must not act after stop). */
|
|
918
932
|
stopped(): boolean;
|
|
@@ -976,3 +990,7 @@ export interface AuthVerdict {
|
|
|
976
990
|
reason?: GatewayErrorReason;
|
|
977
991
|
detail?: string;
|
|
978
992
|
}
|
|
993
|
+
/** How many of a service tree's last output lines are kept for a failed start's answer ({@link ServiceCtl.outputTail}). */
|
|
994
|
+
export declare const OUTPUT_TAIL_LINES = 19;
|
|
995
|
+
/** The most lines a failed start's `error` carries: its reason, then the tree's last lines. */
|
|
996
|
+
export declare const START_ERROR_LINES = 20;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var O=Object.defineProperty;var
|
|
1
|
+
"use strict";var O=Object.defineProperty;var L=(_,E)=>O(_,"name",{value:E,configurable:!0});var e=Object.defineProperty,R=L((_,E)=>e(_,"name",{value:E,configurable:!0}),"R");Object.defineProperty(exports,"__esModule",{value:!0}),exports.BODY_STALL_MS=exports.GATEWAY_CONN_CHECK_MS=exports.GATEWAY_MAX_CONNECTIONS=exports.GATEWAY_STOP_GRACE_MS=exports.GATEWAY_HEADERS_TIMEOUT_MS=exports.GATEWAY_KEEPALIVE_TIMEOUT_MS=exports.LENS_REQUEST_RECOVERY_WAIT_MS=exports.LENS_REPLACEMENT_DRAIN_MS=exports.LENS_REPLACEMENT_READY_MS=exports.LENS_RESTART_MODE=exports.LENS_RECYCLE_KILL_GRACE_MS=exports.LENS_PARKED_PORT_REPROBE_MS=exports.MAX_PORT_CONFLICT_RETRIES=exports.CHILD_START_FAIL_MS=exports.PORT_FREE_POLL_MS=exports.PORT_FREE_WAIT_MS=exports.LENS_PROBE_BOOT_GRACE_MS=exports.LENS_PROBE_COOLDOWN_MS=exports.LENS_PROBE_TIMEOUT_MS=exports.LENS_PROBE_FAILS=exports.LENS_PROBE_GRACE_MS=exports.MAX_COLD_STARTS=exports.ORPHAN_REAP_EVERY_MS=exports.TREE_KILL_GRACE_MS=exports.POD_MAX_CONCURRENT_ROLLS=exports.POD_ROLL_READY_MS=exports.POD_RECYCLE_MODE=exports.POD_WATCHER_SILENT=exports.POD_WATCHER_UNVERIFIED=exports.LENS_WATCH_SCOPE_ENABLED=exports.LENS_WATCHER_UNVERIFIED=exports.LENS_WATCHER_PROBE_ENABLED=exports.LENS_PROBE_ENABLED=exports.POD_STALE_RECYCLE_COOLDOWN_MS=exports.POD_STALE_SCAN_MS=exports.POD_RECYCLE_SETTLE_MS=exports.POD_STALE_GRACE_MS=exports.POD_MAX_AGE_MS=exports.POD_RECYCLE_ENABLED=exports.WEDGE_RECYCLE_GRACE_MS=exports.POD_ALIVE_PATH=exports.POD_WEDGE_CONFIRM_MS=exports.POD_ALIVE_PROBE_TIMEOUT_MS=exports.POD_SLOW_FIRST_BYTE_MS=exports.POD_RESPONSE_TIMEOUT_MS=exports.UPSTREAM_HEAL_STEP_MS=exports.UPSTREAM_HEAL_WINDOW_MS=exports.SERVICE_RESTART_WINDOW_MS=exports.SERVICE_MAX_RESTARTS=exports.SERVICE_ERROR_THROTTLE_MS=void 0,exports.START_ERROR_LINES=exports.OUTPUT_TAIL_LINES=exports.GATEWAY_H2_RESET_RATE=exports.GATEWAY_H2_RESET_BURST=void 0;const tslib_1=require("tslib"),os=tslib_1.__importStar(require("node:os"));function envInt(_,E,M=!1){const S=Number(process.env[_]);return!Number.isFinite(S)||S<0?E:S===0?M?0:E:S}L(envInt,"envInt"),R(envInt,"envInt"),exports.SERVICE_ERROR_THROTTLE_MS=5e3,exports.SERVICE_MAX_RESTARTS=5,exports.SERVICE_RESTART_WINDOW_MS=6e4,exports.UPSTREAM_HEAL_WINDOW_MS=8e3,exports.UPSTREAM_HEAL_STEP_MS=300,exports.POD_RESPONSE_TIMEOUT_MS=(()=>{const _=Number(process.env.LENSMCP_POD_RESPONSE_TIMEOUT_MS);return Number.isFinite(_)&&_>0?_:3e4})(),exports.POD_SLOW_FIRST_BYTE_MS=envInt("LENSMCP_POD_SLOW_FIRST_BYTE_MS",10*6e4,!0),exports.POD_ALIVE_PROBE_TIMEOUT_MS=envInt("LENSMCP_POD_ALIVE_PROBE_TIMEOUT_MS",1e3),exports.POD_WEDGE_CONFIRM_MS=envInt("LENSMCP_POD_WEDGE_CONFIRM_MS",1e4,!0),exports.POD_ALIVE_PATH="/__lensmcp/alive",exports.WEDGE_RECYCLE_GRACE_MS=(()=>{const _=Number(process.env.LENSMCP_WEDGE_RECYCLE_GRACE_MS);return Number.isFinite(_)&&_>0?_:15e3})(),exports.POD_RECYCLE_ENABLED=process.env.LENSMCP_POD_RECYCLE!=="0",exports.POD_MAX_AGE_MS=envInt("LENSMCP_POD_MAX_AGE_MS",240*6e4,!0),exports.POD_STALE_GRACE_MS=envInt("LENSMCP_POD_STALE_GRACE_MS",1e4),exports.POD_RECYCLE_SETTLE_MS=envInt("LENSMCP_POD_RECYCLE_SETTLE_MS",8e3),exports.POD_STALE_SCAN_MS=envInt("LENSMCP_POD_STALE_SCAN_MS",3e4),exports.POD_STALE_RECYCLE_COOLDOWN_MS=envInt("LENSMCP_POD_STALE_RECYCLE_COOLDOWN_MS",6e4),exports.LENS_PROBE_ENABLED=process.env.LENSMCP_LENS_PROBE!=="0",exports.LENS_WATCHER_PROBE_ENABLED=process.env.LENSMCP_LENS_WATCHER_PROBE!=="0",exports.LENS_WATCHER_UNVERIFIED=process.env.LENSMCP_LENS_WATCHER_UNVERIFIED==="keep"?"keep":"recycle",exports.LENS_WATCH_SCOPE_ENABLED=process.env.LENSMCP_LENS_WATCH_SCOPE!=="0",exports.POD_WATCHER_UNVERIFIED=process.env.LENSMCP_POD_WATCHER_UNVERIFIED==="keep"?"keep":"recycle",exports.POD_WATCHER_SILENT=process.env.LENSMCP_POD_WATCHER_SILENT==="recycle"?"recycle":"keep",exports.POD_RECYCLE_MODE=process.env.LENSMCP_POD_RECYCLE_MODE==="in-place"?"in-place":"rolling",exports.POD_ROLL_READY_MS=envInt("LENSMCP_POD_ROLL_READY_MS",18e4),exports.POD_MAX_CONCURRENT_ROLLS=envInt("LENSMCP_POD_MAX_CONCURRENT_ROLLS",2,!0),exports.TREE_KILL_GRACE_MS=envInt("LENSMCP_TREE_KILL_GRACE_MS",1e4,!0),exports.ORPHAN_REAP_EVERY_MS=envInt("LENSMCP_ORPHAN_REAP_MS",3e5,!0),exports.MAX_COLD_STARTS=envInt("LENSMCP_MAX_COLD_STARTS",Math.max(2,Math.floor(os.availableParallelism()/2)),!0),exports.LENS_PROBE_GRACE_MS=envInt("LENSMCP_LENS_PROBE_GRACE_MS",45e3),exports.LENS_PROBE_FAILS=envInt("LENSMCP_LENS_PROBE_FAILS",2),exports.LENS_PROBE_TIMEOUT_MS=envInt("LENSMCP_LENS_PROBE_TIMEOUT_MS",1e3),exports.LENS_PROBE_COOLDOWN_MS=envInt("LENSMCP_LENS_PROBE_COOLDOWN_MS",3e4),exports.LENS_PROBE_BOOT_GRACE_MS=envInt("LENSMCP_LENS_PROBE_BOOT_GRACE_MS",24e4),exports.PORT_FREE_WAIT_MS=envInt("LENSMCP_PORT_FREE_WAIT_MS",1e4),exports.PORT_FREE_POLL_MS=envInt("LENSMCP_PORT_FREE_POLL_MS",250),exports.CHILD_START_FAIL_MS=envInt("LENSMCP_CHILD_START_FAIL_MS",1e4),exports.MAX_PORT_CONFLICT_RETRIES=envInt("LENSMCP_MAX_PORT_CONFLICT_RETRIES",5),exports.LENS_PARKED_PORT_REPROBE_MS=envInt("LENSMCP_PARKED_PORT_REPROBE_MS",3e5),exports.LENS_RECYCLE_KILL_GRACE_MS=envInt("LENSMCP_RECYCLE_KILL_GRACE_MS",5e3),exports.LENS_RESTART_MODE=process.env.LENSMCP_LENS_RESTART_MODE==="in-place"?"in-place":"rolling",exports.LENS_REPLACEMENT_READY_MS=envInt("LENSMCP_LENS_REPLACEMENT_READY_MS",3e4),exports.LENS_REPLACEMENT_DRAIN_MS=envInt("LENSMCP_LENS_REPLACEMENT_DRAIN_MS",2e3,!0),exports.LENS_REQUEST_RECOVERY_WAIT_MS=envInt("LENSMCP_LENS_REQUEST_RECOVERY_WAIT_MS",15e3),exports.GATEWAY_KEEPALIVE_TIMEOUT_MS=envInt("LENSMCP_KEEPALIVE_TIMEOUT_MS",76e3),exports.GATEWAY_HEADERS_TIMEOUT_MS=envInt("LENSMCP_HEADERS_TIMEOUT_MS",6e4),exports.GATEWAY_STOP_GRACE_MS=envInt("LENSMCP_STOP_GRACE_MS",3e3),exports.GATEWAY_MAX_CONNECTIONS=envInt("LENSMCP_MAX_CONNECTIONS",0,!0),exports.GATEWAY_CONN_CHECK_MS=envInt("LENSMCP_CONN_CHECK_MS",0,!0),exports.BODY_STALL_MS=envInt("LENSMCP_BODY_STALL_MS",6e4,!0),exports.GATEWAY_H2_RESET_BURST=envInt("LENSMCP_H2_RESET_BURST",1e5),exports.GATEWAY_H2_RESET_RATE=envInt("LENSMCP_H2_RESET_RATE",1e4),exports.OUTPUT_TAIL_LINES=19,exports.START_ERROR_LINES=20;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type * as http from 'node:http';
|
|
2
2
|
import type * as stream from 'node:stream';
|
|
3
|
+
import { type ParkedHostLookup } from './on-demand';
|
|
3
4
|
import type { GatewayRuntime, HookHandler } from './types';
|
|
4
5
|
import type { EdgeAuth } from './auth';
|
|
5
6
|
import type { ProxyLayer } from './proxy';
|
|
@@ -21,6 +22,8 @@ export interface UpgradeDeps {
|
|
|
21
22
|
preAuth: HookHandler;
|
|
22
23
|
beforeForward: HookHandler;
|
|
23
24
|
};
|
|
25
|
+
/** Which parked on-demand worktree a host names (on-demand.ts); the default reads `~/.lensmcp/instances.json`. */
|
|
26
|
+
parkedHosts?: ParkedHostLookup;
|
|
24
27
|
}
|
|
25
28
|
/** One report per frontend per this window: a reload storm must not become a log storm. */
|
|
26
29
|
export declare const LENS_HMR_REFUSAL_REPORT_MS = 10000;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var q=Object.defineProperty;var _=(c,o)=>q(c,"name",{value:o,configurable:!0});var k=Object.defineProperty,d=_((c,o)=>k(c,"name",{value:o,configurable:!0}),"d");Object.defineProperty(exports,"__esModule",{value:!0}),exports.LENS_HMR_REFUSAL_REPORT_MS=void 0,exports.createUpgrade=createUpgrade;const tslib_1=require("tslib"),path=tslib_1.__importStar(require("node:path")),manifest_1=require("../manifest"),discovery_1=require("./discovery"),edge_1=require("./edge"),hmr_reload_1=require("./hmr-reload"),on_demand_1=require("./on-demand"),service_keys_1=require("./service-keys");exports.LENS_HMR_REFUSAL_REPORT_MS=1e4;function accountUpgrade(c,o){const l=c.svc;if(!l||o.destroyed)return;l.inflight+=1,l.lastUsed=Date.now();let u=!1;o.once("close",()=>{u||(u=!0,l.inflight-=1,l.lastUsed=Date.now())})}_(accountUpgrade,"accountUpgrade"),d(accountUpgrade,"accountUpgrade");function createUpgrade(c){const{rt:o,auth:l,proxy:u,hooks:p,obs:K,middleware:g}=c;let H=c.parkedHosts;const M=d(()=>H??=(0,on_demand_1.createParkedHostLookup)({registry:d(()=>o.registry,"registry")}),"parkedHosts"),h=new Set,m=d(e=>{e.destroyed||(h.add(e),e.once("close",()=>h.delete(e)))},"track");u.proxy.on?.("open",m);const v=new WeakMap,R=new Map,b=d((e,t)=>{const n=Date.now();n-(R.get(e.frontendKey)??0)<exports.LENS_HMR_REFUSAL_REPORT_MS||(R.set(e.frontendKey,n),console.warn(`[gateway] lens HMR socket refused: ${e.frontendKey} at ${e.target} answered ${t} for a tab on ${e.host} \u2014 that tab loads but gets no hot updates; the lens runtime reloads it once if it had a socket before.`),K?.emit("warning",`lens HMR socket refused: ${e.frontendKey} (${t})`,`cluster-lens-hmr-refused:${e.frontendKey}`,{kind:"lens-hmr-refused",frontendKey:e.frontendKey,host:e.host,target:e.target,answer:t},void 0,e.busFile))},"reportRefusal");u.proxy.on?.("proxyReqWs",(e,t)=>{const n=v.get(t);if(!n)return;const i=e;i.once("upgrade",()=>{n.answered=!0}),i.once("response",f=>{n.answered=!0,b(n,`HTTP ${f.statusCode??"?"}`)})});const U=d(async(e,t,n)=>{(0,edge_1.stripOwnedHeaders)(e);const i=(0,edge_1.canonicalize)(e.url??"/");if(i===void 0){t.destroy();return}e.url=i.path+i.query;const f=(e.headers.host||"").split(":")[0],r=(0,manifest_1.matchRoute)(o.routes,f,i.policy+i.query);if((!r||!r.host||r.host.startsWith("*."))&&M().match(f)){t.destroy();return}if(!r){t.destroy();return}(0,edge_1.resolveClientIp)(o,e);const a=p.upgradeContext(e,t,void 0);if(a.route=r,r.internal){const s=l.internal(e,r,void 0);if(!s.ok){t.destroy();return}a.caller=s.caller}else{if(g&&(await g.preAuth(a),a.responded()))return;const s=l.public(e,r,void 0,i.policy);if(!s.ok){t.destroy();return}if(a.claims=s.claims,p.has("afterAuth")&&(await p.run("afterAuth",a),a.responded()))return}const S=r.pool?o.serviceKeys[(0,service_keys_1.serviceKeyId)(r.svc?.wsKey,r.project)]:void 0;if(S&&(e.headers["x-internal-token"]=S),r.prependPrefix&&!e.url?.startsWith(r.prependPrefix)&&(e.url=r.prependPrefix+(e.url??"/")),(0,edge_1.stampForwardingHeaders)(o,e),g&&!r.internal&&(await g.beforeForward(a),a.responded())||p.has("onUpgrade")&&(await p.run("onUpgrade",a),a.responded()))return;const w=r.pool?(()=>{const s=(0,discovery_1.pickSock)(r.pool,o.scanTtlMs);return s?{socketPath:s}:void 0})():r.target;if(!w){t.destroy();return}if(r.lens&&String(e.headers["sec-websocket-protocol"]??"").split(",").map(s=>s.trim()).includes("vite-hmr")){const s=r.lens.workspaceKey?`${r.lens.workspaceKey}:${r.lens.project}`:r.lens.project;(0,hmr_reload_1.registerHmrClient)(o,s,t);const y=!r.lens.workspaceRoot||path.resolve(r.lens.workspaceRoot)===path.resolve(o.root??"");v.set(e,{frontendKey:s,host:f,target:String(w),answered:!1,...y?{}:{busFile:path.join(r.lens.workspaceRoot,".lensmcp","events.jsonl")}})}accountUpgrade(r,t),(0,on_demand_1.touchRun)(o.registry,r,t),u.proxy.ws(e,t,n,{target:w,changeOrigin:!r.pool,agent:u.agentForTarget(w)},s=>{const y=v.get(e);y&&!y.answered&&b(y,s?.code??s?.message??"an error"),t.destroy()})},"run"),x=d(((e,t,n)=>{t.on("error",()=>t.destroy()),m(t),U(e,t,n).catch(()=>t.destroy())}),"listener");return x.closeTunnels=()=>{const e=[...h];for(const t of e)t.destroy();return h.clear(),e.length},x}_(createUpgrade,"createUpgrade"),d(createUpgrade,"createUpgrade");
|
|
@@ -5,6 +5,12 @@ export declare const WARM_MIN_FREE_ENV = "LENSMCP_WARM_MIN_FREE_MB";
|
|
|
5
5
|
export declare const DEFAULT_WARM_MIN_FREE_MB = 4096;
|
|
6
6
|
export declare const WORKTREE_IDLE_ENV = "LENSMCP_WORKTREE_IDLE_SEC";
|
|
7
7
|
export declare const DEFAULT_WORKTREE_IDLE_SEC = 1800;
|
|
8
|
+
export declare const MAIN_ALWAYS_UP_ENV = "LENSMCP_MAIN_ALWAYS_UP";
|
|
9
|
+
/**
|
|
10
|
+
* Is the main checkout always up — every one of the daemon's own services started at boot, none stopped for idleness?
|
|
11
|
+
* On unless `0`, `off`, `false` or `no` (any case). Read where it is used, so a kept setting applies at the next start.
|
|
12
|
+
*/
|
|
13
|
+
export declare function mainAlwaysUp(env?: NodeJS.ProcessEnv): boolean;
|
|
8
14
|
/** The floor a warm start keeps, in bytes. */
|
|
9
15
|
export declare function warmMinFreeBytes(env?: NodeJS.ProcessEnv): number;
|
|
10
16
|
/**
|
|
@@ -15,6 +21,8 @@ export declare function instanceIdleSec(svc: Pick<ServiceCtl, 'decl'>, isInstanc
|
|
|
15
21
|
/**
|
|
16
22
|
* The idle window the sweep gives `svc` (lifecycle.ts `sweepOnce`) — {@link instanceIdleSec}, an instance being a
|
|
17
23
|
* registered worktree's service, never the daemon's own. One rule for the sweep and for what `/status` says of it.
|
|
24
|
+
* While the main checkout is always up ({@link mainAlwaysUp}) the daemon's own services have none — not even a declared
|
|
25
|
+
* `idleKillSec` (OD-D3: FoodGuard's foodguard-mcp, processor and channels declare 900).
|
|
18
26
|
*/
|
|
19
27
|
export declare function serviceIdleSec(rt: {
|
|
20
28
|
readonly root?: string;
|
|
@@ -43,10 +51,13 @@ export interface WarmStartDeps {
|
|
|
43
51
|
/** Onto the service's own bus. */
|
|
44
52
|
emit(svc: ServiceCtl, severity: 'info' | 'warning', title: string, raw: Record<string, unknown>): void;
|
|
45
53
|
log(line: string): void;
|
|
54
|
+
/** Which services to start: the always-warm ones (`decl.eager`) unless said otherwise — main's rest for `warmOwn`. */
|
|
55
|
+
select?: (svc: ServiceCtl) => boolean;
|
|
46
56
|
}
|
|
47
57
|
export interface WarmOutcome {
|
|
48
58
|
project: string;
|
|
49
|
-
|
|
59
|
+
/** `skipped`: stopped by hand — a warm start does not undo what a person stopped. */
|
|
60
|
+
outcome: 'up' | 'failed' | 'deferred' | 'already' | 'skipped';
|
|
50
61
|
reason?: string;
|
|
51
62
|
}
|
|
52
63
|
/** Why a start waits, when the memory the system can still give out is under the floor; nothing when it is not (or unread). */
|
|
@@ -73,10 +84,13 @@ export interface WorktreeWarmerDeps {
|
|
|
73
84
|
export declare function createWorktreeWarmer(deps: WorktreeWarmerDeps): {
|
|
74
85
|
onRegister(fragment: WorkspaceFragment): Promise<WarmOutcome[]> | undefined;
|
|
75
86
|
onUnregister(wsKey: string): void;
|
|
87
|
+
/** {@link take}: the machine's one turn. */
|
|
88
|
+
take: <T>(job: () => Promise<T>) => Promise<T>;
|
|
76
89
|
/**
|
|
77
|
-
*
|
|
78
|
-
*
|
|
79
|
-
*
|
|
90
|
+
* MAIN ALWAYS UP (OD-D3): the daemon's own services that are not always-warm, started one at a time in the machine's
|
|
91
|
+
* one turn — after the daemon's own eager ones have settled ({@link WorktreeWarmerDeps.ready}), before any worktree
|
|
92
|
+
* asked after this call — while the floor holds. Below it the rest start on their first request, each saying why on
|
|
93
|
+
* the daemon's bus. Call it at boot, before any registration, so main warms first.
|
|
80
94
|
*/
|
|
81
|
-
|
|
95
|
+
warmOwn(services: readonly ServiceCtl[]): Promise<WarmOutcome[]>;
|
|
82
96
|
};
|