@lensmcp/cluster 1.22.2 → 1.22.4
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/handler.js +1 -1
- package/executors/gateway/runtime/lens-children.d.ts +12 -0
- package/executors/gateway/runtime/lens-children.js +1 -1
- package/executors/gateway/runtime/observability.d.ts +2 -1
- package/executors/gateway/runtime/observability.js +2 -2
- package/executors/gateway/runtime/proxy.js +1 -1
- package/package.json +4 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var O=Object.defineProperty;var w=(p,i)=>O(p,"name",{value:i,configurable:!0});var E=Object.defineProperty,h=w((p,i)=>E(p,"name",{value:i,configurable:!0}),"h");Object.defineProperty(exports,"__esModule",{value:!0}),exports.createHandler=createHandler;const manifest_1=require("../manifest"),service_keys_1=require("./service-keys"),gateway_errors_1=require("../gateway-errors"),discovery_1=require("./discovery"),edge_1=require("./edge"),observability_1=require("./observability"),chooser_1=require("./chooser");function createHandler(p){const{rt:i,obs:d,auth:y,proxy:m,hooks:c}=p,g=h(e=>(e.headers.host||"").split(":")[0],"hostOf"),_=h((e,r)=>{if((0,edge_1.cors)(e,r,i.routes),e.method==="OPTIONS"){r.writeHead(204,{"access-control-allow-methods":edge_1.PREFLIGHT_METHODS_NOROUTE,"access-control-allow-headers":String(e.headers["access-control-request-headers"]??"*")}),r.end();return}const s=(e.headers.host||"").split(":")[0],t=i.routes.filter(o=>o.host&&(0,manifest_1.hostMatches)(o.host,s)&&o.prefix),n=(e.url??"/").split("?")[0];if((n==="/"||n==="/index.html"||n==="")&&i.routes.some(o=>o.host&&(0,manifest_1.hostMatches)(o.host,s)&&o.project===observability_1.LENS_DASHBOARD_PROJECT)){(0,chooser_1.serveChooser)(r,i.wsKey,e);return}if(t.length>0&&(n==="/health"||n==="/healthz")){const o=t.map(l=>({project:l.project,prefix:l.prefix,pods:l.pool?((0,discovery_1.pickSock)(l.pool,0),l.pool.socks.length):void 0,state:l.svc?.state??(l.target?"up":"unknown")})),f=o.every(l=>l.state!=="down"||!0);r.writeHead(f?200:503,{"content-type":"application/json"}),r.end(JSON.stringify({status:"ok",host:s,services:o},null,2));return}if(t.length>0&&n==="/.well-known/services"){r.writeHead(200,{"content-type":"application/json"}),r.end(JSON.stringify({host:s,services:t.map(o=>({prefix:o.prefix,project:o.project,internal:!!o.internal}))},null,2));return}(0,edge_1.sendError)(r,e,404,"not_found",t.length>0?`No service mounted at ${n}. Mounted on ${s}: ${[...new Set(t.map(o=>o.prefix))].join(", ")} (+ /health, /.well-known/services)`:"No gateway route for this hostname.")},"handleNoRoute"),S=h(async(e,r)=>{if(!e.headers.host){const n=e.authority??e.headers[":authority"];n&&(e.headers.host=n)}for(const n of edge_1.GATEWAY_OWNED_HEADERS)delete e.headers[n];(0,gateway_errors_1.ensureRequestId)(e);const s=d.beginTrace(e);s&&(d.traceStep(s,"received",{host:s.host,method:s.method,url:s.url}),e.__lensmcpTrace=s);const t=c.httpContext(e,r,s);try{const n=e.url??"/",o=(0,edge_1.canonicalize)(n);if(o===void 0){d.traceStep(s,"bad-path",{}),d.finishTrace(s,"gateway",400),(0,edge_1.sendError)(r,e,400,"bad_request","Bad Request");return}const f=o.policy,l=o.path+o.query;if(l!==n&&(0,edge_1.rememberRawTarget)(e,n),e.url=l,(0,edge_1.resolveClientIp)(i,e),c.has("onRequest")&&(await c.run("onRequest",t),t.responded()))return;const a=(0,manifest_1.matchRoute)(i.routes,g(e),f+o.query);if(!a){_(e,r);return}if(t.route=a,d.traceStep(s,"route-match",{project:a.project,...a.prefix?{prefix:a.prefix}:{},...a.host?{routeHost:a.host}:{},...a.internal?{internal:!0}:{}}),e.method==="OPTIONS"){(0,edge_1.cors)(e,r,i.routes),r.writeHead(204,{"access-control-allow-methods":edge_1.PREFLIGHT_METHODS_ROUTED,"access-control-allow-headers":String(e.headers["access-control-request-headers"]??"*")}),r.end();return}if((0,edge_1.cors)(e,r,i.routes),c.has("beforeAuth")&&(await c.run("beforeAuth",t),t.responded()))return;if(a.internal){const u=y.internal(e,a,s);if(!u.ok){d.finishTrace(s,a.project,u.status),(0,edge_1.sendError)(r,e,u.status,u.reason,u.detail);return}t.caller=u.caller}else{const u=y.public(e,a,s,f);if(!u.ok){d.finishTrace(s,a.project,u.status),(0,edge_1.sendError)(r,e,u.status,u.reason,u.detail);return}if(t.claims=u.claims,c.has("afterAuth")&&(await c.run("afterAuth",t),t.responded()))return}const v=a.pool?i.serviceKeys[(0,service_keys_1.serviceKeyId)(a.svc?.wsKey,a.project)]:void 0;if(v&&(e.headers["x-internal-token"]=v),(0,edge_1.stampForwardingHeaders)(i,e),c.has("beforeForward")&&(await c.run("beforeForward",t),t.responded()))return;c.has("onResponse")&&r.on("close",()=>{t.status=r.statusCode??0,c.run("onResponse",t)}),m.forward(a,e,r)}catch(n){t.error=n,console.error(`[gateway] ${new Date().toISOString()} pipeline error traceId=${(0,gateway_errors_1.ensureRequestId)(e)}: ${n?.stack??String(n)}`),c.has("onError")&&await c.run("onError",t),t.responded()||(0,edge_1.sendError)(r,e,500,"internal","Internal gateway error.")}},"runPipeline");return(e,r)=>{S(e,r)}}w(createHandler,"createHandler"),h(createHandler,"createHandler");
|
|
1
|
+
"use strict";var O=Object.defineProperty;var w=(p,i)=>O(p,"name",{value:i,configurable:!0});var E=Object.defineProperty,h=w((p,i)=>E(p,"name",{value:i,configurable:!0}),"h");Object.defineProperty(exports,"__esModule",{value:!0}),exports.createHandler=createHandler;const manifest_1=require("../manifest"),service_keys_1=require("./service-keys"),gateway_errors_1=require("../gateway-errors"),discovery_1=require("./discovery"),edge_1=require("./edge"),observability_1=require("./observability"),chooser_1=require("./chooser");function createHandler(p){const{rt:i,obs:d,auth:y,proxy:m,hooks:c}=p,g=h(e=>(e.headers.host||"").split(":")[0],"hostOf"),_=h((e,r)=>{if((0,edge_1.cors)(e,r,i.routes),e.method==="OPTIONS"){r.writeHead(204,{"access-control-allow-methods":edge_1.PREFLIGHT_METHODS_NOROUTE,"access-control-allow-headers":String(e.headers["access-control-request-headers"]??"*")}),r.end();return}const s=(e.headers.host||"").split(":")[0],t=i.routes.filter(o=>o.host&&(0,manifest_1.hostMatches)(o.host,s)&&o.prefix),n=(e.url??"/").split("?")[0];if((n==="/"||n==="/index.html"||n==="")&&i.routes.some(o=>o.host&&(0,manifest_1.hostMatches)(o.host,s)&&o.project===observability_1.LENS_DASHBOARD_PROJECT)){(0,chooser_1.serveChooser)(r,i.wsKey,e);return}if(t.length>0&&(n==="/health"||n==="/healthz")){const o=t.map(l=>({project:l.project,prefix:l.prefix,pods:l.pool?((0,discovery_1.pickSock)(l.pool,0),l.pool.socks.length):void 0,state:l.svc?.state??(l.target?"up":"unknown")})),f=o.every(l=>l.state!=="down"||!0);r.writeHead(f?200:503,{"content-type":"application/json"}),r.end(JSON.stringify({status:"ok",host:s,services:o},null,2));return}if(t.length>0&&n==="/.well-known/services"){r.writeHead(200,{"content-type":"application/json"}),r.end(JSON.stringify({host:s,services:t.map(o=>({prefix:o.prefix,project:o.project,internal:!!o.internal}))},null,2));return}(0,edge_1.sendError)(r,e,404,"not_found",t.length>0?`No service mounted at ${n}. Mounted on ${s}: ${[...new Set(t.map(o=>o.prefix))].join(", ")} (+ /health, /.well-known/services)`:"No gateway route for this hostname.")},"handleNoRoute"),S=h(async(e,r)=>{if(!e.headers.host){const n=e.authority??e.headers[":authority"];n&&(e.headers.host=n)}for(const n of edge_1.GATEWAY_OWNED_HEADERS)delete e.headers[n];(0,gateway_errors_1.ensureRequestId)(e);const s=d.beginTrace(e);s&&(d.traceStep(s,"received",{host:s.host,method:s.method,url:s.url}),e.__lensmcpTrace=s);const t=c.httpContext(e,r,s);try{const n=e.url??"/",o=(0,edge_1.canonicalize)(n);if(o===void 0){d.traceStep(s,"bad-path",{}),d.finishTrace(s,"gateway",400),(0,edge_1.sendError)(r,e,400,"bad_request","Bad Request");return}const f=o.policy,l=o.path+o.query;if(l!==n&&(0,edge_1.rememberRawTarget)(e,n),e.url=l,(0,edge_1.resolveClientIp)(i,e),c.has("onRequest")&&(await c.run("onRequest",t),t.responded()))return;const a=(0,manifest_1.matchRoute)(i.routes,g(e),f+o.query);if(!a){_(e,r);return}if(t.route=a,d.traceStep(s,"route-match",{project:a.project,...a.prefix?{prefix:a.prefix}:{},...a.host?{routeHost:a.host}:{},...a.internal?{internal:!0}:{}}),e.method==="OPTIONS"){(0,edge_1.cors)(e,r,i.routes),r.writeHead(204,{"access-control-allow-methods":edge_1.PREFLIGHT_METHODS_ROUTED,"access-control-allow-headers":String(e.headers["access-control-request-headers"]??"*")}),r.end();return}if((0,edge_1.cors)(e,r,i.routes),c.has("beforeAuth")&&(await c.run("beforeAuth",t),t.responded()))return;if(a.internal){const u=y.internal(e,a,s);if(!u.ok){d.finishTrace(s,a.project,u.status,void 0,a),(0,edge_1.sendError)(r,e,u.status,u.reason,u.detail);return}t.caller=u.caller}else{const u=y.public(e,a,s,f);if(!u.ok){d.finishTrace(s,a.project,u.status,void 0,a),(0,edge_1.sendError)(r,e,u.status,u.reason,u.detail);return}if(t.claims=u.claims,c.has("afterAuth")&&(await c.run("afterAuth",t),t.responded()))return}const v=a.pool?i.serviceKeys[(0,service_keys_1.serviceKeyId)(a.svc?.wsKey,a.project)]:void 0;if(v&&(e.headers["x-internal-token"]=v),(0,edge_1.stampForwardingHeaders)(i,e),c.has("beforeForward")&&(await c.run("beforeForward",t),t.responded()))return;c.has("onResponse")&&r.on("close",()=>{t.status=r.statusCode??0,c.run("onResponse",t)}),m.forward(a,e,r)}catch(n){t.error=n,console.error(`[gateway] ${new Date().toISOString()} pipeline error traceId=${(0,gateway_errors_1.ensureRequestId)(e)}: ${n?.stack??String(n)}`),c.has("onError")&&await c.run("onError",t),t.responded()||(0,edge_1.sendError)(r,e,500,"internal","Internal gateway error.")}},"runPipeline");return(e,r)=>{S(e,r)}}w(createHandler,"createHandler"),h(createHandler,"createHandler");
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type ChildProcess } from 'node:child_process';
|
|
1
2
|
import { type SpawnChild } from '@lensmcp/nx-plugin/lens-frontend';
|
|
2
3
|
import type { WorkspaceFragment } from './route-registry';
|
|
3
4
|
import type { GatewayRuntime, GatewayRuntimeOptions, LensWatcherHealth } from './types';
|
|
@@ -37,6 +38,17 @@ export declare function waitForPortFree(port: number, timeoutMs: number, deps?:
|
|
|
37
38
|
* this child owns — the port the liveness probe checks and the port its respawn must wait to be free.
|
|
38
39
|
* `undefined` for an unpinned child (nothing to probe, nothing to wait for). */
|
|
39
40
|
export declare function viteArgPort(args: readonly string[]): number | undefined;
|
|
41
|
+
/**
|
|
42
|
+
* Why a child process is gone, in the few words a log line can carry.
|
|
43
|
+
*
|
|
44
|
+
* A SIGNAL and an exit CODE are different diagnoses and the difference is the whole value: a signal
|
|
45
|
+
* means something OUTSIDE the process ended it (the OS reclaiming memory, a stray `pkill`, the recycle
|
|
46
|
+
* escalation), a non-zero code means the process decided to leave on its own terms (a heap abort at
|
|
47
|
+
* 134, a refused `--strictPort` bind at 1). Node sets exactly one of the two, so reading both and
|
|
48
|
+
* naming which one fired is the entire diagnosis. Pure, and reads `exitCode`/`signalCode` rather than
|
|
49
|
+
* taking them as arguments, because both are already settled by the time an 'exit' handler runs.
|
|
50
|
+
*/
|
|
51
|
+
export declare function describeChildExit(child: Pick<ChildProcess, 'exitCode' | 'signalCode'>): string;
|
|
40
52
|
export interface LensChildren {
|
|
41
53
|
spawnManagedChild: SpawnChild;
|
|
42
54
|
/** Boot the dashboard + MCP singletons and every `lens:true` app. Pushes the
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var Re=Object.defineProperty;var P=(s,f)=>Re(s,"name",{value:f,configurable:!0});var Le=Object.defineProperty,d=P((s,f)=>Le(s,"name",{value:f,configurable:!0}),"d");Object.defineProperty(exports,"__esModule",{value:!0}),exports.probePortFree=probePortFree,exports.probePortListening=probePortListening,exports.probeWatcherHealth=probeWatcherHealth,exports.waitForPortFree=waitForPortFree,exports.viteArgPort=viteArgPort,exports.claimPort=claimPort,exports.createLensChildren=createLensChildren;const tslib_1=require("tslib"),net=tslib_1.__importStar(require("node:net")),path=tslib_1.__importStar(require("node:path")),node_child_process_1=require("node:child_process"),lens_frontend_1=require("@lensmcp/nx-plugin/lens-frontend"),hmr_reload_1=require("./hmr-reload"),pod_env_1=require("./pod-env"),scope_1=require("./scope"),workspace_registry_1=require("./workspace-registry"),lifecycle_1=require("./lifecycle"),types_1=require("./types"),observability_1=require("./observability"),HEAL_BASE_MS=1500,HEAL_MAX_MS=3e4,HEAL_HEALTHY_MS=2e4;function tryBind(s,f){return new Promise(u=>{const _=net.createServer();_.unref(),_.once("error",p=>{const E=p.code??"";u(E==="EADDRINUSE"||E==="EACCES"?"in-use":"unavailable")}),_.listen(f===void 0?{port:s}:{port:s,host:f},()=>_.close(()=>u("free")))})}P(tryBind,"tryBind"),d(tryBind,"tryBind");async function probePortFree(s){for(const f of[void 0,"0.0.0.0","127.0.0.1","::1"])if(await tryBind(s,f)==="in-use")return!1;return!0}P(probePortFree,"probePortFree"),d(probePortFree,"probePortFree");function probeConnect(s,f,u){return new Promise(_=>{let p=!1;const E=net.createConnection({host:s,port:f});E.unref();const C=setTimeout(()=>y(!1),u);C.unref?.();function y(k){p||(p=!0,clearTimeout(C),E.destroy(),_(k))}P(y,"y"),d(y,"finish"),E.once("connect",()=>y(!0)),E.once("error",()=>y(!1))})}P(probeConnect,"probeConnect"),d(probeConnect,"probeConnect");async function probePortListening(s,f=1e3){return await probeConnect("127.0.0.1",s,f)?!0:probeConnect("::1",s,f)}P(probePortListening,"probePortListening"),d(probePortListening,"probePortListening");async function probeWatcherHealth(s,f=1500){try{const u=new AbortController,_=setTimeout(()=>u.abort(),f);_.unref?.();try{const p=await fetch(`http://127.0.0.1:${s}/__lensmcp/watcher-health`,{signal:u.signal});if(!p.ok)return null;const E=await p.json();if(typeof E?.lastFsSetEventAt!="number")return null;const C=Array.isArray(E.recentEvents)?E.recentEvents.filter(y=>y&&typeof y.path=="string"&&typeof y.at=="number"&&typeof y.sequence=="number"&&["add","addDir","unlink","unlinkDir"].includes(y.kind)):[];return{schemaVersion:E.schemaVersion===2?2:1,ready:E.ready!==!1,sequence:typeof E.sequence=="number"?E.sequence:0,lastFsSetEventAt:E.lastFsSetEventAt,fsSetEvents:typeof E.fsSetEvents=="number"?E.fsSetEvents:0,recentEvents:C}}finally{clearTimeout(_)}}catch{return null}}P(probeWatcherHealth,"probeWatcherHealth"),d(probeWatcherHealth,"probeWatcherHealth");const sleepUnref=d(s=>new Promise(f=>{setTimeout(f,s).unref?.()}),"sleepUnref");async function waitForPortFree(s,f,u={}){const _=u.isPortFree??probePortFree,p=Math.max(1,u.intervalMs??types_1.PORT_FREE_POLL_MS),E=Date.now()+Math.max(0,f);for(;;){if(await _(s))return!0;const C=E-Date.now();if(C<=0)return!1;await sleepUnref(Math.min(p,C))}}P(waitForPortFree,"waitForPortFree"),d(waitForPortFree,"waitForPortFree");function viteArgPort(s){const f=d(u=>Number.isInteger(u)&&u>0&&u<65536?u:void 0,"valid");for(let u=0;u<s.length;u+=1){const _=s[u];if(_==="--port")return f(Number(s[u+1]));if(_.startsWith("--port="))return f(Number(_.slice(7)))}}P(viteArgPort,"viteArgPort"),d(viteArgPort,"viteArgPort");async function claimPort(s,f,u,_){let p=s;for(;f.has(p)||_?.has(p)||!await u(p);)p+=1;return f.add(p),p}P(claimPort,"claimPort"),d(claimPort,"claimPort");function createLensChildren(s,f,u,_){const{emit:p}=f,E=_?.isPortFree??probePortFree,C=_?.probeWatcherHealth??probeWatcherHealth,y=[],k=new Map,A=new Map,j=new Map,W=new Map,K=new Set;let O;const N=new Map,$=new Set,X=new Set,H=new Set,b=new Set,v=new Map,D=new WeakMap,x=new Set,J=d((e,r,n)=>{if(x.has(e))return;x.add(e);const t=setInterval(()=>{(async()=>{if(s.stopped()||$.has(e)){clearInterval(t),x.delete(e);return}await E(r)&&(clearInterval(t),x.delete(e),console.log(`[gateway] lens child ${e}: :${r} freed \u2014 respawning.`),n())})().catch(()=>{})},types_1.LENS_PARKED_PORT_REPROBE_MS);t.unref?.()},"parkUntilPortFree"),F=d(async(e,r,n)=>{const t=await claimPort(e,r,E,n?.reserved);return t!==e&&(n?.heldBy?console.log(`[gateway] handoff: :${e} is held by ${n.heldBy} \u2014 replacement on :${t}.`):console.warn(`[gateway] port ${e} is unavailable (another process holds it \u2014 an orphan from a crashed gateway?) \u2014 using ${t} instead.`)),t},"claimFreePort"),le=d((e,r,n)=>{const t=n?.LENSMCP_FRONTEND_KEY,o=Number(n?.LENSMCP_FRONTEND_GENERATION);if(!t||!Number.isFinite(o))return;const a=[...v.get(t)?.generations??[]].find(i=>i.generation===o);a&&(e.endsWith(":vite")?a.vite=r:e.endsWith(":browser-capture")&&(a.capture=r))},"attachRespawnedGenerationChild"),B=d(e=>{if(!(e.exitCode!==null||e.signalCode!==null)){X.add(e);try{e.kill("SIGTERM")}catch{}setTimeout(()=>{if(e.exitCode===null&&e.signalCode===null)try{e.kill("SIGKILL")}catch{}},types_1.LENS_RECYCLE_KILL_GRACE_MS).unref?.()}},"retireChild"),ce=d((e,r)=>{const n=N.get(e);!n||n===r||n.exitCode!==null||n.signalCode!==null||(console.warn(`[gateway] lens child ${e}: a replacement took the label \u2014 retiring the previous child (pid ${n.pid??"?"}).`),B(n))},"retireLabelHolder"),T=d((e,r,n,t,o=!1,a,i,l)=>{const g=Date.now(),c=(0,node_child_process_1.spawn)(r,n,{cwd:i??s.root,env:{...(0,pod_env_1.podBaseEnv)(process.env,s.root,i??s.root),...t??{},LENSMCP_PARENT_PID:String(process.pid)},stdio:"inherit"});y.push(c),ce(e,c),N.set(e,c),le(e,c,t);const S=e==="vite"||e.endsWith(":vite"),M=typeof t?.LENSMCP_EVENT_FILE=="string"?t.LENSMCP_EVENT_FILE:void 0,L=M&&M!==s.eventFile?M:void 0,w=S?viteArgPort(n):l;S&&A.set(c,{key:t?.LENSMCP_FRONTEND_KEY??`${i??s.root}:${t?.LENSMCP_PROJECT??"app"}`,project:t?.LENSMCP_PROJECT??"app",workspaceRoot:i??s.root,spawnedAt:g,port:w,probeFails:0,listening:!1,generation:Number(t?.LENSMCP_FRONTEND_GENERATION??0),role:t?.LENSMCP_FRONTEND_ROLE==="replacement"?"replacement":"active",...L?{bus:L}:{}});const h=e==="lens-mcp"?"lens-mcp":e==="lens-dashboard"||e.startsWith("lens-dashboard:")?"lens-dashboard":void 0;return h&&w!==void 0&&(p("info",`lens child starting: ${h} (:${w})`,`cluster-lens-child:${h}`,{kind:"lens-child-starting",project:h,label:e,pid:c.pid,port:w},void 0,L),(async()=>{const m=Date.now()+types_1.LENS_REPLACEMENT_READY_MS;for(;!s.stopped()&&Date.now()<m;){if(c.exitCode!==null||c.signalCode!==null||$.has(e))return;if(await probePortListening(w,Math.min(500,types_1.LENS_PROBE_TIMEOUT_MS))){p("info",`lens child up: ${h} (:${w})`,`cluster-lens-child:${h}`,{kind:"lens-child-up",project:h,label:e,pid:c.pid,port:w},void 0,L);return}await sleepUnref(150)}})().catch(()=>{})),c.on("exit",(m,z)=>{const ne=y.indexOf(c);ne>=0&&y.splice(ne,1),N.get(e)===c&&N.delete(e);const re=A.get(c);if(A.delete(c),X.delete(c))return;const ye=$.delete(e);if(s.stopped()||ye||(h&&p("warning",`lens child exited: ${h}`,`cluster-lens-child:${h}`,{kind:"lens-child-exit",project:h,label:e,pid:c.pid,code:m,signal:z},void 0,L),re&&ue(c,re)))return;const se=Date.now()-g,R=k.get(e)??{attempts:0,portConflicts:0};(async()=>{const ve=w!==void 0&&!await E(w),ae=(0,lifecycle_1.isPortConflictExit)({code:m,signal:z,ranMs:se,portHeld:ve},{fastFailMs:types_1.CHILD_START_FAIL_MS});if(ae&&R.portConflicts<types_1.MAX_PORT_CONFLICT_RETRIES)R.portConflicts+=1,k.set(e,R),console.warn(`[gateway] lens child ${e} lost the :${w} bind race (EADDRINUSE, code=${m}); waiting for the port, then retrying (port-retry ${R.portConflicts}/${types_1.MAX_PORT_CONFLICT_RETRIES}; crash budget untouched).`);else if(ae){R.portConflicts=0,k.set(e,R),console.warn(`[gateway] lens child ${e}: :${w} persistently held after ${types_1.MAX_PORT_CONFLICT_RETRIES} bind races \u2014 another server owns it (an external/shared daemon?). Parking; re-probing every ${Math.round(types_1.LENS_PARKED_PORT_REPROBE_MS/1e3)}s, will respawn if it frees.`),p("warning",`lens child parked: ${e} (:${w} held externally)`,`cluster-lens-child:${e}`,{kind:"lens-child-parked",label:e,port:w}),J(e,w,()=>T(e,r,n,t,o,a,i,l));return}else{R.portConflicts=0,se>=HEAL_HEALTHY_MS&&(R.attempts=0);const ie=Math.min(HEAL_MAX_MS,HEAL_BASE_MS*2**R.attempts);R.attempts+=1,k.set(e,R),console.warn(`[gateway] lens child ${e} exited (code=${m} sig=${z}); auto-healing in ${Math.round(ie/1e3)}s (attempt ${R.attempts}).`),await sleepUnref(ie)}s.stopped()||$.has(e)||(w!==void 0&&!await waitForPortFree(w,types_1.PORT_FREE_WAIT_MS,{isPortFree:E,intervalMs:types_1.PORT_FREE_POLL_MS})&&console.warn(`[gateway] lens child ${e}: :${w} still held after ${Math.round(types_1.PORT_FREE_WAIT_MS/1e3)}s \u2014 spawning anyway.`),!(s.stopped()||$.has(e))&&T(e,r,n,t,o,a,i,l))})().catch(()=>{})}),c},"spawnManagedChild"),Q=d(e=>{const r=`${e.wsKey}:${e.project}`,n=v.get(r);if(n)return n;const t={key:r,...e,sourceDirs:e.frontend.sourceRoots?.length?e.frontend.sourceRoots:[e.projectRoot],generation:0,state:"starting",generations:new Set,disposed:!1};v.set(r,t);for(const o of e.routes)o.lens&&(o.lens.workspaceKey??=e.wsKey,D.set(o.lens,t));return e.frontend.workspaceKey??=e.wsKey,D.set(e.frontend,t),t},"registerFrontend"),de=d(e=>{if(!types_1.LENS_WATCH_SCOPE_ENABLED)return{};const r=path.resolve(e.projectRoot),n=e.sourceDirs.map(t=>path.resolve(t)).filter(t=>t!==r);return n.length>0?{LENSMCP_WATCH_DIRS:n.join(path.delimiter)}:{}},"lensWatchScopeEnv"),Z=d((e,r,n)=>{const t=++e.generation,o=`${e.key}:g${t}:`,a=`${o}vite`,i=`${o}browser-capture`;$.delete(a),$.delete(i);const l=d((S,M,L,w,h,m)=>T(S,M,L,w,h,m,e.workspaceRoot),"spawnInRoot"),g=(0,lens_frontend_1.spawnLensFrontend)({projectRoot:e.projectRoot,workspaceRoot:e.workspaceRoot,project:e.project,eventFile:e.eventFile,port:r,chrome:!0,headless:!0,viteEnv:{LENSMCP_PROJECT:e.project,LENSMCP_FRONTEND_KEY:e.key,LENSMCP_FRONTEND_GENERATION:String(t),LENSMCP_FRONTEND_ROLE:n,...de(e),NX_DAEMON:"false",NX_ISOLATE_PLUGINS:"false"},labelPrefix:o,log:d(S=>console.log(S),"log")},l),c={ownerKey:e.key,generation:t,port:r,labelPrefix:o,vite:g?.vite??N.get(a),capture:N.get(i)};return e.generations.add(c),c},"spawnFrontendGeneration"),I=d((e,r)=>{if(!e)return;v.get(e.ownerKey)?.generations.delete(e);const n=[[`${e.labelPrefix}browser-capture`,e.capture],[`${e.labelPrefix}vite`,e.vite]];for(const[t,o]of n)$.add(t),o&&B(o);r&&b.delete(e.port)},"terminateGeneration"),pe=d(async e=>{const r=Date.now()+types_1.LENS_REPLACEMENT_READY_MS;for(;!s.stopped()&&Date.now()<r;){const n=e.vite;if(!n||n.exitCode!==null||n.signalCode!==null)return!1;if(await probePortListening(e.port,Math.min(500,types_1.LENS_PROBE_TIMEOUT_MS))){const t=await C(e.port);if(!t||t.ready)return!0}await sleepUnref(150)}return!1},"waitForGenerationReady"),G=d(async e=>{const r=e?.vite;return!!(e&&r&&r.exitCode===null&&r.signalCode===null&&await probePortListening(e.port,Math.min(500,types_1.LENS_PROBE_TIMEOUT_MS)))},"generationIsServing"),Y=d(e=>!e.disposed&&!s.stopped()&&v.get(e.key)===e,"frontendIsCurrent"),q=d((e,r)=>{if(!Y(e))return Promise.resolve(!1);if(e.replacement)return e.replacement;const n=e.active;e.state=n?"replacing":"starting",e.reason=r,e.startedAt=Date.now();const t=(async()=>{let o,a;const i=Date.now();try{const l=new Set;for(const h of v.values())h!==e&&l.add(h.desiredPort);const g=n&&n.port===e.desiredPort?`g${n.generation}`:void 0,c=await F(e.desiredPort,b,{reserved:l,heldBy:g});if(a=c,!Y(e))return b.delete(c),!1;o=Z(e,c,"replacement"),e.candidate=o;const S=await G(n);console.log(`[gateway] lens handoff start: ${e.key} g${n?.generation??0}\u2192g${o.generation} :${n?.port??"down"}\u2192:${c} reason=${r}`),p("info",`lens handoff starting: ${e.project}`,`cluster-lens-app:${e.project}`,{kind:"lens-handoff-start",wsKey:e.wsKey,project:e.project,reason:r,generation:o.generation,oldPort:n?.port,newPort:c,oldServing:S},void 0,e.eventFile===s.eventFile?void 0:e.eventFile);const M=await pe(o);if(!Y(e))return I(o,!0),e.candidate=void 0,!1;if(!M){I(o,!0),e.candidate=void 0;const h=await G(n);return e.state=h?"ready":"failed",h&&(e.reason=void 0,e.startedAt=void 0),console.error(`[gateway] lens handoff failed: ${e.key} g${o.generation} did not become ready within ${types_1.LENS_REPLACEMENT_READY_MS}ms; ${e.state==="ready"?"old generation kept serving":"no active generation"}.`),p("warning",`lens handoff failed: ${e.project}`,`cluster-lens-app:${e.project}`,{kind:"lens-handoff-failed",wsKey:e.wsKey,project:e.project,reason:r,generation:o.generation,port:c,durationMs:Date.now()-i,oldKept:h},void 0,e.eventFile===s.eventFile?void 0:e.eventFile),!1}for(const h of e.routes)h.target=`http://localhost:${o.port}`,h.lens&&(h.lens.port=o.port);e.frontend.port=o.port,e.active=o,e.candidate=void 0,e.state="ready",e.reason=void 0,e.startedAt=void 0;const L=o.vite?A.get(o.vite):void 0;L&&(L.role="active",L.listening=!0);const w=(0,hmr_reload_1.broadcastFullReload)(s,e.key);if(console.log(`[gateway] lens handoff ready: ${e.key} g${o.generation} :${o.port} in ${Date.now()-i}ms; draining g${n?.generation??0}${w>0?`; reloading ${w} tab(s)`:""}.`),p("info",`lens handoff complete: ${e.project}`,`cluster-lens-app:${e.project}`,{kind:"lens-handoff-complete",wsKey:e.wsKey,project:e.project,reason:r,generation:o.generation,oldPort:n?.port,newPort:o.port,durationMs:Date.now()-i,reloadedTabs:w},void 0,e.eventFile===s.eventFile?void 0:e.eventFile),n){const h=`${n.labelPrefix}browser-capture`;$.add(h),n.capture&&B(n.capture),setTimeout(()=>I(n,!0),types_1.LENS_REPLACEMENT_DRAIN_MS).unref?.()}return!0}catch(l){I(o,!0),!o&&a!==void 0&&b.delete(a),e.candidate=void 0;const g=await G(n);e.state=g?"ready":"failed",g&&(e.reason=void 0,e.startedAt=void 0);const c=l.message;return console.error(`[gateway] lens handoff failed: ${e.key}: ${c}`),p("warning",`lens handoff failed: ${e.project}`,`cluster-lens-app:${e.project}`,{kind:"lens-handoff-failed",wsKey:e.wsKey,project:e.project,reason:r,generation:o?.generation??e.generation,port:o?.port??a,durationMs:Date.now()-i,oldKept:g,error:c},void 0,e.eventFile===s.eventFile?void 0:e.eventFile),!1}finally{e.replacement=void 0}})();return e.replacement=t,t},"rollFrontend"),ee=d((e,r)=>{e.active=Z(e,r,"active"),e.state="starting",e.startedAt=Date.now()},"spawnInitialFrontend"),ue=d((e,r)=>{const n=v.get(r.key);return!n||types_1.LENS_RESTART_MODE==="in-place"?!1:(n.candidate?.vite===e||n.active?.vite!==e||(n.state="starting",n.reason="child-exit",n.startedAt=Date.now(),console.warn(`[gateway] lens frontend exited: ${n.key} g${r.generation} :${r.port}; starting an alternate-port replacement.`),q(n,"child-exit")),!0)},"handleManagedViteExit");s.lensSupervisor=types_1.LENS_RESTART_MODE==="rolling"?{status(e){const r=D.get(e);return r?{state:r.state,generation:r.candidate?.generation??r.active?.generation??r.generation,reason:r.reason,startedAt:r.startedAt}:void 0},recover(e,r){const n=D.get(e);return n?q(n,r):Promise.resolve(!1)}}:void 0;let V=!1,te=0;const fe=d(()=>{V||Date.now()-te<types_1.POD_STALE_SCAN_MS||(V=!0,te=Date.now(),(async()=>{for(const e of[...v.values()]){if(s.stopped())return;const r=Date.now(),n=(0,scope_1.readSourceSetOptions)(e.workspaceRoot),t=await(0,lifecycle_1.sourceSetSnapshot)(e.workspaceRoot,e.sourceDirs,n.exclude,{ignoreTests:n.ignoreTests});if(v.get(e.key)!==e)continue;const o=e.sourceSnapshot,a=e.sourceScanStartedAt;if(e.sourceSnapshot=t,e.sourceScanStartedAt=r,!o)continue;const i=Date.now(),l=(0,lifecycle_1.diffSourceSets)(o,t,i,(0,lifecycle_1.sourceChangeWindowMs)(i,a,types_1.POD_STALE_SCAN_MS,types_1.POD_RECYCLE_SETTLE_MS));l&&(e.sourceChange=l,p("info",`source file set changed for ${e.key}`,`cluster-lens-app:${e.project}`,{kind:"source-set-changed",scoped:!0,wsKey:e.wsKey,project:e.project,added:l.added,removed:l.removed,truncated:l.truncated},void 0,e.eventFile===s.eventFile?void 0:e.eventFile))}})().catch(()=>{}).finally(()=>{V=!1}))},"scanFrontendSourceSets");let U=!1;const Ee=d(async(e,r)=>{if(!U){U=!0;try{for(const[n,t]of[...A]){if(s.stopped())return;if(t.port===void 0||n.exitCode!==null||n.signalCode!==null)continue;if(await probePortListening(t.port,types_1.LENS_PROBE_TIMEOUT_MS)){if(t.probeFails=0,!t.listening){t.listening=!0;const l=v.get(t.key);l?.active?.vite===n&&(l.state="ready",l.reason=void 0),p("info",`lens app up: ${t.project} (vite :${t.port} listening)`,`cluster-lens-app:${t.project}`,{kind:"service-up",project:t.project,port:t.port},void 0,t.bus)}continue}const o=t.listening?e.graceMs:Math.max(e.graceMs,e.neverListenedGraceMs);if(Date.now()-t.spawnedAt<o){t.probeFails=0;continue}if(!r)continue;t.probeFails+=1;const a=(0,lifecycle_1.lensChildWedged)({spawnedAt:t.spawnedAt,probeFails:t.probeFails,hasListened:t.listening},j.get(t.key)??0,Date.now(),e);if(!a)continue;const i=t.listening?"its listener VANISHED (was up, now refusing)":`it NEVER bound within the ${Math.round(o/1e3)}s boot allowance`;j.set(t.key,Date.now()),t.probeFails=0,t.listening=!1,console.error(`[gateway] wedge recycle: lens app ${t.project} is ALIVE but NOT LISTENING on :${t.port} after ${Math.max(2,e.failureThreshold)} probes \u2014 ${i} \u2014 SIGKILL; a fresh vite is coming.`),p("warning",`wedge recycle: ${t.project} (${a})`,`cluster-lens-app:${t.project}`,{kind:"pod-recycle",project:t.project,reason:a,port:t.port},void 0,t.bus);try{n.kill("SIGKILL")}catch{}}}finally{U=!1}}},"probeLensChildren"),he=d(()=>{if(O||!types_1.POD_RECYCLE_ENABLED&&!types_1.LENS_PROBE_ENABLED)return;const e={graceMs:types_1.POD_STALE_GRACE_MS,settleMs:types_1.POD_RECYCLE_SETTLE_MS,cooldownMs:types_1.POD_STALE_RECYCLE_COOLDOWN_MS};O=setInterval(()=>{if(s.stopped()||A.size===0||(oe(),!types_1.POD_RECYCLE_ENABLED))return;fe();const r=Date.now();for(const[n,t]of A){const o=v.get(t.key),a=o?.sourceChange?.changedAt??0,i=j.get(t.key)??0;(0,lifecycle_1.lensFrontendStale)(t.spawnedAt,i,a,r,e)&&((W.get(t.key)??0)>=a||K.has(t.key)||(K.add(t.key),(async()=>{try{const l=o?.sourceChange,g=l&&!l.truncated?[...l.added,...l.removed].map(L=>path.resolve(t.workspaceRoot,L)):[],c=types_1.LENS_WATCHER_PROBE_ENABLED&&t.port!==void 0?(0,lifecycle_1.lensWatcherVerdict)(await C(t.port),a,l?.windowMs??types_1.POD_STALE_SCAN_MS+types_1.POD_RECYCLE_SETTLE_MS,g):"unknown";if(c==="heard"){W.set(t.key,a),console.log(`[gateway] stale source set: lens app ${t.project} watcher CONFIRMED the change \u2014 no recycle, HMR intact.`),p("info",`stale check: ${t.project} watcher confirmed \u2014 no recycle`,`cluster-lens-app:${t.project}`,{kind:"pod-stale-verified",project:t.project},void 0,t.bus);return}if(c==="unknown"&&types_1.LENS_WATCHER_UNVERIFIED==="keep"){console.log(`[gateway] stale source set: lens app ${t.project} unverifiable (no watcher testimony) \u2014 keeping it (LENSMCP_LENS_WATCHER_UNVERIFIED=keep).`);return}if(n.exitCode!==null||n.signalCode!==null)return;j.set(t.key,Date.now());const S=v.get(t.key);if(types_1.LENS_RESTART_MODE==="rolling"&&S){console.log(`[gateway] stale refresh: lens app ${t.key} (stale-source-set) \u2014 watcher ${c==="missed"?"missed the exact path change":"unverifiable"}; preparing a standby without dropping traffic.`),p("warning",`stale refresh: ${t.project} (stale-source-set)`,`cluster-lens-app:${t.project}`,{kind:"pod-refresh",wsKey:S.wsKey,project:t.project,reason:"stale-source-set",watcher:c,added:l?.added,removed:l?.removed},void 0,t.bus),await q(S,"stale-source-set");return}t.listening=!1,console.log(`[gateway] zombie recycle: lens app ${t.project} (stale-source-set) \u2014 watcher ${c==="missed"?"SILENT across the change":"unverifiable"}; restarting it`),p("warning",`zombie recycle: ${t.project} (stale-source-set)`,`cluster-lens-app:${t.project}`,{kind:"pod-recycle",project:t.project,reason:"stale-source-set",watcher:c},void 0,t.bus);const M=(0,hmr_reload_1.broadcastFullReload)(s,t.key);M>0&&console.log(`[gateway] \u2192 told ${M} open tab(s) to reload (stale optimize-dep generation)`);try{n.kill("SIGTERM")}catch{}setTimeout(()=>{if(n.exitCode===null&&n.signalCode===null){console.log(`[gateway] zombie recycle: lens app ${t.project} ignored SIGTERM for ${Math.round(types_1.LENS_RECYCLE_KILL_GRACE_MS/1e3)}s \u2014 escalating to SIGKILL.`);try{n.kill("SIGKILL")}catch{}}},types_1.LENS_RECYCLE_KILL_GRACE_MS).unref?.()}finally{K.delete(t.key)}})()))}},Math.min(types_1.POD_STALE_SCAN_MS,15e3)),O.unref?.()},"startLensSweeper"),ge=d(async()=>{const e=[...new Map(s.routes.filter(t=>t.lens).map(t=>[t.project,t.lens])).values()],r=u.dashboard!==!1,n=u.mcp!==!1&&e.length>0;if(r){const t=(0,lens_frontend_1.findDashboardBundle)(s.root);if(!t)console.warn("[gateway] lens dashboard bundle not found \u2014 skipping. Install the self-contained CLI: `npm i -D lensmcp` (it ships `bundled/dashboard.js`), or `yarn nx build @lensmcp/lensmcp-mcp` in-repo.");else{const o=(0,scope_1.readLensScope)(s.root),a=await F(u.dashboardPort??o.dashboardPort,H),i=u.lensHost??"lensmcp.local",l=o.basePath;s.registry.appendRoutes(s.wsKey,[{host:i,prefix:l,project:observability_1.LENS_DASHBOARD_PROJECT,target:`http://localhost:${a}`}]),s.rebuildRoutes(),(0,workspace_registry_1.registerWorkspace)({key:o.key,root:s.root,base:l,pid:process.pid,procStamp:(0,workspace_registry_1.processStamp)(process.pid),updatedAt:new Date().toISOString()}),console.log(`[gateway] starting lens dashboard \u2192 http://localhost:${a} (routed at https://${i}${l}/)`),p("info",`lens dashboard up: ${i}${l} \u2192 :${a}`,"cluster-lens-dashboard",{kind:"lens-dashboard-up",host:i,port:a,base:l}),T("lens-dashboard",process.execPath,[t],{LENSMCP_EVENT_FILE:s.eventFile,LENSMCP_PROCESS_ROLE:"dashboard",LENSMCP_DASHBOARD_PORT:String(a),LENSMCP_DASHBOARD_BASE:l},!1,void 0,void 0,a)}}if(n){const t=(0,lens_frontend_1.findMcpBundle)(s.root);if(!t)console.warn("[gateway] MCP server bundle not found \u2014 skipping (lens apps will still publish to the bus; an external `lensmcp mcp` can read it). Install: `npm i -D lensmcp`.");else{const o=(0,scope_1.readLensScope)(s.root),a=Number(process.env.LENSMCP_PORT??o.mcpHttpPort),i=d(()=>{console.log(`[gateway] starting lens MCP server on 127.0.0.1:${a} (${t})`),T("lens-mcp",process.execPath,[t],{LENSMCP_EVENT_FILE:s.eventFile,LENSMCP_PROCESS_ROLE:"mcp",LENSMCP_TRANSPORT:process.env.LENSMCP_TRANSPORT??"http",LENSMCP_PORT:String(a),LENSMCP_WORKSPACE_KEY:o.key,LENSMCP_WORKSPACE_ROOT:s.root},!1,void 0,void 0,a)},"spawnMcp");await E(a)?i():(console.warn(`[gateway] lens MCP port :${a} is already served \u2014 an external lensmcp server (a shared daemon?) owns this workspace's MCP; not spawning a second. Re-probing every ${Math.round(types_1.LENS_PARKED_PORT_REPROBE_MS/1e3)}s; will take over if it frees.`),p("info",`lens MCP served externally on :${a} \u2014 gateway parked its own`,"cluster-lens-child:lens-mcp",{kind:"lens-child-up",project:"lens-mcp",label:"lens-mcp",port:a,external:!0}),J("lens-mcp",a,i))}}for(const t of e){if(t.started)continue;t.started=!0;const o=t.port,a=(s.registry.get(s.wsKey)?.routes??s.routes).filter(g=>g.lens?.project===t.project),i=await F(t.port,b);for(const g of a)g.lens&&(g.lens.port=i),g.target=`http://localhost:${i}`;t.port=i;const l=Q({wsKey:s.wsKey,project:t.project,workspaceRoot:s.root,projectRoot:t.projectRoot,eventFile:s.eventFile,routes:a,frontend:t,desiredPort:o});try{ee(l,i),p("info",`lens app started: ${t.project} (vite :${t.port})`,`cluster-lens-app:${t.project}`,{kind:"lens-app-up",project:t.project,port:t.port})}catch(g){b.delete(i),l.state="failed",console.error(`[gateway] lens app ${t.project}: ${g.message}`)}}he()},"bootSingletonsAndApps"),we=d(async e=>{if(u.dashboard===!1)return;const r=(0,lens_frontend_1.findDashboardBundle)(s.root);if(!r)return;const n=(0,scope_1.readLensScope)(e.root),t=u.lensHost??"lensmcp.local",o=n.basePath,a=await F(n.dashboardPort,H),i=`lens-dashboard:${e.wsKey}`,l=path.join(e.root,".lensmcp","events.jsonl");return $.delete(i),s.registry.appendRoutes(e.wsKey,[{host:t,prefix:o,project:observability_1.LENS_DASHBOARD_PROJECT,target:`http://localhost:${a}`}]),(0,workspace_registry_1.registerWorkspace)({key:e.wsKey,root:e.root,base:o,pid:process.pid,procStamp:(0,workspace_registry_1.processStamp)(process.pid),updatedAt:new Date().toISOString()}),console.log(`[gateway] hosting dashboard for workspace '${e.wsKey}' \u2192 http://localhost:${a} (routed at https://${t}${o}/)`),p("info",`lens dashboard up: ${t}${o} \u2192 :${a}`,"cluster-lens-dashboard",{kind:"lens-dashboard-up",host:t,port:a,base:o}),T(i,process.execPath,[r],{LENSMCP_EVENT_FILE:l,LENSMCP_PROCESS_ROLE:"dashboard",LENSMCP_DASHBOARD_PORT:String(a),LENSMCP_DASHBOARD_BASE:o,LENSMCP_WS_KEY:e.wsKey},!1,void 0,e.root,a),()=>{$.add(i),H.delete(a),(0,workspace_registry_1.unregisterWorkspace)(e.wsKey);const g=N.get(i);g&&B(g),N.delete(i)}},"hostWorkspaceDashboard"),_e=d(async e=>{const r=new Map;for(const o of e.routes){if(!o.lens)continue;const a=r.get(o.lens.project)??[];a.push(o),r.set(o.lens.project,a)}if(r.size===0)return()=>{};const n=path.join(e.root,".lensmcp","events.jsonl"),t=[];for(const[o,a]of r){const i=a[0].lens;if(i.started)continue;const l=await F(i.port,b),g=i.port;for(const S of a)S.lens.started=!0,S.lens.port=l,S.target=`http://localhost:${l}`;const c=Q({wsKey:e.wsKey,project:o,workspaceRoot:e.root,projectRoot:i.projectRoot,eventFile:n,routes:a,frontend:i,desiredPort:g});t.push(c),console.log(`[gateway] hosting lens app '${o}' of '${e.wsKey}' \u2192 vite :${l}`);try{ee(c,l),p("info",`lens app started: ${e.wsKey}/${o} (vite :${l})`,`cluster-lens-app:${e.wsKey}:${o}`,{kind:"lens-app-up",project:o,port:l},void 0,n)}catch(S){b.delete(l),c.state="failed",console.error(`[gateway] lens app ${e.wsKey}/${o}: ${S.message}`)}}return()=>{for(const o of t){o.disposed=!0;for(const a of[...o.generations])I(a,!0);for(const a of o.routes)a.lens&&D.delete(a.lens);D.delete(o.frontend),j.delete(o.key),W.delete(o.key),K.delete(o.key),v.delete(o.key)}}},"hostWorkspaceApps"),Se=d(async(e=2500)=>{O&&(clearInterval(O),O=void 0);const r=[...y];for(const o of r)try{o.kill("SIGTERM")}catch{}const n=d(o=>o.exitCode===null&&o.signalCode===null,"alive"),t=Date.now()+e;for(;Date.now()<t&&r.some(n);)await new Promise(o=>setTimeout(o,100));for(const o of r)if(n(o))try{o.kill("SIGKILL")}catch{}},"reapAll"),oe=d(()=>Ee({graceMs:types_1.LENS_PROBE_GRACE_MS,failureThreshold:types_1.LENS_PROBE_FAILS,cooldownMs:types_1.LENS_PROBE_COOLDOWN_MS,neverListenedGraceMs:types_1.LENS_PROBE_BOOT_GRACE_MS},types_1.LENS_PROBE_ENABLED),"probeLensFrontends");return{spawnManagedChild:T,bootSingletonsAndApps:ge,hostWorkspaceDashboard:we,hostWorkspaceApps:_e,probeLensFrontends:oe,reapAll:Se}}P(createLensChildren,"createLensChildren"),d(createLensChildren,"createLensChildren");
|
|
1
|
+
"use strict";var Re=Object.defineProperty;var R=(r,E)=>Re(r,"name",{value:E,configurable:!0});var Le=Object.defineProperty,d=R((r,E)=>Le(r,"name",{value:E,configurable:!0}),"d");Object.defineProperty(exports,"__esModule",{value:!0}),exports.probePortFree=probePortFree,exports.probePortListening=probePortListening,exports.probeWatcherHealth=probeWatcherHealth,exports.waitForPortFree=waitForPortFree,exports.viteArgPort=viteArgPort,exports.describeChildExit=describeChildExit,exports.claimPort=claimPort,exports.createLensChildren=createLensChildren;const tslib_1=require("tslib"),net=tslib_1.__importStar(require("node:net")),path=tslib_1.__importStar(require("node:path")),node_child_process_1=require("node:child_process"),lens_frontend_1=require("@lensmcp/nx-plugin/lens-frontend"),hmr_reload_1=require("./hmr-reload"),pod_env_1=require("./pod-env"),scope_1=require("./scope"),workspace_registry_1=require("./workspace-registry"),lifecycle_1=require("./lifecycle"),types_1=require("./types"),observability_1=require("./observability"),HEAL_BASE_MS=1500,HEAL_MAX_MS=3e4,HEAL_HEALTHY_MS=2e4;function tryBind(r,E){return new Promise(u=>{const _=net.createServer();_.unref(),_.once("error",p=>{const f=p.code??"";u(f==="EADDRINUSE"||f==="EACCES"?"in-use":"unavailable")}),_.listen(E===void 0?{port:r}:{port:r,host:E},()=>_.close(()=>u("free")))})}R(tryBind,"tryBind"),d(tryBind,"tryBind");async function probePortFree(r){for(const E of[void 0,"0.0.0.0","127.0.0.1","::1"])if(await tryBind(r,E)==="in-use")return!1;return!0}R(probePortFree,"probePortFree"),d(probePortFree,"probePortFree");function probeConnect(r,E,u){return new Promise(_=>{let p=!1;const f=net.createConnection({host:r,port:E});f.unref();const C=setTimeout(()=>y(!1),u);C.unref?.();function y(O){p||(p=!0,clearTimeout(C),f.destroy(),_(O))}R(y,"y"),d(y,"finish"),f.once("connect",()=>y(!0)),f.once("error",()=>y(!1))})}R(probeConnect,"probeConnect"),d(probeConnect,"probeConnect");async function probePortListening(r,E=1e3){return await probeConnect("127.0.0.1",r,E)?!0:probeConnect("::1",r,E)}R(probePortListening,"probePortListening"),d(probePortListening,"probePortListening");async function probeWatcherHealth(r,E=1500){try{const u=new AbortController,_=setTimeout(()=>u.abort(),E);_.unref?.();try{const p=await fetch(`http://127.0.0.1:${r}/__lensmcp/watcher-health`,{signal:u.signal});if(!p.ok)return null;const f=await p.json();if(typeof f?.lastFsSetEventAt!="number")return null;const C=Array.isArray(f.recentEvents)?f.recentEvents.filter(y=>y&&typeof y.path=="string"&&typeof y.at=="number"&&typeof y.sequence=="number"&&["add","addDir","unlink","unlinkDir"].includes(y.kind)):[];return{schemaVersion:f.schemaVersion===2?2:1,ready:f.ready!==!1,sequence:typeof f.sequence=="number"?f.sequence:0,lastFsSetEventAt:f.lastFsSetEventAt,fsSetEvents:typeof f.fsSetEvents=="number"?f.fsSetEvents:0,recentEvents:C}}finally{clearTimeout(_)}}catch{return null}}R(probeWatcherHealth,"probeWatcherHealth"),d(probeWatcherHealth,"probeWatcherHealth");const sleepUnref=d(r=>new Promise(E=>{setTimeout(E,r).unref?.()}),"sleepUnref");async function waitForPortFree(r,E,u={}){const _=u.isPortFree??probePortFree,p=Math.max(1,u.intervalMs??types_1.PORT_FREE_POLL_MS),f=Date.now()+Math.max(0,E);for(;;){if(await _(r))return!0;const C=f-Date.now();if(C<=0)return!1;await sleepUnref(Math.min(p,C))}}R(waitForPortFree,"waitForPortFree"),d(waitForPortFree,"waitForPortFree");function viteArgPort(r){const E=d(u=>Number.isInteger(u)&&u>0&&u<65536?u:void 0,"valid");for(let u=0;u<r.length;u+=1){const _=r[u];if(_==="--port")return E(Number(r[u+1]));if(_.startsWith("--port="))return E(Number(_.slice(7)))}}R(viteArgPort,"viteArgPort"),d(viteArgPort,"viteArgPort");function describeChildExit(r){return r.signalCode?`killed by ${r.signalCode}`:r.exitCode===null?"exit status unknown":`exit code ${r.exitCode}`}R(describeChildExit,"describeChildExit"),d(describeChildExit,"describeChildExit");async function claimPort(r,E,u,_){let p=r;for(;E.has(p)||_?.has(p)||!await u(p);)p+=1;return E.add(p),p}R(claimPort,"claimPort"),d(claimPort,"claimPort");function createLensChildren(r,E,u,_){const{emit:p}=E,f=_?.isPortFree??probePortFree,C=_?.probeWatcherHealth??probeWatcherHealth,y=[],O=new Map,T=new Map,F=new Map,H=new Map,K=new Set;let D;const N=new Map,P=new Set,J=new Set,Y=new Set,m=new Set,L=new Map,j=new WeakMap,B=new Set,Q=d((e,s,n)=>{if(B.has(e))return;B.add(e);const t=setInterval(()=>{(async()=>{if(r.stopped()||P.has(e)){clearInterval(t),B.delete(e);return}await f(s)&&(clearInterval(t),B.delete(e),console.log(`[gateway] lens child ${e}: :${s} freed \u2014 respawning.`),n())})().catch(()=>{})},types_1.LENS_PARKED_PORT_REPROBE_MS);t.unref?.()},"parkUntilPortFree"),I=d(async(e,s,n)=>{const t=await claimPort(e,s,f,n?.reserved);return t!==e&&(n?.heldBy?console.log(`[gateway] handoff: :${e} is held by ${n.heldBy} \u2014 replacement on :${t}.`):console.warn(`[gateway] port ${e} is unavailable (another process holds it \u2014 an orphan from a crashed gateway?) \u2014 using ${t} instead.`)),t},"claimFreePort"),le=d((e,s,n)=>{const t=n?.LENSMCP_FRONTEND_KEY,o=Number(n?.LENSMCP_FRONTEND_GENERATION);if(!t||!Number.isFinite(o))return;const a=[...L.get(t)?.generations??[]].find(i=>i.generation===o);a&&(e.endsWith(":vite")?a.vite=s:e.endsWith(":browser-capture")&&(a.capture=s))},"attachRespawnedGenerationChild"),W=d(e=>{if(!(e.exitCode!==null||e.signalCode!==null)){J.add(e);try{e.kill("SIGTERM")}catch{}setTimeout(()=>{if(e.exitCode===null&&e.signalCode===null)try{e.kill("SIGKILL")}catch{}},types_1.LENS_RECYCLE_KILL_GRACE_MS).unref?.()}},"retireChild"),ce=d((e,s)=>{const n=N.get(e);!n||n===s||n.exitCode!==null||n.signalCode!==null||(console.warn(`[gateway] lens child ${e}: a replacement took the label \u2014 retiring the previous child (pid ${n.pid??"?"}).`),W(n))},"retireLabelHolder"),k=d((e,s,n,t,o=!1,a,i,l)=>{const h=Date.now(),c=(0,node_child_process_1.spawn)(s,n,{cwd:i??r.root,env:{...(0,pod_env_1.podBaseEnv)(process.env,r.root,i??r.root),...t??{},LENSMCP_PARENT_PID:String(process.pid)},stdio:"inherit"});y.push(c),ce(e,c),N.set(e,c),le(e,c,t);const S=e==="vite"||e.endsWith(":vite"),M=typeof t?.LENSMCP_EVENT_FILE=="string"?t.LENSMCP_EVENT_FILE:void 0,v=M&&M!==r.eventFile?M:void 0,w=S?viteArgPort(n):l;S&&T.set(c,{key:t?.LENSMCP_FRONTEND_KEY??`${i??r.root}:${t?.LENSMCP_PROJECT??"app"}`,project:t?.LENSMCP_PROJECT??"app",workspaceRoot:i??r.root,spawnedAt:h,port:w,probeFails:0,listening:!1,generation:Number(t?.LENSMCP_FRONTEND_GENERATION??0),role:t?.LENSMCP_FRONTEND_ROLE==="replacement"?"replacement":"active",...v?{bus:v}:{}});const g=e==="lens-mcp"?"lens-mcp":e==="lens-dashboard"||e.startsWith("lens-dashboard:")?"lens-dashboard":void 0;return g&&w!==void 0&&(p("info",`lens child starting: ${g} (:${w})`,`cluster-lens-child:${g}`,{kind:"lens-child-starting",project:g,label:e,pid:c.pid,port:w},void 0,v),(async()=>{const b=Date.now()+types_1.LENS_REPLACEMENT_READY_MS;for(;!r.stopped()&&Date.now()<b;){if(c.exitCode!==null||c.signalCode!==null||P.has(e))return;if(await probePortListening(w,Math.min(500,types_1.LENS_PROBE_TIMEOUT_MS))){p("info",`lens child up: ${g} (:${w})`,`cluster-lens-child:${g}`,{kind:"lens-child-up",project:g,label:e,pid:c.pid,port:w},void 0,v);return}await sleepUnref(150)}})().catch(()=>{})),c.on("exit",(b,G)=>{const re=y.indexOf(c);re>=0&&y.splice(re,1),N.get(e)===c&&N.delete(e);const A=T.get(c);if(T.delete(c),J.delete(c))return;const ye=P.delete(e);if(r.stopped()||ye||(g?p("warning",`lens child exited: ${g}`,`cluster-lens-child:${g}`,{kind:"lens-child-exit",project:g,label:e,pid:c.pid,code:b,signal:G},void 0,v):A&&p("warning",`lens frontend exited: ${A.project}`,`cluster-lens-child:${A.project}`,{kind:"lens-child-exit",project:A.project,label:e,pid:c.pid,code:b,signal:G,generation:A.generation,port:A.port,ranMs:Date.now()-h},void 0,v),A&&ue(c,A)))return;const se=Date.now()-h,$=O.get(e)??{attempts:0,portConflicts:0};(async()=>{const ve=w!==void 0&&!await f(w),ae=(0,lifecycle_1.isPortConflictExit)({code:b,signal:G,ranMs:se,portHeld:ve},{fastFailMs:types_1.CHILD_START_FAIL_MS});if(ae&&$.portConflicts<types_1.MAX_PORT_CONFLICT_RETRIES)$.portConflicts+=1,O.set(e,$),console.warn(`[gateway] lens child ${e} lost the :${w} bind race (EADDRINUSE, code=${b}); waiting for the port, then retrying (port-retry ${$.portConflicts}/${types_1.MAX_PORT_CONFLICT_RETRIES}; crash budget untouched).`);else if(ae){$.portConflicts=0,O.set(e,$),console.warn(`[gateway] lens child ${e}: :${w} persistently held after ${types_1.MAX_PORT_CONFLICT_RETRIES} bind races \u2014 another server owns it (an external/shared daemon?). Parking; re-probing every ${Math.round(types_1.LENS_PARKED_PORT_REPROBE_MS/1e3)}s, will respawn if it frees.`),p("warning",`lens child parked: ${e} (:${w} held externally)`,`cluster-lens-child:${e}`,{kind:"lens-child-parked",label:e,port:w}),Q(e,w,()=>k(e,s,n,t,o,a,i,l));return}else{$.portConflicts=0,se>=HEAL_HEALTHY_MS&&($.attempts=0);const ie=Math.min(HEAL_MAX_MS,HEAL_BASE_MS*2**$.attempts);$.attempts+=1,O.set(e,$),console.warn(`[gateway] lens child ${e} exited (code=${b} sig=${G}); auto-healing in ${Math.round(ie/1e3)}s (attempt ${$.attempts}).`),await sleepUnref(ie)}r.stopped()||P.has(e)||(w!==void 0&&!await waitForPortFree(w,types_1.PORT_FREE_WAIT_MS,{isPortFree:f,intervalMs:types_1.PORT_FREE_POLL_MS})&&console.warn(`[gateway] lens child ${e}: :${w} still held after ${Math.round(types_1.PORT_FREE_WAIT_MS/1e3)}s \u2014 spawning anyway.`),!(r.stopped()||P.has(e))&&k(e,s,n,t,o,a,i,l))})().catch(()=>{})}),c},"spawnManagedChild"),Z=d(e=>{const s=`${e.wsKey}:${e.project}`,n=L.get(s);if(n)return n;const t={key:s,...e,sourceDirs:e.frontend.sourceRoots?.length?e.frontend.sourceRoots:[e.projectRoot],generation:0,state:"starting",generations:new Set,disposed:!1};L.set(s,t);for(const o of e.routes)o.lens&&(o.lens.workspaceKey??=e.wsKey,j.set(o.lens,t));return e.frontend.workspaceKey??=e.wsKey,j.set(e.frontend,t),t},"registerFrontend"),de=d(e=>{if(!types_1.LENS_WATCH_SCOPE_ENABLED)return{};const s=path.resolve(e.projectRoot),n=e.sourceDirs.map(t=>path.resolve(t)).filter(t=>t!==s);return n.length>0?{LENSMCP_WATCH_DIRS:n.join(path.delimiter)}:{}},"lensWatchScopeEnv"),ee=d((e,s,n)=>{const t=++e.generation,o=`${e.key}:g${t}:`,a=`${o}vite`,i=`${o}browser-capture`;P.delete(a),P.delete(i);const l=d((S,M,v,w,g,b)=>k(S,M,v,w,g,b,e.workspaceRoot),"spawnInRoot"),h=(0,lens_frontend_1.spawnLensFrontend)({projectRoot:e.projectRoot,workspaceRoot:e.workspaceRoot,project:e.project,eventFile:e.eventFile,port:s,chrome:!0,headless:!0,viteEnv:{LENSMCP_PROJECT:e.project,LENSMCP_FRONTEND_KEY:e.key,LENSMCP_FRONTEND_GENERATION:String(t),LENSMCP_FRONTEND_ROLE:n,...de(e),NX_DAEMON:"false",NX_ISOLATE_PLUGINS:"false"},labelPrefix:o,log:d(S=>console.log(S),"log")},l),c={ownerKey:e.key,generation:t,port:s,labelPrefix:o,vite:h?.vite??N.get(a),capture:N.get(i)};return e.generations.add(c),c},"spawnFrontendGeneration"),x=d((e,s)=>{if(!e)return;L.get(e.ownerKey)?.generations.delete(e);const n=[[`${e.labelPrefix}browser-capture`,e.capture],[`${e.labelPrefix}vite`,e.vite]];for(const[t,o]of n)P.add(t),o&&W(o);s&&m.delete(e.port)},"terminateGeneration"),pe=d(async e=>{const s=Date.now()+types_1.LENS_REPLACEMENT_READY_MS;for(;!r.stopped()&&Date.now()<s;){const n=e.vite;if(!n||n.exitCode!==null||n.signalCode!==null)return!1;if(await probePortListening(e.port,Math.min(500,types_1.LENS_PROBE_TIMEOUT_MS))){const t=await C(e.port);if(!t||t.ready)return!0}await sleepUnref(150)}return!1},"waitForGenerationReady"),q=d(async e=>{const s=e?.vite;return!!(e&&s&&s.exitCode===null&&s.signalCode===null&&await probePortListening(e.port,Math.min(500,types_1.LENS_PROBE_TIMEOUT_MS)))},"generationIsServing"),V=d(e=>!e.disposed&&!r.stopped()&&L.get(e.key)===e,"frontendIsCurrent"),U=d((e,s)=>{if(!V(e))return Promise.resolve(!1);if(e.replacement)return e.replacement;const n=e.active;e.state=n?"replacing":"starting",e.reason=s,e.startedAt=Date.now();const t=(async()=>{let o,a;const i=Date.now();try{const l=new Set;for(const g of L.values())g!==e&&l.add(g.desiredPort);const h=n&&n.port===e.desiredPort?`g${n.generation}`:void 0,c=await I(e.desiredPort,m,{reserved:l,heldBy:h});if(a=c,!V(e))return m.delete(c),!1;o=ee(e,c,"replacement"),e.candidate=o;const S=await q(n);console.log(`[gateway] lens handoff start: ${e.key} g${n?.generation??0}\u2192g${o.generation} :${n?.port??"down"}\u2192:${c} reason=${s}`),p("info",`lens handoff starting: ${e.project}`,`cluster-lens-app:${e.project}`,{kind:"lens-handoff-start",wsKey:e.wsKey,project:e.project,reason:s,generation:o.generation,oldPort:n?.port,newPort:c,oldServing:S},void 0,e.eventFile===r.eventFile?void 0:e.eventFile);const M=await pe(o);if(!V(e))return x(o,!0),e.candidate=void 0,!1;if(!M){x(o,!0),e.candidate=void 0;const g=await q(n);return e.state=g?"ready":"failed",g&&(e.reason=void 0,e.startedAt=void 0),console.error(`[gateway] lens handoff failed: ${e.key} g${o.generation} did not become ready within ${types_1.LENS_REPLACEMENT_READY_MS}ms; ${e.state==="ready"?"old generation kept serving":"no active generation"}.`),p("warning",`lens handoff failed: ${e.project}`,`cluster-lens-app:${e.project}`,{kind:"lens-handoff-failed",wsKey:e.wsKey,project:e.project,reason:s,generation:o.generation,port:c,durationMs:Date.now()-i,oldKept:g},void 0,e.eventFile===r.eventFile?void 0:e.eventFile),!1}for(const g of e.routes)g.target=`http://localhost:${o.port}`,g.lens&&(g.lens.port=o.port);e.frontend.port=o.port,e.active=o,e.candidate=void 0,e.state="ready",e.reason=void 0,e.startedAt=void 0;const v=o.vite?T.get(o.vite):void 0;v&&(v.role="active",v.listening=!0);const w=(0,hmr_reload_1.broadcastFullReload)(r,e.key);if(console.log(`[gateway] lens handoff ready: ${e.key} g${o.generation} :${o.port} in ${Date.now()-i}ms; draining g${n?.generation??0}${w>0?`; reloading ${w} tab(s)`:""}.`),p("info",`lens handoff complete: ${e.project}`,`cluster-lens-app:${e.project}`,{kind:"lens-handoff-complete",wsKey:e.wsKey,project:e.project,reason:s,generation:o.generation,oldPort:n?.port,newPort:o.port,durationMs:Date.now()-i,reloadedTabs:w},void 0,e.eventFile===r.eventFile?void 0:e.eventFile),n){const g=`${n.labelPrefix}browser-capture`;P.add(g),n.capture&&W(n.capture),setTimeout(()=>x(n,!0),types_1.LENS_REPLACEMENT_DRAIN_MS).unref?.()}return!0}catch(l){x(o,!0),!o&&a!==void 0&&m.delete(a),e.candidate=void 0;const h=await q(n);e.state=h?"ready":"failed",h&&(e.reason=void 0,e.startedAt=void 0);const c=l.message;return console.error(`[gateway] lens handoff failed: ${e.key}: ${c}`),p("warning",`lens handoff failed: ${e.project}`,`cluster-lens-app:${e.project}`,{kind:"lens-handoff-failed",wsKey:e.wsKey,project:e.project,reason:s,generation:o?.generation??e.generation,port:o?.port??a,durationMs:Date.now()-i,oldKept:h,error:c},void 0,e.eventFile===r.eventFile?void 0:e.eventFile),!1}finally{e.replacement=void 0}})();return e.replacement=t,t},"rollFrontend"),te=d((e,s)=>{e.active=ee(e,s,"active"),e.state="starting",e.startedAt=Date.now()},"spawnInitialFrontend"),ue=d((e,s)=>{const n=L.get(s.key);return!n||types_1.LENS_RESTART_MODE==="in-place"?!1:(n.candidate?.vite===e||n.active?.vite!==e||(n.state="starting",n.reason="child-exit",n.startedAt=Date.now(),console.warn(`[gateway] lens frontend exited: ${n.key} g${s.generation} :${s.port} (${describeChildExit(e)}); starting an alternate-port replacement.`),U(n,"child-exit")),!0)},"handleManagedViteExit");r.lensSupervisor=types_1.LENS_RESTART_MODE==="rolling"?{status(e){const s=j.get(e);return s?{state:s.state,generation:s.candidate?.generation??s.active?.generation??s.generation,reason:s.reason,startedAt:s.startedAt}:void 0},recover(e,s){const n=j.get(e);return n?U(n,s):Promise.resolve(!1)}}:void 0;let z=!1,oe=0;const Ee=d(()=>{z||Date.now()-oe<types_1.POD_STALE_SCAN_MS||(z=!0,oe=Date.now(),(async()=>{for(const e of[...L.values()]){if(r.stopped())return;const s=Date.now(),n=(0,scope_1.readSourceSetOptions)(e.workspaceRoot),t=await(0,lifecycle_1.sourceSetSnapshot)(e.workspaceRoot,e.sourceDirs,n.exclude,{ignoreTests:n.ignoreTests});if(L.get(e.key)!==e)continue;const o=e.sourceSnapshot,a=e.sourceScanStartedAt;if(e.sourceSnapshot=t,e.sourceScanStartedAt=s,!o)continue;const i=Date.now(),l=(0,lifecycle_1.diffSourceSets)(o,t,i,(0,lifecycle_1.sourceChangeWindowMs)(i,a,types_1.POD_STALE_SCAN_MS,types_1.POD_RECYCLE_SETTLE_MS));l&&(e.sourceChange=l,p("info",`source file set changed for ${e.key}`,`cluster-lens-app:${e.project}`,{kind:"source-set-changed",scoped:!0,wsKey:e.wsKey,project:e.project,added:l.added,removed:l.removed,truncated:l.truncated},void 0,e.eventFile===r.eventFile?void 0:e.eventFile))}})().catch(()=>{}).finally(()=>{z=!1}))},"scanFrontendSourceSets");let X=!1;const fe=d(async(e,s)=>{if(!X){X=!0;try{for(const[n,t]of[...T]){if(r.stopped())return;if(t.port===void 0||n.exitCode!==null||n.signalCode!==null)continue;if(await probePortListening(t.port,types_1.LENS_PROBE_TIMEOUT_MS)){if(t.probeFails=0,!t.listening){t.listening=!0;const l=L.get(t.key);l?.active?.vite===n&&(l.state="ready",l.reason=void 0),p("info",`lens app up: ${t.project} (vite :${t.port} listening)`,`cluster-lens-app:${t.project}`,{kind:"service-up",project:t.project,port:t.port},void 0,t.bus)}continue}const o=t.listening?e.graceMs:Math.max(e.graceMs,e.neverListenedGraceMs);if(Date.now()-t.spawnedAt<o){t.probeFails=0;continue}if(!s)continue;t.probeFails+=1;const a=(0,lifecycle_1.lensChildWedged)({spawnedAt:t.spawnedAt,probeFails:t.probeFails,hasListened:t.listening},F.get(t.key)??0,Date.now(),e);if(!a)continue;const i=t.listening?"its listener VANISHED (was up, now refusing)":`it NEVER bound within the ${Math.round(o/1e3)}s boot allowance`;F.set(t.key,Date.now()),t.probeFails=0,t.listening=!1,console.error(`[gateway] wedge recycle: lens app ${t.project} is ALIVE but NOT LISTENING on :${t.port} after ${Math.max(2,e.failureThreshold)} probes \u2014 ${i} \u2014 SIGKILL; a fresh vite is coming.`),p("warning",`wedge recycle: ${t.project} (${a})`,`cluster-lens-app:${t.project}`,{kind:"pod-recycle",project:t.project,reason:a,port:t.port},void 0,t.bus);try{n.kill("SIGKILL")}catch{}}}finally{X=!1}}},"probeLensChildren"),he=d(()=>{if(D||!types_1.POD_RECYCLE_ENABLED&&!types_1.LENS_PROBE_ENABLED)return;const e={graceMs:types_1.POD_STALE_GRACE_MS,settleMs:types_1.POD_RECYCLE_SETTLE_MS,cooldownMs:types_1.POD_STALE_RECYCLE_COOLDOWN_MS};D=setInterval(()=>{if(r.stopped()||T.size===0||(ne(),!types_1.POD_RECYCLE_ENABLED))return;Ee();const s=Date.now();for(const[n,t]of T){const o=L.get(t.key),a=o?.sourceChange?.changedAt??0,i=F.get(t.key)??0;(0,lifecycle_1.lensFrontendStale)(t.spawnedAt,i,a,s,e)&&((H.get(t.key)??0)>=a||K.has(t.key)||(K.add(t.key),(async()=>{try{const l=o?.sourceChange,h=l&&!l.truncated?[...l.added,...l.removed].map(v=>path.resolve(t.workspaceRoot,v)):[],c=types_1.LENS_WATCHER_PROBE_ENABLED&&t.port!==void 0?(0,lifecycle_1.lensWatcherVerdict)(await C(t.port),a,l?.windowMs??types_1.POD_STALE_SCAN_MS+types_1.POD_RECYCLE_SETTLE_MS,h):"unknown";if(c==="heard"){H.set(t.key,a),console.log(`[gateway] stale source set: lens app ${t.project} watcher CONFIRMED the change \u2014 no recycle, HMR intact.`),p("info",`stale check: ${t.project} watcher confirmed \u2014 no recycle`,`cluster-lens-app:${t.project}`,{kind:"pod-stale-verified",project:t.project},void 0,t.bus);return}if(c==="unknown"&&types_1.LENS_WATCHER_UNVERIFIED==="keep"){console.log(`[gateway] stale source set: lens app ${t.project} unverifiable (no watcher testimony) \u2014 keeping it (LENSMCP_LENS_WATCHER_UNVERIFIED=keep).`);return}if(n.exitCode!==null||n.signalCode!==null)return;F.set(t.key,Date.now());const S=L.get(t.key);if(types_1.LENS_RESTART_MODE==="rolling"&&S){console.log(`[gateway] stale refresh: lens app ${t.key} (stale-source-set) \u2014 watcher ${c==="missed"?"missed the exact path change":"unverifiable"}; preparing a standby without dropping traffic.`),p("warning",`stale refresh: ${t.project} (stale-source-set)`,`cluster-lens-app:${t.project}`,{kind:"pod-refresh",wsKey:S.wsKey,project:t.project,reason:"stale-source-set",watcher:c,added:l?.added,removed:l?.removed},void 0,t.bus),await U(S,"stale-source-set");return}t.listening=!1,console.log(`[gateway] zombie recycle: lens app ${t.project} (stale-source-set) \u2014 watcher ${c==="missed"?"SILENT across the change":"unverifiable"}; restarting it`),p("warning",`zombie recycle: ${t.project} (stale-source-set)`,`cluster-lens-app:${t.project}`,{kind:"pod-recycle",project:t.project,reason:"stale-source-set",watcher:c},void 0,t.bus);const M=(0,hmr_reload_1.broadcastFullReload)(r,t.key);M>0&&console.log(`[gateway] \u2192 told ${M} open tab(s) to reload (stale optimize-dep generation)`);try{n.kill("SIGTERM")}catch{}setTimeout(()=>{if(n.exitCode===null&&n.signalCode===null){console.log(`[gateway] zombie recycle: lens app ${t.project} ignored SIGTERM for ${Math.round(types_1.LENS_RECYCLE_KILL_GRACE_MS/1e3)}s \u2014 escalating to SIGKILL.`);try{n.kill("SIGKILL")}catch{}}},types_1.LENS_RECYCLE_KILL_GRACE_MS).unref?.()}finally{K.delete(t.key)}})()))}},Math.min(types_1.POD_STALE_SCAN_MS,15e3)),D.unref?.()},"startLensSweeper"),ge=d(async()=>{const e=[...new Map(r.routes.filter(t=>t.lens).map(t=>[t.project,t.lens])).values()],s=u.dashboard!==!1,n=u.mcp!==!1&&e.length>0;if(s){const t=(0,lens_frontend_1.findDashboardBundle)(r.root);if(!t)console.warn("[gateway] lens dashboard bundle not found \u2014 skipping. Install the self-contained CLI: `npm i -D lensmcp` (it ships `bundled/dashboard.js`), or `yarn nx build @lensmcp/lensmcp-mcp` in-repo.");else{const o=(0,scope_1.readLensScope)(r.root),a=await I(u.dashboardPort??o.dashboardPort,Y),i=u.lensHost??"lensmcp.local",l=o.basePath;r.registry.appendRoutes(r.wsKey,[{host:i,prefix:l,project:observability_1.LENS_DASHBOARD_PROJECT,target:`http://localhost:${a}`}]),r.rebuildRoutes(),(0,workspace_registry_1.registerWorkspace)({key:o.key,root:r.root,base:l,pid:process.pid,procStamp:(0,workspace_registry_1.processStamp)(process.pid),updatedAt:new Date().toISOString()}),console.log(`[gateway] starting lens dashboard \u2192 http://localhost:${a} (routed at https://${i}${l}/)`),p("info",`lens dashboard up: ${i}${l} \u2192 :${a}`,"cluster-lens-dashboard",{kind:"lens-dashboard-up",host:i,port:a,base:l}),k("lens-dashboard",process.execPath,[t],{LENSMCP_EVENT_FILE:r.eventFile,LENSMCP_PROCESS_ROLE:"dashboard",LENSMCP_DASHBOARD_PORT:String(a),LENSMCP_DASHBOARD_BASE:l},!1,void 0,void 0,a)}}if(n){const t=(0,lens_frontend_1.findMcpBundle)(r.root);if(!t)console.warn("[gateway] MCP server bundle not found \u2014 skipping (lens apps will still publish to the bus; an external `lensmcp mcp` can read it). Install: `npm i -D lensmcp`.");else{const o=(0,scope_1.readLensScope)(r.root),a=Number(process.env.LENSMCP_PORT??o.mcpHttpPort),i=d(()=>{console.log(`[gateway] starting lens MCP server on 127.0.0.1:${a} (${t})`),k("lens-mcp",process.execPath,[t],{LENSMCP_EVENT_FILE:r.eventFile,LENSMCP_PROCESS_ROLE:"mcp",LENSMCP_TRANSPORT:process.env.LENSMCP_TRANSPORT??"http",LENSMCP_PORT:String(a),LENSMCP_WORKSPACE_KEY:o.key,LENSMCP_WORKSPACE_ROOT:r.root},!1,void 0,void 0,a)},"spawnMcp");await f(a)?i():(console.warn(`[gateway] lens MCP port :${a} is already served \u2014 an external lensmcp server (a shared daemon?) owns this workspace's MCP; not spawning a second. Re-probing every ${Math.round(types_1.LENS_PARKED_PORT_REPROBE_MS/1e3)}s; will take over if it frees.`),p("info",`lens MCP served externally on :${a} \u2014 gateway parked its own`,"cluster-lens-child:lens-mcp",{kind:"lens-child-up",project:"lens-mcp",label:"lens-mcp",port:a,external:!0}),Q("lens-mcp",a,i))}}for(const t of e){if(t.started)continue;t.started=!0;const o=t.port,a=(r.registry.get(r.wsKey)?.routes??r.routes).filter(h=>h.lens?.project===t.project),i=await I(t.port,m);for(const h of a)h.lens&&(h.lens.port=i),h.target=`http://localhost:${i}`;t.port=i;const l=Z({wsKey:r.wsKey,project:t.project,workspaceRoot:r.root,projectRoot:t.projectRoot,eventFile:r.eventFile,routes:a,frontend:t,desiredPort:o});try{te(l,i),p("info",`lens app started: ${t.project} (vite :${t.port})`,`cluster-lens-app:${t.project}`,{kind:"lens-app-up",project:t.project,port:t.port})}catch(h){m.delete(i),l.state="failed",console.error(`[gateway] lens app ${t.project}: ${h.message}`)}}he()},"bootSingletonsAndApps"),we=d(async e=>{if(u.dashboard===!1)return;const s=(0,lens_frontend_1.findDashboardBundle)(r.root);if(!s)return;const n=(0,scope_1.readLensScope)(e.root),t=u.lensHost??"lensmcp.local",o=n.basePath,a=await I(n.dashboardPort,Y),i=`lens-dashboard:${e.wsKey}`,l=path.join(e.root,".lensmcp","events.jsonl");return P.delete(i),r.registry.appendRoutes(e.wsKey,[{host:t,prefix:o,project:observability_1.LENS_DASHBOARD_PROJECT,target:`http://localhost:${a}`}]),(0,workspace_registry_1.registerWorkspace)({key:e.wsKey,root:e.root,base:o,pid:process.pid,procStamp:(0,workspace_registry_1.processStamp)(process.pid),updatedAt:new Date().toISOString()}),console.log(`[gateway] hosting dashboard for workspace '${e.wsKey}' \u2192 http://localhost:${a} (routed at https://${t}${o}/)`),p("info",`lens dashboard up: ${t}${o} \u2192 :${a}`,"cluster-lens-dashboard",{kind:"lens-dashboard-up",host:t,port:a,base:o}),k(i,process.execPath,[s],{LENSMCP_EVENT_FILE:l,LENSMCP_PROCESS_ROLE:"dashboard",LENSMCP_DASHBOARD_PORT:String(a),LENSMCP_DASHBOARD_BASE:o,LENSMCP_WS_KEY:e.wsKey},!1,void 0,e.root,a),()=>{P.add(i),Y.delete(a),(0,workspace_registry_1.unregisterWorkspace)(e.wsKey);const h=N.get(i);h&&W(h),N.delete(i)}},"hostWorkspaceDashboard"),_e=d(async e=>{const s=new Map;for(const o of e.routes){if(!o.lens)continue;const a=s.get(o.lens.project)??[];a.push(o),s.set(o.lens.project,a)}if(s.size===0)return()=>{};const n=path.join(e.root,".lensmcp","events.jsonl"),t=[];for(const[o,a]of s){const i=a[0].lens;if(i.started)continue;const l=await I(i.port,m),h=i.port;for(const S of a)S.lens.started=!0,S.lens.port=l,S.target=`http://localhost:${l}`;const c=Z({wsKey:e.wsKey,project:o,workspaceRoot:e.root,projectRoot:i.projectRoot,eventFile:n,routes:a,frontend:i,desiredPort:h});t.push(c),console.log(`[gateway] hosting lens app '${o}' of '${e.wsKey}' \u2192 vite :${l}`);try{te(c,l),p("info",`lens app started: ${e.wsKey}/${o} (vite :${l})`,`cluster-lens-app:${e.wsKey}:${o}`,{kind:"lens-app-up",project:o,port:l},void 0,n)}catch(S){m.delete(l),c.state="failed",console.error(`[gateway] lens app ${e.wsKey}/${o}: ${S.message}`)}}return()=>{for(const o of t){o.disposed=!0;for(const a of[...o.generations])x(a,!0);for(const a of o.routes)a.lens&&j.delete(a.lens);j.delete(o.frontend),F.delete(o.key),H.delete(o.key),K.delete(o.key),L.delete(o.key)}}},"hostWorkspaceApps"),Se=d(async(e=2500)=>{D&&(clearInterval(D),D=void 0);const s=[...y];for(const o of s)try{o.kill("SIGTERM")}catch{}const n=d(o=>o.exitCode===null&&o.signalCode===null,"alive"),t=Date.now()+e;for(;Date.now()<t&&s.some(n);)await new Promise(o=>setTimeout(o,100));for(const o of s)if(n(o))try{o.kill("SIGKILL")}catch{}},"reapAll"),ne=d(()=>fe({graceMs:types_1.LENS_PROBE_GRACE_MS,failureThreshold:types_1.LENS_PROBE_FAILS,cooldownMs:types_1.LENS_PROBE_COOLDOWN_MS,neverListenedGraceMs:types_1.LENS_PROBE_BOOT_GRACE_MS},types_1.LENS_PROBE_ENABLED),"probeLensFrontends");return{spawnManagedChild:k,bootSingletonsAndApps:ge,hostWorkspaceDashboard:we,hostWorkspaceApps:_e,probeLensFrontends:ne,reapAll:Se}}R(createLensChildren,"createLensChildren"),d(createLensChildren,"createLensChildren");
|
|
@@ -18,7 +18,8 @@ export interface Observability {
|
|
|
18
18
|
eid(): string;
|
|
19
19
|
beginTrace(req: http.IncomingMessage): GwTrace | undefined;
|
|
20
20
|
traceStep(t: GwTrace | undefined, stepName: string, info?: Record<string, unknown>): void;
|
|
21
|
-
|
|
21
|
+
/** `route` identifies the OWNING workspace, so a guest's request narration goes to its own bus. */
|
|
22
|
+
finishTrace(t: GwTrace | undefined, project: string, status: number, extra?: Record<string, unknown>, route?: Route): void;
|
|
22
23
|
recordEdge(route: Route, ms: number, status: number, caller?: string): void;
|
|
23
24
|
/** Start the periodic traffic-edge flush; returns the interval (already `.unref()`'d). */
|
|
24
25
|
startEdgeFlusher(): NodeJS.Timeout;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`;busHygiene?.maybeRotateEventFile(
|
|
1
|
+
"use strict";var D=Object.defineProperty;var l=(s,d)=>D(s,"name",{value:d,configurable:!0});var b=Object.defineProperty,o=l((s,d)=>b(s,"name",{value:d,configurable:!0}),"o");Object.defineProperty(exports,"__esModule",{value:!0}),exports.LENS_DASHBOARD_PROJECT=void 0,exports.createObservability=createObservability;const tslib_1=require("tslib"),fs=tslib_1.__importStar(require("node:fs")),path=tslib_1.__importStar(require("node:path")),redact_1=require("@lensmcp/core/redact"),busHygiene=(()=>{try{return require("@lensmcp/node-instrumentation")}catch{return}})();exports.LENS_DASHBOARD_PROJECT="(lens-dashboard)";function ownerOf(s){return s?.svc?{root:s.svc.root,wsKey:s.svc.wsKey}:s?.lens?.workspaceKey?{wsKey:s.lens.workspaceKey}:{}}l(ownerOf,"ownerOf"),o(ownerOf,"ownerOf");function busFileFor(s,d){const{root:u}=ownerOf(s);if(!u)return;const p=path.join(u,".lensmcp","events.jsonl");return p===d?void 0:p}l(busFileFor,"busFileFor"),o(busFileFor,"busFileFor");const hdr=o(s=>typeof s=="string"&&s!==""?s:Array.isArray(s)?s[0]:void 0,"hdr");function createObservability(s,d){const u=o(()=>Date.now().toString(36)+Math.random().toString(36).slice(2,12),"eid"),p=busHygiene?.createEventFloodGuard({burst:30,perSec:5}),h=o((e,r,t,n,a,c)=>{const i=c??s;try{const y=p?p.admit(t):{ok:!0,suppressed:0};if(!y.ok)return;fs.mkdirSync(path.dirname(i),{recursive:!0});const w=n&&(0,redact_1.redactDeep)(n),g=JSON.stringify({id:u(),sessionId:"pending",timestamp:Date.now(),source:"gateway",category:"cluster",severity:e,context:(0,redact_1.redactDeep)({sessionId:"pending",...a}),fingerprint:t,title:(0,redact_1.safeTitle)(r),raw:y.suppressed>0?{...w,floodSuppressed:y.suppressed}:w})+`
|
|
2
|
+
`;busHygiene?.maybeRotateEventFile(i,g.length),fs.appendFileSync(i,g)}catch{}},"emit"),m=o(e=>{const r=hdr(e.headers["x-lensmcp-flow-id"]);let t=hdr(e.headers["x-request-id"]);if(!(!r&&!t&&!hdr(e.headers.traceparent)))return t||(t=u(),e.headers["x-request-id"]=t),{startedAt:Date.now(),method:(e.method??"GET").toUpperCase(),host:(e.headers.host||"").split(":")[0],url:e.url??"/",steps:[],...r?{flowId:r}:{},...t?{requestId:t}:{},...hdr(e.headers["x-lensmcp-origin-node-id"])?{originNodeId:hdr(e.headers["x-lensmcp-origin-node-id"])}:{}}},"beginTrace"),v=o((e,r,t)=>{e&&e.steps.push({step:r,atMs:Date.now()-e.startedAt,...t})},"traceStep"),S=o((e,r,t,n,a)=>{if(!e||e.done||(e.done=!0,r===exports.LENS_DASHBOARD_PROJECT&&t<500))return;const c=Date.now()-e.startedAt;h(t>=500?"error":"info",`gateway ${e.method} ${e.host}${e.url} \u2192 ${t} (${c}ms)`,`gateway-request:${r}`,{kind:"gateway-request",project:r,host:e.host,method:e.method,url:e.url,status:t,durationMs:c,startedAt:e.startedAt,steps:e.steps,...ownerOf(a).wsKey?{wsKey:ownerOf(a).wsKey}:{},...n},{...e.flowId?{flowId:e.flowId}:{},...e.requestId?{requestId:e.requestId}:{},...e.originNodeId?{originNodeId:e.originNodeId}:{}},busFileFor(a,s))},"finishTrace"),f=new Map;return{emit:h,eid:u,beginTrace:m,traceStep:v,finishTrace:S,recordEdge:o((e,r,t,n)=>{if(e.project===exports.LENS_DASHBOARD_PROJECT&&t<500&&t!==0)return;const a=e.host??"(default)",c=(n?n+"\u21D2":"")+a+"\u2192"+e.project,i=f.get(c)??{host:a,project:e.project,caller:n,count:0,totalMs:0,errors:0,...busFileFor(e,s)?{busFile:busFileFor(e,s)}:{},...ownerOf(e).wsKey?{wsKey:ownerOf(e).wsKey}:{}};i.count+=1,i.totalMs+=r,(t>=500||t===0)&&(i.errors+=1),f.set(c,i)},"recordEdge"),startEdgeFlusher:o(()=>{const e=setInterval(()=>{for(const r of f.values()){const t=Math.round(r.totalMs/r.count);h(r.errors?"warning":"info",`traffic ${r.host} \u2192 ${r.project}: ${r.count} req, ~${t}ms${r.errors?`, ${r.errors} errors`:""}`,`gateway-traffic:${r.host}->${r.project}`,{kind:"gateway-traffic",host:r.host,project:r.project,caller:r.caller,count:r.count,avgMs:t,errors:r.errors,...r.wsKey?{wsKey:r.wsKey}:{}},void 0,r.busFile)}f.clear()},d.trafficFlushMs);return e.unref(),e},"startEdgeFlusher")}}l(createObservability,"createObservability"),o(createObservability,"createObservability");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var L=Object.defineProperty;var T=(n,i)=>L(n,"name",{value:i,configurable:!0});var H=Object.defineProperty,r=T((n,i)=>H(n,"name",{value:i,configurable:!0}),"r");Object.defineProperty(exports,"__esModule",{value:!0}),exports.isReplayableRequest=isReplayableRequest,exports.createProxy=createProxy;const tslib_1=require("tslib"),fs=tslib_1.__importStar(require("node:fs")),http=tslib_1.__importStar(require("node:http")),path=tslib_1.__importStar(require("node:path")),discovery_1=require("./discovery"),edge_1=require("./edge"),gateway_errors_1=require("../gateway-errors"),body_stall_1=require("../body-stall"),types_1=require("./types"),pod_probe_1=require("./pod-probe"),service_keys_1=require("./service-keys");function isConnError(n){const i=n.code??"";return i==="ECONNREFUSED"||i==="ECONNRESET"||i==="ETIMEDOUT"||i==="EPIPE"||i==="EHOSTUNREACH"||i==="ENOENT"||/ECONNREFUSED|ECONNRESET|socket hang up|EPIPE/i.test(n.message)}T(isConnError,"isConnError"),r(isConnError,"isConnError");const IDEMPOTENT_METHODS=new Set(["GET","HEAD","OPTIONS","PUT","DELETE","TRACE"]);function isReplayableRequest(n){if(!IDEMPOTENT_METHODS.has((n.method??"GET").toUpperCase())||n.headers["transfer-encoding"]!==void 0)return!1;const i=n.headers["content-length"];return!(i!==void 0&&String(i).trim()!=="0")}T(isReplayableRequest,"isReplayableRequest"),r(isReplayableRequest,"isReplayableRequest");function edgeGone(n,i){return i.headersSent||i.writableEnded||i.destroyed===!0||n.aborted===!0}T(edgeGone,"edgeGone"),r(edgeGone,"edgeGone");const HOP_BY_HOP=new Set(["connection","keep-alive","proxy-connection","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade"]),UPSTREAM_CONNECTION_HEADERS=["connection","keep-alive","proxy-connection"],httpProxy=require("http-proxy");function declaredFirstByteMs(n){const i=Number(n);return Number.isFinite(i)&&i>0?i:types_1.POD_RESPONSE_TIMEOUT_MS}T(declaredFirstByteMs,"declaredFirstByteMs"),r(declaredFirstByteMs,"declaredFirstByteMs");function armFirstByteGuard(n){let i,m=0,$=!1,O=!1;const P=r(b=>{i=setTimeout(x,b),i.unref?.()},"arm"),x=r(()=>{if(!($||!n.pending())){if(m+=n.firstByteMs,n.ceilingMs<=0||m>=n.ceilingMs){n.onWedged(`no response within ${m}ms (wedged socket) \u2014 evicted + respawning`);return}(0,pod_probe_1.probePodAlive)(n.socketPath,void 0,n.serviceKey).then(b=>{if(!($||!n.pending())){if(!b){n.onWedged(`no response within ${m}ms and no answer on ${types_1.POD_ALIVE_PATH} (wedged socket) \u2014 evicted + respawning`);return}O||(O=!0,n.onSlow(m,b)),P(Math.max(n.firstByteMs,types_1.POD_ALIVE_PROBE_TIMEOUT_MS))}})}},"onDeadline");return P(n.firstByteMs),{clear:r(()=>{$=!0,i&&clearTimeout(i)},"clear")}}T(armFirstByteGuard,"armFirstByteGuard"),r(armFirstByteGuard,"armFirstByteGuard");function createProxy(n,i,m){const{recordEdge:$,finishTrace:O,traceStep:P,emit:x}=i,b=r(async e=>{if(!e.lens||!n.lensSupervisor)return"unsupported";let t;const o=new Promise(p=>{t=setTimeout(()=>p("timeout"),types_1.LENS_REQUEST_RECOVERY_WAIT_MS),t.unref?.()}),u=n.lensSupervisor.recover(e.lens,"proxy-connection").then(p=>p?"ready":"failed").catch(()=>"failed"),y=await Promise.race([u,o]);t&&clearTimeout(t);const _=n.lensSupervisor.status(e.lens);return y==="failed"&&(!_||_.state==="ready")?"unsupported":y},"waitForManagedRecovery"),j=r((e,t,o,u,y,_)=>{if(o.headersSent||o.writableEnded||o.destroyed){o.destroyed||o.destroy();return}const p=e.lens?n.lensSupervisor?.status(e.lens):void 0,h=_==="timeout"||p?.state==="starting"||p?.state==="replacing",f=(0,gateway_errors_1.ensureRequestId)(t),c=e.lens?{project:e.project,reason:p?.reason??"connection-failure",generation:p?.generation??0,...h?{retryAfterMs:2e3}:{}}:void 0,s=h?503:502,d=h?"starting":"unavailable";console.error(`[gateway] ${new Date().toISOString()} upstream-error traceId=${f} project=${e.project} target=${String(u)} state=${p?.state??"unmanaged"} generation=${p?.generation??0}: ${y.message}`),x("warning",`upstream unavailable: ${e.project}`,`cluster-upstream:${e.project}`,{kind:"upstream-error",traceId:f,project:e.project,target:String(u),state:p?.state??"unmanaged",generation:p?.generation,error:y.message}),(0,edge_1.sendError)(o,t,s,d,h?`Upstream ${e.project} is restarting.`:`Upstream ${e.project} unavailable.`,c,h?{"retry-after":"2"}:void 0)},"sendTerminalUpstreamError"),k=(0,body_stall_1.createBodyStallGuard)(n.bodyStallMs??types_1.BODY_STALL_MS),D={keepAlive:!0,keepAliveMsecs:3e4,maxSockets:1024,maxFreeSockets:256},R=new http.Agent(D),U=new(require("node:https")).Agent(D),A=r(e=>typeof e=="string"&&e.startsWith("https:")?U:R,"agentForTarget"),M=httpProxy.createProxyServer({xfwd:!1,secure:!1,proxyTimeout:12e4,agent:R}),C=r((e,t,o)=>{const u=r(()=>{o()||e.destroyed||e.destroy()},"onEdgeClose");t.once("close",u),e.once("close",()=>t.removeListener("close",u))},"propagateEdgeCancel");M.on("proxyReq",(e,t,o)=>{for(const u of UPSTREAM_CONNECTION_HEADERS)e.removeHeader(u);e.setHeader("connection","keep-alive"),C(e,o,()=>o.writableEnded)}),M.on("proxyRes",(e,t,o)=>{const u=t.__lensmcpPod;u&&(e.headers["x-lensmcp-pod"]=u),delete e.headers["x-powered-by"],e.headers.server="LensMCP",o&&C(e,o,()=>o.writableEnded),o&&k.armResponse(o)});const N=r((e,t,o,u)=>{(0,edge_1.stampForwardingHeaders)(n,t),k.arm(t);const y={},_=t.method==="GET"||t.method==="HEAD"||t.method==="OPTIONS";for(const[a,l]of Object.entries(t.headers))l===void 0||a.startsWith(":")||HOP_BY_HOP.has(a)||_&&(a==="content-length"||a==="transfer-encoding")||(y[a]=l);let p=http,h;if(typeof e=="object")h={socketPath:e.socketPath,path:t.url,method:t.method,headers:y,agent:R};else{const a=new URL(e),l=a.protocol==="https:";p=l?require("node:https"):http,y.host=a.host,h={protocol:a.protocol,hostname:a.hostname,port:a.port||(l?443:80),path:t.url,method:t.method,headers:y,agent:A(e)}}const f=o;f.__lensmcpErrContained||(f.__lensmcpErrContained=!0,o.on("error",()=>{}));let c;const s=r(()=>{o.writableEnded||E.destroy()},"onReqGone"),d=r(()=>{c&&!c.destroyed&&c.destroy()},"onEdgeClose"),g=r(()=>{t.removeListener("error",s),t.removeListener("aborted",s),t.removeListener("close",s),o.removeListener("close",d)},"detach"),E=p.request(h,a=>{if(c=a,u.onResponse(),o.headersSent||o.writableEnded||o.destroyed){a.destroy();return}const l={};for(const[v,I]of Object.entries(a.headers))I===void 0||HOP_BY_HOP.has(v)||(l[v]=I);delete l["x-powered-by"],l.server="LensMCP";const w=t.__lensmcpPod;w&&(l["x-lensmcp-pod"]=w);try{o.writeHead(a.statusCode??502,l)}catch(v){console.error("[gateway] h2 relay: bad response header, resetting stream:",v.message),a.destroy(),o.destroyed||o.destroy(v);return}a.pipe(o),k.armResponse(o);const S=r(()=>{!o.writableEnded&&!o.destroyed&&o.destroy()},"abortEdge");a.once("error",S),a.once("close",S),o.on("close",d)});E.once("error",a=>u.onError(a)),E.once("close",g),t.on("error",s),t.on("aborted",s),t.on("close",s),_?E.end():t.pipe(E)},"pipeUpstream"),q=r(async(e,t,o)=>{const u=t.__lensmcpTrace;if(e.pool){const c=e.svc;c&&(c.lastUsed=Date.now(),c.inflight+=1,o.on("close",()=>{c.inflight-=1,c.lastUsed=Date.now()}));let s=(0,discovery_1.pickSock)(e.pool,n.scanTtlMs);if(!s&&c&&(P(u,"cold-start",{project:e.project}),await m.ensureUp(c)&&(s=(0,discovery_1.pickSock)(e.pool,n.scanTtlMs))),c&&s&&m.markUp(c,"observed"),c&&m.scaleUp(c),!s){const l=c?.lastErrors?.length?` Service errors: ${c.lastErrors.join("; ")}`:"";(0,edge_1.sendError)(o,t,503,"unavailable",`Service ${e.project} is not reachable (no pods in ${e.pool.dir}).${l} The watcher recovers and the next request retries automatically.`);return}const d=path.basename(s,".sock");t.__lensmcpPod=d,P(u,"pod-select",{pod:d,pods:e.pool.socks.length,strategy:"round-robin"});let g=!1;const E=r(l=>{e.pool.socks=e.pool.socks.filter(w=>w!==s),e.pool.idx=-1;try{fs.unlinkSync(s)}catch{}console.error(`[gateway] pod ${d} of ${e.project}: ${l}`)},"evictPod"),a=armFirstByteGuard({socketPath:s,serviceKey:n.serviceKeys[(0,service_keys_1.serviceKeyId)(e.svc?.wsKey,e.project)],firstByteMs:declaredFirstByteMs(e.svc?.decl?.firstByteMs),ceilingMs:types_1.POD_SLOW_FIRST_BYTE_MS,pending:r(()=>!g&&!o.headersSent&&!o.writableEnded,"pending"),onWedged:r(l=>{g=!0,E(l),(0,edge_1.sendError)(o,t,502,"unavailable",`Pod ${d} of ${e.project} was unresponsive \u2014 evicted, retry.`)},"onWedged"),onSlow:r((l,w)=>{console.log(`[gateway] pod ${d} of ${e.project}: slow first byte, pod alive (${l}ms, ${w.inflight} in-flight, ${w.activeWork} background) \u2014 waiting, not evicting. Set cluster.firstByteMs on ${e.project} to size this route's budget.`)},"onSlow")});o.on("close",()=>a.clear()),N({socketPath:s},t,o,{onResponse:r(()=>{a.clear(),g=!0},"onResponse"),onError:r(l=>{a.clear(),!g&&(g=!0,E(l.message),(0,edge_1.sendError)(o,t,502,"unavailable",`Pod ${d} of ${e.project} unavailable \u2014 retry.`))},"onError")});return}const y=Date.now()+types_1.UPSTREAM_HEAL_WINDOW_MS;let _=0,p=!1;const h=isReplayableRequest(t),f=r(()=>{if(edgeGone(t,o))return;const c=e.target;N(c,t,o,{onResponse:r(()=>{},"onResponse"),onError:r(s=>{if(isConnError(s)&&(_+=1),e.lens&&isConnError(s)&&h&&_>=2&&!p&&!edgeGone(t,o)){p=!0,b(e).then(d=>{if(!edgeGone(t,o)){if(d==="ready"){f();return}if(d==="unsupported"&&Date.now()<y){setTimeout(f,types_1.UPSTREAM_HEAL_STEP_MS).unref?.();return}j(e,t,o,e.target,s,d)}});return}if(isConnError(s)&&h&&Date.now()<y&&!edgeGone(t,o)){setTimeout(f,types_1.UPSTREAM_HEAL_STEP_MS).unref?.();return}if(o.headersSent||o.writableEnded||o.destroyed){o.destroyed||o.destroy();return}j(e,t,o,c,s)},"onError")})},"tryTcp");f()},"forwardNative");return{proxy:M,forward:r(async(e,t,o)=>{const u=Date.now(),y=t.__lensmcpTrace;if(o.on("close",()=>{$(e,Date.now()-u,o.statusCode??0,t.__lensmcpCaller),O(y,e.project,o.statusCode??0,{...t.__lensmcpPod?{pod:t.__lensmcpPod}:{},...t.__lensmcpCaller?{caller:t.__lensmcpCaller}:{}})}),e.prependPrefix&&!t.url?.startsWith(e.prependPrefix)&&(t.url=e.prependPrefix+(t.url??"/")),(0,edge_1.stampForwardingHeaders)(n,t),k.arm(t),(t.httpVersionMajor??1)>=2){await q(e,t,o);return}if(e.pool){const s=e.svc;s&&(s.lastUsed=Date.now(),s.inflight+=1,o.on("close",()=>{s.inflight-=1,s.lastUsed=Date.now()}));let d=(0,discovery_1.pickSock)(e.pool,n.scanTtlMs);if(!d&&s&&(P(y,"cold-start",{project:e.project}),await m.ensureUp(s)&&(d=(0,discovery_1.pickSock)(e.pool,n.scanTtlMs))),s&&d&&m.markUp(s,"observed"),s&&m.scaleUp(s),!d){const S=s?.lastErrors?.length?` Service errors: ${s.lastErrors.join("; ")}`:"";(0,edge_1.sendError)(o,t,503,"unavailable",`Service ${e.project} is not reachable (no pods in ${e.pool.dir}).${S} The watcher recovers and the next request retries automatically.`);return}const g=path.basename(d,".sock");t.__lensmcpPod=g,P(y,"pod-select",{pod:g,pods:e.pool.socks.length,strategy:"round-robin"});let E=!1;const a=r(S=>{e.pool.socks=e.pool.socks.filter(v=>v!==d),e.pool.idx=-1;try{fs.unlinkSync(d)}catch{}console.error(`[gateway] pod ${g} of ${e.project}: ${S}`)},"evictPod"),l=armFirstByteGuard({socketPath:d,serviceKey:n.serviceKeys[(0,service_keys_1.serviceKeyId)(e.svc?.wsKey,e.project)],firstByteMs:declaredFirstByteMs(e.svc?.decl?.firstByteMs),ceilingMs:types_1.POD_SLOW_FIRST_BYTE_MS,pending:r(()=>!E&&!o.headersSent&&!o.writableEnded,"pending"),onWedged:r(S=>{E=!0,a(S),(0,edge_1.sendError)(o,t,502,"unavailable",`Pod ${g} of ${e.project} was unresponsive \u2014 evicted, retry.`)},"onWedged"),onSlow:r((S,v)=>{console.log(`[gateway] pod ${g} of ${e.project}: slow first byte, pod alive (${S}ms, ${v.inflight} in-flight, ${v.activeWork} background) \u2014 waiting, not evicting. Set cluster.firstByteMs on ${e.project} to size this route's budget.`)},"onSlow")});o.on("close",()=>l.clear());const w=Math.max(12e4,types_1.POD_SLOW_FIRST_BYTE_MS+6e4);M.web(t,o,{target:{socketPath:d},agent:R,proxyTimeout:w},S=>{l.clear(),!E&&(E=!0,a(S.message),(0,edge_1.sendError)(o,t,502,"unavailable",`Pod ${g} of ${e.project} unavailable \u2014 retry.`))});return}const _=Date.now()+types_1.UPSTREAM_HEAL_WINDOW_MS;let p=0,h=!1;const f=isReplayableRequest(t),c=r(()=>{if(edgeGone(t,o))return;const s=e.target,d={target:s,autoRewrite:typeof s=="string",changeOrigin:!0,agent:A(s)};M.web(t,o,d,g=>{if(isConnError(g)&&(p+=1),e.lens&&isConnError(g)&&f&&p>=2&&!h&&!edgeGone(t,o)){h=!0,b(e).then(E=>{if(!edgeGone(t,o)){if(E==="ready"){c();return}if(E==="unsupported"&&Date.now()<_){setTimeout(c,types_1.UPSTREAM_HEAL_STEP_MS).unref?.();return}j(e,t,o,e.target,g,E)}});return}if(isConnError(g)&&f&&Date.now()<_&&!edgeGone(t,o)){setTimeout(c,types_1.UPSTREAM_HEAL_STEP_MS).unref?.();return}o.destroyed||j(e,t,o,s,g)})},"tryTcp");c()},"forward"),agentForTarget:A,destroyAgents:r(()=>{k.stop(),R.destroy(),U.destroy()},"destroyAgents"),closeProxy:r(()=>{try{M.close?.()}catch{}},"closeProxy")}}T(createProxy,"createProxy"),r(createProxy,"createProxy");
|
|
1
|
+
"use strict";var L=Object.defineProperty;var T=(n,i)=>L(n,"name",{value:i,configurable:!0});var H=Object.defineProperty,r=T((n,i)=>H(n,"name",{value:i,configurable:!0}),"r");Object.defineProperty(exports,"__esModule",{value:!0}),exports.isReplayableRequest=isReplayableRequest,exports.createProxy=createProxy;const tslib_1=require("tslib"),fs=tslib_1.__importStar(require("node:fs")),http=tslib_1.__importStar(require("node:http")),path=tslib_1.__importStar(require("node:path")),discovery_1=require("./discovery"),edge_1=require("./edge"),gateway_errors_1=require("../gateway-errors"),body_stall_1=require("../body-stall"),types_1=require("./types"),pod_probe_1=require("./pod-probe"),service_keys_1=require("./service-keys");function isConnError(n){const i=n.code??"";return i==="ECONNREFUSED"||i==="ECONNRESET"||i==="ETIMEDOUT"||i==="EPIPE"||i==="EHOSTUNREACH"||i==="ENOENT"||/ECONNREFUSED|ECONNRESET|socket hang up|EPIPE/i.test(n.message)}T(isConnError,"isConnError"),r(isConnError,"isConnError");const IDEMPOTENT_METHODS=new Set(["GET","HEAD","OPTIONS","PUT","DELETE","TRACE"]);function isReplayableRequest(n){if(!IDEMPOTENT_METHODS.has((n.method??"GET").toUpperCase())||n.headers["transfer-encoding"]!==void 0)return!1;const i=n.headers["content-length"];return!(i!==void 0&&String(i).trim()!=="0")}T(isReplayableRequest,"isReplayableRequest"),r(isReplayableRequest,"isReplayableRequest");function edgeGone(n,i){return i.headersSent||i.writableEnded||i.destroyed===!0||n.aborted===!0}T(edgeGone,"edgeGone"),r(edgeGone,"edgeGone");const HOP_BY_HOP=new Set(["connection","keep-alive","proxy-connection","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade"]),UPSTREAM_CONNECTION_HEADERS=["connection","keep-alive","proxy-connection"],httpProxy=require("http-proxy");function declaredFirstByteMs(n){const i=Number(n);return Number.isFinite(i)&&i>0?i:types_1.POD_RESPONSE_TIMEOUT_MS}T(declaredFirstByteMs,"declaredFirstByteMs"),r(declaredFirstByteMs,"declaredFirstByteMs");function armFirstByteGuard(n){let i,m=0,$=!1,O=!1;const P=r(b=>{i=setTimeout(x,b),i.unref?.()},"arm"),x=r(()=>{if(!($||!n.pending())){if(m+=n.firstByteMs,n.ceilingMs<=0||m>=n.ceilingMs){n.onWedged(`no response within ${m}ms (wedged socket) \u2014 evicted + respawning`);return}(0,pod_probe_1.probePodAlive)(n.socketPath,void 0,n.serviceKey).then(b=>{if(!($||!n.pending())){if(!b){n.onWedged(`no response within ${m}ms and no answer on ${types_1.POD_ALIVE_PATH} (wedged socket) \u2014 evicted + respawning`);return}O||(O=!0,n.onSlow(m,b)),P(Math.max(n.firstByteMs,types_1.POD_ALIVE_PROBE_TIMEOUT_MS))}})}},"onDeadline");return P(n.firstByteMs),{clear:r(()=>{$=!0,i&&clearTimeout(i)},"clear")}}T(armFirstByteGuard,"armFirstByteGuard"),r(armFirstByteGuard,"armFirstByteGuard");function createProxy(n,i,m){const{recordEdge:$,finishTrace:O,traceStep:P,emit:x}=i,b=r(async e=>{if(!e.lens||!n.lensSupervisor)return"unsupported";let t;const o=new Promise(p=>{t=setTimeout(()=>p("timeout"),types_1.LENS_REQUEST_RECOVERY_WAIT_MS),t.unref?.()}),u=n.lensSupervisor.recover(e.lens,"proxy-connection").then(p=>p?"ready":"failed").catch(()=>"failed"),y=await Promise.race([u,o]);t&&clearTimeout(t);const _=n.lensSupervisor.status(e.lens);return y==="failed"&&(!_||_.state==="ready")?"unsupported":y},"waitForManagedRecovery"),j=r((e,t,o,u,y,_)=>{if(o.headersSent||o.writableEnded||o.destroyed){o.destroyed||o.destroy();return}const p=e.lens?n.lensSupervisor?.status(e.lens):void 0,h=_==="timeout"||p?.state==="starting"||p?.state==="replacing",f=(0,gateway_errors_1.ensureRequestId)(t),c=e.lens?{project:e.project,reason:p?.reason??"connection-failure",generation:p?.generation??0,...h?{retryAfterMs:2e3}:{}}:void 0,s=h?503:502,d=h?"starting":"unavailable";console.error(`[gateway] ${new Date().toISOString()} upstream-error traceId=${f} project=${e.project} target=${String(u)} state=${p?.state??"unmanaged"} generation=${p?.generation??0}: ${y.message}`),x("warning",`upstream unavailable: ${e.project}`,`cluster-upstream:${e.project}`,{kind:"upstream-error",traceId:f,project:e.project,target:String(u),state:p?.state??"unmanaged",generation:p?.generation,error:y.message}),(0,edge_1.sendError)(o,t,s,d,h?`Upstream ${e.project} is restarting.`:`Upstream ${e.project} unavailable.`,c,h?{"retry-after":"2"}:void 0)},"sendTerminalUpstreamError"),k=(0,body_stall_1.createBodyStallGuard)(n.bodyStallMs??types_1.BODY_STALL_MS),D={keepAlive:!0,keepAliveMsecs:3e4,maxSockets:1024,maxFreeSockets:256},R=new http.Agent(D),U=new(require("node:https")).Agent(D),A=r(e=>typeof e=="string"&&e.startsWith("https:")?U:R,"agentForTarget"),M=httpProxy.createProxyServer({xfwd:!1,secure:!1,proxyTimeout:12e4,agent:R}),C=r((e,t,o)=>{const u=r(()=>{o()||e.destroyed||e.destroy()},"onEdgeClose");t.once("close",u),e.once("close",()=>t.removeListener("close",u))},"propagateEdgeCancel");M.on("proxyReq",(e,t,o)=>{for(const u of UPSTREAM_CONNECTION_HEADERS)e.removeHeader(u);e.setHeader("connection","keep-alive"),C(e,o,()=>o.writableEnded)}),M.on("proxyRes",(e,t,o)=>{const u=t.__lensmcpPod;u&&(e.headers["x-lensmcp-pod"]=u),delete e.headers["x-powered-by"],e.headers.server="LensMCP",o&&C(e,o,()=>o.writableEnded),o&&k.armResponse(o)});const N=r((e,t,o,u)=>{(0,edge_1.stampForwardingHeaders)(n,t),k.arm(t);const y={},_=t.method==="GET"||t.method==="HEAD"||t.method==="OPTIONS";for(const[a,l]of Object.entries(t.headers))l===void 0||a.startsWith(":")||HOP_BY_HOP.has(a)||_&&(a==="content-length"||a==="transfer-encoding")||(y[a]=l);let p=http,h;if(typeof e=="object")h={socketPath:e.socketPath,path:t.url,method:t.method,headers:y,agent:R};else{const a=new URL(e),l=a.protocol==="https:";p=l?require("node:https"):http,y.host=a.host,h={protocol:a.protocol,hostname:a.hostname,port:a.port||(l?443:80),path:t.url,method:t.method,headers:y,agent:A(e)}}const f=o;f.__lensmcpErrContained||(f.__lensmcpErrContained=!0,o.on("error",()=>{}));let c;const s=r(()=>{o.writableEnded||E.destroy()},"onReqGone"),d=r(()=>{c&&!c.destroyed&&c.destroy()},"onEdgeClose"),g=r(()=>{t.removeListener("error",s),t.removeListener("aborted",s),t.removeListener("close",s),o.removeListener("close",d)},"detach"),E=p.request(h,a=>{if(c=a,u.onResponse(),o.headersSent||o.writableEnded||o.destroyed){a.destroy();return}const l={};for(const[v,I]of Object.entries(a.headers))I===void 0||HOP_BY_HOP.has(v)||(l[v]=I);delete l["x-powered-by"],l.server="LensMCP";const w=t.__lensmcpPod;w&&(l["x-lensmcp-pod"]=w);try{o.writeHead(a.statusCode??502,l)}catch(v){console.error("[gateway] h2 relay: bad response header, resetting stream:",v.message),a.destroy(),o.destroyed||o.destroy(v);return}a.pipe(o),k.armResponse(o);const S=r(()=>{!o.writableEnded&&!o.destroyed&&o.destroy()},"abortEdge");a.once("error",S),a.once("close",S),o.on("close",d)});E.once("error",a=>u.onError(a)),E.once("close",g),t.on("error",s),t.on("aborted",s),t.on("close",s),_?E.end():t.pipe(E)},"pipeUpstream"),q=r(async(e,t,o)=>{const u=t.__lensmcpTrace;if(e.pool){const c=e.svc;c&&(c.lastUsed=Date.now(),c.inflight+=1,o.on("close",()=>{c.inflight-=1,c.lastUsed=Date.now()}));let s=(0,discovery_1.pickSock)(e.pool,n.scanTtlMs);if(!s&&c&&(P(u,"cold-start",{project:e.project}),await m.ensureUp(c)&&(s=(0,discovery_1.pickSock)(e.pool,n.scanTtlMs))),c&&s&&m.markUp(c,"observed"),c&&m.scaleUp(c),!s){const l=c?.lastErrors?.length?` Service errors: ${c.lastErrors.join("; ")}`:"";(0,edge_1.sendError)(o,t,503,"unavailable",`Service ${e.project} is not reachable (no pods in ${e.pool.dir}).${l} The watcher recovers and the next request retries automatically.`);return}const d=path.basename(s,".sock");t.__lensmcpPod=d,P(u,"pod-select",{pod:d,pods:e.pool.socks.length,strategy:"round-robin"});let g=!1;const E=r(l=>{e.pool.socks=e.pool.socks.filter(w=>w!==s),e.pool.idx=-1;try{fs.unlinkSync(s)}catch{}console.error(`[gateway] pod ${d} of ${e.project}: ${l}`)},"evictPod"),a=armFirstByteGuard({socketPath:s,serviceKey:n.serviceKeys[(0,service_keys_1.serviceKeyId)(e.svc?.wsKey,e.project)],firstByteMs:declaredFirstByteMs(e.svc?.decl?.firstByteMs),ceilingMs:types_1.POD_SLOW_FIRST_BYTE_MS,pending:r(()=>!g&&!o.headersSent&&!o.writableEnded,"pending"),onWedged:r(l=>{g=!0,E(l),(0,edge_1.sendError)(o,t,502,"unavailable",`Pod ${d} of ${e.project} was unresponsive \u2014 evicted, retry.`)},"onWedged"),onSlow:r((l,w)=>{console.log(`[gateway] pod ${d} of ${e.project}: slow first byte, pod alive (${l}ms, ${w.inflight} in-flight, ${w.activeWork} background) \u2014 waiting, not evicting. Set cluster.firstByteMs on ${e.project} to size this route's budget.`)},"onSlow")});o.on("close",()=>a.clear()),N({socketPath:s},t,o,{onResponse:r(()=>{a.clear(),g=!0},"onResponse"),onError:r(l=>{a.clear(),!g&&(g=!0,E(l.message),(0,edge_1.sendError)(o,t,502,"unavailable",`Pod ${d} of ${e.project} unavailable \u2014 retry.`))},"onError")});return}const y=Date.now()+types_1.UPSTREAM_HEAL_WINDOW_MS;let _=0,p=!1;const h=isReplayableRequest(t),f=r(()=>{if(edgeGone(t,o))return;const c=e.target;N(c,t,o,{onResponse:r(()=>{},"onResponse"),onError:r(s=>{if(isConnError(s)&&(_+=1),e.lens&&isConnError(s)&&h&&_>=2&&!p&&!edgeGone(t,o)){p=!0,b(e).then(d=>{if(!edgeGone(t,o)){if(d==="ready"){f();return}if(d==="unsupported"&&Date.now()<y){setTimeout(f,types_1.UPSTREAM_HEAL_STEP_MS).unref?.();return}j(e,t,o,e.target,s,d)}});return}if(isConnError(s)&&h&&Date.now()<y&&!edgeGone(t,o)){setTimeout(f,types_1.UPSTREAM_HEAL_STEP_MS).unref?.();return}if(o.headersSent||o.writableEnded||o.destroyed){o.destroyed||o.destroy();return}j(e,t,o,c,s)},"onError")})},"tryTcp");f()},"forwardNative");return{proxy:M,forward:r(async(e,t,o)=>{const u=Date.now(),y=t.__lensmcpTrace;if(o.on("close",()=>{$(e,Date.now()-u,o.statusCode??0,t.__lensmcpCaller),O(y,e.project,o.statusCode??0,{...t.__lensmcpPod?{pod:t.__lensmcpPod}:{},...t.__lensmcpCaller?{caller:t.__lensmcpCaller}:{}},e)}),e.prependPrefix&&!t.url?.startsWith(e.prependPrefix)&&(t.url=e.prependPrefix+(t.url??"/")),(0,edge_1.stampForwardingHeaders)(n,t),k.arm(t),(t.httpVersionMajor??1)>=2){await q(e,t,o);return}if(e.pool){const s=e.svc;s&&(s.lastUsed=Date.now(),s.inflight+=1,o.on("close",()=>{s.inflight-=1,s.lastUsed=Date.now()}));let d=(0,discovery_1.pickSock)(e.pool,n.scanTtlMs);if(!d&&s&&(P(y,"cold-start",{project:e.project}),await m.ensureUp(s)&&(d=(0,discovery_1.pickSock)(e.pool,n.scanTtlMs))),s&&d&&m.markUp(s,"observed"),s&&m.scaleUp(s),!d){const S=s?.lastErrors?.length?` Service errors: ${s.lastErrors.join("; ")}`:"";(0,edge_1.sendError)(o,t,503,"unavailable",`Service ${e.project} is not reachable (no pods in ${e.pool.dir}).${S} The watcher recovers and the next request retries automatically.`);return}const g=path.basename(d,".sock");t.__lensmcpPod=g,P(y,"pod-select",{pod:g,pods:e.pool.socks.length,strategy:"round-robin"});let E=!1;const a=r(S=>{e.pool.socks=e.pool.socks.filter(v=>v!==d),e.pool.idx=-1;try{fs.unlinkSync(d)}catch{}console.error(`[gateway] pod ${g} of ${e.project}: ${S}`)},"evictPod"),l=armFirstByteGuard({socketPath:d,serviceKey:n.serviceKeys[(0,service_keys_1.serviceKeyId)(e.svc?.wsKey,e.project)],firstByteMs:declaredFirstByteMs(e.svc?.decl?.firstByteMs),ceilingMs:types_1.POD_SLOW_FIRST_BYTE_MS,pending:r(()=>!E&&!o.headersSent&&!o.writableEnded,"pending"),onWedged:r(S=>{E=!0,a(S),(0,edge_1.sendError)(o,t,502,"unavailable",`Pod ${g} of ${e.project} was unresponsive \u2014 evicted, retry.`)},"onWedged"),onSlow:r((S,v)=>{console.log(`[gateway] pod ${g} of ${e.project}: slow first byte, pod alive (${S}ms, ${v.inflight} in-flight, ${v.activeWork} background) \u2014 waiting, not evicting. Set cluster.firstByteMs on ${e.project} to size this route's budget.`)},"onSlow")});o.on("close",()=>l.clear());const w=Math.max(12e4,types_1.POD_SLOW_FIRST_BYTE_MS+6e4);M.web(t,o,{target:{socketPath:d},agent:R,proxyTimeout:w},S=>{l.clear(),!E&&(E=!0,a(S.message),(0,edge_1.sendError)(o,t,502,"unavailable",`Pod ${g} of ${e.project} unavailable \u2014 retry.`))});return}const _=Date.now()+types_1.UPSTREAM_HEAL_WINDOW_MS;let p=0,h=!1;const f=isReplayableRequest(t),c=r(()=>{if(edgeGone(t,o))return;const s=e.target,d={target:s,autoRewrite:typeof s=="string",changeOrigin:!0,agent:A(s)};M.web(t,o,d,g=>{if(isConnError(g)&&(p+=1),e.lens&&isConnError(g)&&f&&p>=2&&!h&&!edgeGone(t,o)){h=!0,b(e).then(E=>{if(!edgeGone(t,o)){if(E==="ready"){c();return}if(E==="unsupported"&&Date.now()<_){setTimeout(c,types_1.UPSTREAM_HEAL_STEP_MS).unref?.();return}j(e,t,o,e.target,g,E)}});return}if(isConnError(g)&&f&&Date.now()<_&&!edgeGone(t,o)){setTimeout(c,types_1.UPSTREAM_HEAL_STEP_MS).unref?.();return}o.destroyed||j(e,t,o,s,g)})},"tryTcp");c()},"forward"),agentForTarget:A,destroyAgents:r(()=>{k.stop(),R.destroy(),U.destroy()},"destroyAgents"),closeProxy:r(()=>{try{M.close?.()}catch{}},"closeProxy")}}T(createProxy,"createProxy"),r(createProxy,"createProxy");
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lensmcp/cluster",
|
|
3
|
-
"version": "1.22.
|
|
3
|
+
"version": "1.22.4",
|
|
4
4
|
"description": "Run your Nx workspace as a local production cluster: pods on unix sockets with true HMR, one https gateway with per-project domains, scale-from-zero, autoscale, idle-kill, local-CA TLS — observed by the LensMCP lens.",
|
|
5
5
|
"main": "./index.js",
|
|
6
6
|
"types": "./index.d.ts",
|
|
@@ -57,9 +57,9 @@
|
|
|
57
57
|
}
|
|
58
58
|
},
|
|
59
59
|
"dependencies": {
|
|
60
|
-
"@lensmcp/core": "1.22.
|
|
61
|
-
"@lensmcp/node-instrumentation": "1.22.
|
|
62
|
-
"@lensmcp/nx-plugin": "1.22.
|
|
60
|
+
"@lensmcp/core": "1.22.4",
|
|
61
|
+
"@lensmcp/node-instrumentation": "1.22.4",
|
|
62
|
+
"@lensmcp/nx-plugin": "1.22.4",
|
|
63
63
|
"fastify": "^5.8.5",
|
|
64
64
|
"@fastify/reply-from": "^12.6.2",
|
|
65
65
|
"@typescript/native-preview": "^7.0.0-dev.20260707.2",
|