@lensmcp/cluster 1.26.2 → 1.26.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/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/services-decl.d.ts +2 -0
- package/executors/gateway/runtime/services-decl.js +1 -1
- 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/executors/trust/trust.impl.js +3 -3
- 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 +1 @@
|
|
|
1
|
-
"use strict";var re=Object.defineProperty;var R=(o,i)=>re(o,"name",{value:i,configurable:!0});var q=Object.defineProperty,s=R((o,i)=>q(o,"name",{value:i,configurable:!0}),"s");Object.defineProperty(exports,"__esModule",{value:!0}),exports.isReplayableRequest=isReplayableRequest,exports.upstreamOpen=upstreamOpen,exports.wedgedMessage=wedgedMessage,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("ringwall/gateway-errors"),body_stall_1=require("ringwall/body-stall"),types_1=require("./types"),pod_probe_1=require("./pod-probe"),gc_notice_1=require("../../../gc-notice"),service_keys_1=require("./service-keys");function isConnError(o){const i=o.code??"";return i==="ECONNREFUSED"||i==="ECONNRESET"||i==="ETIMEDOUT"||i==="EPIPE"||i==="EHOSTUNREACH"||i==="ENOENT"||/ECONNREFUSED|ECONNRESET|socket hang up|EPIPE/i.test(o.message)}R(isConnError,"isConnError"),s(isConnError,"isConnError");function isDroppedConnection(o){const i=o.code??"";return i==="ECONNRESET"||i==="EPIPE"||/ECONNRESET|socket hang up|EPIPE/i.test(o.message)}R(isDroppedConnection,"isDroppedConnection"),s(isDroppedConnection,"isDroppedConnection");const IDEMPOTENT_METHODS=new Set(["GET","HEAD","OPTIONS","PUT","DELETE","TRACE"]);function isReplayableRequest(o){if(!IDEMPOTENT_METHODS.has((o.method??"GET").toUpperCase())||o.headers["transfer-encoding"]!==void 0)return!1;const i=o.headers["content-length"];return!(i!==void 0&&String(i).trim()!=="0")}R(isReplayableRequest,"isReplayableRequest"),s(isReplayableRequest,"isReplayableRequest");function edgeGone(o,i){return i.headersSent||i.writableEnded||i.destroyed===!0||o.aborted===!0}R(edgeGone,"edgeGone"),s(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"];function returnRequestId(o,i){if(o["x-request-id"]!==void 0)return;const g=i.headers["x-request-id"],x=Array.isArray(g)?g[0]:g;typeof x=="string"&&x!==""&&(o["x-request-id"]=x)}R(returnRequestId,"returnRequestId"),s(returnRequestId,"returnRequestId");const httpProxy=require("http-proxy");function declaredFirstByteMs(o){const i=Number(o);return Number.isFinite(i)&&i>0?i:types_1.POD_RESPONSE_TIMEOUT_MS}R(declaredFirstByteMs,"declaredFirstByteMs"),s(declaredFirstByteMs,"declaredFirstByteMs");const secs=s(o=>`${(o/1e3).toFixed(1)}s`,"secs"),upstreams=new WeakMap;function upstreamOpen(o){const i=upstreams.get(o),g=i?.socket;return!!i&&!i.destroyed&&!!g&&!g.destroyed}R(upstreamOpen,"upstreamOpen"),s(upstreamOpen,"upstreamOpen");function wedgedMessage(o,i,g){const x=g.failure==="gone"?"its process is gone":g.failure==="silent"?`it did not answer its liveness check for ${secs(g.silentMs)}`:"it gave no liveness answer";return`Pod ${o} of ${i} sent no response for ${secs(g.heldMs)} and ${x} \u2014 taken out of rotation, and the service is being restarted, so work it was still doing for this request may have been cut short. Retry if the call is safe to repeat.`}R(wedgedMessage,"wedgedMessage"),s(wedgedMessage,"wedgedMessage");function armFirstByteGuard(o){let i,g=!1,x=!1,K=!1,k,C=0,_=(0,body_stall_1.requestBodyArriving)(o.req)?void 0:Date.now();const H=s(()=>{_??=Date.now()},"onBodyEnd");_===void 0&&o.req.once("end",H);const W=s(()=>(_===void 0&&!(0,body_stall_1.requestBodyArriving)(o.req)&&(_=Date.now()),_===void 0?0:Date.now()-_),"heldMs"),I=s(b=>{i=setTimeout(L,b),i.unref?.()},"arm"),L=s(()=>{if(g||!o.pending())return;const b=W();if(o.ceilingMs<=0){if(_!==void 0&&b>=o.firstByteMs){o.onWedged(`no response within ${b}ms (wedged socket) \u2014 evicted + respawning`,{heldMs:b,silentMs:0,probes:0,failure:"deadline"});return}I(_===void 0?o.firstByteMs:o.firstByteMs-b);return}(0,pod_probe_1.probePodAliveVerdict)(o.socketPath,void 0,o.serviceKey).then(({alive:B,failure:j})=>{if(g||!o.pending())return;const D=W();if(!B){if(j==="gone"&&o.upstreamOpen?.()){if(D>=o.ceilingMs){o.onCeiling(`retiring (its socket is gone) and no response within ${D}ms (ceiling ${o.ceilingMs}ms) \u2014 giving up on this request, pod kept`);return}K||(K=!0,o.onRetiring?.(D)),I(Math.max(o.firstByteMs,types_1.POD_ALIVE_PROBE_TIMEOUT_MS));return}if(C+=1,j==="silent"&&(0,gc_notice_1.inAnnouncedGc)(o.socketPath)){k=void 0,I(types_1.POD_ALIVE_PROBE_TIMEOUT_MS);return}if(j==="silent"&&types_1.POD_WEDGE_CONFIRM_MS>0&&(k??=Date.now(),Date.now()-k<types_1.POD_WEDGE_CONFIRM_MS)){I(types_1.POD_ALIVE_PROBE_TIMEOUT_MS);return}const F=k===void 0?0:Date.now()-k,U=j==="gone"?"its socket no longer accepts (the pod process is gone)":j==="silent"?`nothing answered on ${types_1.POD_ALIVE_PATH} for ${F}ms (${C} probe${C===1?"":"s"})`:`no liveness answer on ${types_1.POD_ALIVE_PATH}`;o.onWedged(`no response within ${D}ms and ${U} (wedged socket) \u2014 evicted + respawning`,{heldMs:D,silentMs:F,probes:C,failure:j??"no-route"});return}if(k=void 0,D>=o.ceilingMs){o.onCeiling(`alive on ${types_1.POD_ALIVE_PATH} but no response within ${D}ms (ceiling ${o.ceilingMs}ms) \u2014 giving up on this request, pod kept`,B);return}!x&&_!==void 0&&(x=!0,o.onSlow(D,B)),I(Math.max(o.firstByteMs,types_1.POD_ALIVE_PROBE_TIMEOUT_MS))})},"onDeadline");return I(o.firstByteMs),{clear:s(()=>{g=!0,i&&clearTimeout(i),o.req.removeListener("end",H)},"clear")}}R(armFirstByteGuard,"armFirstByteGuard"),s(armFirstByteGuard,"armFirstByteGuard");function createProxy(o,i,g){const{recordEdge:x,finishTrace:K,traceStep:k,emit:C}=i,_=s((e,r,t,c)=>{const h=c.kind==="pod-evicted";C(h?"error":"warning",`${h?"pod evicted":"request given up"}: ${e.project} (${t}) \u2014 ${c.status}`,`cluster-pod-incident:${e.project}`,{kind:c.kind,project:e.project,pod:t,status:c.status,reason:c.reason,traceId:(0,gateway_errors_1.ensureRequestId)(r),method:r.method,path:(r.url??"").split("?")[0],...c.detail??{}})},"reportPodIncident"),H=s(async(e,r)=>{const t=e.pool;if(!t)return;t.scannedAt=0;let c=(0,discovery_1.pickSock)(t,o.scanTtlMs);return!c&&e.svc&&(k(r,"cold-start",{project:e.project}),await g.ensureUp(e.svc)&&(t.scannedAt=0,c=(0,discovery_1.pickSock)(t,o.scanTtlMs))),c},"anotherPod"),W=s((e,r,t,c,h)=>{console.log(`[gateway] pod ${t} of ${e.project} is gone \u2014 its ${r.method} was not answered, sending it to ${c}`),C("info",`request moved to another pod: ${e.project} (${t} \u2192 ${c})`,`cluster-pod-moved:${e.project}`,{kind:"pod-gone-rerouted",project:e.project,pod:t,to:c,reason:h,traceId:(0,gateway_errors_1.ensureRequestId)(r),method:r.method,path:(r.url??"").split("?")[0]})},"reportPodMoved"),I=s(async e=>{if(!e.lens||!o.lensSupervisor)return"unsupported";let r;const t=new Promise(y=>{r=setTimeout(()=>y("timeout"),types_1.LENS_REQUEST_RECOVERY_WAIT_MS),r.unref?.()}),c=o.lensSupervisor.recover(e.lens,"proxy-connection").then(y=>y?"ready":"failed").catch(()=>"failed"),h=await Promise.race([c,t]);r&&clearTimeout(r);const $=o.lensSupervisor.status(e.lens);return h==="failed"&&(!$||$.state==="ready")?"unsupported":h},"waitForManagedRecovery"),L=s((e,r,t,c,h,$)=>{if(t.headersSent||t.writableEnded||t.destroyed){t.destroyed||t.destroy();return}const y=e.lens?o.lensSupervisor?.status(e.lens):void 0,w=$==="timeout"||y?.state==="starting"||y?.state==="replacing",P=(0,gateway_errors_1.ensureRequestId)(r),M=e.lens?{project:e.project,reason:y?.reason??"connection-failure",generation:y?.generation??0,...w?{retryAfterMs:2e3}:{}}:void 0,l=w?503:502,d=w?"starting":"unavailable";console.error(`[gateway] ${new Date().toISOString()} upstream-error traceId=${P} project=${e.project} target=${String(c)} state=${y?.state??"unmanaged"} generation=${y?.generation??0}: ${h.message}`),C("warning",`upstream unavailable: ${e.project}`,`cluster-upstream:${e.project}`,{kind:"upstream-error",traceId:P,project:e.project,target:String(c),state:y?.state??"unmanaged",generation:y?.generation,error:h.message}),(0,edge_1.sendError)(t,r,l,d,w?`Upstream ${e.project} is restarting.`:`Upstream ${e.project} unavailable.`,M,w?{"retry-after":"2"}:void 0)},"sendTerminalUpstreamError"),b=(0,body_stall_1.createBodyStallGuard)(o.bodyStallMs??types_1.BODY_STALL_MS),B={keepAlive:!0,keepAliveMsecs:3e4,maxSockets:1024,maxFreeSockets:256},j=new http.Agent(B),D=new(require("node:https")).Agent(B),F=s(e=>typeof e=="string"&&e.startsWith("https:")?D:j,"agentForTarget"),U=httpProxy.createProxyServer({xfwd:!1,secure:!1,proxyTimeout:12e4,agent:j}),J=s((e,r,t)=>{const c=s(()=>{t()||e.destroyed||e.destroy()},"onEdgeClose");r.once("close",c),e.once("close",()=>r.removeListener("close",c))},"propagateEdgeCancel");U.on("proxyReq",(e,r,t)=>{upstreams.set(r,e);for(const h of UPSTREAM_CONNECTION_HEADERS)e.removeHeader(h);const c=e.agent?.keepAlive!==!1;e.setHeader("connection",c?"keep-alive":"close"),J(e,t,()=>t.writableEnded)}),U.on("proxyRes",(e,r,t)=>{const c=r.__lensmcpPod;c&&(e.headers["x-lensmcp-pod"]=c),delete e.headers["x-powered-by"],e.headers.server="LensMCP",returnRequestId(e.headers,r),t&&J(e,t,()=>t.writableEnded),t&&b.armResponse(t)});const X=s((e,r,t,c,h=!1)=>{(0,edge_1.stampForwardingHeaders)(o,r),b.arm(r);const $={},y=r.method==="GET"||r.method==="HEAD"||r.method==="OPTIONS";for(const[n,a]of Object.entries(r.headers))a===void 0||n.startsWith(":")||HOP_BY_HOP.has(n)||y&&(n==="content-length"||n==="transfer-encoding")||($[n]=a);let w=http,P;if(typeof e=="object")P={socketPath:e.socketPath,path:r.url,method:r.method,headers:$,agent:j};else{const n=new URL(e),a=n.protocol==="https:";w=a?require("node:https"):http,$.host=n.host,P={protocol:n.protocol,hostname:n.hostname,port:n.port||(a?443:80),path:r.url,method:r.method,headers:$,agent:h?!1:F(e)}}const M=t;M.__lensmcpErrContained||(M.__lensmcpErrContained=!0,t.on("error",()=>{}));let l;const d=s(()=>{t.writableEnded||p.destroy()},"onReqGone"),u=s(()=>{l&&!l.destroyed&&l.destroy()},"onEdgeClose"),m=s(()=>{r.removeListener("error",d),r.removeListener("aborted",d),r.removeListener("close",d),t.removeListener("close",u)},"detach"),p=w.request(P,n=>{if(l=n,c.onResponse(),t.headersSent||t.writableEnded||t.destroyed){n.destroy();return}const a={};for(const[O,N]of Object.entries(n.headers))N===void 0||HOP_BY_HOP.has(O)||(a[O]=N);delete a["x-powered-by"],a.server="LensMCP",returnRequestId(a,r);const S=r.__lensmcpPod;S&&(a["x-lensmcp-pod"]=S);try{t.writeHead(n.statusCode??502,a)}catch(O){console.error("[gateway] h2 relay: bad response header, resetting stream:",O.message),n.destroy(),t.destroyed||t.destroy(O);return}n.pipe(t),b.armResponse(t);const A=s(()=>{!t.writableEnded&&!t.destroyed&&t.destroy()},"abortEdge");n.once("error",A),n.once("close",A),t.on("close",u)});p.once("error",n=>c.onError(n)),upstreams.set(r,p),p.once("close",m),r.on("error",d),r.on("aborted",d),r.on("close",d),y?p.end():r.pipe(p)},"pipeUpstream"),ee=s(async(e,r,t)=>{const c=r.__lensmcpTrace;if(e.pool){const l=e.svc;l&&(l.lastUsed=Date.now(),l.inflight+=1,t.on("close",()=>{l.inflight-=1,l.lastUsed=Date.now()}));let d=(0,discovery_1.pickSock)(e.pool,o.scanTtlMs);if(!d&&l&&(k(c,"cold-start",{project:e.project}),await g.ensureUp(l)&&(d=(0,discovery_1.pickSock)(e.pool,o.scanTtlMs))),l&&d&&g.markUp(l,"observed"),l&&g.scaleUp(l),!d){const m=l?.lastErrors?.length?` Service errors: ${l.lastErrors.join("; ")}`:"";(0,edge_1.sendError)(t,r,503,"unavailable",`Service ${e.project} is not reachable (no pods in ${e.pool.dir}).${m} The watcher recovers and the next request retries automatically.`);return}const u=s((m,p)=>{const n=path.basename(m,".sock");r.__lensmcpPod=n,k(c,"pod-select",{pod:n,pods:e.pool.socks.length,strategy:"round-robin",...p?{movedFrom:p}:{}});let a=!1;const S=s((f,T="unlink")=>{if(e.pool.socks=e.pool.socks.filter(v=>v!==m),e.pool.idx=-1,T==="unlink")try{fs.unlinkSync(m)}catch{}console.error(`[gateway] pod ${n} of ${e.project}: ${f}`)},"evictPod"),A=armFirstByteGuard({socketPath:m,serviceKey:o.serviceKeys[(0,service_keys_1.serviceKeyId)(e.svc?.wsKey,e.project)],req:r,firstByteMs:declaredFirstByteMs(e.svc?.decl?.firstByteMs),ceilingMs:types_1.POD_SLOW_FIRST_BYTE_MS,pending:s(()=>!a&&!t.headersSent&&!t.writableEnded,"pending"),upstreamOpen:s(()=>upstreamOpen(r),"upstreamOpen"),onRetiring:s(f=>{console.log(`[gateway] pod ${n} of ${e.project}: retiring (its socket is gone) but still holds this ${r.method} after ${f}ms \u2014 waiting for it, not evicting`)},"onRetiring"),onWedged:s((f,T)=>{a=!0,S(f),_(e,r,n,{kind:"pod-evicted",status:502,reason:f,detail:T}),(0,edge_1.sendError)(t,r,502,"unavailable",wedgedMessage(n,e.project,T))},"onWedged"),onCeiling:s(f=>{a=!0,S(f,"keep"),_(e,r,n,{kind:"request-gave-up",status:504,reason:f}),(0,edge_1.sendError)(t,r,504,"unavailable",`Pod ${n} of ${e.project} did not answer in time \u2014 retry, or raise cluster.firstByteMs. The pod was kept: the request may still complete there.`)},"onCeiling"),onSlow:s((f,T)=>{console.log(`[gateway] pod ${n} of ${e.project}: slow first byte, pod alive (${f}ms, ${T.inflight} in-flight, ${T.activeWork} background) \u2014 waiting, not evicting. Set cluster.firstByteMs on ${e.project} to size this route's budget.`)},"onSlow")});t.on("close",()=>A.clear());const O=m,N=isReplayableRequest(r);let G=0;const V=s(()=>{G+=1,X({socketPath:O},r,t,{onResponse:s(()=>{A.clear(),a=!0},"onResponse"),onError:s(f=>{if(!a){if(edgeGone(r,t)){A.clear(),a=!0;return}(0,pod_probe_1.podConnectionVerdict)(O,f).then(T=>{if(!a){if(T==="alive"&&G<2&&N&&!edgeGone(r,t)){console.log(`[gateway] pod ${n} of ${e.project}: ${f.message} on one connection, the pod still accepts \u2014 sending the ${r.method} again on a fresh one`),V();return}if(A.clear(),a=!0,T==="gone"){S(f.message);const v=s(()=>{_(e,r,n,{kind:"pod-evicted",status:502,reason:`${f.message} \u2014 its socket no longer accepts (the pod process is gone)${p?`; the request had already been moved here from ${p}`:""}`}),(0,edge_1.sendError)(t,r,502,"unavailable",`Pod ${n} of ${e.project} is gone (${f.message}) \u2014 retry.`)},"giveUp");if(p||!N){v();return}H(e,c).then(E=>{if(!edgeGone(r,t)){if(!E){v();return}W(e,r,n,path.basename(E,".sock"),f.message),u(E,n)}},v);return}console.error(`[gateway] pod ${n} of ${e.project}: ${f.message} on one connection \u2014 the pod still accepts connections, so it stays in the pool`),(0,edge_1.sendError)(t,r,502,"unavailable",`Pod ${n} of ${e.project} dropped the connection \u2014 retry.`)}})}},"onError")})},"sendToPod");V()},"onPod");u(d);return}const h=Date.now()+types_1.UPSTREAM_HEAL_WINDOW_MS;let $=0,y=!1;const w=isReplayableRequest(r);let P=!1;const M=s((l=!1)=>{if(edgeGone(r,t))return;const d=e.target;X(d,r,t,{onResponse:s(()=>{},"onResponse"),onError:s(u=>{if(isConnError(u)&&($+=1),e.lens&&isConnError(u)&&w&&$>=2&&!y&&!edgeGone(r,t)){y=!0,I(e).then(m=>{if(!edgeGone(r,t)){if(m==="ready"){M();return}if(m==="unsupported"&&Date.now()<h){setTimeout(M,types_1.UPSTREAM_HEAL_STEP_MS).unref?.();return}L(e,r,t,e.target,u,m)}});return}if(isConnError(u)&&w&&Date.now()<h&&!edgeGone(r,t)){setTimeout(M,types_1.UPSTREAM_HEAL_STEP_MS).unref?.();return}if(isDroppedConnection(u)&&w&&!P&&!t.headersSent&&!edgeGone(r,t)){P=!0,console.log(`[gateway] ${e.project}: ${u.message} after the heal window \u2014 sending the ${r.method} again on a fresh connection`),M(!0);return}if(t.headersSent||t.writableEnded||t.destroyed){t.destroyed||t.destroy();return}L(e,r,t,d,u)},"onError")},l)},"tryTcp");M()},"forwardNative");return{proxy:U,forward:s(async(e,r,t)=>{const c=Date.now(),h=r.__lensmcpTrace;if(t.on("close",()=>{const d=t.headersSent,u=d?t.statusCode??0:void 0,m=d?t.writableFinished?{}:{aborted:"during-response",error:"the caller went away before the response ended"}:{aborted:"before-response",error:"the caller went away before any response was sent"};x(e,Date.now()-c,u,r.__lensmcpCaller),K(h,e.project,u,{...m,...r.__lensmcpPod?{pod:r.__lensmcpPod}:{},...r.__lensmcpCaller?{caller:r.__lensmcpCaller}:{}},e)}),e.prependPrefix&&!r.url?.startsWith(e.prependPrefix)&&(r.url=e.prependPrefix+(r.url??"/")),(0,edge_1.stampForwardingHeaders)(o,r),b.arm(r),(r.httpVersionMajor??1)>=2){await ee(e,r,t);return}if(e.pool){const d=e.svc;d&&(d.lastUsed=Date.now(),d.inflight+=1,t.on("close",()=>{d.inflight-=1,d.lastUsed=Date.now()}));let u=(0,discovery_1.pickSock)(e.pool,o.scanTtlMs);if(!u&&d&&(k(h,"cold-start",{project:e.project}),await g.ensureUp(d)&&(u=(0,discovery_1.pickSock)(e.pool,o.scanTtlMs))),d&&u&&g.markUp(d,"observed"),d&&g.scaleUp(d),!u){const p=d?.lastErrors?.length?` Service errors: ${d.lastErrors.join("; ")}`:"";(0,edge_1.sendError)(t,r,503,"unavailable",`Service ${e.project} is not reachable (no pods in ${e.pool.dir}).${p} The watcher recovers and the next request retries automatically.`);return}const m=s((p,n)=>{const a=path.basename(p,".sock");r.__lensmcpPod=a,k(h,"pod-select",{pod:a,pods:e.pool.socks.length,strategy:"round-robin",...n?{movedFrom:n}:{}});let S=!1;const A=s((v,E="unlink")=>{if(e.pool.socks=e.pool.socks.filter(Y=>Y!==p),e.pool.idx=-1,E==="unlink")try{fs.unlinkSync(p)}catch{}console.error(`[gateway] pod ${a} of ${e.project}: ${v}`)},"evictPod"),O=armFirstByteGuard({socketPath:p,serviceKey:o.serviceKeys[(0,service_keys_1.serviceKeyId)(e.svc?.wsKey,e.project)],req:r,firstByteMs:declaredFirstByteMs(e.svc?.decl?.firstByteMs),ceilingMs:types_1.POD_SLOW_FIRST_BYTE_MS,pending:s(()=>!S&&!t.headersSent&&!t.writableEnded,"pending"),upstreamOpen:s(()=>upstreamOpen(r),"upstreamOpen"),onRetiring:s(v=>{console.log(`[gateway] pod ${a} of ${e.project}: retiring (its socket is gone) but still holds this ${r.method} after ${v}ms \u2014 waiting for it, not evicting`)},"onRetiring"),onWedged:s((v,E)=>{S=!0,A(v),_(e,r,a,{kind:"pod-evicted",status:502,reason:v,detail:E}),(0,edge_1.sendError)(t,r,502,"unavailable",wedgedMessage(a,e.project,E))},"onWedged"),onCeiling:s(v=>{S=!0,A(v,"keep"),_(e,r,a,{kind:"request-gave-up",status:504,reason:v}),(0,edge_1.sendError)(t,r,504,"unavailable",`Pod ${a} of ${e.project} did not answer in time \u2014 retry, or raise cluster.firstByteMs. The pod was kept: the request may still complete there.`)},"onCeiling"),onSlow:s((v,E)=>{console.log(`[gateway] pod ${a} of ${e.project}: slow first byte, pod alive (${v}ms, ${E.inflight} in-flight, ${E.activeWork} background) \u2014 waiting, not evicting. Set cluster.firstByteMs on ${e.project} to size this route's budget.`)},"onSlow")});t.on("close",()=>O.clear());const N=Math.max(12e4,types_1.POD_SLOW_FIRST_BYTE_MS+6e4),G=p,V=isReplayableRequest(r);let f=0;const T=s(()=>{f+=1;const v=Date.now();U.web(r,t,{target:{socketPath:G},agent:j,proxyTimeout:N},E=>{if(!S){if(edgeGone(r,t)){O.clear(),S=!0;return}(0,pod_probe_1.podConnectionVerdict)(G,E).then(Y=>{if(S)return;const Z=Date.now()-v>=N-250;if(Y==="alive"&&f<2&&V&&!Z&&!edgeGone(r,t)){console.log(`[gateway] pod ${a} of ${e.project}: ${E.message} on one connection, the pod still accepts \u2014 sending the ${r.method} again on a fresh one`),T();return}if(O.clear(),S=!0,Y==="gone"){A(E.message);const Q=s(()=>{_(e,r,a,{kind:"pod-evicted",status:502,reason:`${E.message} \u2014 its socket no longer accepts (the pod process is gone)${n?`; the request had already been moved here from ${n}`:""}`}),(0,edge_1.sendError)(t,r,502,"unavailable",`Pod ${a} of ${e.project} is gone (${E.message}) \u2014 retry.`)},"giveUp");if(n||!V||Z){Q();return}H(e,h).then(z=>{if(!edgeGone(r,t)){if(!z){Q();return}W(e,r,a,path.basename(z,".sock"),E.message),m(z,a)}},Q);return}console.error(`[gateway] pod ${a} of ${e.project}: ${E.message} on one connection \u2014 the pod still accepts connections, so it stays in the pool`),(0,edge_1.sendError)(t,r,502,"unavailable",`Pod ${a} of ${e.project} dropped the connection \u2014 retry.`)})}})},"sendToPod");T()},"onPod");m(u);return}const $=Date.now()+types_1.UPSTREAM_HEAL_WINDOW_MS;let y=0,w=!1;const P=isReplayableRequest(r);let M=!1;const l=s((d=!1)=>{if(edgeGone(r,t))return;const u=e.target,m={target:u,autoRewrite:typeof u=="string",changeOrigin:!0,agent:d?!1:F(u)};U.web(r,t,m,p=>{if(isConnError(p)&&(y+=1),e.lens&&isConnError(p)&&P&&y>=2&&!w&&!edgeGone(r,t)){w=!0,I(e).then(n=>{if(!edgeGone(r,t)){if(n==="ready"){l();return}if(n==="unsupported"&&Date.now()<$){setTimeout(l,types_1.UPSTREAM_HEAL_STEP_MS).unref?.();return}L(e,r,t,e.target,p,n)}});return}if(isConnError(p)&&P&&Date.now()<$&&!edgeGone(r,t)){setTimeout(l,types_1.UPSTREAM_HEAL_STEP_MS).unref?.();return}if(isDroppedConnection(p)&&P&&!M&&!t.headersSent&&!edgeGone(r,t)){M=!0,console.log(`[gateway] ${e.project}: ${p.message} after the heal window \u2014 sending the ${r.method} again on a fresh connection`),l(!0);return}t.destroyed||L(e,r,t,u,p)})},"tryTcp");l()},"forward"),agentForTarget:F,destroyAgents:s(()=>{b.stop(),j.destroy(),D.destroy()},"destroyAgents"),closeProxy:s(()=>{try{U.close?.()}catch{}},"closeProxy")}}R(createProxy,"createProxy"),s(createProxy,"createProxy");
|
|
1
|
+
"use strict";var re=Object.defineProperty;var R=(o,i)=>re(o,"name",{value:i,configurable:!0});var q=Object.defineProperty,s=R((o,i)=>q(o,"name",{value:i,configurable:!0}),"s");Object.defineProperty(exports,"__esModule",{value:!0}),exports.isReplayableRequest=isReplayableRequest,exports.upstreamOpen=upstreamOpen,exports.wedgedMessage=wedgedMessage,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("ringwall/gateway-errors"),body_stall_1=require("ringwall/body-stall"),types_1=require("./types"),pod_probe_1=require("./pod-probe"),gc_notice_1=require("../../../gc-notice"),remote_instances_1=require("./remote-instances"),run_routes_1=require("./run-routes"),service_keys_1=require("./service-keys");function isConnError(o){const i=o.code??"";return i==="ECONNREFUSED"||i==="ECONNRESET"||i==="ETIMEDOUT"||i==="EPIPE"||i==="EHOSTUNREACH"||i==="ENOENT"||/ECONNREFUSED|ECONNRESET|socket hang up|EPIPE/i.test(o.message)}R(isConnError,"isConnError"),s(isConnError,"isConnError");function isDroppedConnection(o){const i=o.code??"";return i==="ECONNRESET"||i==="EPIPE"||/ECONNRESET|socket hang up|EPIPE/i.test(o.message)}R(isDroppedConnection,"isDroppedConnection"),s(isDroppedConnection,"isDroppedConnection");const IDEMPOTENT_METHODS=new Set(["GET","HEAD","OPTIONS","PUT","DELETE","TRACE"]);function isReplayableRequest(o){if(!IDEMPOTENT_METHODS.has((o.method??"GET").toUpperCase())||o.headers["transfer-encoding"]!==void 0)return!1;const i=o.headers["content-length"];return!(i!==void 0&&String(i).trim()!=="0")}R(isReplayableRequest,"isReplayableRequest"),s(isReplayableRequest,"isReplayableRequest");function edgeGone(o,i){return i.headersSent||i.writableEnded||i.destroyed===!0||o.aborted===!0}R(edgeGone,"edgeGone"),s(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"];function returnRequestId(o,i){if(o["x-request-id"]!==void 0)return;const g=i.headers["x-request-id"],I=Array.isArray(g)?g[0]:g;typeof I=="string"&&I!==""&&(o["x-request-id"]=I)}R(returnRequestId,"returnRequestId"),s(returnRequestId,"returnRequestId");const httpProxy=require("http-proxy");function declaredFirstByteMs(o){const i=Number(o);return Number.isFinite(i)&&i>0?i:types_1.POD_RESPONSE_TIMEOUT_MS}R(declaredFirstByteMs,"declaredFirstByteMs"),s(declaredFirstByteMs,"declaredFirstByteMs");const secs=s(o=>`${(o/1e3).toFixed(1)}s`,"secs"),upstreams=new WeakMap;function upstreamOpen(o){const i=upstreams.get(o),g=i?.socket;return!!i&&!i.destroyed&&!!g&&!g.destroyed}R(upstreamOpen,"upstreamOpen"),s(upstreamOpen,"upstreamOpen");function wedgedMessage(o,i,g){const I=g.failure==="gone"?"its process is gone":g.failure==="silent"?`it did not answer its liveness check for ${secs(g.silentMs)}`:"it gave no liveness answer";return`Pod ${o} of ${i} sent no response for ${secs(g.heldMs)} and ${I} \u2014 taken out of rotation, and the service is being restarted, so work it was still doing for this request may have been cut short. Retry if the call is safe to repeat.`}R(wedgedMessage,"wedgedMessage"),s(wedgedMessage,"wedgedMessage");function armFirstByteGuard(o){let i,g=!1,I=!1,G=!1,M,C=0,$=(0,body_stall_1.requestBodyArriving)(o.req)?void 0:Date.now();const H=s(()=>{$??=Date.now()},"onBodyEnd");$===void 0&&o.req.once("end",H);const W=s(()=>($===void 0&&!(0,body_stall_1.requestBodyArriving)(o.req)&&($=Date.now()),$===void 0?0:Date.now()-$),"heldMs"),x=s(T=>{i=setTimeout(L,T),i.unref?.()},"arm"),L=s(()=>{if(g||!o.pending())return;const T=W();if(o.ceilingMs<=0){if($!==void 0&&T>=o.firstByteMs){o.onWedged(`no response within ${T}ms (wedged socket) \u2014 evicted + respawning`,{heldMs:T,silentMs:0,probes:0,failure:"deadline"});return}x($===void 0?o.firstByteMs:o.firstByteMs-T);return}(0,pod_probe_1.probePodAliveVerdict)(o.socketPath,void 0,o.serviceKey).then(({alive:B,failure:O})=>{if(g||!o.pending())return;const D=W();if(!B){if(O==="gone"&&o.upstreamOpen?.()){if(D>=o.ceilingMs){o.onCeiling(`retiring (its socket is gone) and no response within ${D}ms (ceiling ${o.ceilingMs}ms) \u2014 giving up on this request, pod kept`);return}G||(G=!0,o.onRetiring?.(D)),x(Math.max(o.firstByteMs,types_1.POD_ALIVE_PROBE_TIMEOUT_MS));return}if(C+=1,O==="silent"&&(0,gc_notice_1.inAnnouncedGc)(o.socketPath)){M=void 0,x(types_1.POD_ALIVE_PROBE_TIMEOUT_MS);return}if(O==="silent"&&types_1.POD_WEDGE_CONFIRM_MS>0&&(M??=Date.now(),Date.now()-M<types_1.POD_WEDGE_CONFIRM_MS)){x(types_1.POD_ALIVE_PROBE_TIMEOUT_MS);return}const F=M===void 0?0:Date.now()-M,U=O==="gone"?"its socket no longer accepts (the pod process is gone)":O==="silent"?`nothing answered on ${types_1.POD_ALIVE_PATH} for ${F}ms (${C} probe${C===1?"":"s"})`:`no liveness answer on ${types_1.POD_ALIVE_PATH}`;o.onWedged(`no response within ${D}ms and ${U} (wedged socket) \u2014 evicted + respawning`,{heldMs:D,silentMs:F,probes:C,failure:O??"no-route"});return}if(M=void 0,D>=o.ceilingMs){o.onCeiling(`alive on ${types_1.POD_ALIVE_PATH} but no response within ${D}ms (ceiling ${o.ceilingMs}ms) \u2014 giving up on this request, pod kept`,B);return}!I&&$!==void 0&&(I=!0,o.onSlow(D,B)),x(Math.max(o.firstByteMs,types_1.POD_ALIVE_PROBE_TIMEOUT_MS))})},"onDeadline");return x(o.firstByteMs),{clear:s(()=>{g=!0,i&&clearTimeout(i),o.req.removeListener("end",H)},"clear")}}R(armFirstByteGuard,"armFirstByteGuard"),s(armFirstByteGuard,"armFirstByteGuard");function createProxy(o,i,g){const{recordEdge:I,finishTrace:G,traceStep:M,emit:C}=i,$=s((e,r,t,d)=>{const h=d.kind==="pod-evicted";C(h?"error":"warning",`${h?"pod evicted":"request given up"}: ${e.project} (${t}) \u2014 ${d.status}`,`cluster-pod-incident:${e.project}`,{kind:d.kind,project:e.project,pod:t,status:d.status,reason:d.reason,traceId:(0,gateway_errors_1.ensureRequestId)(r),method:r.method,path:(r.url??"").split("?")[0],...d.detail??{}})},"reportPodIncident"),H=s(async(e,r)=>{const t=e.pool;if(!t)return;t.scannedAt=0;let d=(0,discovery_1.pickSock)(t,o.scanTtlMs);return!d&&e.svc&&(M(r,"cold-start",{project:e.project}),await g.ensureUp(e.svc)&&(t.scannedAt=0,d=(0,discovery_1.pickSock)(t,o.scanTtlMs))),d},"anotherPod"),W=s((e,r,t,d,h)=>{console.log(`[gateway] pod ${t} of ${e.project} is gone \u2014 its ${r.method} was not answered, sending it to ${d}`),C("info",`request moved to another pod: ${e.project} (${t} \u2192 ${d})`,`cluster-pod-moved:${e.project}`,{kind:"pod-gone-rerouted",project:e.project,pod:t,to:d,reason:h,traceId:(0,gateway_errors_1.ensureRequestId)(r),method:r.method,path:(r.url??"").split("?")[0]})},"reportPodMoved"),x=s(async e=>{if(!e.lens||!o.lensSupervisor)return"unsupported";let r;const t=new Promise(S=>{r=setTimeout(()=>S("timeout"),types_1.LENS_REQUEST_RECOVERY_WAIT_MS),r.unref?.()}),d=o.lensSupervisor.recover(e.lens,"proxy-connection").then(S=>S?"ready":"failed").catch(()=>"failed"),h=await Promise.race([d,t]);r&&clearTimeout(r);const _=o.lensSupervisor.status(e.lens);return h==="failed"&&(!_||_.state==="ready")?"unsupported":h},"waitForManagedRecovery"),L=s((e,r,t,d,h,_)=>{if(t.headersSent||t.writableEnded||t.destroyed){t.destroyed||t.destroy();return}const S=e.lens?.workspaceKey??e.wsKey;if(e.lens&&S&&o.updates?.stateOf(S,e.project)==="parked"){(0,edge_1.sendError)(t,r,503,"unavailable",`${e.project} is parked (update mode off). \`lensmcp updates mode ${e.project} hmr\` or the Cluster tab starts it.`);return}const v=e.lens?o.lensSupervisor?.status(e.lens):void 0,w=_==="timeout"||v?.state==="starting"||v?.state==="replacing",P=(0,gateway_errors_1.ensureRequestId)(r),l=e.lens?{project:e.project,reason:v?.reason??"connection-failure",generation:v?.generation??0,...w?{retryAfterMs:2e3}:{}}:void 0,a=w?503:502,p=w?"starting":"unavailable";console.error(`[gateway] ${new Date().toISOString()} upstream-error traceId=${P} project=${e.project} target=${String(d)} state=${v?.state??"unmanaged"} generation=${v?.generation??0}: ${h.message}`),C("warning",`upstream unavailable: ${e.project}`,`cluster-upstream:${e.project}`,{kind:"upstream-error",traceId:P,project:e.project,target:String(d),state:v?.state??"unmanaged",generation:v?.generation,error:h.message}),(0,edge_1.sendError)(t,r,a,p,w?`Upstream ${e.project} is restarting.`:`Upstream ${e.project} unavailable.`,l,w?{"retry-after":"2"}:void 0)},"sendTerminalUpstreamError"),T=(0,body_stall_1.createBodyStallGuard)(o.bodyStallMs??types_1.BODY_STALL_MS),B={keepAlive:!0,keepAliveMsecs:3e4,maxSockets:1024,maxFreeSockets:256},O=new http.Agent(B),D=new(require("node:https")).Agent(B),F=s(e=>typeof e=="string"&&e.startsWith("https:")?D:O,"agentForTarget"),U=httpProxy.createProxyServer({xfwd:!1,secure:!1,proxyTimeout:12e4,agent:O}),J=s((e,r,t)=>{const d=s(()=>{t()||e.destroyed||e.destroy()},"onEdgeClose");r.once("close",d),e.once("close",()=>r.removeListener("close",d))},"propagateEdgeCancel");U.on("proxyReq",(e,r,t)=>{upstreams.set(r,e);for(const h of UPSTREAM_CONNECTION_HEADERS)e.removeHeader(h);const d=e.agent?.keepAlive!==!1;e.setHeader("connection",d?"keep-alive":"close"),J(e,t,()=>t.writableEnded)}),U.on("proxyRes",(e,r,t)=>{const d=r.__lensmcpPod;d&&(e.headers["x-lensmcp-pod"]=d),delete e.headers["x-powered-by"],e.headers.server="LensMCP",returnRequestId(e.headers,r),t&&J(e,t,()=>t.writableEnded),t&&T.armResponse(t)});const X=s((e,r,t,d,h=!1)=>{(0,edge_1.stampForwardingHeaders)(o,r),T.arm(r);const _={},S=r.method==="GET"||r.method==="HEAD"||r.method==="OPTIONS";for(const[n,c]of Object.entries(r.headers))c===void 0||n.startsWith(":")||HOP_BY_HOP.has(n)||S&&(n==="content-length"||n==="transfer-encoding")||(_[n]=c);let v=http,w;if(typeof e=="object")e.host&&(_.host=e.port?`${e.host}:${e.port}`:e.host),w={socketPath:e.socketPath,path:r.url,method:r.method,headers:_,agent:h?!1:O};else{const n=new URL(e),c=n.protocol==="https:";v=c?require("node:https"):http,_.host=n.host,w={protocol:n.protocol,hostname:n.hostname,port:n.port||(c?443:80),path:r.url,method:r.method,headers:_,agent:h?!1:F(e)}}const P=t;P.__lensmcpErrContained||(P.__lensmcpErrContained=!0,t.on("error",()=>{}));let l;const a=s(()=>{t.writableEnded||u.destroy()},"onReqGone"),p=s(()=>{l&&!l.destroyed&&l.destroy()},"onEdgeClose"),f=s(()=>{r.removeListener("error",a),r.removeListener("aborted",a),r.removeListener("close",a),t.removeListener("close",p)},"detach"),u=v.request(w,n=>{if(l=n,d.onResponse(),t.headersSent||t.writableEnded||t.destroyed){n.destroy();return}const c={};for(const[j,N]of Object.entries(n.headers))N===void 0||HOP_BY_HOP.has(j)||(c[j]=N);delete c["x-powered-by"],c.server="LensMCP",returnRequestId(c,r);const b=r.__lensmcpPod;b&&(c["x-lensmcp-pod"]=b);try{t.writeHead(n.statusCode??502,c)}catch(j){console.error("[gateway] h2 relay: bad response header, resetting stream:",j.message),n.destroy(),t.destroyed||t.destroy(j);return}n.pipe(t),T.armResponse(t);const A=s(()=>{!t.writableEnded&&!t.destroyed&&t.destroy()},"abortEdge");n.once("error",A),n.once("close",A),t.on("close",p)});u.once("error",n=>d.onError(n)),upstreams.set(r,u),u.once("close",f),r.on("error",a),r.on("aborted",a),r.on("close",a),S?u.end():r.pipe(u)},"pipeUpstream"),ee=s(async(e,r,t)=>{const d=r.__lensmcpTrace;if(e.pool){const l=e.svc;l&&(l.lastUsed=Date.now(),l.inflight+=1,t.on("close",()=>{l.inflight-=1,l.lastUsed=Date.now()}));let a=(0,discovery_1.pickSock)(e.pool,o.scanTtlMs);if(!a&&l&&(M(d,"cold-start",{project:e.project}),await g.ensureUp(l)&&(a=(0,discovery_1.pickSock)(e.pool,o.scanTtlMs))),l&&a&&g.markUp(l,"observed"),l&&g.scaleUp(l),!a&&l&&o.updates?.stateOf(l.wsKey,l.project)==="parked"){(0,edge_1.sendError)(t,r,503,"unavailable",`Service ${e.project} is parked (update mode off). \`lensmcp updates mode ${e.project} hmr\` or the Cluster tab starts it.`);return}if(!a){const f=l?.lastErrors?.length?` Service errors: ${l.lastErrors.join("; ")}`:"";(0,edge_1.sendError)(t,r,503,"unavailable",`Service ${e.project} is not reachable (no pods in ${e.pool.dir}).${f} The watcher recovers and the next request retries automatically.`);return}const p=s((f,u)=>{const n=path.basename(f,".sock");r.__lensmcpPod=n,M(d,"pod-select",{pod:n,pods:e.pool.socks.length,strategy:"round-robin",...u?{movedFrom:u}:{}});let c=!1;const b=s((m,k="unlink")=>{if(e.pool.socks=e.pool.socks.filter(y=>y!==f),e.pool.idx=-1,k==="unlink")try{fs.unlinkSync(f)}catch{}console.error(`[gateway] pod ${n} of ${e.project}: ${m}`)},"evictPod"),A=armFirstByteGuard({socketPath:f,serviceKey:o.serviceKeys[(0,service_keys_1.serviceKeyId)(e.svc?.wsKey,e.project)],req:r,firstByteMs:declaredFirstByteMs(e.svc?.decl?.firstByteMs),ceilingMs:types_1.POD_SLOW_FIRST_BYTE_MS,pending:s(()=>!c&&!t.headersSent&&!t.writableEnded,"pending"),upstreamOpen:s(()=>upstreamOpen(r),"upstreamOpen"),onRetiring:s(m=>{console.log(`[gateway] pod ${n} of ${e.project}: retiring (its socket is gone) but still holds this ${r.method} after ${m}ms \u2014 waiting for it, not evicting`)},"onRetiring"),onWedged:s((m,k)=>{c=!0,b(m),$(e,r,n,{kind:"pod-evicted",status:502,reason:m,detail:k}),(0,edge_1.sendError)(t,r,502,"unavailable",wedgedMessage(n,e.project,k))},"onWedged"),onCeiling:s(m=>{c=!0,b(m,"keep"),$(e,r,n,{kind:"request-gave-up",status:504,reason:m}),(0,edge_1.sendError)(t,r,504,"unavailable",`Pod ${n} of ${e.project} did not answer in time \u2014 retry, or raise cluster.firstByteMs. The pod was kept: the request may still complete there.`)},"onCeiling"),onSlow:s((m,k)=>{console.log(`[gateway] pod ${n} of ${e.project}: slow first byte, pod alive (${m}ms, ${k.inflight} in-flight, ${k.activeWork} background) \u2014 waiting, not evicting. Set cluster.firstByteMs on ${e.project} to size this route's budget.`)},"onSlow")});t.on("close",()=>A.clear());const j=f,N=isReplayableRequest(r);let K=0;const V=s(()=>{K+=1,X({socketPath:j},r,t,{onResponse:s(()=>{A.clear(),c=!0},"onResponse"),onError:s(m=>{if(!c){if(edgeGone(r,t)){A.clear(),c=!0;return}(0,pod_probe_1.podConnectionVerdict)(j,m).then(k=>{if(!c){if(k==="alive"&&K<2&&N&&!edgeGone(r,t)){console.log(`[gateway] pod ${n} of ${e.project}: ${m.message} on one connection, the pod still accepts \u2014 sending the ${r.method} again on a fresh one`),V();return}if(A.clear(),c=!0,k==="gone"){b(m.message);const y=s(()=>{$(e,r,n,{kind:"pod-evicted",status:502,reason:`${m.message} \u2014 its socket no longer accepts (the pod process is gone)${u?`; the request had already been moved here from ${u}`:""}`}),(0,edge_1.sendError)(t,r,502,"unavailable",`Pod ${n} of ${e.project} is gone (${m.message}) \u2014 retry.`)},"giveUp");if(u||!N){y();return}H(e,d).then(E=>{if(!edgeGone(r,t)){if(!E){y();return}W(e,r,n,path.basename(E,".sock"),m.message),p(E,n)}},y);return}console.error(`[gateway] pod ${n} of ${e.project}: ${m.message} on one connection \u2014 the pod still accepts connections, so it stays in the pool`),(0,edge_1.sendError)(t,r,502,"unavailable",`Pod ${n} of ${e.project} dropped the connection \u2014 retry.`)}})}},"onError")})},"sendToPod");V()},"onPod");p(a);return}const h=Date.now()+types_1.UPSTREAM_HEAL_WINDOW_MS;let _=0,S=!1;const v=isReplayableRequest(r);let w=!1;const P=s((l=!1)=>{if(edgeGone(r,t))return;const a=(0,remote_instances_1.remoteInstanceUpstream)(e)??(0,run_routes_1.runSocketUpstream)(e)??e.target;X(a,r,t,{onResponse:s(()=>{},"onResponse"),onError:s(p=>{if(isConnError(p)&&(_+=1),e.lens&&isConnError(p)&&v&&_>=2&&!S&&!edgeGone(r,t)){S=!0,x(e).then(f=>{if(!edgeGone(r,t)){if(f==="ready"){P();return}if(f==="unsupported"&&Date.now()<h){setTimeout(P,types_1.UPSTREAM_HEAL_STEP_MS).unref?.();return}L(e,r,t,e.target,p,f)}});return}if(isConnError(p)&&v&&Date.now()<h&&!edgeGone(r,t)){setTimeout(P,types_1.UPSTREAM_HEAL_STEP_MS).unref?.();return}if(isDroppedConnection(p)&&v&&!w&&!t.headersSent&&!edgeGone(r,t)){w=!0,console.log(`[gateway] ${e.project}: ${p.message} after the heal window \u2014 sending the ${r.method} again on a fresh connection`),P(!0);return}if(t.headersSent||t.writableEnded||t.destroyed){t.destroyed||t.destroy();return}L(e,r,t,a,p)},"onError")},l)},"tryTcp");P()},"forwardNative");return{proxy:U,forward:s(async(e,r,t)=>{const d=Date.now(),h=r.__lensmcpTrace;if(t.on("close",()=>{const a=t.headersSent,p=a?t.statusCode??0:void 0,f=a?t.writableFinished?{}:{aborted:"during-response",error:"the caller went away before the response ended"}:{aborted:"before-response",error:"the caller went away before any response was sent"};I(e,Date.now()-d,p,r.__lensmcpCaller),G(h,e.project,p,{...f,...r.__lensmcpPod?{pod:r.__lensmcpPod}:{},...r.__lensmcpCaller?{caller:r.__lensmcpCaller}:{}},e)}),e.prependPrefix&&!r.url?.startsWith(e.prependPrefix)&&(r.url=e.prependPrefix+(r.url??"/")),(0,edge_1.stampForwardingHeaders)(o,r),T.arm(r),(r.httpVersionMajor??1)>=2){await ee(e,r,t);return}if(e.pool){const a=e.svc;a&&(a.lastUsed=Date.now(),a.inflight+=1,t.on("close",()=>{a.inflight-=1,a.lastUsed=Date.now()}));let p=(0,discovery_1.pickSock)(e.pool,o.scanTtlMs);if(!p&&a&&(M(h,"cold-start",{project:e.project}),await g.ensureUp(a)&&(p=(0,discovery_1.pickSock)(e.pool,o.scanTtlMs))),a&&p&&g.markUp(a,"observed"),a&&g.scaleUp(a),!p&&a&&o.updates?.stateOf(a.wsKey,a.project)==="parked"){(0,edge_1.sendError)(t,r,503,"unavailable",`Service ${e.project} is parked (update mode off). \`lensmcp updates mode ${e.project} hmr\` or the Cluster tab starts it.`);return}if(!p){const u=a?.lastErrors?.length?` Service errors: ${a.lastErrors.join("; ")}`:"";(0,edge_1.sendError)(t,r,503,"unavailable",`Service ${e.project} is not reachable (no pods in ${e.pool.dir}).${u} The watcher recovers and the next request retries automatically.`);return}const f=s((u,n)=>{const c=path.basename(u,".sock");r.__lensmcpPod=c,M(h,"pod-select",{pod:c,pods:e.pool.socks.length,strategy:"round-robin",...n?{movedFrom:n}:{}});let b=!1;const A=s((y,E="unlink")=>{if(e.pool.socks=e.pool.socks.filter(Y=>Y!==u),e.pool.idx=-1,E==="unlink")try{fs.unlinkSync(u)}catch{}console.error(`[gateway] pod ${c} of ${e.project}: ${y}`)},"evictPod"),j=armFirstByteGuard({socketPath:u,serviceKey:o.serviceKeys[(0,service_keys_1.serviceKeyId)(e.svc?.wsKey,e.project)],req:r,firstByteMs:declaredFirstByteMs(e.svc?.decl?.firstByteMs),ceilingMs:types_1.POD_SLOW_FIRST_BYTE_MS,pending:s(()=>!b&&!t.headersSent&&!t.writableEnded,"pending"),upstreamOpen:s(()=>upstreamOpen(r),"upstreamOpen"),onRetiring:s(y=>{console.log(`[gateway] pod ${c} of ${e.project}: retiring (its socket is gone) but still holds this ${r.method} after ${y}ms \u2014 waiting for it, not evicting`)},"onRetiring"),onWedged:s((y,E)=>{b=!0,A(y),$(e,r,c,{kind:"pod-evicted",status:502,reason:y,detail:E}),(0,edge_1.sendError)(t,r,502,"unavailable",wedgedMessage(c,e.project,E))},"onWedged"),onCeiling:s(y=>{b=!0,A(y,"keep"),$(e,r,c,{kind:"request-gave-up",status:504,reason:y}),(0,edge_1.sendError)(t,r,504,"unavailable",`Pod ${c} of ${e.project} did not answer in time \u2014 retry, or raise cluster.firstByteMs. The pod was kept: the request may still complete there.`)},"onCeiling"),onSlow:s((y,E)=>{console.log(`[gateway] pod ${c} of ${e.project}: slow first byte, pod alive (${y}ms, ${E.inflight} in-flight, ${E.activeWork} background) \u2014 waiting, not evicting. Set cluster.firstByteMs on ${e.project} to size this route's budget.`)},"onSlow")});t.on("close",()=>j.clear());const N=Math.max(12e4,types_1.POD_SLOW_FIRST_BYTE_MS+6e4),K=u,V=isReplayableRequest(r);let m=0;const k=s(()=>{m+=1;const y=Date.now();U.web(r,t,{target:{socketPath:K},agent:O,proxyTimeout:N},E=>{if(!b){if(edgeGone(r,t)){j.clear(),b=!0;return}(0,pod_probe_1.podConnectionVerdict)(K,E).then(Y=>{if(b)return;const Z=Date.now()-y>=N-250;if(Y==="alive"&&m<2&&V&&!Z&&!edgeGone(r,t)){console.log(`[gateway] pod ${c} of ${e.project}: ${E.message} on one connection, the pod still accepts \u2014 sending the ${r.method} again on a fresh one`),k();return}if(j.clear(),b=!0,Y==="gone"){A(E.message);const Q=s(()=>{$(e,r,c,{kind:"pod-evicted",status:502,reason:`${E.message} \u2014 its socket no longer accepts (the pod process is gone)${n?`; the request had already been moved here from ${n}`:""}`}),(0,edge_1.sendError)(t,r,502,"unavailable",`Pod ${c} of ${e.project} is gone (${E.message}) \u2014 retry.`)},"giveUp");if(n||!V||Z){Q();return}H(e,h).then(z=>{if(!edgeGone(r,t)){if(!z){Q();return}W(e,r,c,path.basename(z,".sock"),E.message),f(z,c)}},Q);return}console.error(`[gateway] pod ${c} of ${e.project}: ${E.message} on one connection \u2014 the pod still accepts connections, so it stays in the pool`),(0,edge_1.sendError)(t,r,502,"unavailable",`Pod ${c} of ${e.project} dropped the connection \u2014 retry.`)})}})},"sendToPod");k()},"onPod");f(p);return}const _=Date.now()+types_1.UPSTREAM_HEAL_WINDOW_MS;let S=0,v=!1;const w=isReplayableRequest(r);let P=!1;const l=s((a=!1)=>{if(edgeGone(r,t))return;const p=(0,remote_instances_1.remoteInstanceUpstream)(e)??(0,run_routes_1.runSocketUpstream)(e)??e.target,f={target:p,autoRewrite:typeof p=="string",changeOrigin:!e.remote,agent:a?!1:F(p)};U.web(r,t,f,u=>{if(isConnError(u)&&(S+=1),e.lens&&isConnError(u)&&w&&S>=2&&!v&&!edgeGone(r,t)){v=!0,x(e).then(n=>{if(!edgeGone(r,t)){if(n==="ready"){l();return}if(n==="unsupported"&&Date.now()<_){setTimeout(l,types_1.UPSTREAM_HEAL_STEP_MS).unref?.();return}L(e,r,t,e.target,u,n)}});return}if(isConnError(u)&&w&&Date.now()<_&&!edgeGone(r,t)){setTimeout(l,types_1.UPSTREAM_HEAL_STEP_MS).unref?.();return}if(isDroppedConnection(u)&&w&&!P&&!t.headersSent&&!edgeGone(r,t)){P=!0,console.log(`[gateway] ${e.project}: ${u.message} after the heal window \u2014 sending the ${r.method} again on a fresh connection`),l(!0);return}t.destroyed||L(e,r,t,p,u)})},"tryTcp");l()},"forward"),agentForTarget:F,destroyAgents:s(()=>{T.stop(),O.destroy(),D.destroy()},"destroyAgents"),closeProxy:s(()=>{try{U.close?.()}catch{}},"closeProxy")}}R(createProxy,"createProxy"),s(createProxy,"createProxy");
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
import type { ParkedHostLookup } from './on-demand';
|
|
2
|
+
import type { RouteRegistry } from './route-registry';
|
|
3
|
+
import type { Route } from './types';
|
|
4
|
+
/** What a remote instance's route says its project is — in a traffic edge, a trace, a 502. */
|
|
5
|
+
export declare const REMOTE_INSTANCE_PROJECT = "(remote)";
|
|
6
|
+
/** The id every remote instance's routes are kept under in the registry's standalone routes. */
|
|
7
|
+
export declare const REMOTE_INSTANCES_STANDALONE_ID = "(remote-instances)";
|
|
8
|
+
/** The longest lease (s): a forgotten route lives no longer than this. */
|
|
9
|
+
export declare const MAX_REMOTE_INSTANCE_SEC: number;
|
|
10
|
+
/** The most remote instances routed at once: each is a handful of names on the leaf certificate. */
|
|
11
|
+
export declare const MAX_REMOTE_INSTANCES = 16;
|
|
12
|
+
/** The most a `POST /remote-instance` body may be. */
|
|
13
|
+
export declare const REMOTE_INSTANCE_BODY_BYTES = 4096;
|
|
14
|
+
/**
|
|
15
|
+
* A remote instance's id: letters, digits, `_` and `-`, 8 to 40 characters — safe in a log line and a path, and short
|
|
16
|
+
* enough that `<home>/.lensmcp/peers/instances/<id>.sock` fits a unix socket's 103 bytes under a usual home.
|
|
17
|
+
*/
|
|
18
|
+
export declare const REMOTE_INSTANCE_ID_PATTERN: RegExp;
|
|
19
|
+
/**
|
|
20
|
+
* What a remote instance's name begins with. It is a goal's worktree on a worker, named as LensMCP names one
|
|
21
|
+
* (`g-<slug>-<id6>`, apps/agent `lib/goal-worktrees.ts`): so its apex never takes a name the main checkout serves under
|
|
22
|
+
* its wildcard — a tenant's (`acme.<apex>`), which an exact route would otherwise take from it.
|
|
23
|
+
*/
|
|
24
|
+
export declare const REMOTE_INSTANCE_NAME_PREFIX = "g-";
|
|
25
|
+
/** The label of a remote instance's lens host: `lensmcp.<apex>` — an origin of its own (see the module's comment). */
|
|
26
|
+
export declare const REMOTE_LENS_LABEL = "lensmcp";
|
|
27
|
+
/** The lens dashboard's base path, as the worker's gateway serves it: ONE path segment (`/<instance key>`). */
|
|
28
|
+
export declare const REMOTE_DASHBOARD_BASE_PATTERN: RegExp;
|
|
29
|
+
/** `POST /remote-instance`. */
|
|
30
|
+
export interface RemoteInstanceRouteRequest {
|
|
31
|
+
/** The instance, as the hub names it ({@link REMOTE_INSTANCE_ID_PATTERN}): its socket is named for it. */
|
|
32
|
+
instanceId: string;
|
|
33
|
+
/** A workspace registered with this gateway — the main checkout of the instance's project: its apex is under that one's. */
|
|
34
|
+
wsKey: string;
|
|
35
|
+
/** The instance's apex as the worker's gateway serves it: `g-<goal>.<the workspace's apex>`. */
|
|
36
|
+
apex: string;
|
|
37
|
+
/** Its tunnel's socket: `<home>/.lensmcp/peers/instances/<instanceId>.sock`, and nothing else. */
|
|
38
|
+
socket: string;
|
|
39
|
+
/** How long the route lives unless asked again (s): more than 0, at most {@link MAX_REMOTE_INSTANCE_SEC}. */
|
|
40
|
+
forSec: number;
|
|
41
|
+
/** The instance's lens dashboard base path on the worker (`/<instance key>`): asked, its lens host is routed too. */
|
|
42
|
+
dashboardBase?: string;
|
|
43
|
+
}
|
|
44
|
+
/** A remote instance's routes as `/remote-instance` answers them. */
|
|
45
|
+
export interface RemoteInstanceRouteView {
|
|
46
|
+
instanceId: string;
|
|
47
|
+
wsKey: string;
|
|
48
|
+
apex: string;
|
|
49
|
+
/** Every host routed to its tunnel: the apex, `*.<apex>`, the workspace's hosts named under it, its lens host. */
|
|
50
|
+
hosts: string[];
|
|
51
|
+
/** Where a browser opens its app: `https://<apex>`, with the front door's port when it is not the scheme's own. */
|
|
52
|
+
origin: string;
|
|
53
|
+
socket: string;
|
|
54
|
+
/** Its lens: `lensmcp.<apex>` and the dashboard's base on the worker — `url` is what a browser opens. */
|
|
55
|
+
lens?: {
|
|
56
|
+
host: string;
|
|
57
|
+
base: string;
|
|
58
|
+
url: string;
|
|
59
|
+
};
|
|
60
|
+
registeredAt: number;
|
|
61
|
+
/** When it goes unless renewed (ms). */
|
|
62
|
+
expiresAt: number;
|
|
63
|
+
}
|
|
64
|
+
export type RemoteInstanceRouteRefusalCode = 'bad-request' | 'no-workspace' | 'no-apex' | 'apex-not-loopback' | 'not-its-apex' | 'instance-in-use' | 'host-conflict' | 'no-socket' | 'too-many-instances' | 'no-instance-route';
|
|
65
|
+
/** Why a request was refused: a code, and one sentence a person or the hub's log can act on. */
|
|
66
|
+
export interface RemoteInstanceRouteRefusal {
|
|
67
|
+
error: RemoteInstanceRouteRefusalCode;
|
|
68
|
+
message: string;
|
|
69
|
+
/** `bad-request`: the field that is wrong. */
|
|
70
|
+
field?: string;
|
|
71
|
+
/** The host that is held. */
|
|
72
|
+
host?: string;
|
|
73
|
+
/** Who holds it: `workspace '<key>' (<project>)`, `run '<id>'`, `remote instance '<id>'`, the dashboard, a parked worktree. */
|
|
74
|
+
heldBy?: string;
|
|
75
|
+
/** `no-workspace`: the keys that are registered. */
|
|
76
|
+
workspaces?: string[];
|
|
77
|
+
/** `too-many-instances`: the cap. */
|
|
78
|
+
max?: number;
|
|
79
|
+
}
|
|
80
|
+
/** Flat (this package compiles with `strict: false`): `status` 200 with a view, else a refusal. */
|
|
81
|
+
export interface RemoteInstanceAnswer {
|
|
82
|
+
status: number;
|
|
83
|
+
json: RemoteInstanceRouteRefusal | (RemoteInstanceRouteView & {
|
|
84
|
+
ok: true;
|
|
85
|
+
renewed: boolean;
|
|
86
|
+
}) | {
|
|
87
|
+
ok: true;
|
|
88
|
+
removed: boolean;
|
|
89
|
+
instanceId: string;
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
export interface RemoteInstancesDeps {
|
|
93
|
+
registry: RouteRegistry;
|
|
94
|
+
/** The route table changed: rebuild it — and with it the leaf certificate's names (server.ts `rebuildRoutes`). */
|
|
95
|
+
rebuild: () => void;
|
|
96
|
+
/** Does the front door speak TLS? Read at use. */
|
|
97
|
+
https: () => boolean;
|
|
98
|
+
/** The front door's bound ports: the port an origin names when it is not the scheme's own. */
|
|
99
|
+
ownPorts?: () => readonly number[];
|
|
100
|
+
/** Which parked on-demand worktree a host names (on-demand.ts) — a remote apex is never in one's namespace. */
|
|
101
|
+
parkedHosts?: Pick<ParkedHostLookup, 'match'>;
|
|
102
|
+
/** The folder a remote instance's socket must be in, read at use — {@link remoteInstanceSocketsDir} of this home unless a spec gives its own. */
|
|
103
|
+
socketsDir?: () => string;
|
|
104
|
+
now?: () => number;
|
|
105
|
+
log?: (line: string) => void;
|
|
106
|
+
}
|
|
107
|
+
export interface RemoteInstances {
|
|
108
|
+
/** `POST /remote-instance`: route an instance, or renew its route. */
|
|
109
|
+
set(body: unknown): RemoteInstanceAnswer;
|
|
110
|
+
/** `DELETE /remote-instance?instanceId=`: the instance went. Removing one that is not there is no error. */
|
|
111
|
+
remove(instanceId: unknown): RemoteInstanceAnswer;
|
|
112
|
+
/** The live ones, oldest first. */
|
|
113
|
+
list(): RemoteInstanceRouteView[];
|
|
114
|
+
get(instanceId: string): RemoteInstanceRouteView | undefined;
|
|
115
|
+
/** Drop those whose lease ran out, and rebuild when any went. Their ids. */
|
|
116
|
+
expire(now?: number): string[];
|
|
117
|
+
/**
|
|
118
|
+
* After a workspace registered or left: drop the instances whose workspace is gone, is an instance now, has another
|
|
119
|
+
* apex, or now declares a host in their namespace; name again the hosts of those whose workspace's hosts changed.
|
|
120
|
+
* The CALLER rebuilds, as a registration and an unregistration do anyway.
|
|
121
|
+
*/
|
|
122
|
+
reconcile(): string[];
|
|
123
|
+
/** The daemon stops: every remote instance's routes go. */
|
|
124
|
+
close(): void;
|
|
125
|
+
}
|
|
126
|
+
/** `lensmcp.<apex>`: the remote instance's lens, on an origin of its own. */
|
|
127
|
+
export declare function remoteLensHost(apex: string): string;
|
|
128
|
+
/**
|
|
129
|
+
* `<LENSMCP_HOME or ~>/.lensmcp/peers/instances` — the folder of the remote instances' sockets (plan «The contract»:
|
|
130
|
+
* `~/.lensmcp/peers/`). The peer hub's side derives the same (`apps/agent` `peers/remote-instance.ts`
|
|
131
|
+
* `remoteInstanceSocketsDirOf`); a route to a socket anywhere else is refused.
|
|
132
|
+
*/
|
|
133
|
+
export declare function remoteInstanceSocketsDir(env?: NodeJS.ProcessEnv): string;
|
|
134
|
+
/** The one name an instance's socket has: `<instanceId>.sock`. */
|
|
135
|
+
export declare const remoteInstanceSocketName: (instanceId: string) => string;
|
|
136
|
+
/**
|
|
137
|
+
* Why `socket` is no path instance `instanceId`'s routes may forward to — or `undefined`. From the string alone: an
|
|
138
|
+
* absolute path written plainly, directly in `dir`, named for the instance, short enough to be a unix socket's.
|
|
139
|
+
*/
|
|
140
|
+
export declare function remoteSocketPathProblem(socket: unknown, instanceId: string, dir: string): string | undefined;
|
|
141
|
+
/**
|
|
142
|
+
* What the proxy dials for a remote instance's route — none for any other route: the bytes go to its tunnel's socket,
|
|
143
|
+
* and the request keeps its own Host (no `host`/`port` here, and no `changeOrigin`: the worker's gateway routes by the
|
|
144
|
+
* name the browser asked for). Made afresh at each use.
|
|
145
|
+
*/
|
|
146
|
+
export interface RemoteInstanceUpstream {
|
|
147
|
+
socketPath: string;
|
|
148
|
+
protocol: 'http:';
|
|
149
|
+
}
|
|
150
|
+
export declare function remoteInstanceUpstream(route: Pick<Route, 'remote'>): RemoteInstanceUpstream | undefined;
|
|
151
|
+
/**
|
|
152
|
+
* The request, checked field by field — or the 400 that names what is wrong. Nothing here reads the gateway's state;
|
|
153
|
+
* the socket is checked against `socketsDir` as a string only.
|
|
154
|
+
*/
|
|
155
|
+
export declare function parseRemoteInstanceRequest(body: unknown, options?: {
|
|
156
|
+
socketsDir?: string;
|
|
157
|
+
}): {
|
|
158
|
+
request?: RemoteInstanceRouteRequest;
|
|
159
|
+
refused?: RemoteInstanceAnswer;
|
|
160
|
+
};
|
|
161
|
+
/**
|
|
162
|
+
* Why a remote instance's routes may not forward to `socket` — or `undefined` — as the disk has it now: the folder is
|
|
163
|
+
* a folder (not a link) of this user's that no one else may enter, and in it is a socket of this user's that no one
|
|
164
|
+
* else may open. What the peer hub makes; asked again at each renewal.
|
|
165
|
+
*/
|
|
166
|
+
export declare function remoteSocketOnDiskProblem(socket: string, instanceId: string): string | undefined;
|
|
167
|
+
export declare function createRemoteInstances(deps: RemoteInstancesDeps): RemoteInstances;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var B=Object.defineProperty;var A=(t,r)=>B(t,"name",{value:r,configurable:!0});var v=Object.defineProperty,u=A((t,r)=>v(t,"name",{value:r,configurable:!0}),"u");Object.defineProperty(exports,"__esModule",{value:!0}),exports.remoteInstanceSocketName=exports.REMOTE_DASHBOARD_BASE_PATTERN=exports.REMOTE_LENS_LABEL=exports.REMOTE_INSTANCE_NAME_PREFIX=exports.REMOTE_INSTANCE_ID_PATTERN=exports.REMOTE_INSTANCE_BODY_BYTES=exports.MAX_REMOTE_INSTANCES=exports.MAX_REMOTE_INSTANCE_SEC=exports.REMOTE_INSTANCES_STANDALONE_ID=exports.REMOTE_INSTANCE_PROJECT=void 0,exports.remoteLensHost=remoteLensHost,exports.remoteInstanceSocketsDir=remoteInstanceSocketsDir,exports.remoteSocketPathProblem=remoteSocketPathProblem,exports.remoteInstanceUpstream=remoteInstanceUpstream,exports.parseRemoteInstanceRequest=parseRemoteInstanceRequest,exports.remoteSocketOnDiskProblem=remoteSocketOnDiskProblem,exports.createRemoteInstances=createRemoteInstances;const tslib_1=require("tslib"),fs=tslib_1.__importStar(require("node:fs")),os=tslib_1.__importStar(require("node:os")),path=tslib_1.__importStar(require("node:path")),instance_1=require("./instance"),observability_1=require("./observability"),run_routes_1=require("./run-routes");exports.REMOTE_INSTANCE_PROJECT="(remote)",exports.REMOTE_INSTANCES_STANDALONE_ID="(remote-instances)",exports.MAX_REMOTE_INSTANCE_SEC=14400,exports.MAX_REMOTE_INSTANCES=16,exports.REMOTE_INSTANCE_BODY_BYTES=4096,exports.REMOTE_INSTANCE_ID_PATTERN=/^[A-Za-z0-9][A-Za-z0-9_-]{7,39}$/,exports.REMOTE_INSTANCE_NAME_PREFIX="g-",exports.REMOTE_LENS_LABEL="lensmcp",exports.REMOTE_DASHBOARD_BASE_PATTERN=/^\/[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/;const REQUEST_FIELDS=new Set(["instanceId","wsKey","apex","socket","forSec","dashboardBase"]),MAX_WS_KEY_LENGTH=200,HOST_NAME=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$/;function remoteLensHost(t){return`${exports.REMOTE_LENS_LABEL}.${t.toLowerCase()}`}A(remoteLensHost,"remoteLensHost"),u(remoteLensHost,"remoteLensHost");function remoteInstanceSocketsDir(t=process.env){return path.resolve(t.LENSMCP_HOME||os.homedir(),".lensmcp","peers","instances")}A(remoteInstanceSocketsDir,"remoteInstanceSocketsDir"),u(remoteInstanceSocketsDir,"remoteInstanceSocketsDir");const remoteInstanceSocketName=u(t=>`${t}.sock`,"remoteInstanceSocketName");exports.remoteInstanceSocketName=remoteInstanceSocketName;function remoteSocketPathProblem(t,r,d){const h=path.join(d,(0,exports.remoteInstanceSocketName)(r));if(typeof t!="string"||t.length===0)return`socket is required: the path of the instance's tunnel socket, ${h}`;if(/[\u0000-\u001f\u007f]/.test(t))return"socket has a control character in it: an instance's socket is a plain path";if(!path.isAbsolute(t)||path.normalize(t)!==t||t.endsWith("/"))return`socket must be an absolute path written plainly \u2014 no '.', '..', repeated or trailing '/': ${h}`;const a=t.length>160?`${t.slice(0,160)}\u2026`:t;if(path.dirname(t)!==d)return`socket ${a} is outside ${d}: a remote instance's routes forward only to its tunnel socket in the peers' instances folder of this gateway's home, never to another socket or file`;if(path.basename(t)!==(0,exports.remoteInstanceSocketName)(r))return`socket ${a} is not instance '${r}'s: an instance's tunnel socket is named for it (${(0,exports.remoteInstanceSocketName)(r)})`;const p=Buffer.byteLength(t);if(p>run_routes_1.MAX_RUN_SOCKET_PATH_BYTES)return`socket is ${p} bytes long, over the ${run_routes_1.MAX_RUN_SOCKET_PATH_BYTES} a unix socket's path may have: give LENSMCP_HOME a shorter path`}A(remoteSocketPathProblem,"remoteSocketPathProblem"),u(remoteSocketPathProblem,"remoteSocketPathProblem");function remoteInstanceUpstream(t){const r=t.remote;if(!r)return;const d={socketPath:r.socket,protocol:"http:"};return Object.defineProperty(d,"toString",{value:u(()=>`unix:${r.socket} (the tunnel of remote instance '${r.id}' to its worker's gateway)`,"value"),enumerable:!1}),d}A(remoteInstanceUpstream,"remoteInstanceUpstream"),u(remoteInstanceUpstream,"remoteInstanceUpstream");const refusal=u((t,r,d,h={})=>({status:t,json:{error:r,message:d,...h}}),"refusal"),bad=u((t,r)=>refusal(400,"bad-request",r,{field:t}),"bad");function parseRemoteInstanceRequest(t,r={}){if(!t||typeof t!="object"||Array.isArray(t))return{refused:bad("body","the body is a JSON object: { instanceId, wsKey, apex, socket, forSec, dashboardBase? }")};const d=t;for(const $ of Object.keys(d))if(!REQUEST_FIELDS.has($))return{refused:bad($,`'${$.slice(0,40)}' is not a field of a remote instance's route \u2014 the gateway derives its hosts from wsKey and apex, and forwards only to its tunnel's socket in the peers' instances folder; a request names neither a host nor an upstream`)};const{instanceId:h,wsKey:a,apex:p,socket:N,forSec:_,dashboardBase:S}=d;if(typeof h!="string"||!exports.REMOTE_INSTANCE_ID_PATTERN.test(h))return{refused:bad("instanceId","instanceId is required: 8 to 40 letters, digits, `_` or `-`")};if(typeof a!="string"||a.length===0||a.length>MAX_WS_KEY_LENGTH)return{refused:bad("wsKey","wsKey is required: the key of the workspace registered with this gateway that the instance is an instance of")};if(typeof p!="string"||p.length>253||!HOST_NAME.test(p.toLowerCase()))return{refused:bad("apex","apex is required: the instance's apex as its worker's gateway serves it, `<name>.<the workspace's apex>`")};if(typeof _!="number"||!Number.isFinite(_)||_<=0)return{refused:bad("forSec","forSec is required: the seconds the route lives unless asked again (DELETE /remote-instance removes it)")};if(_>exports.MAX_REMOTE_INSTANCE_SEC)return{refused:bad("forSec",`forSec ${_} is over the ${exports.MAX_REMOTE_INSTANCE_SEC} s (4 h) a route may live \u2014 ask again before it ends to keep it longer`)};const k=remoteSocketPathProblem(N,h,r.socketsDir??remoteInstanceSocketsDir());return k?{refused:bad("socket",k)}:S!==void 0&&(typeof S!="string"||!exports.REMOTE_DASHBOARD_BASE_PATTERN.test(S))?{refused:bad("dashboardBase","dashboardBase, when given, is the lens dashboard's base path on the worker: one path segment, `/<instance key>`")}:{request:{instanceId:h,wsKey:a,apex:p.toLowerCase(),socket:N,forSec:_,...typeof S=="string"?{dashboardBase:S}:{}}}}A(parseRemoteInstanceRequest,"parseRemoteInstanceRequest"),u(parseRemoteInstanceRequest,"parseRemoteInstanceRequest");function hostsUnder(t,r,d){const h=new Set;for(const a of t){if(!a.host||a.project===observability_1.LENS_DASHBOARD_PROJECT||a.run||a.remote)continue;const p=(0,instance_1.rewriteHost)(a.host,r,d);p&&h.add(p)}return[...h]}A(hostsUnder,"hostsUnder"),u(hostsUnder,"hostsUnder");const sameList=u((t,r)=>t.length===r.length&&t.every((d,h)=>d===r[h]),"sameList");function remoteSocketOnDiskProblem(t,r){const d=typeof process.getuid=="function"?process.getuid():void 0,h=path.dirname(t);let a;try{a=fs.lstatSync(h)}catch{return`there is no folder ${h}`}if(a.isSymbolicLink()||!a.isDirectory())return`${h} is not a folder of its own (a link, or a file)`;if(d!==void 0&&a.uid!==d)return`${h} belongs to another user`;if((a.mode&63)!==0)return`${h} is open to other users (mode ${(a.mode&511).toString(8)}, not 700)`;try{a=fs.lstatSync(t)}catch{return`nothing serves remote instance '${r}' at ${t}`}if(!a.isSocket())return`${t} is not a socket`;if(d!==void 0&&a.uid!==d)return`${t} belongs to another user`;if((a.mode&63)!==0)return`${t} is open to other users (mode ${(a.mode&511).toString(8)}, not 600)`}A(remoteSocketOnDiskProblem,"remoteSocketOnDiskProblem"),u(remoteSocketOnDiskProblem,"remoteSocketOnDiskProblem");function createRemoteInstances(t){const{registry:r}=t,d=t.now??Date.now,h=t.log??(e=>console.log(e)),a=t.socketsDir??(()=>remoteInstanceSocketsDir()),p=new Map,N=u(()=>{p.size===0?r.dropStandalone(exports.REMOTE_INSTANCES_STANDALONE_ID):r.setStandalone(exports.REMOTE_INSTANCES_STANDALONE_ID,[...p.values()].flatMap(e=>e.routes))},"publish"),_=u(e=>{const s=t.https(),o=t.ownPorts?.()??[],n=s?443:80;return`${s?"https":"http"}://${e}${o.length===0||o.includes(n)?"":`:${o[0]}`}`},"origin"),S=u(e=>{const s=remoteLensHost(e.apex);return{instanceId:e.instanceId,wsKey:e.wsKey,apex:e.apex,hosts:[...e.hosts],origin:_(e.apex),socket:e.socket,...e.dashboardBase!==void 0?{lens:{host:s,base:e.dashboardBase,url:`${_(s)}${e.dashboardBase}/`}}:{},registeredAt:e.registeredAt,expiresAt:e.expiresAt}},"view"),k=u(e=>{const s=e.dashboardBase!==void 0?remoteLensHost(e.apex):void 0;return e.hosts.map(o=>({host:o,project:exports.REMOTE_INSTANCE_PROJECT,remote:{id:e.instanceId,wsKey:e.wsKey,apex:e.apex,socket:e.socket,part:o===s?"lens":"app"}}))},"routesOf"),$=u(()=>{const e=new Map;for(const s of r.keys())for(const o of r.get(s)?.routes??[])e.set(o,s);return s=>{if(s.remote)return`remote instance '${s.remote.id}'`;if(s.run)return`run '${s.run.id}'`;if(s.project===observability_1.LENS_DASHBOARD_PROJECT)return"the lens dashboard";const o=e.get(s)??s.wsKey;return o?`workspace '${o}' (${s.project})`:`'${s.project}'`}},"holders"),I=u((e,s)=>{const o=e.toLowerCase(),n=o.startsWith("*.")?o.slice(2):o;return n===s||n.endsWith(`.${s}`)},"inNamespace"),L=u((e,s)=>{const o=$(),n=u((f,c,T)=>refusal(409,"host-conflict",`${c} ${T} (${f}): a remote instance's routes never take a host from what the gateway already serves. Nothing was routed.`,{host:c,heldBy:f}),"refused"),i=r.merged().filter(f=>f.remote?.id!==s),m=i.find(f=>!!f.host&&I(f.host,e));if(m)return n(o(m),m.host,`is in the namespace of ${e}, and already routed`);const E=i.find(f=>f.project===observability_1.LENS_DASHBOARD_PROJECT&&!!f.host&&(e===f.host.toLowerCase()||e.endsWith(`.${f.host.toLowerCase()}`)));if(E)return n("the lens dashboard",e,`is under the dashboard's host ${E.host}`);for(const f of r.keys()){const c=r.get(f)?.instance?.apex.toLowerCase();if(c&&(c===e||c.endsWith(`.${e}`)))return n(`workspace '${f}'`,e,`is the namespace of the worktree instance at ${c} on this Mac`)}const l=t.parkedHosts?.match(e)??t.parkedHosts?.match(remoteLensHost(e));if(l)return n(`the parked worktree '${l.name}'`,e,"is in the namespace of a parked worktree of this Mac")},"namespaceRefusal"),y=u((e,s)=>{const o=r.get(e);if(!o)return{refused:refusal(404,"no-workspace",`no workspace '${e}' is registered with this gateway: a remote instance is named under the apex of the main checkout of its project, which this gateway must serve`,{workspaces:r.keys()})};if(o.instance)return{refused:refusal(409,"no-apex",`workspace '${e}' is itself a worktree instance (${o.instance.apex}): a remote instance is named under its main checkout's apex \u2014 name that workspace`)};const n=(0,run_routes_1.runApexOf)(o);if(!n)return{refused:refusal(409,"no-apex",`the hosts of workspace '${e}' share no apex to name a remote instance under`)};if(!(0,run_routes_1.isLocalhostName)(n))return{refused:refusal(409,"apex-not-loopback",`the apex of workspace '${e}' is ${n}: a remote instance is served under a .localhost name only \u2014 any other may resolve to another machine`)};const i=s.endsWith(`.${n}`)?s.slice(0,-(n.length+1)):void 0;return!i||!instance_1.INSTANCE_NAME_PATTERN.test(i)||!i.startsWith(exports.REMOTE_INSTANCE_NAME_PREFIX)?{refused:refusal(409,"not-its-apex",`${s} is not a remote instance's apex of workspace '${e}': it is a goal worktree's name (${exports.REMOTE_INSTANCE_NAME_PREFIX}\u2026, one DNS label of at most 20 characters) in front of ${n}, as ${exports.REMOTE_INSTANCE_NAME_PREFIX}<goal>.${n}`,{host:s})}:{baseApex:n,name:i}},"derive"),b=u((e,s,o,n,i)=>{const m=hostsUnder(r.get(e)?.routes??[],o,n),E=remoteLensHost(s);return i!==void 0&&m.includes(E)?{refused:refusal(409,"host-conflict",`${E} is a host workspace '${e}' declares, so it cannot be the remote instance's lens: rename that host. Nothing was routed.`,{host:E,heldBy:`workspace '${e}'`})}:{hosts:[...new Set([s,`*.${s}`,...m,...i!==void 0?[E]:[]])].sort()}},"hostsFor"),w=u((e,s)=>{p.delete(e.instanceId),h(`[gateway] ${new Date(d()).toISOString()} remote instance route removed: ${e.apex} (instance '${e.instanceId}', workspace '${e.wsKey}') \u2014 ${s}`)},"drop"),O=u((e=d())=>{const s=[...p.values()].filter(o=>o.expiresAt<=e);if(s.length===0)return[];for(const o of s)w(o,`its lease ended at ${new Date(o.expiresAt).toISOString()} and nothing renewed it`);return N(),t.rebuild(),s.map(o=>o.instanceId)},"expire");return{set(e){const s=parseRemoteInstanceRequest(e,{socketsDir:a()});if(s.refused||!s.request)return s.refused??bad("body","the request could not be read");const{instanceId:o,wsKey:n,apex:i,socket:m,forSec:E,dashboardBase:l}=s.request,f=d();O(f);const c=p.get(o);if(c&&(c.wsKey!==n||c.apex!==i||c.dashboardBase!==l))return refusal(409,"instance-in-use",`instance '${o}' is routed at ${c.apex} for workspace '${c.wsKey}'${c.dashboardBase!==void 0?` with its lens at ${c.dashboardBase}`:""}: an instance has one set of routes. Remove it first (DELETE /remote-instance?instanceId=${o}).`,{host:c.apex,heldBy:`remote instance '${o}'`});const T=y(n,i);if(T.refused||!T.baseApex||!T.name)return T.refused??bad("apex","the request could not be read");const x=b(n,i,T.baseApex,T.name,l);if(x.refused||!x.hosts)return x.refused??bad("apex","the request could not be read");const R=L(i,o);if(R)return R;const M=remoteSocketOnDiskProblem(m,o);if(M)return refusal(409,"no-socket",`${M}: a remote instance's routes forward to the socket its tunnel serves, and to nothing else. Nothing was routed.`);if(!c&&p.size>=exports.MAX_REMOTE_INSTANCES)return refusal(409,"too-many-instances",`${p.size} remote instances are routed already, the most at once (${exports.MAX_REMOTE_INSTANCES}): remove one that went (GET /remote-instance lists them).`,{max:exports.MAX_REMOTE_INSTANCES});const g=f+Math.round(E*1e3);if(c)return c.expiresAt=g,sameList(c.hosts,x.hosts)||(c.hosts=x.hosts,c.routes=k(c),N(),t.rebuild(),h(`[gateway] ${new Date(f).toISOString()} remote instance route renamed: ${i} \u2192 ${c.hosts.join(", ")} (instance '${o}')`)),{status:200,json:{ok:!0,renewed:!0,...S(c)}};const C={instanceId:o,wsKey:n,apex:i,socket:m,hosts:x.hosts,...l!==void 0?{dashboardBase:l}:{}},D={...C,registeredAt:f,expiresAt:g,routes:k(C)};return p.set(o,D),N(),t.rebuild(),h(`[gateway] ${new Date(f).toISOString()} remote instance route: ${_(i)} and every host beneath it${l!==void 0?`, its lens at ${_(remoteLensHost(i))}${l}/`:""} \u2192 unix:${m} (instance '${o}', workspace '${n}', until ${new Date(g).toISOString()} unless renewed)`),{status:200,json:{ok:!0,renewed:!1,...S(D)}}},remove(e){if(typeof e!="string"||!exports.REMOTE_INSTANCE_ID_PATTERN.test(e))return bad("instanceId","instanceId is required: DELETE /remote-instance?instanceId=<the instance>");const s=p.get(e);return s&&(w(s,"asked (DELETE /remote-instance)"),N(),t.rebuild()),{status:200,json:{ok:!0,removed:!!s,instanceId:e}}},list(){return[...p.values()].sort((e,s)=>e.registeredAt-s.registeredAt).map(S)},get(e){const s=p.get(e);return s?S(s):void 0},expire:O,reconcile(){const e=[];let s=!1;for(const o of[...p.values()]){const n=r.get(o.wsKey);let i;const m=n?y(o.wsKey,o.apex):void 0;if(!n)i=`workspace '${o.wsKey}' is no longer registered`;else if(m?.refused)i=m.refused.json.message;else for(const E of r.keys()){const l=(r.get(E)?.routes??[]).find(f=>!!f.host&&I(f.host,o.apex));if(l){i=`workspace '${E}' now declares ${l.host}, in its namespace`;break}}if(!i&&m?.baseApex&&m.name){const E=b(o.wsKey,o.apex,m.baseApex,m.name,o.dashboardBase);E.refused||!E.hosts?i=E.refused?.json?.message??"its hosts could not be named":sameList(E.hosts,o.hosts)||(o.hosts=E.hosts,o.routes=k(o),s=!0)}i&&(w(o,i),e.push(o.instanceId))}return(e.length>0||s)&&N(),e},close(){p.clear(),r.dropStandalone(exports.REMOTE_INSTANCES_STANDALONE_ID)}}}A(createRemoteInstances,"createRemoteInstances"),u(createRemoteInstances,"createRemoteInstances");
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
import type { ParkedHostLookup } from './on-demand';
|
|
2
|
+
import type { RouteRegistry, WorkspaceFragment } from './route-registry';
|
|
3
|
+
import type { Route } from './types';
|
|
4
|
+
/** What a run's route says its project is — in a traffic edge, a trace, a 502. One home for the literal. */
|
|
5
|
+
export declare const RUN_ROUTE_PROJECT = "(run)";
|
|
6
|
+
/** The id every run's route is kept under in the registry's standalone routes — no workspace key reads like it. */
|
|
7
|
+
export declare const RUN_ROUTES_STANDALONE_ID = "(run-routes)";
|
|
8
|
+
/** The longest lease: a forgotten route lives no longer than this (awake.ts `MAX_AWAKE_SEC`, the same bound a hold has). */
|
|
9
|
+
export declare const MAX_RUN_ROUTE_SEC: number;
|
|
10
|
+
/** The most runs routed at once: each is a name on the leaf certificate, minted again as it comes and goes. */
|
|
11
|
+
export declare const MAX_RUN_ROUTES = 32;
|
|
12
|
+
/** The most a `POST /run-route` body may be: four short fields. */
|
|
13
|
+
export declare const RUN_ROUTE_BODY_BYTES = 4096;
|
|
14
|
+
/** A run's id: letters, digits, `_` and `-`, eight to eighty characters (`wa_<uuid>`, `q_<uuid>`) — safe in a log line and a path. */
|
|
15
|
+
export declare const RUN_ID_PATTERN: RegExp;
|
|
16
|
+
/** The lowest port a run may be routed to: the edge is published on an ephemeral one, never a privileged one. */
|
|
17
|
+
export declare const MIN_RUN_PORT = 1024;
|
|
18
|
+
/** The longest path a unix socket may be bound at: macOS keeps 104 bytes for it, the NUL that ends it included. */
|
|
19
|
+
export declare const MAX_RUN_SOCKET_PATH_BYTES = 103;
|
|
20
|
+
/** `POST /run-route`. */
|
|
21
|
+
export interface RunRouteRequest {
|
|
22
|
+
/** The run ({@link RUN_ID_PATTERN}); its first eight letters and digits after a `wa_`-like prefix name the host. */
|
|
23
|
+
runId: string;
|
|
24
|
+
/** A workspace registered with this gateway: the run's host goes under its apex. */
|
|
25
|
+
wsKey: string;
|
|
26
|
+
/** The loopback port the stack's edge is published on (`docker compose port`) — on the worker, for a remote run. */
|
|
27
|
+
port: number;
|
|
28
|
+
/** How long the route lives unless asked again (s): more than 0, at most {@link MAX_RUN_ROUTE_SEC}. */
|
|
29
|
+
forSec: number;
|
|
30
|
+
/** A remote run (D17): its tunnel's socket, `<home>/.lensmcp/peers/runs/<runId>.sock` — then never `127.0.0.1:<port>` of this Mac. */
|
|
31
|
+
socket?: string;
|
|
32
|
+
}
|
|
33
|
+
/** A run's route as `/run-route` answers it. */
|
|
34
|
+
export interface RunRouteView {
|
|
35
|
+
runId: string;
|
|
36
|
+
wsKey: string;
|
|
37
|
+
/** `run-<short>.<apex>`. */
|
|
38
|
+
host: string;
|
|
39
|
+
/** Where a browser opens it: the gateway's scheme, the host, and the front door's port when it is not the scheme's own. */
|
|
40
|
+
origin: string;
|
|
41
|
+
port: number;
|
|
42
|
+
registeredAt: number;
|
|
43
|
+
/** When it goes unless renewed (ms). */
|
|
44
|
+
expiresAt: number;
|
|
45
|
+
/** A remote run's: the socket its requests go to. */
|
|
46
|
+
socket?: string;
|
|
47
|
+
}
|
|
48
|
+
export type RunRouteRefusalCode = 'bad-request' | 'no-workspace' | 'run-in-use' | 'no-apex' | 'apex-not-loopback' | 'host-conflict' | 'upstream-is-gateway' | 'upstream-in-use' | 'too-many-runs' | 'no-run-route' | 'no-socket';
|
|
49
|
+
/** Why a request was refused: a code, and one sentence a person or a runner's log can act on. */
|
|
50
|
+
export interface RunRouteRefusal {
|
|
51
|
+
error: RunRouteRefusalCode;
|
|
52
|
+
message: string;
|
|
53
|
+
/** `bad-request`: the field that is wrong. */
|
|
54
|
+
field?: string;
|
|
55
|
+
/** The host the run would have had. */
|
|
56
|
+
host?: string;
|
|
57
|
+
/** Who holds the host or the port: `run '<id>'`, `workspace '<key>' (<project>)`, the dashboard, a parked worktree. */
|
|
58
|
+
heldBy?: string;
|
|
59
|
+
/** `no-workspace`: the keys that are registered. */
|
|
60
|
+
workspaces?: string[];
|
|
61
|
+
/** `too-many-runs`: the cap. */
|
|
62
|
+
max?: number;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* `GET /run-route?runId=&wsKey=`: where a run would be routed, asked before its edge is up — the project's command is
|
|
66
|
+
* given its public origin (`LENSMCP_RUN_ORIGIN`) before it boots the stack. `routed` says whether the route is there yet.
|
|
67
|
+
*/
|
|
68
|
+
export interface RunRoutePreview {
|
|
69
|
+
ok: true;
|
|
70
|
+
routed: boolean;
|
|
71
|
+
runId: string;
|
|
72
|
+
wsKey: string;
|
|
73
|
+
host: string;
|
|
74
|
+
origin: string;
|
|
75
|
+
/** Only once routed. */
|
|
76
|
+
port?: number;
|
|
77
|
+
registeredAt?: number;
|
|
78
|
+
expiresAt?: number;
|
|
79
|
+
}
|
|
80
|
+
/** Flat (this package compiles with `strict: false`): `status` 200 with a view, else a refusal. */
|
|
81
|
+
export interface RunRouteAnswer {
|
|
82
|
+
status: number;
|
|
83
|
+
json: RunRouteRefusal | (RunRouteView & {
|
|
84
|
+
ok: true;
|
|
85
|
+
renewed: boolean;
|
|
86
|
+
}) | RunRoutePreview | {
|
|
87
|
+
ok: true;
|
|
88
|
+
removed: boolean;
|
|
89
|
+
runId: string;
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
export interface RunRoutesDeps {
|
|
93
|
+
registry: RouteRegistry;
|
|
94
|
+
/** The route table changed: rebuild it — and with it the leaf certificate's names (server.ts `rebuildRoutes`). */
|
|
95
|
+
rebuild: () => void;
|
|
96
|
+
/** Does the front door speak TLS? Read at use. */
|
|
97
|
+
https: () => boolean;
|
|
98
|
+
/** The front door's bound ports: never a run's upstream, and the port a run's origin names. None in a spec without a front door. */
|
|
99
|
+
ownPorts?: () => readonly number[];
|
|
100
|
+
/** Which parked on-demand worktree a host names (on-demand.ts) — a run's host is never in one's namespace. */
|
|
101
|
+
parkedHosts?: Pick<ParkedHostLookup, 'match'>;
|
|
102
|
+
/** The folder a remote run's socket must be in, read at use — {@link runSocketsDir} of this process's home unless a spec gives its own. */
|
|
103
|
+
socketsDir?: () => string;
|
|
104
|
+
now?: () => number;
|
|
105
|
+
log?: (line: string) => void;
|
|
106
|
+
}
|
|
107
|
+
export interface RunRoutes {
|
|
108
|
+
/** `POST /run-route`: route a run, or renew the route it has. */
|
|
109
|
+
set(body: unknown): RunRouteAnswer;
|
|
110
|
+
/**
|
|
111
|
+
* `GET /run-route?runId=&wsKey=`: the host and origin the run has or would get — the same derivation and the same
|
|
112
|
+
* refusals of a host as {@link set}, and nothing routed.
|
|
113
|
+
*/
|
|
114
|
+
preview(runId: unknown, wsKey: unknown): RunRouteAnswer;
|
|
115
|
+
/** `DELETE /run-route?runId=`: the run's cleanup. Removing one that is not there is no error. */
|
|
116
|
+
remove(runId: unknown): RunRouteAnswer;
|
|
117
|
+
/** The live routes, oldest first. */
|
|
118
|
+
list(): RunRouteView[];
|
|
119
|
+
get(runId: string): RunRouteView | undefined;
|
|
120
|
+
/** Drop the routes whose lease ran out, and rebuild when any went. The run ids. */
|
|
121
|
+
expire(now?: number): string[];
|
|
122
|
+
/**
|
|
123
|
+
* After a workspace registered or left: drop the routes whose workspace is gone or has another apex now, and those
|
|
124
|
+
* whose host a workspace now declares. The CALLER rebuilds, as a registration and an unregistration do anyway.
|
|
125
|
+
*/
|
|
126
|
+
reconcile(): string[];
|
|
127
|
+
/** The daemon stops: every run's route goes. */
|
|
128
|
+
close(): void;
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* The eight characters of a run's id that name its host: its letters and digits, lowercased, after a `wa_`-like
|
|
132
|
+
* prefix — `wa_f986b59f-1c2d-…` → `f986b59f`, the short form the logs already use. `undefined` when it has fewer.
|
|
133
|
+
* The compose runner derives the same for its Compose project name (`lensmcp-<short>`) and `LENSMCP_RUN_ORIGIN`.
|
|
134
|
+
*/
|
|
135
|
+
export declare function runShortId(runId: string): string | undefined;
|
|
136
|
+
/** `run-<short>.<apex>`. */
|
|
137
|
+
export declare function runHost(short: string, apex: string): string;
|
|
138
|
+
/**
|
|
139
|
+
* The apex a workspace's runs are named under: an instance's own (`gate1.foodguard.localhost`), else the common suffix
|
|
140
|
+
* of its declared hosts (`foodguard.localhost`) — the dashboard's route, appended to the daemon's own fragment, is not
|
|
141
|
+
* one of them. `undefined` when its hosts share none.
|
|
142
|
+
*/
|
|
143
|
+
export declare function runApexOf(f: Pick<WorkspaceFragment, 'routes' | 'instance'>): string | undefined;
|
|
144
|
+
/** Is `name` certain to resolve to this machine — `localhost` or a name under it (RFC 6761)? */
|
|
145
|
+
export declare function isLocalhostName(name: string): boolean;
|
|
146
|
+
/** The loopback port a route's TCP target forwards to — `undefined` for a pod pool, another machine, or no port. */
|
|
147
|
+
export declare function loopbackPortOf(route: Pick<Route, 'target' | 'lens'>): number | undefined;
|
|
148
|
+
/**
|
|
149
|
+
* `<LENSMCP_HOME or ~>/.lensmcp/peers/runs` — the folder of the remote runs' sockets (plan «The contract»: `~/.lensmcp/
|
|
150
|
+
* peers/`). The peer hub's side derives the same (`apps/agent` `peers/tunnel.ts` `runSocketsDirOf`); a route to a
|
|
151
|
+
* socket anywhere else is refused.
|
|
152
|
+
*/
|
|
153
|
+
export declare function runSocketsDir(env?: NodeJS.ProcessEnv): string;
|
|
154
|
+
/** The one name a run's socket has: `<runId>.sock` — a route never reaches another run's tunnel. */
|
|
155
|
+
export declare const runSocketName: (runId: string) => string;
|
|
156
|
+
/**
|
|
157
|
+
* Why `socket` is no path run `runId`'s route may forward to — or `undefined`. Read from the string alone, before
|
|
158
|
+
* anything on disk is looked at: an absolute path, written plainly (nothing `path.normalize` would change, no trailing
|
|
159
|
+
* `/`, no control character), directly in `dir`, named for the run, short enough to be a unix socket's.
|
|
160
|
+
*/
|
|
161
|
+
export declare function socketPathProblem(socket: unknown, runId: string, dir: string): string | undefined;
|
|
162
|
+
/**
|
|
163
|
+
* What the proxy dials for a remote run's route (D17) — none for any other route. The bytes go to `socketPath`;
|
|
164
|
+
* `protocol`, `host` and `port` are what the edge is told it was asked for: http-proxy's `changeOrigin` (and the
|
|
165
|
+
* HTTP/2 relay, proxy.ts `pipeUpstream`) write `Host: 127.0.0.1:<port>`, as a local run's edge is given its own
|
|
166
|
+
* address. Made afresh at each use, so a renewal that moved the port is followed.
|
|
167
|
+
*/
|
|
168
|
+
export interface RunSocketUpstream {
|
|
169
|
+
socketPath: string;
|
|
170
|
+
protocol: 'http:';
|
|
171
|
+
host: '127.0.0.1';
|
|
172
|
+
port: number;
|
|
173
|
+
}
|
|
174
|
+
export declare function runSocketUpstream(route: Pick<Route, 'run'>): RunSocketUpstream | undefined;
|
|
175
|
+
/**
|
|
176
|
+
* The request, checked field by field — or the 400 that names what is wrong. Nothing here reads the gateway's state;
|
|
177
|
+
* a `socket` is checked against `socketsDir` (the gateway's home's, unless one is given) as a string only.
|
|
178
|
+
*/
|
|
179
|
+
export declare function parseRunRouteRequest(body: unknown, options?: {
|
|
180
|
+
socketsDir?: string;
|
|
181
|
+
}): {
|
|
182
|
+
request?: RunRouteRequest;
|
|
183
|
+
short?: string;
|
|
184
|
+
refused?: RunRouteAnswer;
|
|
185
|
+
};
|
|
186
|
+
export declare function createRunRoutes(deps: RunRoutesDeps): RunRoutes;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var P=Object.defineProperty;var l=(e,r)=>P(e,"name",{value:r,configurable:!0});var L=Object.defineProperty,i=l((e,r)=>L(e,"name",{value:r,configurable:!0}),"i");Object.defineProperty(exports,"__esModule",{value:!0}),exports.runSocketName=exports.MAX_RUN_SOCKET_PATH_BYTES=exports.MIN_RUN_PORT=exports.RUN_ID_PATTERN=exports.RUN_ROUTE_BODY_BYTES=exports.MAX_RUN_ROUTES=exports.MAX_RUN_ROUTE_SEC=exports.RUN_ROUTES_STANDALONE_ID=exports.RUN_ROUTE_PROJECT=void 0,exports.runShortId=runShortId,exports.runHost=runHost,exports.runApexOf=runApexOf,exports.isLocalhostName=isLocalhostName,exports.loopbackPortOf=loopbackPortOf,exports.runSocketsDir=runSocketsDir,exports.socketPathProblem=socketPathProblem,exports.runSocketUpstream=runSocketUpstream,exports.parseRunRouteRequest=parseRunRouteRequest,exports.createRunRoutes=createRunRoutes;const tslib_1=require("tslib"),fs=tslib_1.__importStar(require("node:fs")),os=tslib_1.__importStar(require("node:os")),path=tslib_1.__importStar(require("node:path")),instance_1=require("./instance"),observability_1=require("./observability");exports.RUN_ROUTE_PROJECT="(run)",exports.RUN_ROUTES_STANDALONE_ID="(run-routes)",exports.MAX_RUN_ROUTE_SEC=14400,exports.MAX_RUN_ROUTES=32,exports.RUN_ROUTE_BODY_BYTES=4096,exports.RUN_ID_PATTERN=/^[A-Za-z0-9][A-Za-z0-9_-]{7,79}$/;const MAX_WS_KEY_LENGTH=200;exports.MIN_RUN_PORT=1024;const REQUEST_FIELDS=new Set(["runId","wsKey","port","forSec","socket"]);exports.MAX_RUN_SOCKET_PATH_BYTES=103;function runShortId(e){const r=e.toLowerCase().replace(/^[a-z]+_/,"").replace(/[^a-z0-9]/g,"").slice(0,8);return r.length===8?r:void 0}l(runShortId,"runShortId"),i(runShortId,"runShortId");function runHost(e,r){return`run-${e}.${r.toLowerCase()}`}l(runHost,"runHost"),i(runHost,"runHost");function runApexOf(e){return e.instance?e.instance.apex.toLowerCase():(0,instance_1.commonApex)(e.routes.filter(r=>!!r.host&&r.project!==observability_1.LENS_DASHBOARD_PROJECT).map(r=>r.host))}l(runApexOf,"runApexOf"),i(runApexOf,"runApexOf");function isLocalhostName(e){const r=e.toLowerCase();return r==="localhost"||r.endsWith(".localhost")}l(isLocalhostName,"isLocalhostName"),i(isLocalhostName,"isLocalhostName");function loopbackPortOf(e){if(typeof e.target=="string")try{const r=new URL(e.target),d=r.hostname.toLowerCase();if(isLocalhostName(d)||/^127\./.test(d)||d==="[::1]"||d==="0.0.0.0"){const p=Number(r.port||(r.protocol==="https:"?443:80));if(Number.isInteger(p))return p}}catch{}return e.lens?.port}l(loopbackPortOf,"loopbackPortOf"),i(loopbackPortOf,"loopbackPortOf");function runSocketsDir(e=process.env){return path.resolve(e.LENSMCP_HOME||os.homedir(),".lensmcp","peers","runs")}l(runSocketsDir,"runSocketsDir"),i(runSocketsDir,"runSocketsDir");const runSocketName=i(e=>`${e}.sock`,"runSocketName");exports.runSocketName=runSocketName;function socketPathProblem(e,r,d){const p=path.join(d,(0,exports.runSocketName)(r));if(typeof e!="string"||e.length===0)return`socket, when given, is the path of the run's tunnel socket: ${p}`;if(/[\u0000-\u001f\u007f]/.test(e))return"socket has a control character in it: a run's socket is a plain path";if(!path.isAbsolute(e)||path.normalize(e)!==e||e.endsWith("/"))return`socket must be an absolute path written plainly \u2014 no '.', '..', repeated or trailing '/': ${p}`;const g=e.length>160?`${e.slice(0,160)}\u2026`:e;if(path.dirname(e)!==d)return`socket ${g} is outside ${d}: a run's route forwards only to a tunnel socket in the peers' runs folder of this gateway's home, never to another socket or file`;if(path.basename(e)!==(0,exports.runSocketName)(r))return`socket ${g} is not run '${r}'s: a run's tunnel socket is named for its run (${(0,exports.runSocketName)(r)})`;const c=Buffer.byteLength(e);if(c>exports.MAX_RUN_SOCKET_PATH_BYTES)return`socket is ${c} bytes long, over the ${exports.MAX_RUN_SOCKET_PATH_BYTES} a unix socket's path may have: give LENSMCP_HOME a shorter path`}l(socketPathProblem,"socketPathProblem"),i(socketPathProblem,"socketPathProblem");function runSocketUpstream(e){const r=e.run?.socket;if(!r)return;const d={socketPath:r.path,protocol:"http:",host:"127.0.0.1",port:r.port};return Object.defineProperty(d,"toString",{value:i(()=>`unix:${r.path} (the run's tunnel to its edge at 127.0.0.1:${r.port})`,"value"),enumerable:!1}),d}l(runSocketUpstream,"runSocketUpstream"),i(runSocketUpstream,"runSocketUpstream");const refusal=i((e,r,d,p={})=>({status:e,json:{error:r,message:d,...p}}),"refusal"),bad=i((e,r)=>refusal(400,"bad-request",r,{field:e}),"bad");function readRun(e,r){if(typeof e!="string"||!exports.RUN_ID_PATTERN.test(e))return{refused:bad("runId","runId is required: 8 to 80 letters, digits, `_` or `-`")};const d=runShortId(e);return d?typeof r!="string"||r.length===0||r.length>MAX_WS_KEY_LENGTH?{refused:bad("wsKey","wsKey is required: the key of a workspace registered with this gateway")}:{runId:e,wsKey:r,short:d}:{refused:bad("runId","runId needs eight letters or digits after its prefix: they name the run's host")}}l(readRun,"readRun"),i(readRun,"readRun");function parseRunRouteRequest(e,r={}){if(!e||typeof e!="object"||Array.isArray(e))return{refused:bad("body","the body is a JSON object: { runId, wsKey, port, forSec, socket? }")};const d=e;for(const k of Object.keys(d))if(!REQUEST_FIELDS.has(k))return{refused:bad(k,`'${k.slice(0,40)}' is not a field of a run route \u2014 the gateway derives the host from runId and wsKey, and forwards to 127.0.0.1:<port>, or for a remote run to its tunnel's socket in the peers' runs folder (socket); a request names neither a host nor an upstream`)};const p=readRun(d.runId,d.wsKey);if(p.refused||!p.runId||!p.wsKey)return{refused:p.refused};const{port:g,forSec:c,socket:y}=d;if(typeof g!="number"||!Number.isInteger(g)||g<exports.MIN_RUN_PORT||g>65535)return{refused:bad("port",`port is required: the loopback port the stack's edge is published on, ${exports.MIN_RUN_PORT} to 65535`)};if(typeof c!="number"||!Number.isFinite(c)||c<=0)return{refused:bad("forSec","forSec is required: the seconds the route lives unless asked again (DELETE /run-route removes it)")};if(c>exports.MAX_RUN_ROUTE_SEC)return{refused:bad("forSec",`forSec ${c} is over the ${exports.MAX_RUN_ROUTE_SEC} s (4 h) a route may live \u2014 ask again before it ends to keep it longer`)};if(y!==void 0){const k=socketPathProblem(y,p.runId,r.socketsDir??runSocketsDir());if(k)return{refused:bad("socket",k)}}return{request:{runId:p.runId,wsKey:p.wsKey,port:g,forSec:c,...typeof y=="string"?{socket:y}:{}},short:p.short}}l(parseRunRouteRequest,"parseRunRouteRequest"),i(parseRunRouteRequest,"parseRunRouteRequest");function aim(e,r,d,p){return p===void 0?(e.target=`http://127.0.0.1:${d}`,e.run={id:r.id,wsKey:r.wsKey}):(delete e.target,e.run={id:r.id,wsKey:r.wsKey,socket:{path:p,port:d}}),e}l(aim,"aim"),i(aim,"aim");const whereTo=i((e,r)=>r===void 0?`127.0.0.1:${e}`:`unix:${r} (its edge at 127.0.0.1:${e} of the Mac that runs it)`,"whereTo");function createRunRoutes(e){const{registry:r}=e,d=e.now??Date.now,p=e.log??(t=>console.log(t)),g=e.socketsDir??(()=>runSocketsDir()),c=new Map,y=i(()=>{c.size===0?r.dropStandalone(exports.RUN_ROUTES_STANDALONE_ID):r.setStandalone(exports.RUN_ROUTES_STANDALONE_ID,[...c.values()].map(t=>t.route))},"publish"),k=i(t=>{const s=e.https(),o=e.ownPorts?.()??[],n=s?443:80;return`${s?"https":"http"}://${t}${o.length===0||o.includes(n)?"":`:${o[0]}`}`},"origin"),m=i(t=>({runId:t.runId,wsKey:t.wsKey,host:t.host,origin:k(t.host),port:t.port,registeredAt:t.registeredAt,expiresAt:t.expiresAt,...t.socket!==void 0?{socket:t.socket}:{}}),"view"),N=i(()=>{const t=new Map;for(const s of r.keys())for(const o of r.get(s)?.routes??[])t.set(o,s);return s=>{if(s.run)return`run '${s.run.id}'`;if(s.project===observability_1.LENS_DASHBOARD_PROJECT)return"the lens dashboard";const o=t.get(s)??s.wsKey;return o?`workspace '${o}' (${s.project})`:`'${s.project}'`}},"holders"),T=i((t,s)=>t.find(o=>{const n=o.host?.toLowerCase();return!!n&&(n===s||n.startsWith("*.")&&n.slice(2)===s)}),"declaredBy"),I=i((t,s,o)=>{const n=r.merged().filter(f=>f.run?.id!==s),u=N(),a=i((f,$)=>refusal(409,"host-conflict",`${t} ${$} (${f}): a run's route never takes a host from what the gateway already serves. Nothing was routed.`,{host:t,heldBy:f}),"refused"),h=T(n,t);if(h)return a(u(h),h.host?.startsWith("*.")?`is the name ${h.host} is declared for`:"is already routed");const w=n.find(f=>f.project===observability_1.LENS_DASHBOARD_PROJECT&&!!f.host&&t.endsWith(`.${f.host.toLowerCase()}`));if(w)return a("the lens dashboard",`is under the dashboard's host ${w.host}`);for(const f of r.keys()){if(f===o)continue;const $=r.get(f)?.instance?.apex.toLowerCase();if($&&(t===$||t.endsWith(`.${$}`)))return a(`workspace '${f}'`,`is in the namespace of the worktree instance at ${$}`)}const R=e.parkedHosts?.match(t);if(R)return a(`the parked worktree '${R.name}'`,"is in the namespace of a parked worktree")},"hostRefusal"),U=i((t,s)=>{if(e.ownPorts?.().includes(t))return refusal(409,"upstream-is-gateway",`port ${t} is the gateway's own front door: a run's route forwards to its stack's edge, never back into the gateway. Nothing was routed.`);const o=N(),n=r.merged().find(a=>a.run?.id!==s&&loopbackPortOf(a)===t);if(!n)return;const u=o(n);return refusal(409,"upstream-in-use",n.run?`port ${t} is where ${u} is routed. A port is one stack's edge: if that run has ended, remove its route (DELETE /run-route?runId=${n.run.id}) and ask again. Nothing was routed.`:`port ${t} is what ${u} is served from (${n.host??"its default route"}): a run's route never serves another route's upstream under a second name. Nothing was routed.`,{heldBy:u})},"portRefusal"),D=i((t,s)=>{const o=i(h=>refusal(409,"no-socket",`${h}: a remote run's route forwards to the socket its tunnel serves, and to nothing else. Nothing was routed.`),"no"),n=typeof process.getuid=="function"?process.getuid():void 0,u=path.dirname(t);let a;try{a=fs.lstatSync(u)}catch{return o(`there is no folder ${u}`)}if(a.isSymbolicLink()||!a.isDirectory())return o(`${u} is not a folder of its own (a link, or a file)`);if(n!==void 0&&a.uid!==n)return o(`${u} belongs to another user`);if((a.mode&63)!==0)return o(`${u} is open to other users (mode ${(a.mode&511).toString(8)}, not 700)`);try{a=fs.lstatSync(t)}catch{return o(`nothing serves run '${s}' at ${t}`)}if(!a.isSocket())return o(`${t} is not a socket`);if(n!==void 0&&a.uid!==n)return o(`${t} belongs to another user`);if((a.mode&63)!==0)return o(`${t} is open to other users (mode ${(a.mode&511).toString(8)}, not 600)`)},"socketRefusal"),S=i((t,s)=>{c.delete(t.runId),p(`[gateway] ${new Date(d()).toISOString()} run route removed: ${t.host} (run '${t.runId}', workspace '${t.wsKey}') \u2014 ${s}`)},"drop"),x=i((t=d())=>{const s=[...c.values()].filter(o=>o.expiresAt<=t);if(s.length===0)return[];for(const o of s)S(o,`its lease ended at ${new Date(o.expiresAt).toISOString()} and nothing renewed it`);return y(),e.rebuild(),s.map(o=>o.runId)},"expire"),A=i((t,s,o)=>{const n=r.get(o);if(!n)return{refused:refusal(404,"no-workspace",`no workspace '${o}' is registered with this gateway: a run's host goes under the apex of one it serves`,{workspaces:r.keys()})};const u=c.get(t);if(u&&u.wsKey!==o)return{refused:refusal(409,"run-in-use",`run '${t}' is routed at ${u.host} for workspace '${u.wsKey}': a run has one route. Remove it first (DELETE /run-route?runId=${t}).`,{host:u.host,heldBy:`run '${t}'`})};const a=runApexOf(n);if(!a)return{refused:refusal(409,"no-apex",`the hosts of workspace '${o}' share no apex to name a run under, so its runs have no URL`)};if(!isLocalhostName(a))return{refused:refusal(409,"apex-not-loopback",`the apex of workspace '${o}' is ${a}: a run's URL is served under a .localhost name only \u2014 any other needs a hosts entry per run, and may resolve to another machine. Its runs have no URL.`)};const h=runHost(s,a),w=I(h,t,o);return w?{refused:w}:{host:h,apex:a}},"derive");return{set(t){const s=parseRunRouteRequest(t,{socketsDir:g()});if(s.refused||!s.request||!s.short)return s.refused??bad("body","the request could not be read");const{runId:o,wsKey:n,port:u,forSec:a,socket:h}=s.request,w=d();x(w);const R=A(o,s.short,n);if(R.refused||!R.host||!R.apex)return R.refused??bad("body","the request could not be read");const{host:f,apex:$}=R,O=h===void 0?U(u,o):D(h,o);if(O)return O;const _=c.get(o);if(!_&&c.size>=exports.MAX_RUN_ROUTES)return refusal(409,"too-many-runs",`${c.size} runs are routed already, the most at once (${exports.MAX_RUN_ROUTES}): remove one that ended (GET /run-route lists them).`,{max:exports.MAX_RUN_ROUTES});const E=w+Math.round(a*1e3),b={id:o,wsKey:n};if(_&&_.host===f){const K=_.port!==u||_.socket!==h;return _.port=u,_.socket=h,aim(_.route,b,u,h),_.expiresAt=E,K&&p(`[gateway] ${new Date(w).toISOString()} run route moved: ${f} \u2192 ${whereTo(u,h)} (run '${o}')`),{status:200,json:{ok:!0,renewed:!0,...m(_)}}}const v={runId:o,wsKey:n,apex:$,host:f,port:u,...h!==void 0?{socket:h}:{},registeredAt:_?.registeredAt??w,expiresAt:E,route:aim({host:f,project:exports.RUN_ROUTE_PROJECT},b,u,h)};return c.set(o,v),y(),e.rebuild(),p(`[gateway] ${new Date(w).toISOString()} run route: ${k(f)} \u2192 ${whereTo(u,h)} (run '${o}', workspace '${n}', until ${new Date(E).toISOString()} unless renewed)`),{status:200,json:{ok:!0,renewed:!!_,...m(v)}}},preview(t,s){const o=readRun(t,s);if(o.refused||!o.runId||!o.wsKey||!o.short)return o.refused??bad("runId","the request could not be read");x();const n=A(o.runId,o.short,o.wsKey);if(n.refused||!n.host)return n.refused??bad("runId","the request could not be read");const u=c.get(o.runId),a=!!u&&u.host===n.host;return{status:200,json:{ok:!0,routed:a,runId:o.runId,wsKey:o.wsKey,host:n.host,origin:k(n.host),...a&&u?{port:u.port,registeredAt:u.registeredAt,expiresAt:u.expiresAt}:{}}}},remove(t){if(typeof t!="string"||!exports.RUN_ID_PATTERN.test(t))return bad("runId","runId is required: DELETE /run-route?runId=<the run>");const s=c.get(t);return s&&(S(s,"asked (DELETE /run-route)"),y(),e.rebuild()),{status:200,json:{ok:!0,removed:!!s,runId:t}}},list(){return[...c.values()].sort((t,s)=>t.registeredAt-s.registeredAt).map(m)},get(t){const s=c.get(t);return s?m(s):void 0},expire:x,reconcile(){const t=[];for(const s of[...c.values()]){const o=r.get(s.wsKey);let n;if(!o)n=`workspace '${s.wsKey}' is no longer registered`;else if(runApexOf(o)!==s.apex)n=`the apex of workspace '${s.wsKey}' is no longer ${s.apex}`;else for(const u of r.keys())if(T(r.get(u)?.routes??[],s.host)){n=`workspace '${u}' now declares its host`;break}n&&(S(s,n),t.push(s.runId))}return t.length>0&&y(),t},close(){c.clear(),r.dropStandalone(exports.RUN_ROUTES_STANDALONE_ID)}}}l(createRunRoutes,"createRunRoutes"),i(createRunRoutes,"createRunRoutes");
|