@lensmcp/cluster 1.26.2 → 1.26.3
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/build-host.js +1 -1
- package/devserver-host.d.ts +5 -0
- package/devserver-host.js +1 -1
- package/executors/gateway/runtime/auth.js +1 -1
- package/executors/gateway/runtime/control.d.ts +25 -0
- package/executors/gateway/runtime/control.js +2 -2
- package/executors/gateway/runtime/discovery.js +1 -1
- package/executors/gateway/runtime/docker-sweep.d.ts +51 -0
- package/executors/gateway/runtime/docker-sweep.js +1 -0
- package/executors/gateway/runtime/edge.d.ts +2 -0
- package/executors/gateway/runtime/edge.js +1 -1
- package/executors/gateway/runtime/frontend-updates.d.ts +24 -0
- package/executors/gateway/runtime/frontend-updates.js +1 -0
- package/executors/gateway/runtime/handler.js +1 -1
- package/executors/gateway/runtime/legacy-dashboard-link.d.ts +10 -0
- package/executors/gateway/runtime/legacy-dashboard-link.js +1 -0
- package/executors/gateway/runtime/lens-children.d.ts +9 -0
- package/executors/gateway/runtime/lens-children.js +1 -1
- package/executors/gateway/runtime/lifecycle.d.ts +2 -0
- package/executors/gateway/runtime/lifecycle.js +4 -4
- package/executors/gateway/runtime/peer-hub.d.ts +54 -0
- package/executors/gateway/runtime/peer-hub.js +1 -0
- package/executors/gateway/runtime/proxy.js +1 -1
- package/executors/gateway/runtime/remote-instances.d.ts +167 -0
- package/executors/gateway/runtime/remote-instances.js +1 -0
- package/executors/gateway/runtime/run-routes.d.ts +186 -0
- package/executors/gateway/runtime/run-routes.js +1 -0
- package/executors/gateway/runtime/server.js +2 -2
- package/executors/gateway/runtime/service-updates.d.ts +44 -0
- package/executors/gateway/runtime/service-updates.js +1 -0
- package/executors/gateway/runtime/shared-build.d.ts +8 -1
- package/executors/gateway/runtime/shared-build.js +4 -4
- package/executors/gateway/runtime/types.d.ts +54 -0
- package/executors/gateway/runtime/update-wiring.d.ts +57 -0
- package/executors/gateway/runtime/update-wiring.js +2 -0
- package/executors/gateway/runtime/updates.d.ts +148 -0
- package/executors/gateway/runtime/updates.js +1 -0
- package/executors/gateway/runtime/upgrade.js +1 -1
- package/executors/serve/serve.impl.js +1 -1
- package/executors/serve/updates-gate.d.ts +147 -0
- package/executors/serve/updates-gate.js +2 -0
- package/main.devserver.js +10 -10
- package/package.json +5 -5
- package/program-id.d.ts +4 -0
- package/program-id.js +1 -0
- package/shared-build/host.d.ts +102 -2
- package/shared-build/host.js +3 -3
- package/shared-build/protocol.d.ts +59 -3
- package/shared-build/protocol.js +1 -1
- package/shared-build/shared-compilation.d.ts +21 -0
- package/shared-build/shared-compilation.js +3 -3
- package/static-checks-record.d.ts +391 -0
- package/static-checks-record.js +5 -0
- package/tsgo-check-plugin.d.ts +107 -43
- package/tsgo-check-plugin.js +4 -5
- package/tsgo-shim.d.ts +112 -0
- package/tsgo-shim.js +2 -0
- package/typecheck-bus.d.ts +36 -5
- package/typecheck-bus.js +4 -4
- package/typecheck-memory.d.ts +187 -0
- package/typecheck-memory.js +1 -0
- package/typecheck-queue.d.ts +41 -3
- package/typecheck-queue.js +1 -1
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
"use strict";var Ce=Object.defineProperty;var T=(r,t)=>Ce(r,"name",{value:t,configurable:!0});var Ne=Object.defineProperty,s=T((r,t)=>Ne(r,"name",{value:t,configurable:!0}),"s");Object.defineProperty(exports,"__esModule",{value:!0}),exports.GATEWAY_H2_IDLE_SESSION_MS_DEFAULT=exports.GATEWAY_MAX_H2_STREAMS_DEFAULT=exports.GATEWAY_MAX_H2_SESSIONS_DEFAULT=exports.GATEWAY_MAX_CONNECTIONS_DEFAULT=exports.BENIGN_SOCKET_ERRNOS=void 0,exports.buildEdgeVerifierPool=buildEdgeVerifierPool,exports.edgeKeyWait=edgeKeyWait,exports.withBuiltinHooks=withBuiltinHooks,exports.classifyClientError=classifyClientError,exports.createClientErrorLogGate=createClientErrorLogGate,exports.retirePreviousWorkspace=retirePreviousWorkspace,exports.resolveMaxConnections=resolveMaxConnections,exports.h2BudgetFromEnv=h2BudgetFromEnv,exports.createH2Governor=createH2Governor,exports.startGateway=startGateway;const tslib_1=require("tslib"),http=tslib_1.__importStar(require("node:http")),path=tslib_1.__importStar(require("node:path")),discovery_1=require("./discovery"),scope_1=require("./scope"),route_registry_1=require("./route-registry"),act_1=require("./act"),control_1=require("./control"),workspace_middleware_1=require("./workspace-middleware"),workspace_registry_1=require("./workspace-registry"),service_keys_1=require("./service-keys"),source_poller_1=require("./source-poller"),client_ip_1=require("ringwall/client-ip"),client_ip_env_1=require("./client-ip-env"),workspace_log_1=require("./workspace-log"),own_log_1=require("./own-log"),observability_1=require("./observability"),lifecycle_1=require("./lifecycle"),process_names_1=require("./process-names"),project_graph_store_1=require("./project-graph-store"),guest_graph_1=require("./guest-graph"),serve_launch_1=require("./serve-launch"),process_name_1=require("../../../process-name"),protocol_1=require("../../../shared-build/protocol"),lens_children_1=require("./lens-children"),proxy_1=require("./proxy"),auth_1=require("./auth"),hooks_1=require("./hooks"),handler_1=require("./handler"),upgrade_1=require("./upgrade"),jwks_verify_1=require("ringwall/jwks-verify"),gateway_errors_1=require("ringwall/gateway-errors"),workspace_auth_1=require("ringwall/workspace-auth"),internal_fetch_1=require("./internal-fetch"),manifest_1=require("ringwall/manifest"),edge_1=require("./edge"),warm_start_1=require("./warm-start"),on_demand_1=require("./on-demand"),parked_dashboards_1=require("./parked-dashboards"),types_1=require("./types");function insecureLocalFetch(r,t){return new Promise((d,i)=>{const n=(r.startsWith("https:")?require("node:https"):require("node:http")).request(r,{method:"GET",headers:t?.headers,rejectUnauthorized:!1},S=>{const f=[];S.on("data",y=>f.push(y)),S.on("error",i),S.on("end",()=>{const y=S.statusCode??0,A=Buffer.concat(f).toString("utf8");d({ok:y>=200&&y<300,status:y,json:s(async()=>JSON.parse(A),"json")})})});n.on("error",i),t?.signal?.addEventListener("abort",()=>n.destroy(new Error(`JWKS ${r} \u2192 aborted`)),{once:!0}),n.end()})}T(insecureLocalFetch,"insecureLocalFetch"),s(insecureLocalFetch,"insecureLocalFetch");function buildEdgeVerifierPool(r,t={}){const d=process.env.LENSMCP_GW_JWKS_URL,i=process.env.LENSMCP_GW_JWT_ISS,n=new Map;let S,f=!1;const y=s((a,u)=>{console.log(`[gateway] edge JWT: verifying via JWKS ${a}${u}`);const _=(0,jwks_verify_1.createJwksVerifier)({jwksUrl:a,...i?{issuer:i}:{},fetchImpl:t.fetchImpl??insecureLocalFetch});let E=!1;return _.warm({...t.warm,onError:s((k,x,L)=>{E=!0,x===1&&L!==void 0&&console.warn(`[gateway] edge JWKS ${a} not loaded yet (${k.message}) \u2014 retrying in the background`),L===void 0&&console.warn(`[gateway] edge JWKS ${a} still not loaded after ${x} attempts (${k.message}) \u2014 the first token that needs it fetches it`)},"onError")}).then(k=>{k&&E&&console.log(`[gateway] edge JWKS ${a} loaded`)}),_},"make"),A=s(a=>{let u=n.get(a);return u||(u=y(`https://auth.${a}/jwks.json`,` (auto-derived for apex ${a})`),n.set(a,u)),u},"forApex");return{for(a){if(d)return S??=y(d,"");const u=a.split(":")[0].toLowerCase();let _;for(const E of idpApexes(r()))(u===E||u.endsWith(`.${E}`))&&(!_||E.length>_.length)&&(_=E);return _?A(_):void 0},warm(){if(!f){if(d){S??=y(d,"");return}for(const a of idpApexes(r()))A(a)}},stop(){f=!0,S?.stop();for(const a of n.values())a.stop()}}}T(buildEdgeVerifierPool,"buildEdgeVerifierPool"),s(buildEdgeVerifierPool,"buildEdgeVerifierPool");function idpApexes(r){const t=new Set;for(const d of r){const i=d.host;typeof i!="string"||!/^auth\./.test(i)||i.startsWith("internal.")||t.add(i.slice(5))}return t}T(idpApexes,"idpApexes"),s(idpApexes,"idpApexes");function edgeKeyWait(r){return async t=>{const d=t.route;if(!d?.auth||d.internal)return;const{req:i}=t,n=Array.isArray(i.headers.authorization)?i.headers.authorization[0]:i.headers.authorization,S=String(n??""),f=(0,workspace_auth_1.requestToken)(i)??(S.startsWith("Bearer ")?S.slice(7):void 0);if(!f)return;const y=i.url??"/";if((0,manifest_1.authRuleFor)(d.auth,(0,edge_1.canonicalPath)(y)??y.split("?")[0],(i.method??"GET").toUpperCase()).mode!=="jwt")return;const A=String(i.headers.host??"").split(":")[0].toLowerCase();await r.for(A)?.awaitKey(f)}}T(edgeKeyWait,"edgeKeyWait"),s(edgeKeyWait,"edgeKeyWait");function withBuiltinHooks(r,t){return{...r,beforeAuth:[...r.beforeAuth??[],...t.preAuth?[t.preAuth]:[],t.keyWait],afterAuth:[t.middleware,...r.afterAuth??[]],beforeForward:[...t.beforeForward?[t.beforeForward]:[],...r.beforeForward??[]]}}T(withBuiltinHooks,"withBuiltinHooks"),s(withBuiltinHooks,"withBuiltinHooks"),exports.BENIGN_SOCKET_ERRNOS=new Set(["ECONNRESET","EPIPE","ETIMEDOUT","ECONNABORTED","ECANCELED"]);function classifyClientError(r,t){return r&&exports.BENIGN_SOCKET_ERRNOS.has(r)?{status:null,report:!1,cause:"client-abort"}:r==="HPE_INVALID_EOF_STATE"?{status:null,report:!1,cause:"truncated-at-eof"}:r==="ERR_HTTP_REQUEST_TIMEOUT"?{status:408,report:!0,cause:"request-timeout"}:r==="HPE_HEADER_OVERFLOW"?{status:431,report:!0,cause:"header-overflow"}:r?.startsWith("HPE_")?{status:400,report:!0,cause:"parse-error"}:{status:400,report:!0,cause:r??t??"unknown"}}T(classifyClientError,"classifyClientError"),s(classifyClientError,"classifyClientError");const CLIENT_ERROR_REASON={400:"Bad Request",408:"Request Timeout",431:"Request Header Fields Too Large"};function createClientErrorLogGate(r=1e4){const t=new Map;return d=>{const i=Date.now(),n=t.get(d)??0;return i-n<r?!1:(t.set(d,i),!0)}}T(createClientErrorLogGate,"createClientErrorLogGate"),s(createClientErrorLogGate,"createClientErrorLogGate");function guardInboundSocket(r){r.on("error",t=>{exports.BENIGN_SOCKET_ERRNOS.has(t.code??"")||console.warn(`[gateway] inbound socket error (${t.code??t.message}) \u2014 dropping this connection only`),r.destroy()})}T(guardInboundSocket,"guardInboundSocket"),s(guardInboundSocket,"guardInboundSocket");function retirePreviousWorkspace(r,t,d){const i=r.get(t);if(!i)return!1;r.delete(t),d==="re-registered"&&console.log(`[gateway] workspace '${t}' re-registered \u2014 retiring the children of its previous registration first.`);try{i()}catch(n){console.warn(`[gateway] could not fully retire the previous registration of '${t}' (${d}): ${n.message}`)}return!0}T(retirePreviousWorkspace,"retirePreviousWorkspace"),s(retirePreviousWorkspace,"retirePreviousWorkspace"),exports.GATEWAY_MAX_CONNECTIONS_DEFAULT=512,exports.GATEWAY_MAX_H2_SESSIONS_DEFAULT=64,exports.GATEWAY_MAX_H2_STREAMS_DEFAULT=4096,exports.GATEWAY_H2_IDLE_SESSION_MS_DEFAULT=3e5;function parseBudget(r,t){if(r===void 0||r.trim()==="")return t;const d=Number(r);return!Number.isFinite(d)||d<0?t:Math.floor(d)}T(parseBudget,"parseBudget"),s(parseBudget,"parseBudget");function resolveMaxConnections(r){return parseBudget(r,exports.GATEWAY_MAX_CONNECTIONS_DEFAULT)}T(resolveMaxConnections,"resolveMaxConnections"),s(resolveMaxConnections,"resolveMaxConnections");function h2BudgetFromEnv(r=process.env){return{maxSessions:parseBudget(r.LENSMCP_MAX_H2_SESSIONS,exports.GATEWAY_MAX_H2_SESSIONS_DEFAULT),maxStreams:parseBudget(r.LENSMCP_MAX_H2_STREAMS,exports.GATEWAY_MAX_H2_STREAMS_DEFAULT),idleSessionMs:parseBudget(r.LENSMCP_H2_IDLE_MS,exports.GATEWAY_H2_IDLE_SESSION_MS_DEFAULT)}}T(h2BudgetFromEnv,"h2BudgetFromEnv"),s(h2BudgetFromEnv,"h2BudgetFromEnv");function createH2Governor(r,t){const{NGHTTP2_ENHANCE_YOUR_CALM:d,NGHTTP2_REFUSED_STREAM:i}=require("node:http2").constants,n=new Map;let S=0;const f=s(a=>{a.idle&&(clearTimeout(a.idle),a.idle=void 0)},"disarm"),y=s((a,u)=>{f(u),!(r.idleSessionMs<=0||u.open>0)&&(u.idle=setTimeout(()=>{a.destroyed||a.closed||(t("session-reclaimed",{idleMs:r.idleSessionMs,sessions:n.size}),n.delete(a),a.close())},r.idleSessionMs),u.idle.unref?.())},"arm"),A=s(()=>{for(const[a,u]of n)if(!(u.open>0||a.destroyed))return f(u),n.delete(a),t("session-reclaimed",{reason:"cap",sessions:n.size+1,maxSessions:r.maxSessions}),a.close(),!0;return!1},"reclaimOldestIdle");return{admitSession(a){if(r.maxSessions>0&&n.size>=r.maxSessions&&!A()){t("session-refused",{sessions:n.size,maxSessions:r.maxSessions,streams:S});try{a.goaway(d)}catch{}try{a.close()}catch{}return!1}const u={open:0};return n.set(a,u),y(a,u),a.once("close",()=>{f(u),n.delete(a)}),!0},admitStream(a,u){const _=n.get(a);if(!_)return!0;if(r.maxStreams>0&&S>=r.maxStreams){t("stream-refused",{streams:S,maxStreams:r.maxStreams,sessions:n.size});try{u.close(i)}catch{}return!1}return S+=1,_.open+=1,f(_),u.once("close",()=>{S=Math.max(0,S-1),_.open=Math.max(0,_.open-1),_.open===0&&n.has(a)&&y(a,_)}),!0},dispose(){for(const a of n.values())f(a);n.clear()}}}T(createH2Governor,"createH2Governor"),s(createH2Governor,"createH2Governor");async function startGateway(r,t){const d=r.https!==!1,i=r.ports?.length?r.ports:[443],n=r.scanTtlMs??1500,S=r.startupTimeoutMs??12e4,f=r.sweepMs??1e4,y=r.trafficFlushMs??5e3;let A=!1;const a=process.env.LENSMCP_EVENT_FILE??path.join(t.root,".lensmcp","events.jsonl"),u=(0,own_log_1.startOwnLogRotation)(t.root),_=(0,scope_1.readLensScope)(t.root),E=_.key,k=_.sockNs!==E?_.sockNs:void 0,x=t.projectsConfigurations?.projects??{},L=(0,discovery_1.projectSourceRoots)(t.root,x,t.projectDependencies),{routes:D,services:C,instance:oe}=(0,discovery_1.discoverRoutes)(t.root,x,void 0,E,L,k,_.instance);if(D.length===0)throw new Error("[gateway] no project declares a `cluster` field \u2014 nothing to route.");const U=new route_registry_1.RouteRegistry;U.register({wsKey:E,...k?{sockNs:k}:{},root:t.root,routes:D,services:C,...oe?{instance:oe}:{}});const P=[];let ae=s(()=>{},"refreshCert"),B=s(()=>{},"warmEdgeVerifiers");const ne=s(()=>{(0,route_registry_1.rebuildRoutesInPlace)(P,U),ae(),B()},"rebuildRoutes");ne();const{serviceKeys:we,keyToProject:ye,keyToWorkspace:Ee}=(0,service_keys_1.loadServiceKeys)(t.root,C,E),me=(0,client_ip_1.createClientIpResolver)({...(0,client_ip_env_1.clientIpOptionsFromEnv)(),...r.trustProxyHops!==void 0?{trustProxyHops:r.trustProxyHops}:{},...r.clientIpHeader?{clientIpHeader:r.clientIpHeader}:{},...r.clientIpTrustedProxies?{clientIpTrustedProxies:r.clientIpTrustedProxies}:{}});t.projectGraphStore?.setFallback?.(()=>(0,guest_graph_1.ownGraphInFreshProcess)(t.root));const p={root:t.root,wsKey:E,...k?{sockNs:k}:{},eventFile:a,routes:P,registry:U,rebuildRoutes:ne,services:C,serviceKeys:we,keyToProject:ye,keyToWorkspace:Ee,clientIp:me,bodyStallMs:r.bodyStallMs??types_1.BODY_STALL_MS,scanTtlMs:n,startupTimeoutMs:S,sweepMs:f,trafficFlushMs:y,https:d,projectRoots:Object.fromEntries(Object.entries(t.projectsConfigurations?.projects??{}).map(([e,o])=>[e,path.resolve(t.root,o.root)])),projectSourceRoots:L,...t.projectGraphStore?{graphStores:(0,project_graph_store_1.createProjectGraphStores)(t.projectGraphStore)}:{},...r.sharedCompiler!==void 0?{sharedCompiler:r.sharedCompiler}:{},stopped:s(()=>A,"stopped")};(0,process_name_1.prelinkProcessNames)((0,process_names_1.gatewayProcessNames)(C,{runner:(0,serve_launch_1.serveRunnerEnabled)()&&!!t.projectGraphStore,sharedBuild:(0,protocol_1.sharedCompilerEnabled)(process.env,r.sharedCompiler),label:E||path.basename(t.root),lens:{key:E,dashboard:r.dashboard!==!1,mcp:r.mcp!==!1&&D.some(e=>!!e.lens)}}));const m=(0,observability_1.createObservability)(a,{trafficFlushMs:y}),fe=createClientErrorLogGate(),O=h2BudgetFromEnv(),Te=createClientErrorLogGate(3e4),Y=createH2Governor(O,(e,o)=>{Te(e)&&console.warn(`[gateway] h2 aggregate budget: ${e} (${JSON.stringify(o)}). These are the FRONT DOOR's ceilings, not an upstream's \u2014 raise/disable with LENSMCP_MAX_H2_SESSIONS / LENSMCP_MAX_H2_STREAMS / LENSMCP_H2_IDLE_MS / LENSMCP_MAX_CONNECTIONS (0 = unbounded).`),m.emit(e==="session-reclaimed"?"info":"warning",`h2 aggregate budget: ${e}`,`gateway-h2-budget:${e}`,{kind:"h2-aggregate-budget",event:e,project:"gateway",...o})}),v=(0,lifecycle_1.createServiceLayer)(p,m),I=(0,lens_children_1.createLensChildren)(p,m,r),X=(0,on_demand_1.createOnDemandRecordsReader)(),$=(0,parked_dashboards_1.createParkedDashboards)({registry:s(()=>p.registry,"registry"),records:X,host:s(e=>I.hostParkedDashboard(e),"host"),rebuild:s(()=>p.rebuildRoutes(),"rebuild"),stopped:s(()=>A,"stopped")});p.parkedDashboards=$;const q=s(()=>{$.sync().catch(e=>console.warn("[gateway] parked worktree dashboards:",e.message))},"syncParked"),J=new Map;let ie=s(()=>{},"ownBooted");const Ae=new Promise(e=>ie=e),H=(0,warm_start_1.createWorktreeWarmer)({rt:p,obs:m,ready:Ae,ensureUp:s(e=>v.ensureUp(e),"ensureUp")});(0,warm_start_1.mainAlwaysUp)()&&H.warmOwn(C);let z;if(r.middleware){const e=require(path.resolve(t.root,r.middleware));z=(0,workspace_auth_1.validateMiddleware)(e.default??e)}const V=(0,workspace_middleware_1.createWorkspaceMiddleware)({ownerKey:E,...z?{owner:z}:{},policy:(0,workspace_middleware_1.guestMiddlewarePolicy)()});let ce;const le=(0,internal_fetch_1.createInternalFetchers)({registry:p.registry,keyToProject:p.keyToProject,keyToWorkspace:p.keyToWorkspace,door:s(()=>(ce??=(0,internal_fetch_1.openInternalDoor)(Z)).then(e=>e.socketPath),"door")}),W=process.env.LENSMCP_GW_ACT==="0"?void 0:(0,act_1.createActStore)({dir:path.join(path.dirname((0,control_1.controlSocketPath)()),"identities")});let b;try{b=(0,control_1.startControlServer)({rt:p,killService:s((e,o)=>v.killSpawned(e,o),"killService"),restartService:s((e,o)=>v.restartService(e,o),"restartService"),ensureService:s(e=>v.ensureUp(e),"ensureService"),startTurn:s(e=>H.take(e),"startTurn"),emitService:s((e,o,g,c)=>v.emitSvc(e,o,g,`cluster-service:${e.project}`,c),"emitService"),emitWorkspace:s((e,o,g,c,h)=>m.emit(o,g,c,{wsKey:e.wsKey,...h},void 0,e.wsKey===E?void 0:path.join(e.root,".lensmcp","events.jsonl")),"emitWorkspace"),...W?{act:W}:{},onRegister:s(async e=>{retirePreviousWorkspace(J,e.wsKey,"re-registered"),await $.drop(e.wsKey),V.set(e.wsKey,e.root,e.middleware);const o=await I.hostWorkspaceDashboard(e),g=await I.hostWorkspaceApps(e);J.set(e.wsKey,()=>{try{o?.()}finally{g()}}),H.onRegister(e)},"onRegister"),onUnregister:s(e=>{H.onUnregister(e.wsKey),retirePreviousWorkspace(J,e.wsKey,"unregistered"),V.drop(e.wsKey),le.forget(e.wsKey),v.stopBuildHost(e.root),q()},"onUnregister")})}catch(e){console.warn("[gateway] control plane failed to start (multi-workspace register disabled):",e.message)}const j=(0,proxy_1.createProxy)(p,m,v),G=buildEdgeVerifierPool(()=>p.routes),de=(0,auth_1.createEdgeAuth)(p,m,G,W),Q=s(e=>async o=>{const g=o.route;if(!g||g.internal||g.project===observability_1.LENS_DASHBOARD_PROJECT)return;const c=g.wsKey,h=V.for(c);if(h)try{const l=c?p.registry.get(c):void 0,w=c&&h.internalFetch===!0?le.for(c):void 0;await(0,workspace_auth_1.dispatchMiddleware)(h,e,o.req,{...c?{wsKey:c}:{},...l?{root:l.root}:{},env:l?.instance?.env??{},...o.claims?{claims:o.claims}:{},...w?{fetchInternal:w}:{}})}catch(l){console.warn(`[gateway] ${new Date().toISOString()} middleware refused a request at ${e} traceId=${(0,gateway_errors_1.ensureRequestId)(o.req)}: ${l?.message??String(l)}`),m.traceStep(o.trace,"auth",{mode:"middleware",ok:!1,reason:`refused at ${e}`}),m.finishTrace(o.trace,g.project,401),o.sendError(401,"unauthorized","Gateway middleware rejected the request")}},"middlewareStep"),ue=Q("preAuth"),pe=Q("beforeForward"),he=(0,hooks_1.createHooks)(withBuiltinHooks(r.hooks??{},{keyWait:edgeKeyWait(G),middleware:Q("afterAuth"),preAuth:ue,beforeForward:pe})),Z=(0,handler_1.createHandler)({rt:p,obs:m,auth:de,proxy:j,hooks:he,parkedHosts:(0,on_demand_1.createParkedHostLookup)({registry:s(()=>p.registry,"registry"),records:X})}),ge=(0,upgrade_1.createUpgrade)({rt:p,auth:de,proxy:j,hooks:he,obs:m,middleware:{preAuth:ue,beforeForward:pe}}),ve=m.startEdgeFlusher(),ke=v.startSweeper(()=>{b?.dropGone(),b?.parkIdle(),q()}),_e=(0,source_poller_1.createSourcePoller)({services:s(()=>p.registry.allServices(),"services"),serviceKey:s(e=>p.serviceKeys[(0,service_keys_1.serviceKeyId)(e.wsKey,e.project)],"serviceKey"),emit:s((e,o,g,c,h)=>m.emit(o,g,c,{wsKey:e.wsKey,...h},void 0,e.wsKey===p.wsKey?void 0:path.join(e.root,".lensmcp","events.jsonl")),"emit"),scanTtlMs:n,stopped:s(()=>A,"stopped")});(0,source_poller_1.sourcesEnabled)()&&_e.start(),await I.bootSingletonsAndApps();const Se=C.filter(e=>e.decl.eager).map(e=>v.ensureUp(e));Promise.allSettled(Se).then(()=>setTimeout(ie,Se.length?2e4:0).unref());let R,ee,K;if(d){const e=require("../../../basic-ssl"),o=(0,service_keys_1.gatewayCacheDir)(t.root);K=s(()=>e.getCertificateSync(o,"gateway",[...new Set([...p.routes.map(g=>g.host).filter(g=>!!g),...(0,parked_dashboards_1.parkedHosts)(p.registry,X())])]),"mintCert"),R=K(),ee=e.caCertPath()}const re=[],F=[],te=r.maxConnections??resolveMaxConnections(process.env.LENSMCP_MAX_CONNECTIONS);for(const e of i){const o=R?require("node:http2").createSecureServer({key:R,cert:R,allowHTTP1:!0,maxSessionMemory:512,settings:{maxConcurrentStreams:512},peerMaxConcurrentStreams:512,streamResetBurst:r.h2ResetBurst??types_1.GATEWAY_H2_RESET_BURST,streamResetRate:r.h2ResetRate??types_1.GATEWAY_H2_RESET_RATE},(c,h)=>Z(c,h)):http.createServer(Z);o.on("upgrade",ge),o.on("error",c=>console.error(`[gateway] port ${e}: ${c.code}`)),o.on("connection",guardInboundSocket),o.on("secureConnection",guardInboundSocket),o.on("tlsClientError",(c,h)=>h.destroy()),o.on("clientError",(c,h)=>{const l=c,w=classifyClientError(l.code,l.message);if(w.report&&fe(w.cause)){const N=h.remoteAddress??"unknown",M=w.status===null?"dropped":String(w.status);console.warn(`[gateway] inbound H1 clientError from ${N}: ${w.cause} (${l.code??l.message}${l.bytesParsed!==void 0?`, bytesParsed=${l.bytesParsed}`:""}) \u2192 ${M}. This status is the GATEWAY's, not the upstream service's.`),m.emit("warning",`inbound clientError: ${w.cause} \u2192 ${M}`,`gateway-client-error:${w.cause}`,{kind:"gateway-client-error",cause:w.cause,code:l.code??null,status:w.status,peer:N,bytesParsed:l.bytesParsed??null})}w.status!==null&&h.writable&&h.end(`HTTP/1.1 ${w.status} ${CLIENT_ERROR_REASON[w.status]}\r
|
|
1
|
+
"use strict";var xe=Object.defineProperty;var T=(r,t)=>xe(r,"name",{value:t,configurable:!0});var be=Object.defineProperty,s=T((r,t)=>be(r,"name",{value:t,configurable:!0}),"s");Object.defineProperty(exports,"__esModule",{value:!0}),exports.GATEWAY_H2_IDLE_SESSION_MS_DEFAULT=exports.GATEWAY_MAX_H2_STREAMS_DEFAULT=exports.GATEWAY_MAX_H2_SESSIONS_DEFAULT=exports.GATEWAY_MAX_CONNECTIONS_DEFAULT=exports.BENIGN_SOCKET_ERRNOS=void 0,exports.buildEdgeVerifierPool=buildEdgeVerifierPool,exports.edgeKeyWait=edgeKeyWait,exports.withBuiltinHooks=withBuiltinHooks,exports.classifyClientError=classifyClientError,exports.createClientErrorLogGate=createClientErrorLogGate,exports.retirePreviousWorkspace=retirePreviousWorkspace,exports.resolveMaxConnections=resolveMaxConnections,exports.h2BudgetFromEnv=h2BudgetFromEnv,exports.createH2Governor=createH2Governor,exports.startGateway=startGateway;const tslib_1=require("tslib"),http=tslib_1.__importStar(require("node:http")),path=tslib_1.__importStar(require("node:path")),discovery_1=require("./discovery"),scope_1=require("./scope"),route_registry_1=require("./route-registry"),act_1=require("./act"),control_1=require("./control"),docker_sweep_1=require("./docker-sweep"),peer_hub_1=require("./peer-hub"),workspace_middleware_1=require("./workspace-middleware"),workspace_registry_1=require("./workspace-registry"),service_keys_1=require("./service-keys"),source_poller_1=require("./source-poller"),client_ip_1=require("ringwall/client-ip"),client_ip_env_1=require("./client-ip-env"),workspace_log_1=require("./workspace-log"),own_log_1=require("./own-log"),observability_1=require("./observability"),lifecycle_1=require("./lifecycle"),process_names_1=require("./process-names"),project_graph_store_1=require("./project-graph-store"),guest_graph_1=require("./guest-graph"),serve_launch_1=require("./serve-launch"),process_name_1=require("../../../process-name"),protocol_1=require("../../../shared-build/protocol"),lens_children_1=require("./lens-children"),proxy_1=require("./proxy"),auth_1=require("./auth"),hooks_1=require("./hooks"),handler_1=require("./handler"),upgrade_1=require("./upgrade"),jwks_verify_1=require("ringwall/jwks-verify"),gateway_errors_1=require("ringwall/gateway-errors"),workspace_auth_1=require("ringwall/workspace-auth"),internal_fetch_1=require("./internal-fetch"),manifest_1=require("ringwall/manifest"),edge_1=require("./edge"),warm_start_1=require("./warm-start"),update_wiring_1=require("./update-wiring"),service_updates_1=require("./service-updates"),on_demand_1=require("./on-demand"),parked_dashboards_1=require("./parked-dashboards"),types_1=require("./types");function insecureLocalFetch(r,t){return new Promise((g,d)=>{const n=(r.startsWith("https:")?require("node:https"):require("node:http")).request(r,{method:"GET",headers:t?.headers,rejectUnauthorized:!1},_=>{const f=[];_.on("data",m=>f.push(m)),_.on("error",d),_.on("end",()=>{const m=_.statusCode??0,A=Buffer.concat(f).toString("utf8");g({ok:m>=200&&m<300,status:m,json:s(async()=>JSON.parse(A),"json")})})});n.on("error",d),t?.signal?.addEventListener("abort",()=>n.destroy(new Error(`JWKS ${r} \u2192 aborted`)),{once:!0}),n.end()})}T(insecureLocalFetch,"insecureLocalFetch"),s(insecureLocalFetch,"insecureLocalFetch");function buildEdgeVerifierPool(r,t={}){const g=process.env.LENSMCP_GW_JWKS_URL,d=process.env.LENSMCP_GW_JWT_ISS,n=new Map;let _,f=!1;const m=s((a,h)=>{console.log(`[gateway] edge JWT: verifying via JWKS ${a}${h}`);const w=(0,jwks_verify_1.createJwksVerifier)({jwksUrl:a,...d?{issuer:d}:{},fetchImpl:t.fetchImpl??insecureLocalFetch});let y=!1;return w.warm({...t.warm,onError:s((k,O,L)=>{y=!0,O===1&&L!==void 0&&console.warn(`[gateway] edge JWKS ${a} not loaded yet (${k.message}) \u2014 retrying in the background`),L===void 0&&console.warn(`[gateway] edge JWKS ${a} still not loaded after ${O} attempts (${k.message}) \u2014 the first token that needs it fetches it`)},"onError")}).then(k=>{k&&y&&console.log(`[gateway] edge JWKS ${a} loaded`)}),w},"make"),A=s(a=>{let h=n.get(a);return h||(h=m(`https://auth.${a}/jwks.json`,` (auto-derived for apex ${a})`),n.set(a,h)),h},"forApex");return{for(a){if(g)return _??=m(g,"");const h=a.split(":")[0].toLowerCase();let w;for(const y of idpApexes(r()))(h===y||h.endsWith(`.${y}`))&&(!w||y.length>w.length)&&(w=y);return w?A(w):void 0},warm(){if(!f){if(g){_??=m(g,"");return}for(const a of idpApexes(r()))A(a)}},stop(){f=!0,_?.stop();for(const a of n.values())a.stop()}}}T(buildEdgeVerifierPool,"buildEdgeVerifierPool"),s(buildEdgeVerifierPool,"buildEdgeVerifierPool");function idpApexes(r){const t=new Set;for(const g of r){const d=g.host;typeof d!="string"||!/^auth\./.test(d)||d.startsWith("internal.")||t.add(d.slice(5))}return t}T(idpApexes,"idpApexes"),s(idpApexes,"idpApexes");function edgeKeyWait(r){return async t=>{const g=t.route;if(!g?.auth||g.internal)return;const{req:d}=t,n=Array.isArray(d.headers.authorization)?d.headers.authorization[0]:d.headers.authorization,_=String(n??""),f=(0,workspace_auth_1.requestToken)(d)??(_.startsWith("Bearer ")?_.slice(7):void 0);if(!f)return;const m=d.url??"/";if((0,manifest_1.authRuleFor)(g.auth,(0,edge_1.canonicalPath)(m)??m.split("?")[0],(d.method??"GET").toUpperCase()).mode!=="jwt")return;const A=String(d.headers.host??"").split(":")[0].toLowerCase();await r.for(A)?.awaitKey(f)}}T(edgeKeyWait,"edgeKeyWait"),s(edgeKeyWait,"edgeKeyWait");function withBuiltinHooks(r,t){return{...r,beforeAuth:[...r.beforeAuth??[],...t.preAuth?[t.preAuth]:[],t.keyWait],afterAuth:[t.middleware,...r.afterAuth??[]],beforeForward:[...t.beforeForward?[t.beforeForward]:[],...r.beforeForward??[]]}}T(withBuiltinHooks,"withBuiltinHooks"),s(withBuiltinHooks,"withBuiltinHooks"),exports.BENIGN_SOCKET_ERRNOS=new Set(["ECONNRESET","EPIPE","ETIMEDOUT","ECONNABORTED","ECANCELED"]);function classifyClientError(r,t){return r&&exports.BENIGN_SOCKET_ERRNOS.has(r)?{status:null,report:!1,cause:"client-abort"}:r==="HPE_INVALID_EOF_STATE"?{status:null,report:!1,cause:"truncated-at-eof"}:r==="ERR_HTTP_REQUEST_TIMEOUT"?{status:408,report:!0,cause:"request-timeout"}:r==="HPE_HEADER_OVERFLOW"?{status:431,report:!0,cause:"header-overflow"}:r?.startsWith("HPE_")?{status:400,report:!0,cause:"parse-error"}:{status:400,report:!0,cause:r??t??"unknown"}}T(classifyClientError,"classifyClientError"),s(classifyClientError,"classifyClientError");const CLIENT_ERROR_REASON={400:"Bad Request",408:"Request Timeout",431:"Request Header Fields Too Large"};function createClientErrorLogGate(r=1e4){const t=new Map;return g=>{const d=Date.now(),n=t.get(g)??0;return d-n<r?!1:(t.set(g,d),!0)}}T(createClientErrorLogGate,"createClientErrorLogGate"),s(createClientErrorLogGate,"createClientErrorLogGate");function guardInboundSocket(r){r.on("error",t=>{exports.BENIGN_SOCKET_ERRNOS.has(t.code??"")||console.warn(`[gateway] inbound socket error (${t.code??t.message}) \u2014 dropping this connection only`),r.destroy()})}T(guardInboundSocket,"guardInboundSocket"),s(guardInboundSocket,"guardInboundSocket");function retirePreviousWorkspace(r,t,g){const d=r.get(t);if(!d)return!1;r.delete(t),g==="re-registered"&&console.log(`[gateway] workspace '${t}' re-registered \u2014 retiring the children of its previous registration first.`);try{d()}catch(n){console.warn(`[gateway] could not fully retire the previous registration of '${t}' (${g}): ${n.message}`)}return!0}T(retirePreviousWorkspace,"retirePreviousWorkspace"),s(retirePreviousWorkspace,"retirePreviousWorkspace"),exports.GATEWAY_MAX_CONNECTIONS_DEFAULT=512,exports.GATEWAY_MAX_H2_SESSIONS_DEFAULT=64,exports.GATEWAY_MAX_H2_STREAMS_DEFAULT=4096,exports.GATEWAY_H2_IDLE_SESSION_MS_DEFAULT=3e5;function parseBudget(r,t){if(r===void 0||r.trim()==="")return t;const g=Number(r);return!Number.isFinite(g)||g<0?t:Math.floor(g)}T(parseBudget,"parseBudget"),s(parseBudget,"parseBudget");function resolveMaxConnections(r){return parseBudget(r,exports.GATEWAY_MAX_CONNECTIONS_DEFAULT)}T(resolveMaxConnections,"resolveMaxConnections"),s(resolveMaxConnections,"resolveMaxConnections");function h2BudgetFromEnv(r=process.env){return{maxSessions:parseBudget(r.LENSMCP_MAX_H2_SESSIONS,exports.GATEWAY_MAX_H2_SESSIONS_DEFAULT),maxStreams:parseBudget(r.LENSMCP_MAX_H2_STREAMS,exports.GATEWAY_MAX_H2_STREAMS_DEFAULT),idleSessionMs:parseBudget(r.LENSMCP_H2_IDLE_MS,exports.GATEWAY_H2_IDLE_SESSION_MS_DEFAULT)}}T(h2BudgetFromEnv,"h2BudgetFromEnv"),s(h2BudgetFromEnv,"h2BudgetFromEnv");function createH2Governor(r,t){const{NGHTTP2_ENHANCE_YOUR_CALM:g,NGHTTP2_REFUSED_STREAM:d}=require("node:http2").constants,n=new Map;let _=0;const f=s(a=>{a.idle&&(clearTimeout(a.idle),a.idle=void 0)},"disarm"),m=s((a,h)=>{f(h),!(r.idleSessionMs<=0||h.open>0)&&(h.idle=setTimeout(()=>{a.destroyed||a.closed||(t("session-reclaimed",{idleMs:r.idleSessionMs,sessions:n.size}),n.delete(a),a.close())},r.idleSessionMs),h.idle.unref?.())},"arm"),A=s(()=>{for(const[a,h]of n)if(!(h.open>0||a.destroyed))return f(h),n.delete(a),t("session-reclaimed",{reason:"cap",sessions:n.size+1,maxSessions:r.maxSessions}),a.close(),!0;return!1},"reclaimOldestIdle");return{admitSession(a){if(r.maxSessions>0&&n.size>=r.maxSessions&&!A()){t("session-refused",{sessions:n.size,maxSessions:r.maxSessions,streams:_});try{a.goaway(g)}catch{}try{a.close()}catch{}return!1}const h={open:0};return n.set(a,h),m(a,h),a.once("close",()=>{f(h),n.delete(a)}),!0},admitStream(a,h){const w=n.get(a);if(!w)return!0;if(r.maxStreams>0&&_>=r.maxStreams){t("stream-refused",{streams:_,maxStreams:r.maxStreams,sessions:n.size});try{h.close(d)}catch{}return!1}return _+=1,w.open+=1,f(w),h.once("close",()=>{_=Math.max(0,_-1),w.open=Math.max(0,w.open-1),w.open===0&&n.has(a)&&m(a,w)}),!0},dispose(){for(const a of n.values())f(a);n.clear()}}}T(createH2Governor,"createH2Governor"),s(createH2Governor,"createH2Governor");async function startGateway(r,t){const g=r.https!==!1,d=r.ports?.length?r.ports:[443],n=r.scanTtlMs??1500,_=r.startupTimeoutMs??12e4,f=r.sweepMs??1e4,m=r.trafficFlushMs??5e3;let A=!1;const a=process.env.LENSMCP_EVENT_FILE??path.join(t.root,".lensmcp","events.jsonl"),h=(0,own_log_1.startOwnLogRotation)(t.root),w=(0,scope_1.readLensScope)(t.root),y=w.key,k=w.sockNs!==y?w.sockNs:void 0,O=t.projectsConfigurations?.projects??{},L=(0,discovery_1.projectSourceRoots)(t.root,O,t.projectDependencies),{routes:Y,services:M,instance:ne}=(0,discovery_1.discoverRoutes)(t.root,O,void 0,y,L,k,w.instance);if(Y.length===0)throw new Error("[gateway] no project declares a `cluster` field \u2014 nothing to route.");const X=new route_registry_1.RouteRegistry;X.register({wsKey:y,...k?{sockNs:k}:{},root:t.root,routes:Y,services:M,...ne?{instance:ne}:{}});const x=[];let ie=s(()=>{},"refreshCert"),J=s(()=>{},"warmEdgeVerifiers");const ce=s(()=>{(0,route_registry_1.rebuildRoutesInPlace)(x,X),ie(),J()},"rebuildRoutes");ce();const{serviceKeys:Ee,keyToProject:fe,keyToWorkspace:ve}=(0,service_keys_1.loadServiceKeys)(t.root,M,y),Te=(0,client_ip_1.createClientIpResolver)({...(0,client_ip_env_1.clientIpOptionsFromEnv)(),...r.trustProxyHops!==void 0?{trustProxyHops:r.trustProxyHops}:{},...r.clientIpHeader?{clientIpHeader:r.clientIpHeader}:{},...r.clientIpTrustedProxies?{clientIpTrustedProxies:r.clientIpTrustedProxies}:{}});t.projectGraphStore?.setFallback?.(()=>(0,guest_graph_1.ownGraphInFreshProcess)(t.root));const i={root:t.root,wsKey:y,...k?{sockNs:k}:{},eventFile:a,routes:x,registry:X,rebuildRoutes:ce,services:M,serviceKeys:Ee,keyToProject:fe,keyToWorkspace:ve,clientIp:Te,bodyStallMs:r.bodyStallMs??types_1.BODY_STALL_MS,scanTtlMs:n,startupTimeoutMs:_,sweepMs:f,trafficFlushMs:m,https:g,projectRoots:Object.fromEntries(Object.entries(t.projectsConfigurations?.projects??{}).map(([e,o])=>[e,path.resolve(t.root,o.root)])),projectSourceRoots:L,...t.projectGraphStore?{graphStores:(0,project_graph_store_1.createProjectGraphStores)(t.projectGraphStore)}:{},...r.sharedCompiler!==void 0?{sharedCompiler:r.sharedCompiler}:{},stopped:s(()=>A,"stopped")};(0,process_name_1.prelinkProcessNames)((0,process_names_1.gatewayProcessNames)(M,{runner:(0,serve_launch_1.serveRunnerEnabled)()&&!!t.projectGraphStore,sharedBuild:(0,protocol_1.sharedCompilerEnabled)(process.env,r.sharedCompiler),label:y||path.basename(t.root),lens:{key:y,dashboard:r.dashboard!==!1,mcp:r.mcp!==!1&&Y.some(e=>!!e.lens)}}));const E=(0,observability_1.createObservability)(a,{trafficFlushMs:m}),Ae=createClientErrorLogGate(),I=h2BudgetFromEnv(),ke=createClientErrorLogGate(3e4),z=createH2Governor(I,(e,o)=>{ke(e)&&console.warn(`[gateway] h2 aggregate budget: ${e} (${JSON.stringify(o)}). These are the FRONT DOOR's ceilings, not an upstream's \u2014 raise/disable with LENSMCP_MAX_H2_SESSIONS / LENSMCP_MAX_H2_STREAMS / LENSMCP_H2_IDLE_MS / LENSMCP_MAX_CONNECTIONS (0 = unbounded).`),E.emit(e==="session-reclaimed"?"info":"warning",`h2 aggregate budget: ${e}`,`gateway-h2-budget:${e}`,{kind:"h2-aggregate-budget",event:e,project:"gateway",...o})}),v=(0,lifecycle_1.createServiceLayer)(i,E),N=(0,lens_children_1.createLensChildren)(i,E,r),R=(0,update_wiring_1.createGatewayUpdates)({registry:i.registry,frontends:s(e=>N.updateFrontends.list(e),"frontends"),serviceOps:(0,service_updates_1.createServiceUpdateOps)({updates:s(()=>i.updates,"updates"),stop:s((e,o)=>{e.stoppingPid=e.proc?.pid,e.stoppingUntil=Date.now()+(e.proc?1600:0),v.killSpawned(e,o),e.state="down"},"stop"),start:s(e=>(e.manualStopped=!1,e.actionFailure=void 0,v.ensureUp(e)),"start"),shared:v.sharedUpdates}),frontendOps:N.updateFrontends.ops,emit:s((e,o,l)=>{const c=i.registry.get(e),u=typeof l.piece=="string"?l.piece:"";E.emit("info",`${o}: ${e}${u?`/${u}`:""}`,`cluster-${o}:${e}:${u}`,{kind:o,wsKey:e,...l},void 0,!c||e===y?void 0:path.join(c.root,".lensmcp","events.jsonl"))},"emit"),log:s(e=>console.log(e),"log")});i.updates=R;const de=s(e=>{for(const o of e.services)R.stateOf(e.wsKey,o.project)==="parked"&&(o.manualStopped=!0,R.startsHeld(e.wsKey,o.project),console.log(`[gateway] ${o.project}: parked (update mode off) \u2014 not started; its mode set to hmr or manual starts it`))},"parkAtStart");de({wsKey:y,services:M});const j=(0,on_demand_1.createOnDemandRecordsReader)(),W=(0,parked_dashboards_1.createParkedDashboards)({registry:s(()=>i.registry,"registry"),records:j,host:s(e=>N.hostParkedDashboard(e),"host"),rebuild:s(()=>i.rebuildRoutes(),"rebuild"),stopped:s(()=>A,"stopped")});i.parkedDashboards=W;const G=s(()=>{W.sync().catch(e=>console.warn("[gateway] parked worktree dashboards:",e.message))},"syncParked"),V=new Map;let le=s(()=>{},"ownBooted");const Me=new Promise(e=>le=e),K=(0,warm_start_1.createWorktreeWarmer)({rt:i,obs:E,ready:Me,ensureUp:s(e=>v.ensureUp(e),"ensureUp")});(0,warm_start_1.mainAlwaysUp)()&&K.warmOwn(M);let Q;if(r.middleware){const e=require(path.resolve(t.root,r.middleware));Q=(0,workspace_auth_1.validateMiddleware)(e.default??e)}const Z=(0,workspace_middleware_1.createWorkspaceMiddleware)({ownerKey:y,...Q?{owner:Q}:{},policy:(0,workspace_middleware_1.guestMiddlewarePolicy)()});let ue;const pe=(0,internal_fetch_1.createInternalFetchers)({registry:i.registry,keyToProject:i.keyToProject,keyToWorkspace:i.keyToWorkspace,door:s(()=>(ue??=(0,internal_fetch_1.openInternalDoor)(re)).then(e=>e.socketPath),"door")}),F=process.env.LENSMCP_GW_ACT==="0"?void 0:(0,act_1.createActStore)({dir:path.join(path.dirname((0,control_1.controlSocketPath)()),"identities")}),q=[];let C;try{C=(0,control_1.startControlServer)({rt:i,ownPorts:s(()=>q,"ownPorts"),parkedHosts:(0,on_demand_1.createParkedHostLookup)({registry:s(()=>i.registry,"registry"),records:j}),killService:s((e,o)=>v.killSpawned(e,o),"killService"),restartService:s((e,o)=>v.restartService(e,o),"restartService"),ensureService:s(e=>v.ensureUp(e),"ensureService"),updates:R,startTurn:s(e=>K.take(e),"startTurn"),emitService:s((e,o,l,c)=>v.emitSvc(e,o,l,`cluster-service:${e.project}`,c),"emitService"),emitWorkspace:s((e,o,l,c,u)=>E.emit(o,l,c,{wsKey:e.wsKey,...u},void 0,e.wsKey===y?void 0:path.join(e.root,".lensmcp","events.jsonl")),"emitWorkspace"),...F?{act:F}:{},onRegister:s(async e=>{retirePreviousWorkspace(V,e.wsKey,"re-registered"),await W.drop(e.wsKey),Z.set(e.wsKey,e.root,e.middleware),R.forget(e.wsKey),de(e);const o=await N.hostWorkspaceDashboard(e),l=await N.hostWorkspaceApps(e);V.set(e.wsKey,()=>{try{o?.()}finally{l()}}),K.onRegister(e)},"onRegister"),onUnregister:s(e=>{K.onUnregister(e.wsKey),R.forget(e.wsKey),retirePreviousWorkspace(V,e.wsKey,"unregistered"),Z.drop(e.wsKey),pe.forget(e.wsKey),v.stopBuildHost(e.root),G()},"onUnregister")})}catch(e){console.warn("[gateway] control plane failed to start (multi-workspace register disabled):",e.message)}const D=(0,proxy_1.createProxy)(i,E,v),U=buildEdgeVerifierPool(()=>i.routes),ge=(0,auth_1.createEdgeAuth)(i,E,U,F),ee=s(e=>async o=>{const l=o.route;if(!l||l.internal||l.run||l.project===observability_1.LENS_DASHBOARD_PROJECT)return;const c=l.wsKey,u=Z.for(c);if(u)try{const p=c?i.registry.get(c):void 0,S=c&&u.internalFetch===!0?pe.for(c):void 0;await(0,workspace_auth_1.dispatchMiddleware)(u,e,o.req,{...c?{wsKey:c}:{},...p?{root:p.root}:{},env:p?.instance?.env??{},...o.claims?{claims:o.claims}:{},...S?{fetchInternal:S}:{}})}catch(p){console.warn(`[gateway] ${new Date().toISOString()} middleware refused a request at ${e} traceId=${(0,gateway_errors_1.ensureRequestId)(o.req)}: ${p?.message??String(p)}`),E.traceStep(o.trace,"auth",{mode:"middleware",ok:!1,reason:`refused at ${e}`}),E.finishTrace(o.trace,l.project,401),o.sendError(401,"unauthorized","Gateway middleware rejected the request")}},"middlewareStep"),he=ee("preAuth"),we=ee("beforeForward"),_e=(0,hooks_1.createHooks)(withBuiltinHooks(r.hooks??{},{keyWait:edgeKeyWait(U),middleware:ee("afterAuth"),preAuth:he,beforeForward:we})),re=(0,handler_1.createHandler)({rt:i,obs:E,auth:ge,proxy:D,hooks:_e,parkedHosts:(0,on_demand_1.createParkedHostLookup)({registry:s(()=>i.registry,"registry"),records:j})}),ye=(0,upgrade_1.createUpgrade)({rt:i,auth:ge,proxy:D,hooks:_e,obs:E,middleware:{preAuth:he,beforeForward:we}}),Pe=E.startEdgeFlusher(),Ce=v.startSweeper(()=>{R.sweep(),C?.dropGone(),C?.parkIdle(),C?.expireRunRoutes(),C?.expireRemoteInstances(),G()}),Se=(0,source_poller_1.createSourcePoller)({services:s(()=>i.registry.allServices(),"services"),serviceKey:s(e=>i.serviceKeys[(0,service_keys_1.serviceKeyId)(e.wsKey,e.project)],"serviceKey"),emit:s((e,o,l,c,u)=>E.emit(o,l,c,{wsKey:e.wsKey,...u},void 0,e.wsKey===i.wsKey?void 0:path.join(e.root,".lensmcp","events.jsonl")),"emit"),scanTtlMs:n,stopped:s(()=>A,"stopped")});(0,source_poller_1.sourcesEnabled)()&&Se.start(),await N.bootSingletonsAndApps();const me=M.filter(e=>e.decl.eager).map(e=>v.ensureUp(e));Promise.allSettled(me).then(()=>setTimeout(le,me.length?2e4:0).unref());let $,te,B;if(g){const e=require("../../../basic-ssl"),o=(0,service_keys_1.gatewayCacheDir)(t.root);B=s(()=>e.getCertificateSync(o,"gateway",[...new Set([...i.routes.map(l=>l.host).filter(l=>!!l),...(0,parked_dashboards_1.parkedHosts)(i.registry,j())])]),"mintCert"),$=B(),te=e.caCertPath()}const se=[],oe=r.maxConnections??resolveMaxConnections(process.env.LENSMCP_MAX_CONNECTIONS);for(const e of d){const o=$?require("node:http2").createSecureServer({key:$,cert:$,allowHTTP1:!0,maxSessionMemory:512,settings:{maxConcurrentStreams:512},peerMaxConcurrentStreams:512,streamResetBurst:r.h2ResetBurst??types_1.GATEWAY_H2_RESET_BURST,streamResetRate:r.h2ResetRate??types_1.GATEWAY_H2_RESET_RATE},(c,u)=>re(c,u)):http.createServer(re);o.on("upgrade",ye),o.on("error",c=>console.error(`[gateway] port ${e}: ${c.code}`)),o.on("connection",guardInboundSocket),o.on("secureConnection",guardInboundSocket),o.on("tlsClientError",(c,u)=>u.destroy()),o.on("clientError",(c,u)=>{const p=c,S=classifyClientError(p.code,p.message);if(S.report&&Ae(S.cause)){const b=u.remoteAddress??"unknown",P=S.status===null?"dropped":String(S.status);console.warn(`[gateway] inbound H1 clientError from ${b}: ${S.cause} (${p.code??p.message}${p.bytesParsed!==void 0?`, bytesParsed=${p.bytesParsed}`:""}) \u2192 ${P}. This status is the GATEWAY's, not the upstream service's.`),E.emit("warning",`inbound clientError: ${S.cause} \u2192 ${P}`,`gateway-client-error:${S.cause}`,{kind:"gateway-client-error",cause:S.cause,code:p.code??null,status:S.status,peer:b,bytesParsed:p.bytesParsed??null})}S.status!==null&&u.writable&&u.end(`HTTP/1.1 ${S.status} ${CLIENT_ERROR_REASON[S.status]}\r
|
|
2
2
|
\r
|
|
3
|
-
`),
|
|
3
|
+
`),u.destroy()}),o.keepAliveTimeout=types_1.GATEWAY_KEEPALIVE_TIMEOUT_MS,o.headersTimeout=r.headersTimeoutMs??types_1.GATEWAY_HEADERS_TIMEOUT_MS,oe>0&&(o.maxConnections=oe);const l=r.connectionsCheckingIntervalMs??types_1.GATEWAY_CONN_CHECK_MS;if(l>0&&(o.connectionsCheckingInterval=l),$!=null){const c=o,{NGHTTP2_CANCEL:u}=require("node:http2").constants;c.on("session",p=>{if(!z.admitSession(p)){p.on("error",()=>{});return}let S=0,b=0;p.on("stream",P=>{z.admitStream(p,P)&&P.once("close",()=>{p.destroyed?b+=1:P.rstCode===u&&(S+=1)})}),p.once("close",()=>{b!==0&&(console.warn(`[gateway] h2 session closed with ${b} stream(s) in flight after ${S} client reset(s) \u2014 every in-flight fetch on that connection failed at once (ERR_HTTP2_PROTOCOL_ERROR in the browser). Reset budget: LENSMCP_H2_RESET_BURST/LENSMCP_H2_RESET_RATE (issues/closed/foodguard-14).`),E.emit("warning",`h2 session lost with ${b} stream(s) in flight`,"gateway-h2-session-lost",{kind:"h2-session-lost",project:"gateway",inflight:b,clientResets:S}))}),p.on("error",P=>{const Re=P.code??P.message;console.warn(`[gateway] h2 session error (${Re}) \u2014 dropping this session only`),p.destroyed||p.destroy()})}),c.on("sessionError",p=>{console.warn(`[gateway] h2 sessionError: ${p.code??p.message}`)})}await new Promise(c=>{o.listen(e,()=>{const u=o.address()?.port??e;q.push(u),console.log(`[gateway] Listening on ${$?"https":"http"}://localhost:${u}`),c()})}),se.push(o)}B&&(ie=s(()=>{const e=B();for(const o of se)o.setSecureContext?.({key:e,cert:e})},"refreshCert")),console.log("[gateway] Routes:");for(const e of x){const o=e.pool?`pods@${e.pool.dir}`:e.target;console.log(`[gateway] ${e.host??"(default)"} \u2192 ${o}${e.prependPrefix?` (+${e.prependPrefix})`:""}${e.internal?" [internal: no middleware]":""} [${e.project}]`)}te&&console.log(`[gateway] CA: ${te} \u2014 one-time setup via the trust executor.`),J=s(()=>U.warm(),"warmEdgeVerifiers"),J();const ae=s(e=>e>0?String(e):"unbounded","unbounded");console.log(`[gateway] front-door budget: \u2264${ae(oe)} connections, \u2264${ae(I.maxSessions)} h2 sessions (each \u2264512 MB session memory, \u2264512 streams), \u2264${ae(I.maxStreams)} open streams in total, idle h2 session reclaimed after ${I.idleSessionMs>0?`${Math.round(I.idleSessionMs/1e3)}s`:"never"}. Override: LENSMCP_MAX_CONNECTIONS / LENSMCP_MAX_H2_SESSIONS / LENSMCP_MAX_H2_STREAMS / LENSMCP_H2_IDLE_MS (0 = unbounded).`),E.emit("info",`gateway up: ${x.length} routes on ${q.join("/")}`,"cluster-gateway",{kind:"gateway-up",project:"gateway",ports:q,routes:x.map(e=>({host:e.host??"(default)",project:e.project,mode:e.pool?"pods":"tcp",internal:!!e.internal,prependPrefix:e.prependPrefix}))}),C&&process.env.LENSMCP_GUEST_REPLAY!=="0"?C.replay().catch(e=>console.warn("[gateway] guest replay failed:",e.message)).finally(G):G();const H=(0,docker_sweep_1.startDockerSweep)(t.root);H.started===!0?console.log(`[gateway] docker sweep started (pid ${H.pid}): what dead Docker runs left is taken down \u2014 ~/.lensmcp/docker/sweep.log`):H.started===!1&&H.why==="failed"&&console.warn(`[gateway] docker sweep could not start: ${H.detail??"unknown"}`);const Ne=(0,peer_hub_1.startPeerHubSupervisor)(t.root);return{ports:q,routes:x,services:M,stop:s(async()=>{if(!A){A=!0,clearInterval(Pe),clearInterval(Ce),Ne.stop(),Se.stop(),E.emit("info","gateway down","cluster-gateway",{kind:"gateway-down",project:"gateway"}),U.stop(),C?.close(),ue?.then(e=>e.close(),()=>{}),F?.flush(),(0,workspace_registry_1.unregisterWorkspace)(y);for(const e of M)v.killSpawned(e,"gateway shutdown");v.stopRetiringTrees(),await v.stopBuildHost(),await v.finishDyingTrees(),W.close(),await N.reapAll(),ye.closeTunnels(),await Promise.all(se.map(e=>new Promise(o=>{let l=!1;const c=s(()=>{l||(l=!0,o())},"done"),u=e;e.close(()=>c());try{u.closeIdleConnections?.()}catch{}setTimeout(()=>{try{u.closeAllConnections?.()}catch{}c()},types_1.GATEWAY_STOP_GRACE_MS).unref?.()}))),D.closeProxy(),D.destroyAgents(),z.dispose(),(0,workspace_log_1.closeWorkspaceLogs)(),h()}},"stop"),...i.lensSupervisor?{lensSupervisor:i.lensSupervisor}:{},...i.graphStores?{graphStores:i.graphStores}:{}}}T(startGateway,"startGateway"),s(startGateway,"startGateway");
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The services' update gates (planning/updates/00-plan.md U2): what holds, releases, updates, parks and starts one
|
|
3
|
+
* service's compile.
|
|
4
|
+
*
|
|
5
|
+
* - A tree started through the gateway's RUNNER compiling on its own: over the runner's IPC channel
|
|
6
|
+
* (`channel: 'lensmcp-updates'`, serve.impl.ts U1a) — `hold` suspends its webpack watcher, `release`/`update` compile
|
|
7
|
+
* what it collected and the runner answers `built`.
|
|
8
|
+
* - A tree the BUILD HOST compiles (the shared compiler, the default): through the host ({@link SharedUpdateGate},
|
|
9
|
+
* runtime/shared-build.ts, U1b).
|
|
10
|
+
* - A tree started through `nx run` has no channel: its saves stay live, and the answer says so.
|
|
11
|
+
* - Parked: the control plane's stop, remembered by the mode; started again as `POST /service` starts.
|
|
12
|
+
*/
|
|
13
|
+
import type { ChildProcess } from 'node:child_process';
|
|
14
|
+
import type { UpdatePieceOps } from './update-wiring';
|
|
15
|
+
import type { UpdateOutcome } from './updates';
|
|
16
|
+
import type { RuntimeUpdates, ServiceCtl } from './types';
|
|
17
|
+
export declare const UPDATES_CHANNEL = "lensmcp-updates";
|
|
18
|
+
/** The build host's half, for the trees it compiles (runtime/shared-build.ts). */
|
|
19
|
+
export interface SharedUpdateGate {
|
|
20
|
+
/** Is this service's current tree compiled by the build host? */
|
|
21
|
+
compiles(svc: ServiceCtl): boolean;
|
|
22
|
+
hold(svc: ServiceCtl, held: boolean): Promise<UpdateOutcome | undefined>;
|
|
23
|
+
update(svc: ServiceCtl): Promise<UpdateOutcome>;
|
|
24
|
+
}
|
|
25
|
+
export interface ServiceUpdateDeps {
|
|
26
|
+
updates(): RuntimeUpdates | undefined;
|
|
27
|
+
/** The control plane's stop (`POST /service stop`). */
|
|
28
|
+
stop(svc: ServiceCtl, reason: string): void;
|
|
29
|
+
/** The control plane's start: clears the stop, starts it, true once it answers. */
|
|
30
|
+
start(svc: ServiceCtl): Promise<boolean>;
|
|
31
|
+
shared?: SharedUpdateGate;
|
|
32
|
+
log?(line: string): void;
|
|
33
|
+
/** The longest a release or an update waits for its runner's answer. Default 15 min — a cold compile is minutes. */
|
|
34
|
+
builtTimeoutMs?: number;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Hand a runner tree's `held` reports (what its gate collected) to the update modes, from now on — once per tree.
|
|
38
|
+
* lifecycle.ts calls it as it spawns each runner tree, and a gate call does for a tree it meets first: a tree spawned
|
|
39
|
+
* HELD (`LENSMCP_UPDATES_HELD=1` — a roll, a restart, a cold start while an agent holds the checkout) reports before any
|
|
40
|
+
* gate has called it, and those reports went unheard — `GET /updates` kept the replaced tree's files and never named a
|
|
41
|
+
* save of the new one (planning/updates/00-plan.md U7, updates.e2e scenario 3 with the shared compiler off).
|
|
42
|
+
*/
|
|
43
|
+
export declare function listenHeldReports(svc: Pick<ServiceCtl, 'wsKey' | 'project'>, proc: ChildProcess, updates: () => RuntimeUpdates | undefined): void;
|
|
44
|
+
export declare function createServiceUpdateOps(d: ServiceUpdateDeps): UpdatePieceOps<ServiceCtl>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var v=Object.defineProperty;var f=(r,i)=>v(r,"name",{value:i,configurable:!0});var x=Object.defineProperty,a=f((r,i)=>x(r,"name",{value:i,configurable:!0}),"a");Object.defineProperty(exports,"__esModule",{value:!0}),exports.UPDATES_CHANNEL=void 0,exports.listenHeldReports=listenHeldReports,exports.createServiceUpdateOps=createServiceUpdateOps,exports.UPDATES_CHANNEL="lensmcp-updates";const isUpdatesMessage=a(r=>!!r&&typeof r=="object"&&r.channel===exports.UPDATES_CHANNEL&&typeof r.type=="string","isUpdatesMessage"),heldListened=new WeakSet;function listenHeldReports(r,i,d){heldListened.has(i)||typeof i.on!="function"||(heldListened.add(i),i.on("message",o=>{if(!isUpdatesMessage(o)||o.type!=="held")return;const p=Array.isArray(o.files)?o.files.filter(m=>typeof m=="string"):[];d()?.collected(r.wsKey,r.project,{files:p,count:typeof o.count=="number"?o.count:p.length,skipped:typeof o.skipped=="number"?o.skipped:0})}))}f(listenHeldReports,"listenHeldReports"),a(listenHeldReports,"listenHeldReports");function createServiceUpdateOps(r){const i=r.log??(e=>console.log(e)),d=r.builtTimeoutMs??15*6e4,o=new WeakMap,p=new Set,m=a((e,t)=>{p.has(e)||(p.add(e),i(t))},"once"),y=a(e=>{const t=e.proc;if(!(!t||e.launcher!=="runner"||typeof t.send!="function"||t.exitCode!==null||t.signalCode!==null)){if(listenHeldReports(e,t,r.updates),!o.has(t)){const c=[];o.set(t,c),t.on("message",n=>{!isUpdatesMessage(n)||n.type!=="built"||c.shift()?.({ok:n.ok===!0,changed:n.changed===!0,ms:typeof n.ms=="number"?n.ms:0,...Array.isArray(n.errors)?{errors:n.errors.map(String).slice(0,20)}:{}})}),t.once("exit",()=>{for(const n of c.splice(0))n(new Error("its tree exited before it answered"))})}return t}},"runner"),w=a((e,t,c)=>{const n=Date.now();return new Promise(u=>{const l=o.get(t);if(!l)return u({piece:e.project,outcome:"failed",ms:0,errors:["its runner is not listened to"]});const k=setTimeout(()=>{const s=l.indexOf(h);s>=0&&l.splice(s,1),u({piece:e.project,outcome:"failed",ms:Date.now()-n,errors:[`no answer from its runner in ${Math.round(d/6e4)} min`]})},d);k.unref?.();const h=a(s=>{if(clearTimeout(k),s instanceof Error)return u({piece:e.project,outcome:"failed",ms:Date.now()-n,errors:[s.message]});u(s.ok?{piece:e.project,outcome:s.changed?"swapped":"unchanged",ms:s.ms}:{piece:e.project,outcome:"failed",ms:s.ms,errors:s.errors?.length?s.errors:["the build failed \u2014 the last good build keeps serving"]})},"settle");l.push(h);try{t.send({channel:exports.UPDATES_CHANNEL,type:c},s=>{s&&h(s)})}catch(s){h(s instanceof Error?s:new Error(String(s)))}})},"ask"),b=a((e,t)=>({piece:e.project,outcome:"skipped",ms:0,why:t}),"skipped"),g=a(e=>{if(e.frozen)return"a frozen instance compiles once and watches nothing \u2014 restart it to build again";if(!e.proc)return"not running \u2014 its next start builds the files as they are";if(e.launcher==="nx")return"started through nx run, which gives it no channel to the gateway \u2014 its saves stay live (restart it through the gateway)"},"notHeldWhy");return{async hold(e){if(r.shared?.compiles(e)){await r.shared.hold(e,!0);return}const t=g(e);if(t){e.proc&&m(`${e.wsKey}/${e.project}:${e.proc.pid}`,`[gateway] ${e.project}: cannot hold its saves \u2014 ${t}`);return}y(e)?.send({channel:exports.UPDATES_CHANNEL,type:"hold"})},async release(e){if(r.shared?.compiles(e))return await r.shared.hold(e,!1)??{piece:e.project,outcome:"unchanged",ms:0};const t=g(e),c=t?void 0:y(e);return c?w(e,c,"release"):b(e,t??"its runner has no channel")},async update(e){if(r.shared?.compiles(e))return r.shared.update(e);const t=g(e),c=t?void 0:y(e);return c?w(e,c,"update"):b(e,t??"its runner has no channel")},async park(e){e.manualStopped=!0,r.stop(e,"parked (update mode off)")},async unpark(e){await r.start(e)||i(`[gateway] ${e.project}: started from parked, but it did not become ready \u2014 the Cluster tab says why`)}}}f(createServiceUpdateOps,"createServiceUpdateOps"),a(createServiceUpdateOps,"createServiceUpdateOps");
|
|
@@ -30,6 +30,7 @@
|
|
|
30
30
|
import { spawn, type ChildProcess } from 'node:child_process';
|
|
31
31
|
import type { RunnerScript } from './serve-launch';
|
|
32
32
|
import type { GatewayRuntime, ServiceCtl } from './types';
|
|
33
|
+
import type { SharedUpdateGate } from './service-updates';
|
|
33
34
|
/** Exits within {@link CRASH_WINDOW_MS} after which the host is given up on. */
|
|
34
35
|
export declare const HOST_MAX_RESTARTS = 3;
|
|
35
36
|
export declare const BUILD_HOST_IDLE_ENV = "LENSMCP_BUILD_HOST_IDLE_SEC";
|
|
@@ -38,7 +39,13 @@ export declare const DEFAULT_BUILD_HOST_IDLE_SEC = 300;
|
|
|
38
39
|
export declare function buildHostIdleMs(env?: NodeJS.ProcessEnv): number | undefined;
|
|
39
40
|
/** The workspace a service belongs to, as the relay needs it: its root, and its key (a registered one's). */
|
|
40
41
|
export type BuildMember = Pick<ServiceCtl, 'root'> & Partial<Pick<ServiceCtl, 'wsKey' | 'sockNs'>>;
|
|
41
|
-
|
|
42
|
+
/**
|
|
43
|
+
* The update modes' gate for the trees a build host compiles (planning/updates/00-plan.md U2 over U1b): `hold` and
|
|
44
|
+
* `update` go to the workspace's host by project; its `held` reports go to `rt.updates`, and an update or a release is
|
|
45
|
+
* answered when the host says it is done (`update-done`), from the `built` it relayed just before. Holds are the gateway's
|
|
46
|
+
* to keep: a host that restarts is told them again, before its members join again — `served` when they run a build.
|
|
47
|
+
*/
|
|
48
|
+
export interface SharedBuildRelay extends SharedUpdateGate {
|
|
42
49
|
/** Will a runner of `svc` be compiled by its workspace's build host (it is then started with `LENSMCP_SHARED_BUILD=1`)? */
|
|
43
50
|
offeredTo(svc: BuildMember): boolean;
|
|
44
51
|
/** Relay this runner's joins: `proc` is the root of `svc`'s tree for `generation`. */
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`)){const
|
|
3
|
-
`))
|
|
4
|
-
`)},"relayOut");return
|
|
1
|
+
"use strict";var z=Object.defineProperty;var b=(i,n)=>z(i,"name",{value:n,configurable:!0});var W=Object.defineProperty,s=b((i,n)=>W(i,"name",{value:n,configurable:!0}),"s");Object.defineProperty(exports,"__esModule",{value:!0}),exports.DEFAULT_BUILD_HOST_IDLE_SEC=exports.BUILD_HOST_IDLE_ENV=exports.HOST_MAX_RESTARTS=void 0,exports.buildHostIdleMs=buildHostIdleMs,exports.buildHostScript=buildHostScript,exports.workspaceBuildHostScript=workspaceBuildHostScript,exports.createSharedBuildRelay=createSharedBuildRelay;const tslib_1=require("tslib"),node_child_process_1=require("node:child_process"),fs=tslib_1.__importStar(require("node:fs")),node_module_1=require("node:module"),path=tslib_1.__importStar(require("node:path")),process_name_1=require("../../../process-name"),protocol_1=require("../../../shared-build/protocol"),pod_env_1=require("./pod-env"),registration_guards_1=require("./registration-guards");exports.HOST_MAX_RESTARTS=3;const CRASH_WINDOW_MS=6e4,HOST_STOP_GRACE_MS=6e3;exports.BUILD_HOST_IDLE_ENV="LENSMCP_BUILD_HOST_IDLE_SEC",exports.DEFAULT_BUILD_HOST_IDLE_SEC=300;function buildHostIdleMs(i=process.env){const n=i[exports.BUILD_HOST_IDLE_ENV]?.trim(),l=n?Number(n):NaN;return!Number.isFinite(l)||l<0?exports.DEFAULT_BUILD_HOST_IDLE_SEC*1e3:l>0?l*1e3:void 0}b(buildHostIdleMs,"buildHostIdleMs"),s(buildHostIdleMs,"buildHostIdleMs");function buildHostScript(i=path.join(__dirname,"../../..")){const n=path.join(i,"build-host.js");if(fs.existsSync(n))return{path:n,execArgv:[]};const l=path.join(i,"build-host.ts");if(fs.existsSync(l))try{return{path:l,execArgv:["--require",require.resolve("@swc-node/register")]}}catch{return}}b(buildHostScript,"buildHostScript"),s(buildHostScript,"buildHostScript");function workspaceBuildHostScript(i,n=buildHostScript){const l=(0,node_module_1.createRequire)(path.join(i,"package.json"));try{return{path:l.resolve("@lensmcp/cluster/build-host.js"),execArgv:[]}}catch{}try{l.resolve("@lensmcp/cluster/package.json");return}catch{return n()}}b(workspaceBuildHostScript,"workspaceBuildHostScript"),s(workspaceBuildHostScript,"workspaceBuildHostScript");function createSharedBuildRelay(i,n={}){const l=n.script===void 0?buildHostScript():n.script??void 0,y=n.scriptFor??workspaceBuildHostScript,f=new Map,v=new WeakMap,p=(0,registration_guards_1.canonicalRoot)(i.root),S=s(t=>{const a=(0,registration_guards_1.canonicalRoot)(t.root);let u=f.get(a);return u||(u=a===p?createWorkspaceRelay(i,{root:i.root,...i.wsKey?{wsKey:i.wsKey}:{},...i.sockNs?{sockNs:i.sockNs}:{},eventFile:i.eventFile},l,n):createWorkspaceRelay(i,{root:t.root,...t.wsKey?{wsKey:t.wsKey}:{},...t.sockNs?{sockNs:t.sockNs}:{},eventFile:path.join(t.root,".lensmcp","events.jsonl")},y(t.root),n),f.set(a,u)),u},"relayFor");return{offeredTo:s(t=>(0,protocol_1.sharedCompilerEnabled)(n.gatewayEnv??process.env,i.sharedCompiler)&&S(t).offered(),"offeredTo"),attach(t,a,u){const E=S(t);v.set(u,E),E.attach(`${t.project}#g${a}`,u)},detach:s(t=>v.get(t)?.detach(t),"detach"),compiles:s(t=>f.get((0,registration_guards_1.canonicalRoot)(t.root))?.compiles(`${t.project}#g${t.generation??0}`)??!1,"compiles"),hold:s((t,a)=>S(t).hold(t.project,a),"hold"),update:s(t=>S(t).update(t.project),"update"),hostPid:s((t=i.root)=>f.get((0,registration_guards_1.canonicalRoot)(t))?.hostPid(),"hostPid"),release(t){const a=(0,registration_guards_1.canonicalRoot)(t),u=f.get(a);return f.delete(a),u?.stop()??Promise.resolve()},async stop(){const t=[...f.values()];f.clear(),await Promise.all(t.map(a=>a.stop()))}}}b(createSharedBuildRelay,"createSharedBuildRelay"),s(createSharedBuildRelay,"createSharedBuildRelay");function createWorkspaceRelay(i,n,l,y){const f=y.spawnProcess??node_child_process_1.spawn,v=y.log??(e=>console.log(e)),p=new Map,S=new WeakMap;let t,a,u;const E="idleMs"in y?y.idleMs:buildHostIdleMs(y.gatewayEnv??process.env);let k=[],_,j=!1;const x=(0,registration_guards_1.canonicalRoot)(n.root)===(0,registration_guards_1.canonicalRoot)(i.root)?"this workspace":`'${n.wsKey??path.basename(n.root)}'`,H=n.wsKey??i.wsKey,T=new Set,I=new Set,D=new Map,g=new Map,P=15*6e4,q=s(e=>e.replace(/#g\d+$/,""),"projectOf"),N=s((e,r)=>{const o=g.get(e);g.delete(e);for(const d of o??[])d(r)},"settle"),A=s(e=>{for(const r of[...g.keys()])N(r,{piece:r,outcome:"failed",ms:0,errors:[e]})},"settleAll"),$=s(()=>{for(const e of T)w({type:"hold",project:e,held:!0});for(const[e,{join:r}]of p)w({type:"join",member:e,join:r,...I.has(e)?{served:!0}:{}})},"rejoin"),C=s((e,r)=>{const o=Date.now();return new Promise(d=>{const c=setTimeout(()=>{const h=g.get(e),L=h?.indexOf(m)??-1;h&&L>=0&&h.splice(L,1),d({piece:e,outcome:"failed",ms:Date.now()-o,errors:[`no answer from the build host in ${Math.round(P/6e4)} min`]})},P);c.unref?.();const m=s(h=>{clearTimeout(c),d(h)},"done");g.set(e,[...g.get(e)??[],m]),w(r)})},"ask"),F=s((e,r)=>{const o=D.get(e);return r?o?o.ok?{piece:e,outcome:o.changed?"swapped":"unchanged",ms:o.durationMs}:{piece:e,outcome:"failed",ms:o.durationMs,errors:[`${o.errors} error(s) in its build \u2014 the last good build keeps serving`]}:{piece:e,outcome:"swapped",ms:0}:o&&!o.ok?{piece:e,outcome:"failed",ms:0,errors:[`${o.errors} error(s) in its last build, and nothing saved since \u2014 the last good build keeps serving`]}:{piece:e,outcome:"unchanged",ms:0}},"doneOutcome"),M=s((e,r)=>{if(!e.connected)return;const o={channel:protocol_1.SHARED_BUILD_CHANNEL,event:r};try{e.send(o,void 0,void 0,()=>{})}catch{}},"toRunner"),w=s(e=>{if(t?.connected)try{t.send(e,void 0,void 0,()=>{})}catch{}},"toHost"),U=s(()=>{if(y.reapStale===!1)return;let e;try{e=(0,node_child_process_1.execFileSync)("ps",["ax","-ww","-o","pid=,pgid=,command="],{encoding:"utf8",timeout:5e3})}catch{return}for(const r of e.split(`
|
|
2
|
+
`)){const o=r.match(/^\s*(\d+)\s+(\d+)\s+(.*)$/);if(!o||!(0,protocol_1.isBuildHostCommandOf)(o[3],n.root))continue;const d=Number(o[1]),c=Number(o[2]);if(!(d===t?.pid||d===a?.pid||d===process.pid)){try{process.kill(-c,"SIGKILL")}catch{try{process.kill(d,"SIGKILL")}catch{}}v(`[gateway] reaped a stale build host (pid ${d}) of ${x}`)}}},"reapStaleHosts"),O=s(()=>{if(t||j||_||!l)return t;U();const e=n.wsKey||path.basename(n.root),r={...(0,pod_env_1.podBaseEnv)(process.env,i.root,n.root),NX_DAEMON:"false",NODE_ENV:"development",NX_WORKSPACE_ROOT:n.root,...n.wsKey?{LENSMCP_WS_KEY:n.wsKey}:{},...n.sockNs?{LENSMCP_SOCK_NS:n.sockNs}:{},LENSMCP_EVENT_FILE:n.eventFile,LENSMCP_GATEWAY_PID:String(process.pid)},o=f((0,process_name_1.namedExecPath)((0,process_name_1.processName)(e,protocol_1.BUILD_HOST_ROLE)),[...l.execArgv,l.path,...(0,protocol_1.buildHostArgs)(n.root)],{cwd:n.root,detached:!0,env:r,stdio:["ignore","pipe","pipe","ipc"]});t=o,v(`[gateway] build host starting (one compilation for the services of ${x} \u2014 LENSMCP_SHARED_COMPILER)`);const d=s(c=>m=>{if(!i.stopped())for(const h of m.toString().split(`
|
|
3
|
+
`))h.trim()&&c.write(`[build] ${h}
|
|
4
|
+
`)},"relayOut");return o.stdout?.on("data",d(process.stdout)),o.stderr?.on("data",d(process.stderr)),o.on("message",c=>{if(c?.type==="member"){const m=p.get(c.member);m&&M(m.proc,c.event);const h=q(c.member);c.event.type==="built"?(I.add(c.member),D.set(h,c.event)):c.event.type==="failed"&&g.has(h)&&N(h,{piece:h,outcome:"failed",ms:0,errors:[c.event.message||"the shared compiler failed \u2014 the last good build keeps serving"]})}else c?.type==="held"?i.updates?.collected(H,c.project,{files:c.files,...c.count!==void 0?{count:c.count}:{},skipped:c.skipped}):c?.type==="update-done"&&N(c.project,F(c.project,c.delivered))}),o.on("exit",(c,m)=>{if(t===o&&(t=void 0),A(`the build host exited (${c??m}) before it answered`),a===o){if(a=void 0,j||i.stopped()||p.size===0)return;O()&&$();return}if(j||i.stopped())return;const h=Date.now();if(k=[...k.filter(L=>h-L<CRASH_WINDOW_MS),h],k.length>=exports.HOST_MAX_RESTARTS){_=`the build host exited ${k.length} times in a minute (last: ${c??m})`,v(`[gateway] ${_} \u2014 every service compiles on its own from now on`);for(const L of p.values())M(L.proc,{type:"refused",reason:_});p.clear();return}p.size!==0&&(v(`[gateway] build host exited (${c??m}) \u2014 restarting it for ${p.size} service tree(s)`),O()&&$())}),o},"start"),K=s(e=>e.exitCode!==null||e.signalCode!==null?Promise.resolve():new Promise(r=>{const o=s(()=>{clearTimeout(d),r()},"done");e.once("exit",o);try{process.kill(-e.pid,"SIGTERM")}catch{try{e.kill("SIGTERM")}catch{}}const d=setTimeout(()=>{try{process.kill(-e.pid,"SIGKILL")}catch{try{e.kill("SIGKILL")}catch{}}r()},HOST_STOP_GRACE_MS);d.unref?.()}),"terminate"),R=s(()=>{u&&clearTimeout(u),u=void 0},"cancelIdle"),G=s(()=>{R(),!(E===void 0||j||!t)&&(u=setTimeout(()=>{u=void 0;const e=t;p.size>0||j||!e||(t=void 0,a=e,v(`[gateway] build host of ${x} stopped \u2014 no service of it has run for ${Math.round(E/1e3)}s (the next one starts it again)`),K(e))},E),u.unref?.())},"idleOut"),B=s(e=>{const r=S.get(e);!r||p.get(r)?.proc!==e||(p.delete(r),I.delete(r),w({type:"leave",member:r}),p.size===0&&G())},"detach");return{offered:s(()=>!!l&&!_,"offered"),compiles:s(e=>!_&&p.has(e),"compiles"),async hold(e,r){if(r){T.add(e),w({type:"hold",project:e,held:!0});return}const o=T.delete(e);return t?.connected?o?C(e,{type:"hold",project:e,held:!1}):{piece:e,outcome:"unchanged",ms:0}:{piece:e,outcome:"unchanged",ms:0,why:"its build host is not running \u2014 its next start builds the files as they are"}},update(e){return t?.connected?C(e,{type:"update",project:e}):Promise.resolve({piece:e,outcome:"skipped",ms:0,why:"its build host is not running \u2014 its next start builds the files as they are"})},attach:s((e,r)=>{S.set(r,e),r.on("message",o=>{if(!(0,protocol_1.isRunnerJoinMessage)(o))return;if(R(),a&&!_){p.set(e,{proc:r,join:o.join});return}if(_||!O()){M(r,{type:"refused",reason:_??"the build host could not be started"});return}p.set(e,{proc:r,join:o.join}),w({type:"join",member:e,join:o.join});const d=i.updates?.stateOf(H,o.join.project);(d==="held"||d==="manual")&&!T.has(o.join.project)&&(T.add(o.join.project),w({type:"hold",project:o.join.project,held:!0}))}),r.once("exit",()=>B(r))},"attach"),detach:B,hostPid:s(()=>t?.pid,"hostPid"),stop(){j=!0,R(),A("the build host was stopped"),p.clear();const e=[t,a].filter(r=>!!r);return t=void 0,Promise.all(e.map(K)).then(()=>{})}}}b(createWorkspaceRelay,"createWorkspaceRelay"),s(createWorkspaceRelay,"createWorkspaceRelay");
|
|
@@ -80,6 +80,11 @@ export interface ClusterProjectDecl {
|
|
|
80
80
|
idleKillSec?: number;
|
|
81
81
|
/** Nx target that runs the service. Default serve-hmr. */
|
|
82
82
|
serveTarget?: string;
|
|
83
|
+
/**
|
|
84
|
+
* Its update mode by default (planning/updates/00-plan.md, UM-D1): `hmr` (every save built and applied — the default),
|
|
85
|
+
* `manual` (saves wait for an update), `off` (parked: not run). A checkout's own choice (`.lensmcp/updates.json`) wins.
|
|
86
|
+
*/
|
|
87
|
+
updates?: 'hmr' | 'manual' | 'off';
|
|
83
88
|
/** What LensMCP runs it as (planning/global ZT-D1): `node` / `nest` pods built from `buildTarget`, a `vite` app. */
|
|
84
89
|
kind?: 'node' | 'nest' | 'vite';
|
|
85
90
|
/** The project's own build target a `node` / `nest` service is built from. Default `build`. */
|
|
@@ -183,6 +188,36 @@ export interface Route {
|
|
|
183
188
|
/** Frontend `lens:true` route: the gateway spawns this app's Vite + lens
|
|
184
189
|
* instrumentation as the upstream (see `LensFrontend`). */
|
|
185
190
|
lens?: LensFrontend;
|
|
191
|
+
/**
|
|
192
|
+
* The route of a Docker run's URL (run-routes.ts, planning/docker/00-plan.md § 3): it belongs to no workspace, so no
|
|
193
|
+
* workspace's edge middleware and no act ticket applies to it, its host is no origin the gateway answers CORS for,
|
|
194
|
+
* and it answers this machine only. `id` is the run, `wsKey` the workspace under whose apex its host was derived.
|
|
195
|
+
* `socket`: a REMOTE run's (slice D17) — its requests go to the tunnel socket at `path` (run-routes.ts
|
|
196
|
+
* `runSocketUpstream`), and `port` is the edge's on the worker, named in the Host header only; such a route has no
|
|
197
|
+
* `target`.
|
|
198
|
+
*/
|
|
199
|
+
run?: {
|
|
200
|
+
id: string;
|
|
201
|
+
wsKey: string;
|
|
202
|
+
socket?: {
|
|
203
|
+
path: string;
|
|
204
|
+
port: number;
|
|
205
|
+
};
|
|
206
|
+
};
|
|
207
|
+
/**
|
|
208
|
+
* A REMOTE instance's route (remote-instances.ts, planning/docker/00-plan.md § 13, slice D35): a goal's runtime on a
|
|
209
|
+
* worker Mac, reached through its tunnel. It has no `target` and no `pool`: its requests go to the tunnel socket at
|
|
210
|
+
* `socket` (`remoteInstanceUpstream`) with the Host the browser sent — the worker's gateway routes by it — and none
|
|
211
|
+
* of this gateway's pipeline runs on it (handler.ts, upgrade.ts). `id` is the instance, `wsKey` the workspace whose
|
|
212
|
+
* apex its own is under; `part` is `lens` on its lens host (`lensmcp.<apex>`), `app` on every other.
|
|
213
|
+
*/
|
|
214
|
+
remote?: {
|
|
215
|
+
id: string;
|
|
216
|
+
wsKey: string;
|
|
217
|
+
apex: string;
|
|
218
|
+
socket: string;
|
|
219
|
+
part: 'app' | 'lens';
|
|
220
|
+
};
|
|
186
221
|
}
|
|
187
222
|
/** A frontend app the gateway runs UNDER the lens (`cluster.lens: true`). The
|
|
188
223
|
* gateway spawns its Vite + browser capture as the upstream, deterministically
|
|
@@ -210,6 +245,8 @@ export interface LensFrontend {
|
|
|
210
245
|
env?: Readonly<Record<string, string>>;
|
|
211
246
|
/** A FROZEN instance's app (instance.ts): its Vite watches nothing, and no source change hands it off. */
|
|
212
247
|
frozen?: boolean;
|
|
248
|
+
/** Its declared update mode (`ClusterProjectDecl.updates`, planning/updates UM-D1). */
|
|
249
|
+
updates?: 'hmr' | 'manual' | 'off';
|
|
213
250
|
}
|
|
214
251
|
export interface SourceSetChange {
|
|
215
252
|
changedAt: number;
|
|
@@ -851,6 +888,18 @@ export interface HmrClientSocket {
|
|
|
851
888
|
once(event: 'close' | 'error', listener: () => void): unknown;
|
|
852
889
|
readonly destroyed: boolean;
|
|
853
890
|
}
|
|
891
|
+
/** What the runtime's layers read of the update modes (updates.ts `Updates` is one): this file imports no layer. */
|
|
892
|
+
export interface RuntimeUpdates {
|
|
893
|
+
stateOf(workspace: string, piece: string): 'live' | 'held' | 'manual' | 'parked';
|
|
894
|
+
/** Should a fresh tree or generation of this piece start held (`LENSMCP_UPDATES_HELD=1`)? Asked at its spawn. */
|
|
895
|
+
startsHeld(workspace: string, piece: string): boolean;
|
|
896
|
+
/** A gate's report of what it collected for a held piece. */
|
|
897
|
+
collected(workspace: string, piece: string, c: {
|
|
898
|
+
files: string[];
|
|
899
|
+
count?: number;
|
|
900
|
+
skipped: number;
|
|
901
|
+
}): void;
|
|
902
|
+
}
|
|
854
903
|
export interface GatewayRuntime {
|
|
855
904
|
readonly root: string;
|
|
856
905
|
/** The per-workspace key (from `readLensScope`) — namespaces this workspace's pod sock dirs so a shared
|
|
@@ -933,6 +982,11 @@ export interface GatewayRuntime {
|
|
|
933
982
|
/** The parked on-demand worktrees whose dashboards this daemon keeps at `lensmcp.local/<key>/` (parked-dashboards.ts):
|
|
934
983
|
* the chooser lists them, the parked host page links them. Installed by server.ts. */
|
|
935
984
|
parkedDashboards?: Pick<ParkedDashboards, 'list'>;
|
|
985
|
+
/**
|
|
986
|
+
* The update modes (updates.ts, planning/updates U2) — set once at boot (server.ts). The spawns ask it whether a fresh
|
|
987
|
+
* tree or generation starts held, the sweeps whether a piece may be recycled, the proxy whether a piece is parked.
|
|
988
|
+
*/
|
|
989
|
+
updates?: RuntimeUpdates;
|
|
936
990
|
/** Teardown flag — a GETTER, never a captured boolean, so every layer reads
|
|
937
991
|
* the LIVE value (an in-flight cold start / auto-heal must not act after stop). */
|
|
938
992
|
stopped(): boolean;
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import type { RouteRegistry } from './route-registry';
|
|
2
|
+
import type { ServiceCtl } from './types';
|
|
3
|
+
import { type UpdateMode, type UpdateOutcome, type Updates } from './updates';
|
|
4
|
+
/** `<checkout>/.lensmcp/updates.json` — the person's modes for that checkout (UM-D1), machine-local like the rest of `.lensmcp/`. */
|
|
5
|
+
export declare const UPDATES_FILE = "updates.json";
|
|
6
|
+
export declare function updatesFile(root: string): string;
|
|
7
|
+
/** The checkout's modes; none when the file is absent. A file that is not ours throws — the controller says so and ignores it. */
|
|
8
|
+
export declare function readUpdateModes(root: string): Record<string, UpdateMode>;
|
|
9
|
+
/** Written whole, through a temporary file: a reader never sees half of it. */
|
|
10
|
+
export declare function writeUpdateModes(root: string, modes: Record<string, UpdateMode>): void;
|
|
11
|
+
/**
|
|
12
|
+
* The registered workspace a path is inside: the one whose root is its longest prefix — a goal worktree under main's
|
|
13
|
+
* `.lensmcp/worktrees/` is itself, not main.
|
|
14
|
+
*/
|
|
15
|
+
export declare function workspaceForPath(registry: Pick<RouteRegistry, 'keys' | 'get'>, p: string): string | undefined;
|
|
16
|
+
/** What touches one piece's process — the gates (updates.ts `UpdateGates`), per kind. */
|
|
17
|
+
export interface UpdatePieceOps<T> {
|
|
18
|
+
hold(piece: T): Promise<void>;
|
|
19
|
+
release(piece: T): Promise<UpdateOutcome>;
|
|
20
|
+
update(piece: T): Promise<UpdateOutcome>;
|
|
21
|
+
park(piece: T): Promise<void>;
|
|
22
|
+
unpark(piece: T, held: boolean): Promise<void>;
|
|
23
|
+
}
|
|
24
|
+
/** A frontend as the update modes see it: its workspace, its project, its declared mode. */
|
|
25
|
+
export interface FrontendPiece {
|
|
26
|
+
wsKey: string;
|
|
27
|
+
project: string;
|
|
28
|
+
updates?: UpdateMode;
|
|
29
|
+
}
|
|
30
|
+
export interface GatewayUpdatesDeps {
|
|
31
|
+
registry: Pick<RouteRegistry, 'keys' | 'get'>;
|
|
32
|
+
/** The workspace's frontends (lens-children). */
|
|
33
|
+
frontends(wsKey: string): FrontendPiece[];
|
|
34
|
+
serviceOps: UpdatePieceOps<ServiceCtl>;
|
|
35
|
+
frontendOps: UpdatePieceOps<FrontendPiece>;
|
|
36
|
+
/** Onto the workspace's own bus. */
|
|
37
|
+
emit(wsKey: string, kind: string, data: Record<string, unknown>): void;
|
|
38
|
+
log?(line: string): void;
|
|
39
|
+
now?(): number;
|
|
40
|
+
}
|
|
41
|
+
export declare function createGatewayUpdates(d: GatewayUpdatesDeps): Updates;
|
|
42
|
+
/** The longest an `/updates/apply` waits for its builds before it answers `pending` for the rest. */
|
|
43
|
+
export declare const MAX_APPLY_WAIT_SEC = 600;
|
|
44
|
+
export interface UpdatesRequest {
|
|
45
|
+
method: string;
|
|
46
|
+
/** Path and query, as the control socket received it. */
|
|
47
|
+
url: string;
|
|
48
|
+
body?: unknown;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* The control socket's `/updates` endpoints (planning/updates/00-plan.md, the contract): `undefined` for a path that is
|
|
52
|
+
* not one of them. A workspace is named by `workspace` (its key) or `root` (a path inside it).
|
|
53
|
+
*/
|
|
54
|
+
export declare function handleUpdatesRequest(updates: Updates, registry: Pick<RouteRegistry, 'keys' | 'get'>, req: UpdatesRequest): Promise<{
|
|
55
|
+
status: number;
|
|
56
|
+
json: unknown;
|
|
57
|
+
} | undefined>;
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";var b=Object.defineProperty;var m=(e,n)=>b(e,"name",{value:n,configurable:!0});var g=Object.defineProperty,i=m((e,n)=>g(e,"name",{value:n,configurable:!0}),"i");Object.defineProperty(exports,"__esModule",{value:!0}),exports.MAX_APPLY_WAIT_SEC=exports.UPDATES_FILE=void 0,exports.updatesFile=updatesFile,exports.readUpdateModes=readUpdateModes,exports.writeUpdateModes=writeUpdateModes,exports.workspaceForPath=workspaceForPath,exports.createGatewayUpdates=createGatewayUpdates,exports.handleUpdatesRequest=handleUpdatesRequest;const tslib_1=require("tslib"),fs=tslib_1.__importStar(require("node:fs")),path=tslib_1.__importStar(require("node:path")),updates_1=require("./updates");exports.UPDATES_FILE="updates.json";function updatesFile(e){return path.join(e,".lensmcp",exports.UPDATES_FILE)}m(updatesFile,"updatesFile"),i(updatesFile,"updatesFile");function readUpdateModes(e){let n;try{n=fs.readFileSync(updatesFile(e),"utf8")}catch(o){if(o.code==="ENOENT")return{};throw o}const s=JSON.parse(n);if(!s||typeof s!="object"||!s.modes||typeof s.modes!="object"||Array.isArray(s.modes))throw new Error(`${updatesFile(e)} has no "modes" object`);return Object.fromEntries(Object.entries(s.modes).filter(o=>(0,updates_1.isUpdateMode)(o[1])))}m(readUpdateModes,"readUpdateModes"),i(readUpdateModes,"readUpdateModes");function writeUpdateModes(e,n){const s=updatesFile(e);fs.mkdirSync(path.dirname(s),{recursive:!0});const o=`${s}.${process.pid}.tmp`;fs.writeFileSync(o,`${JSON.stringify({modes:n},null,2)}
|
|
2
|
+
`),fs.renameSync(o,s)}m(writeUpdateModes,"writeUpdateModes"),i(writeUpdateModes,"writeUpdateModes");function workspaceForPath(e,n){const s=realPath(n);let o;for(const a of e.keys()){const r=e.get(a)?.root;if(!r)continue;const t=realPath(r);(s===t||s.startsWith(t+path.sep))&&(!o||t.length>o.len)&&(o={key:a,len:t.length})}return o?.key}m(workspaceForPath,"workspaceForPath"),i(workspaceForPath,"workspaceForPath");function realPath(e){const n=[];let s=path.resolve(e);for(;;)try{return path.join(fs.realpathSync(s),...n.reverse())}catch{const o=path.dirname(s);if(o===s)return path.resolve(e);n.push(path.basename(s)),s=o}}m(realPath,"realPath"),i(realPath,"realPath");function createGatewayUpdates(e){const n=i(r=>e.registry.get(r.workspace)?.services.find(t=>t.project===r.piece),"service"),s=i(r=>e.frontends(r.workspace).find(t=>t.project===r.piece),"frontend"),o=i(r=>({piece:r.piece,outcome:"skipped",ms:0,why:"no longer in this workspace"}),"gone"),a=i((r,t,c,p)=>{if(r.kind==="service"){const l=n(r);return l?t(l):Promise.resolve(p())}const d=s(r);return d?c(d):Promise.resolve(p())},"on");return(0,updates_1.createUpdates)({now:e.now??Date.now,pieces:i(r=>{const t=e.registry.get(r);if(!t)return[];const c=t.services.map(d=>({piece:d.project,kind:"service"})),p=new Set(c.map(d=>d.piece));return[...c,...e.frontends(r).filter(d=>!p.has(d.project)).map(d=>({piece:d.project,kind:"frontend"}))]},"pieces"),declared:i((r,t)=>{const c=e.registry.get(r)?.services.find(d=>d.project===t),p=c?c.decl.updates:e.frontends(r).find(d=>d.project===t)?.updates;return(0,updates_1.isUpdateMode)(p)?p:void 0},"declared"),load:i(r=>{const t=e.registry.get(r)?.root;return t?readUpdateModes(t):{}},"load"),save:i((r,t)=>{const c=e.registry.get(r)?.root;c&&writeUpdateModes(c,t)},"save"),gates:{hold:i(r=>a(r,t=>e.serviceOps.hold(t),t=>e.frontendOps.hold(t),()=>{}),"hold"),release:i(r=>a(r,t=>e.serviceOps.release(t),t=>e.frontendOps.release(t),()=>o(r)),"release"),update:i(r=>a(r,t=>e.serviceOps.update(t),t=>e.frontendOps.update(t),()=>o(r)),"update"),park:i(r=>a(r,t=>e.serviceOps.park(t),t=>e.frontendOps.park(t),()=>{}),"park"),unpark:i((r,t)=>a(r,c=>e.serviceOps.unpark(c,t),c=>e.frontendOps.unpark(c,t),()=>{}),"unpark")},publish:i((r,t,c)=>e.emit(r,t,c),"publish"),...e.log?{log:e.log}:{}})}m(createGatewayUpdates,"createGatewayUpdates"),i(createGatewayUpdates,"createGatewayUpdates"),exports.MAX_APPLY_WAIT_SEC=600;const DEFAULT_APPLY_WAIT_SEC=120,str=i((e,n=200)=>typeof e=="string"&&e.length>0&&e.length<=n?e:void 0,"str"),strings=i(e=>Array.isArray(e)&&e.every(n=>typeof n=="string"&&n.length>0&&n.length<=200)?e:void 0,"strings");async function handleUpdatesRequest(e,n,s){const o=new URL(s.url,"http://control");if(o.pathname!=="/updates"&&!o.pathname.startsWith("/updates/"))return;const a=s.body&&typeof s.body=="object"&&!Array.isArray(s.body)?s.body:{},r=s.method==="GET"?Object.fromEntries(o.searchParams):a,t=str(r.workspace),c=str(r.root,4096);if(!t&&!c)return{status:400,json:{error:"workspace (its key) or root (a path inside it) is required"}};const p=t??workspaceForPath(n,c);if(!p||!n.get(p))return{status:404,json:{error:t?`no workspace '${t}' is registered`:`no registered workspace holds ${c}`}};const d=str(a.by),l=a.pieces===void 0?void 0:strings(a.pieces);if(a.pieces!==void 0&&!l)return{status:400,json:{error:"pieces must be an array of names"}};const w=n.get(p)?.instance?.name,j=w?{checkout:"worktree",instance:w}:{checkout:"main"};if(s.method==="GET"&&o.pathname==="/updates")return{status:200,json:{...e.status(p),...j}};if(s.method!=="POST")return{status:405,json:{error:`${s.method} ${o.pathname} is not served`}};switch(o.pathname){case"/updates/mode":{const u=a.mode;if(!(0,updates_1.isUpdateMode)(u))return{status:400,json:{error:"mode must be hmr, manual or off"}};if(!l?.length)return{status:400,json:{error:"pieces: name the services and frontends to set"}};const f=e.status(p).pieces.map(h=>h.piece),y=l.filter(h=>!f.includes(h));return y.length?{status:400,json:{error:`${y.join(", ")}: not a service or frontend of '${p}' (it has ${f.join(", ")||"none"})`}}:{status:200,json:{...await e.setMode(p,l,u,d),...j}}}case"/updates/hold":{const u=holderOf(a.holder);if(!u)return{status:400,json:{error:"holder: { client, session, name? } is required"}};const f=a.ttlSec;if(f!==void 0&&(typeof f!="number"||!Number.isFinite(f)||f<=0))return{status:400,json:{error:`ttlSec must be a number of seconds (at most ${updates_1.MAX_HOLD_SEC})`}};const y=str(a.why,500);return{status:200,json:{hold:await e.hold(p,u,{...l?{pieces:l}:{},...typeof f=="number"?{ttlSec:f}:{},...y?{why:y}:{}})}}}case"/updates/release":{const u=holderOf(a.holder);return u?{status:200,json:{outcomes:await e.release(p,u,d)}}:{status:400,json:{error:"holder: { client, session } is required"}}}case"/updates/apply":{const u=a.waitSec;if(u!==void 0&&(typeof u!="number"||!Number.isFinite(u)||u<0))return{status:400,json:{error:`waitSec must be a number of seconds (at most ${exports.MAX_APPLY_WAIT_SEC})`}};const f=Math.min(typeof u=="number"?u:DEFAULT_APPLY_WAIT_SEC,exports.MAX_APPLY_WAIT_SEC)*1e3,y=l?.length?l:e.status(p).pieces.map(h=>h.piece);return{status:200,json:{outcomes:(await Promise.all(y.map(h=>within(f,e.apply(p,[h],d).then(v=>v[0]),h)))).filter(h=>!!h)}}}default:return{status:404,json:{error:`${o.pathname} is not an /updates endpoint`}}}}m(handleUpdatesRequest,"handleUpdatesRequest"),i(handleUpdatesRequest,"handleUpdatesRequest");function holderOf(e){if(!e||typeof e!="object")return;const n=e,s=str(n.client),o=str(n.session);if(!s||!o)return;const a=str(n.name);return{client:s,session:o,...a?{name:a}:{}}}m(holderOf,"holderOf"),i(holderOf,"holderOf");function within(e,n,s){let o;const a=new Promise(r=>{o=setTimeout(()=>r({piece:s,outcome:"pending",ms:e,why:`still building after ${Math.round(e/1e3)} s \u2014 service_updates says when it lands`}),e),o.unref?.()});return Promise.race([n,a]).finally(()=>clearTimeout(o))}m(within,"within"),i(within,"within");
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* UPDATE MODES (planning/updates/00-plan.md, U2): whether a checkout's services and frontends take every save live, hold
|
|
3
|
+
* what is saved until someone asks, or do not run at all — and the HOLDS that let many agents edit one checkout without
|
|
4
|
+
* a build per save.
|
|
5
|
+
*
|
|
6
|
+
* The owner, 2026-11-14: «if we have many agents working, each one can pause hmr and can access the services but not up
|
|
7
|
+
* to date, and when they finished the work it will trigger build. This way we will reduce the CPU, but this feature can be
|
|
8
|
+
* toggled, like hmr, manual, off (parked).»
|
|
9
|
+
*
|
|
10
|
+
* - A piece (a service or a frontend of one workspace) has a MODE: the checkout's override (`.lensmcp/updates.json`,
|
|
11
|
+
* the person's — CLI and Cluster tab) ?? its declaration's (`lensmcp.json → services.<name>.updates`) ?? `hmr`.
|
|
12
|
+
* - A HOLD is one holder's «don't build yet» — an agent's, taken by its hooks before an edit (UM-D2), renewed by its
|
|
13
|
+
* calls, ended by its turn's end, its session's end or its lease lapsing (UM-D4). Holds are counted per holder: one
|
|
14
|
+
* release never ends another's.
|
|
15
|
+
* - The EFFECTIVE state follows: `parked` (mode off) · `manual` (mode manual) · `held` (mode hmr, held) · `live`.
|
|
16
|
+
* Every change of it drives the piece's GATE — the runner's or the build host's compile, a Vite's pushes (U1, U3):
|
|
17
|
+
* live → not live suspends; back to live resumes what was collected; parked stops and starts.
|
|
18
|
+
* - The LAST release updates (UM-D3): a piece left `manual` by the release of its last hold gets one update too — an
|
|
19
|
+
* agent finishing is a request. An explicit update applies at once, whatever holds.
|
|
20
|
+
*
|
|
21
|
+
* Everything that touches a process is behind {@link UpdateGates}; this module only decides, in order, per piece.
|
|
22
|
+
*/
|
|
23
|
+
export type UpdateMode = 'hmr' | 'manual' | 'off';
|
|
24
|
+
export type UpdateState = 'live' | 'held' | 'manual' | 'parked';
|
|
25
|
+
export type PieceKind = 'service' | 'frontend';
|
|
26
|
+
export declare const UPDATE_MODES: readonly UpdateMode[];
|
|
27
|
+
export declare function isUpdateMode(v: unknown): v is UpdateMode;
|
|
28
|
+
/** One workspace's piece, as the gateway knows it. */
|
|
29
|
+
export interface PieceRef {
|
|
30
|
+
workspace: string;
|
|
31
|
+
piece: string;
|
|
32
|
+
kind: PieceKind;
|
|
33
|
+
}
|
|
34
|
+
export interface UpdateHolder {
|
|
35
|
+
/** `claude`, `codex`, `cli`, `dashboard`, … */
|
|
36
|
+
client: string;
|
|
37
|
+
/** The holder's session — the key that counts holds apart. */
|
|
38
|
+
session: string;
|
|
39
|
+
/** A name a person reads: the agent's, the goal's. */
|
|
40
|
+
name?: string;
|
|
41
|
+
}
|
|
42
|
+
export interface UpdateHold {
|
|
43
|
+
holder: UpdateHolder;
|
|
44
|
+
/** `*`: every piece of the workspace (an automatic hold, UM-D7). */
|
|
45
|
+
pieces: '*' | string[];
|
|
46
|
+
since: number;
|
|
47
|
+
until: number;
|
|
48
|
+
why?: string;
|
|
49
|
+
}
|
|
50
|
+
/** What a held piece's gate collected: the files saved since its hold, and the compiles (or pushes) it spared. */
|
|
51
|
+
export interface Collected {
|
|
52
|
+
files: string[];
|
|
53
|
+
/** Unknown for a piece whose saves its gate cannot see (a build host's project out of a live group). */
|
|
54
|
+
count?: number;
|
|
55
|
+
skipped: number;
|
|
56
|
+
since: number;
|
|
57
|
+
}
|
|
58
|
+
export type UpdateOutcomeKind = 'swapped' | 'unchanged' | 'failed' | 'skipped' | 'pending';
|
|
59
|
+
export interface UpdateOutcome {
|
|
60
|
+
piece: string;
|
|
61
|
+
outcome: UpdateOutcomeKind;
|
|
62
|
+
ms: number;
|
|
63
|
+
errors?: string[];
|
|
64
|
+
/** Why `skipped` or `pending`. */
|
|
65
|
+
why?: string;
|
|
66
|
+
}
|
|
67
|
+
/** The processes behind the pieces: each call is for one piece and settles once its gate has done it. */
|
|
68
|
+
export interface UpdateGates {
|
|
69
|
+
/** Stop compiling (pushing) what is saved; collect it. */
|
|
70
|
+
hold(ref: PieceRef): Promise<void>;
|
|
71
|
+
/** Back to live: what was collected is built and applied once. */
|
|
72
|
+
release(ref: PieceRef): Promise<UpdateOutcome>;
|
|
73
|
+
/** Build and apply what was collected once, and stay held. */
|
|
74
|
+
update(ref: PieceRef): Promise<UpdateOutcome>;
|
|
75
|
+
/** Stop it; nothing runs. */
|
|
76
|
+
park(ref: PieceRef): Promise<void>;
|
|
77
|
+
/** Start it again — held from its start when `held` (its first build serves the current files, then it holds). */
|
|
78
|
+
unpark(ref: PieceRef, held: boolean): Promise<void>;
|
|
79
|
+
}
|
|
80
|
+
export interface UpdatesDeps {
|
|
81
|
+
now(): number;
|
|
82
|
+
/** The workspace's pieces now (its services and frontends); unknown workspace → []. */
|
|
83
|
+
pieces(workspace: string): Array<{
|
|
84
|
+
piece: string;
|
|
85
|
+
kind: PieceKind;
|
|
86
|
+
}>;
|
|
87
|
+
/** The declaration's default mode for a piece (lensmcp.json `services.<name>.updates`). */
|
|
88
|
+
declared(workspace: string, piece: string): UpdateMode | undefined;
|
|
89
|
+
/** The checkout's overrides (`.lensmcp/updates.json`), read when the workspace is first asked about. */
|
|
90
|
+
load(workspace: string): Record<string, UpdateMode>;
|
|
91
|
+
save(workspace: string, modes: Record<string, UpdateMode>): void;
|
|
92
|
+
gates: UpdateGates;
|
|
93
|
+
/** A bus event in the workspace's own bus (`updates-held`, `updates-applied`, `updates-mode`). */
|
|
94
|
+
publish?(workspace: string, kind: string, data: Record<string, unknown>): void;
|
|
95
|
+
log?(line: string): void;
|
|
96
|
+
}
|
|
97
|
+
/** A hold lives as long as its agent's session lease (UM-D4): 15 min after its last renewal. */
|
|
98
|
+
export declare const DEFAULT_HOLD_SEC: number;
|
|
99
|
+
/** The longest hold one call can ask for — as `/awake`'s `MAX_AWAKE_SEC`. */
|
|
100
|
+
export declare const MAX_HOLD_SEC: number;
|
|
101
|
+
export interface PieceStatus {
|
|
102
|
+
piece: string;
|
|
103
|
+
kind: PieceKind;
|
|
104
|
+
mode: UpdateMode;
|
|
105
|
+
/** Where the mode came from. */
|
|
106
|
+
modeFrom: 'checkout' | 'declaration' | 'default';
|
|
107
|
+
state: UpdateState;
|
|
108
|
+
holders: Array<UpdateHolder & {
|
|
109
|
+
since: number;
|
|
110
|
+
until: number;
|
|
111
|
+
why?: string;
|
|
112
|
+
}>;
|
|
113
|
+
collected?: Collected;
|
|
114
|
+
lastUpdate?: UpdateOutcome & {
|
|
115
|
+
at: number;
|
|
116
|
+
by?: string;
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
export interface WorkspaceUpdates {
|
|
120
|
+
workspace: string;
|
|
121
|
+
pieces: PieceStatus[];
|
|
122
|
+
holds: UpdateHold[];
|
|
123
|
+
}
|
|
124
|
+
export interface Updates {
|
|
125
|
+
status(workspace: string): WorkspaceUpdates;
|
|
126
|
+
/** The effective state of one piece — what the sweeps and the spawns read. */
|
|
127
|
+
stateOf(workspace: string, piece: string): UpdateState;
|
|
128
|
+
/** Should a fresh tree or generation of this piece start held? (`LENSMCP_UPDATES_HELD=1`) */
|
|
129
|
+
startsHeld(workspace: string, piece: string): boolean;
|
|
130
|
+
setMode(workspace: string, pieces: string[], mode: UpdateMode, by?: string): Promise<WorkspaceUpdates>;
|
|
131
|
+
/** Take or renew `holder`'s hold. Idempotent per holder; a renewal may widen `pieces`. */
|
|
132
|
+
hold(workspace: string, holder: UpdateHolder, opts?: {
|
|
133
|
+
pieces?: string[];
|
|
134
|
+
ttlSec?: number;
|
|
135
|
+
why?: string;
|
|
136
|
+
}): Promise<UpdateHold>;
|
|
137
|
+
/** End `holder`'s hold. Each piece no longer held is released (or, left manual, updated once). */
|
|
138
|
+
release(workspace: string, holder: Pick<UpdateHolder, 'client' | 'session'>, by?: string): Promise<UpdateOutcome[]>;
|
|
139
|
+
/** Update now: every held or manual piece named (default: all of them), whatever holds. */
|
|
140
|
+
apply(workspace: string, pieces?: string[], by?: string): Promise<UpdateOutcome[]>;
|
|
141
|
+
/** A gate's report of what it collected for a piece. */
|
|
142
|
+
collected(workspace: string, piece: string, c: Omit<Collected, 'since'>): void;
|
|
143
|
+
/** End the holds whose lease lapsed — the gateway's sweep calls it. */
|
|
144
|
+
sweep(): Promise<void>;
|
|
145
|
+
/** Forget a workspace (unregistered). */
|
|
146
|
+
forget(workspace: string): void;
|
|
147
|
+
}
|
|
148
|
+
export declare function createUpdates(deps: UpdatesDeps): Updates;
|