@lensmcp/cluster 1.25.79 → 1.26.0

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.
Files changed (135) hide show
  1. package/build-scope-patterns.d.ts +1 -11
  2. package/build-scope-patterns.js +1 -1
  3. package/create-webpack-prod.d.ts +1 -27
  4. package/create-webpack-prod.js +1 -1
  5. package/executors/build/build.impl.js +1 -1
  6. package/executors/gateway/daemon.d.ts +43 -0
  7. package/executors/gateway/daemon.js +1 -0
  8. package/executors/gateway/gateway.lib.d.ts +1 -1
  9. package/executors/gateway/gateway.lib.js +1 -1
  10. package/executors/gateway/jwks-verify.d.ts +1 -79
  11. package/executors/gateway/jwks-verify.js +1 -1
  12. package/executors/gateway/main.rollout.d.ts +2 -1
  13. package/executors/gateway/main.rollout.js +1 -24
  14. package/executors/gateway/manifest.d.ts +1 -418
  15. package/executors/gateway/manifest.js +1 -1
  16. package/executors/gateway/prod-runtime/trust.d.ts +1 -80
  17. package/executors/gateway/prod-runtime/trust.js +1 -1
  18. package/executors/gateway/rate-limit.d.ts +1 -81
  19. package/executors/gateway/rate-limit.js +1 -18
  20. package/executors/gateway/runtime/auth.d.ts +1 -1
  21. package/executors/gateway/runtime/auth.js +1 -1
  22. package/executors/gateway/runtime/dev-auth.d.ts +3 -2
  23. package/executors/gateway/runtime/dev-auth.js +1 -1
  24. package/executors/gateway/runtime/discovery.js +1 -1
  25. package/executors/gateway/runtime/edge.d.ts +2 -2
  26. package/executors/gateway/runtime/edge.js +1 -1
  27. package/executors/gateway/runtime/handler.js +1 -1
  28. package/executors/gateway/runtime/internal-fetch.d.ts +1 -1
  29. package/executors/gateway/runtime/lens-children.js +1 -1
  30. package/executors/gateway/runtime/lens-modules.d.ts +13 -0
  31. package/executors/gateway/runtime/lens-modules.js +1 -0
  32. package/executors/gateway/runtime/lifecycle.js +1 -1
  33. package/executors/gateway/runtime/observability.js +1 -1
  34. package/executors/gateway/runtime/proxy.js +1 -1
  35. package/executors/gateway/runtime/route-registry.js +1 -1
  36. package/executors/gateway/runtime/serve-launch.d.ts +27 -0
  37. package/executors/gateway/runtime/serve-launch.js +3 -3
  38. package/executors/gateway/runtime/server.d.ts +1 -1
  39. package/executors/gateway/runtime/server.js +2 -2
  40. package/executors/gateway/runtime/services-decl.d.ts +24 -0
  41. package/executors/gateway/runtime/services-decl.js +1 -0
  42. package/executors/gateway/runtime/shared-build.d.ts +2 -2
  43. package/executors/gateway/runtime/shared-build.js +3 -3
  44. package/executors/gateway/runtime/types.d.ts +9 -3
  45. package/executors/gateway/runtime/upgrade.js +1 -1
  46. package/executors/gateway/runtime/workspace-auth.d.ts +1 -1
  47. package/executors/gateway/runtime/workspace-auth.js +1 -1
  48. package/executors/gateway/runtime/workspace-middleware.d.ts +2 -2
  49. package/executors/gateway/runtime/workspace-middleware.js +1 -1
  50. package/executors/serve/lens-run.d.ts +6 -0
  51. package/executors/serve/lens-run.js +1 -0
  52. package/executors/serve/schema.d.ts +2 -0
  53. package/executors/serve/schema.json +4 -0
  54. package/executors/serve/serve.impl.js +1 -1
  55. package/executors/trust/run.d.ts +19 -0
  56. package/executors/trust/run.js +1 -0
  57. package/executors/trust/trust.impl.js +5 -5
  58. package/gateway.d.ts +7 -19
  59. package/gateway.js +1 -1
  60. package/gc-notice.d.ts +3 -1
  61. package/gc-notice.js +1 -1
  62. package/main.devserver.js +7 -7
  63. package/package.json +6 -34
  64. package/pod-memory.d.ts +19 -2
  65. package/pod-memory.js +1 -1
  66. package/tsgo-check-plugin.d.ts +3 -2
  67. package/tsgo-check-plugin.js +3 -3
  68. package/typecheck-bus.d.ts +17 -0
  69. package/typecheck-bus.js +4 -3
  70. package/executors/gateway/body-stall.d.ts +0 -62
  71. package/executors/gateway/body-stall.js +0 -1
  72. package/executors/gateway/canonical-path.d.ts +0 -65
  73. package/executors/gateway/canonical-path.js +0 -1
  74. package/executors/gateway/client-ip.d.ts +0 -82
  75. package/executors/gateway/client-ip.js +0 -1
  76. package/executors/gateway/gateway-errors.d.ts +0 -43
  77. package/executors/gateway/gateway-errors.js +0 -1
  78. package/executors/gateway/health-check.d.ts +0 -52
  79. package/executors/gateway/health-check.js +0 -1
  80. package/executors/gateway/jwt-claims.d.ts +0 -51
  81. package/executors/gateway/jwt-claims.js +0 -1
  82. package/executors/gateway/main.prod-gateway.d.ts +0 -1
  83. package/executors/gateway/main.prod-gateway.js +0 -2
  84. package/executors/gateway/metrics.d.ts +0 -36
  85. package/executors/gateway/metrics.js +0 -1
  86. package/executors/gateway/otel-tracing.d.ts +0 -46
  87. package/executors/gateway/otel-tracing.js +0 -1
  88. package/executors/gateway/prod-config.d.ts +0 -130
  89. package/executors/gateway/prod-config.js +0 -1
  90. package/executors/gateway/prod-gateway.lib.d.ts +0 -19
  91. package/executors/gateway/prod-gateway.lib.js +0 -1
  92. package/executors/gateway/prod-runtime/access-log.d.ts +0 -8
  93. package/executors/gateway/prod-runtime/access-log.js +0 -1
  94. package/executors/gateway/prod-runtime/app.d.ts +0 -30
  95. package/executors/gateway/prod-runtime/app.js +0 -1
  96. package/executors/gateway/prod-runtime/auth.d.ts +0 -29
  97. package/executors/gateway/prod-runtime/auth.js +0 -1
  98. package/executors/gateway/prod-runtime/body-stall.d.ts +0 -5
  99. package/executors/gateway/prod-runtime/body-stall.js +0 -1
  100. package/executors/gateway/prod-runtime/cors.d.ts +0 -18
  101. package/executors/gateway/prod-runtime/cors.js +0 -1
  102. package/executors/gateway/prod-runtime/edge.d.ts +0 -44
  103. package/executors/gateway/prod-runtime/edge.js +0 -1
  104. package/executors/gateway/prod-runtime/handler.d.ts +0 -33
  105. package/executors/gateway/prod-runtime/handler.js +0 -1
  106. package/executors/gateway/prod-runtime/hooks.d.ts +0 -19
  107. package/executors/gateway/prod-runtime/hooks.js +0 -1
  108. package/executors/gateway/prod-runtime/observability.d.ts +0 -24
  109. package/executors/gateway/prod-runtime/observability.js +0 -1
  110. package/executors/gateway/prod-runtime/rollout.d.ts +0 -33
  111. package/executors/gateway/prod-runtime/rollout.js +0 -1
  112. package/executors/gateway/prod-runtime/route-limits.d.ts +0 -30
  113. package/executors/gateway/prod-runtime/route-limits.js +0 -1
  114. package/executors/gateway/prod-runtime/routing.d.ts +0 -3
  115. package/executors/gateway/prod-runtime/routing.js +0 -1
  116. package/executors/gateway/prod-runtime/server.d.ts +0 -17
  117. package/executors/gateway/prod-runtime/server.js +0 -1
  118. package/executors/gateway/prod-runtime/types.d.ts +0 -335
  119. package/executors/gateway/prod-runtime/types.js +0 -1
  120. package/executors/gateway/prod-runtime/upgrade.d.ts +0 -23
  121. package/executors/gateway/prod-runtime/upgrade.js +0 -16
  122. package/executors/gateway/prod-runtime/upstream-errors.d.ts +0 -33
  123. package/executors/gateway/prod-runtime/upstream-errors.js +0 -1
  124. package/executors/gateway/prod-runtime/upstream.d.ts +0 -14
  125. package/executors/gateway/prod-runtime/upstream.js +0 -1
  126. package/executors/gateway/providers-prod.d.ts +0 -54
  127. package/executors/gateway/providers-prod.js +0 -1
  128. package/executors/gateway/registry-source.d.ts +0 -68
  129. package/executors/gateway/registry-source.js +0 -2
  130. package/executors/gateway/rollout-ops.d.ts +0 -53
  131. package/executors/gateway/rollout-ops.js +0 -2
  132. package/executors/gateway/ssrf-guard.d.ts +0 -96
  133. package/executors/gateway/ssrf-guard.js +0 -1
  134. package/executors/gateway/workspace-auth.d.ts +0 -100
  135. package/executors/gateway/workspace-auth.js +0 -1
@@ -1,335 +0,0 @@
1
- /**
2
- * Shared types for the layered PROD gateway runtime. TYPES-ONLY (imports only
3
- * `node:*`, `fastify`, `../manifest`, the provider modules, and `../gateway-errors`
4
- * — never a runtime layer) so every layer imports it without a cycle. The
5
- * composition root (`server.ts`) is the only place concrete layers are wired.
6
- */
7
- import type * as http from 'node:http';
8
- import type { FastifyReply, FastifyRequest } from 'fastify';
9
- import type { AuthMode, Attrs, HostOwners, ManifestProvider, PodProvider, Route, RouteManifest } from '../manifest';
10
- import type { GatewayTracer } from '../otel-tracing';
11
- import type { HealthChecker } from '../health-check';
12
- import type { RateLimiter } from '../rate-limit';
13
- import type { ProcessMetrics } from '../metrics';
14
- export type { Attrs };
15
- /** Per-service health rollup, derived from observed traffic over a rolling window.
16
- * `status` is inferred from the recent error rate (passive — not an active probe):
17
- * healthy <5% err · degraded 5–50% · down ≥50% · idle (no recent traffic). */
18
- export interface ServiceStatus {
19
- service: string;
20
- hosts: string[];
21
- status: 'healthy' | 'degraded' | 'down' | 'idle';
22
- requests: number;
23
- errorRate: number;
24
- avgMs: number;
25
- versions: string[];
26
- lastSeen: number | null;
27
- }
28
- export interface ProdGatewayOptions {
29
- /** Ports to bind. Default `[8080]` (or `[8443]` with TLS). One Fastify
30
- * instance per port; all share the route table + providers. */
31
- ports?: number[];
32
- /** The address every listener binds (issues/closed/foodguard-264). Default `0.0.0.0`, every interface: the
33
- * production contract. `127.0.0.1` or `::1` keeps an owned local fixture loopback-only — FoodGuard's QA had to run
34
- * the real export against its real manifest and could only bind the wildcard. An IP literal or `localhost`;
35
- * anything else is refused before any port is bound. */
36
- host?: string;
37
- manifests: ManifestProvider;
38
- /** Resolves a service → upstream when a route has no direct `upstream`. */
39
- pods?: PodProvider;
40
- /** service → its `x-internal-token` (from a k8s Secret / Vault in prod). A LIST rotates a key without a restart:
41
- * the FIRST entry is the one the gateway stamps on forwarded requests, every entry is accepted from callers.
42
- * Two services sharing a key value refuse boot (PG3-22). Replace live with {@link ProdGatewayHandle.setServiceKeys}. */
43
- serviceKeys?: Record<string, string | string[]>;
44
- /** Networks (IPv4 CIDRs or exact addresses) allowed to reach an `internal.<host>` route. Unset ⇒ any caller with a
45
- * valid key, as before. Set ⇒ a caller whose RESOLVED address is outside gets the no-route 404 (PG3-12). */
46
- internalPeers?: string[];
47
- /** Who may mount which host — `{ hostPattern: [service, …] }`, `(default)` for the catch-all (PG4-06). A mount on a
48
- * host that belongs to other services is dropped and named at load. Unset ⇒ any manifest may mount any host, and
49
- * the longer prefix wins whoever declared it — which is how one registry writer takes `/login` on another's host. */
50
- hostOwners?: HostOwners;
51
- /** WebSocket upgrade ceilings, enforced BEFORE any upstream dial (PG3-20). `maxPendingPerClient`: upgrades from
52
- * one resolved client address still waiting for the upstream's 101 (default 32 → 429). `maxTunnelsPerService`:
53
- * live tunnels per service (default 4096 → 503). `maxTunnelsPerClient`: live tunnels one client address (an IPv6
54
- * /64) may hold (default a quarter of the service ceiling → 429) — without it one client fills the service's
55
- * ceiling alone (PG4-09). `idleMs`: a tunnel that carries no byte in either direction for this long is closed
56
- * (default 600 000; 0 disables) — a WebSocket ping keeps a real one alive. */
57
- upgrades?: {
58
- maxPendingPerClient?: number;
59
- maxTunnelsPerService?: number;
60
- maxTunnelsPerClient?: number;
61
- idleMs?: number;
62
- };
63
- /** Validate a `jwt`-mode request; THROW to reject (→ 401). Default: a
64
- * pass-through with a one-time warning — wire a real JWKS validator in prod. */
65
- authenticate?: (mode: AuthMode, req: http.IncomingMessage) => void;
66
- tls?: {
67
- key: string | Buffer;
68
- cert: string | Buffer;
69
- };
70
- /** Lens bus sink — OPT-IN. Omit (default) for zero observability overhead. */
71
- emit?: (event: Record<string, unknown>) => void;
72
- /** Traffic-edge flush period (ms). Default 5000. */
73
- trafficFlushMs?: number;
74
- /** Request header that PINS a rollout cohort (sticky canary / debugging).
75
- * Default `x-lensmcp-version`. The chosen version is echoed on the response. */
76
- versionHeader?: string;
77
- /** undici pool tuning passed to reply-from. `bodyTimeout: 0` (default) keeps
78
- * long-lived SSE / streamable-HTTP MCP responses open — undici's 300s default
79
- * would otherwise abort an idle stream. `rejectUnauthorized` defaults false
80
- * (local-CA / self-signed upstreams); set true for verified east-west on GCP.
81
- * `allowH2` multiplexes many concurrent streams over few HTTP/2 connections
82
- * (Cloud Run supports h2 end-to-end) — useful when one upstream fans many MCP streams.
83
- * `cert`/`key` present a client certificate to upstreams (mTLS); `ca` trusts a
84
- * private CA for the server side. `rejectUnauthorized:false` keeps mTLS while
85
- * skipping server-cert validation (self-signed internal services). */
86
- undici?: {
87
- connections?: number;
88
- pipelining?: number;
89
- keepAliveTimeout?: number;
90
- bodyTimeout?: number;
91
- headersTimeout?: number;
92
- rejectUnauthorized?: boolean;
93
- allowH2?: boolean;
94
- cert?: string | Buffer;
95
- key?: string | Buffer;
96
- ca?: string | Buffer;
97
- };
98
- /** Header carrying the AUTHORITATIVE client IP from a trusted front proxy
99
- * (e.g. `cf-connecting-ip` behind Cloudflare). When set, the `ip` ABAC
100
- * attribute comes from this header instead of the (multi-proxy, spoofable)
101
- * X-Forwarded-For chain. Safe only when the origin is locked to that proxy —
102
- * which Cloudflare Tunnel guarantees (there is no public origin to bypass). */
103
- clientIpHeader?: string;
104
- /** A secret the front proxy adds to every request, e.g. a Cloudflare Transform Rule setting
105
- * `x-lensmcp-proxy-secret` (PG4-17). When set, a peer is the trusted proxy only if its address is trusted AND the
106
- * request carries it — «the peer is loopback» alone is true of every process in the gateway's network namespace.
107
- * The header never reaches an upstream. `header` defaults to `x-lensmcp-proxy-secret`. */
108
- clientIpProxySecret?: {
109
- header?: string;
110
- value: string;
111
- };
112
- /** CIDRs of trusted front proxies. `clientIpHeader` is honored ONLY when the
113
- * immediate peer (socket address) is in this set — otherwise the header is
114
- * ignored and the socket IP is used (prevents spoofing the `ip` ABAC attribute
115
- * by hitting the origin directly). Default when omitted: loopback only
116
- * (matches a co-located cloudflared/sidecar). */
117
- clientIpTrustedProxies?: string[];
118
- /** OpenTelemetry tracer (from `setupTracing`). When set, each request gets a
119
- * SERVER span whose context is propagated downstream (W3C `traceparent`), so
120
- * the gateway hop stitches into the distributed trace. Omit → no span work. */
121
- tracing?: GatewayTracer;
122
- /** Expose `GET /statusz` — the per-service health rollup as JSON. Requires
123
- * `statusToken` too (fail-closed: served only when both are set). Default off (404). */
124
- statusEndpoint?: boolean;
125
- /** Token `/statusz` requires (via `?token=` or `x-status-token`), compared in
126
- * constant time. REQUIRED for the endpoint to serve — no token → /statusz is 404. */
127
- statusToken?: string;
128
- /** How many flush windows the rolling status sums over (default 12 → ~60s at the 5s flush). */
129
- statusWindows?: number;
130
- /** Called each flush window with the per-service status snapshot — wire it to a
131
- * Redis `status:*` fan-out / status page. The gateway is the only thing that
132
- * sees every request, so this is the natural source of observed health. */
133
- onStatus?: (snapshot: ServiceStatus[]) => void;
134
- /** Active upstream health-checker (from `createHealthChecker`). When set, the
135
- * gateway probes upstreams, steers pooled picks toward healthy endpoints, and
136
- * reflects true liveness in /statusz. Omit → passive drop-on-error only. */
137
- healthChecker?: HealthChecker;
138
- /** Opt-in per-client-IP rate limiter — defense-in-depth behind the edge throttle.
139
- * In-memory + per-instance (`createRateLimiter`) or ONE global budget across all
140
- * containers (`createRedisRateLimiter`). The check is `await`ed either way; it
141
- * runs before routing/auth and applies only to proxied traffic (ops endpoints exempt). */
142
- rateLimiter?: RateLimiter;
143
- /** Builds the limiter behind a manifest's `rateLimits` entry (PG4-19) — one per distinct `points` / `duration`.
144
- * Default: the in-memory token bucket (per process). Pass a Redis-backed factory for one budget across replicas. */
145
- routeLimiter?: (limit: number, windowMs: number) => RateLimiter;
146
- /** Process self-metrics (event-loop lag / rss / cpu / req rates) from `createProcessMetrics`;
147
- * exposed at the token-gated `/metricsz` for load/stress tests + production monitoring. */
148
- metrics?: ProcessMetrics;
149
- /** Server-side HTTP timeouts (ms). `keepAliveTimeout` default 620000 — kept
150
- * ABOVE the GCP external ALB's 600s backend keep-alive so the gateway never
151
- * closes a pooled connection the LB still considers live (the classic
152
- * intermittent-502 race). `requestTimeout` default 0 (disabled) for streaming. */
153
- /** `bodyStallMs` bounds INBOUND PROGRESS, not request duration: a request that has
154
- * transferred nothing for this long is aborted (default 60 s; `0` disables). It is the
155
- * bound `requestTimeout: 0` deliberately gives up — without it a trickled body pins an
156
- * upstream pool connection indefinitely. A slow-but-progressing upload is never touched. */
157
- /** `headersTimeout` bounds the HEADER phase (default 60000 — Node's own, and the only bound
158
- * on a slowloris that never completes its headers, since `bodyStallMs` arms only after them).
159
- * `maxHeadersCount` / `maxConnections` are opt-in ceilings for a directly-exposed edge. */
160
- /** `readyStallMs`: `/readyz` answers 503 while a proxied request has waited this long for an upstream's response
161
- * head (a wedged pool, PG3-29). Default: the upstream headers timeout + 5 s; 0 disables the check. */
162
- /** `bodyMinRateBps`: the rate a request BODY must average once `bodyRateGraceMs` (default 30 000) is spent — default
163
- * 500 bytes/s, 0 disables. A stall bound calls one byte a minute progress; this is what stops a trickled upload
164
- * from holding an upstream pool connection (PG4-04). `maxInFlightPerClient`: proxied requests one client address
165
- * may have in flight (→ 429). OFF by default — it is only safe once the gateway resolves real client addresses
166
- * (behind a proxy it does not trust, every caller is one address). */
167
- server?: {
168
- keepAliveTimeout?: number;
169
- requestTimeout?: number;
170
- connectionTimeout?: number;
171
- headersTimeout?: number;
172
- bodyStallMs?: number;
173
- bodyMinRateBps?: number;
174
- bodyRateGraceMs?: number;
175
- maxInFlightPerClient?: number;
176
- maxHeadersCount?: number;
177
- maxConnections?: number;
178
- connectionsCheckingInterval?: number;
179
- readyStallMs?: number;
180
- };
181
- /** Replays of an idempotent upstream request whose connection failed. Default 1 — which also
182
- * disables `@fastify/reply-from`'s built-in 503 storm (10 replays of any GET that draws a
183
- * 503, delayed by the upstream's own `Retry-After`). 0 = never replay. */
184
- upstreamRetries?: number;
185
- /** Opt-in one-JSON-line-per-request access log to stdout, shaped for Cloud
186
- * Logging (severity + time + message). Default off (zero overhead). */
187
- accessLog?: boolean;
188
- /** Browser origins allowed to make CREDENTIALED cross-origin requests (cookies /
189
- * `credentials: 'include'`). For an origin in this allowlist the gateway answers preflights — and
190
- * stamps gateway-generated responses — with `Access-Control-Allow-Origin: <exact origin>` +
191
- * `Access-Control-Allow-Credentials: true` (NEVER `*`: a credentialed `*` is forbidden by the Fetch
192
- * spec and a cross-site read hole). Needed when a first-party browser app POSTs to a routed service
193
- * that sets a cookie (e.g. an IdP SSO cookie set across `login.example.com → auth.example.com`).
194
- * Exact-matched, case-insensitive. Omit (default) → no credentialed CORS (the Bearer-only edge). */
195
- corsCredentialOrigins?: string[];
196
- /** Return verified subject attributes (e.g. JWT claims) for ABAC routing.
197
- * MUST verify (signature/exp) — forged claims must not reach the rules.
198
- * Answer synchronously whenever possible: it runs on every identity-routed request, and the
199
- * gateway awaits ONLY a returned `Promise` (so a sync answer costs no microtask). Return one
200
- * only to wait — e.g. a JWKS `kid` miss waiting on the key-set refresh (`bearerIdentify`,
201
- * issues/closed/prod-gateway-20). A rejection fails the request, as a throw does. */
202
- identify?: (req: http.IncomingMessage) => Record<string, unknown> | undefined | Promise<Record<string, unknown> | undefined>;
203
- /** Allowlist of request headers exposed to rules as `header.<name>` attributes. */
204
- attributeHeaders?: string[];
205
- /** Take the `ip` attribute from `X-Forwarded-For` (behind a trusted LB); default false →
206
- * socket IP. See {@link trustProxyHops} for WHICH entry of the chain is read. */
207
- trustProxyIp?: boolean;
208
- /** How many proxy hops in front of the gateway are trusted to have appended to
209
- * `X-Forwarded-For`. Default 1 (the nearest proxy), so the address read is the one THAT proxy
210
- * observed. Trusting every hop — which is what `trustProxy: true` means — would make the
211
- * attribute the leftmost entry, i.e. a value any client can write for itself. */
212
- trustProxyHops?: number;
213
- /** Gateway-issued device cookie for sticky bucketing (anonymous-friendly).
214
- * Omit to disable cookie stickiness. `secret` is REQUIRED — an unsigned cookie is a value the
215
- * client chooses, so without one the cookie is refused and stickiness stays off. */
216
- cookie?: {
217
- name?: string;
218
- secret?: string;
219
- domain?: string;
220
- maxAge?: number;
221
- };
222
- /** Header carrying a client device/user id — the sticky key when no cookie
223
- * is present (native/mobile/API clients), e.g. `x-device-id`. */
224
- uidHeader?: string;
225
- /** Customer-supplied lifecycle hooks layered on the built-in pipeline (see hooks.ts). */
226
- hooks?: ProdGatewayHooks;
227
- }
228
- export interface ProdGatewayHandle {
229
- ports: number[];
230
- /** The address the listeners bound — `0.0.0.0` unless {@link ProdGatewayOptions.host} said otherwise. */
231
- host: string;
232
- routes: () => Route[];
233
- status: () => ServiceStatus[];
234
- /** Re-derive the health-checked upstream set. Call after an ENDPOINTS reload (a rollout
235
- * ramp / cohort add) — the manifest watch already does this on its own changes, and
236
- * without it a new cohort's endpoints are never probed, only assumed healthy. */
237
- refreshUpstreams: () => void;
238
- /** Swap the service-key registry live (a rotated `keys.json`). Throws — and keeps the current keys — when the
239
- * new map is invalid (two services sharing a key). */
240
- setServiceKeys: (keys: Record<string, string | string[]>) => void;
241
- stop: () => Promise<void>;
242
- }
243
- /** The reply surface {@link sendError} uses — structural so BOTH the HTTP/1 and HTTP/2 fastify reply
244
- * generics (e.g. the `@fastify/reply-from` `onError` reply) satisfy it without a cast. */
245
- export interface ReplyLike {
246
- code(statusCode: number): ReplyLike;
247
- header(key: string, value: string): ReplyLike;
248
- type(contentType: string): ReplyLike;
249
- send(payload: string): ReplyLike;
250
- }
251
- /** Per-request state stashed between the handler and the onResponse hook
252
- * (edge + trace finish) — keyed by the request object, no decoration needed. */
253
- export interface ReqState {
254
- route: Route;
255
- caller?: string;
256
- startedAt: number;
257
- trace?: GwTrace;
258
- version?: string;
259
- upLabel: string;
260
- proxied?: boolean;
261
- }
262
- export interface GwTrace {
263
- startedAt: number;
264
- method: string;
265
- host: string;
266
- url: string;
267
- steps: Array<Record<string, unknown>>;
268
- flowId?: string;
269
- requestId?: string;
270
- done?: boolean;
271
- }
272
- /** The mutable route table, content-replaced atomically on a manifest rebuild
273
- * (the array + map identities are STABLE so layers can hold the reference). */
274
- export interface RouteTable {
275
- routes: Route[];
276
- manifestByService: Map<string, RouteManifest>;
277
- rebuild(next: RouteManifest[]): void;
278
- /** Re-derive + re-track the health-checked upstream set (manifest URLs ∪ pooled endpoints). */
279
- trackUpstreams(): void;
280
- manifests(): RouteManifest[];
281
- stop(): void;
282
- }
283
- /** Shared state + config for the prod layers (no layer-produced functions → acyclic).
284
- * `opts` is read pervasively (providers are DI'd through it); `table` holds the live
285
- * route refs; the rest is option-derived config resolved once in `server.ts`. */
286
- /** Requests waiting on an upstream's response head — `/readyz` reads the oldest to notice a wedged pool (PG3-29). */
287
- export interface UpstreamWaits {
288
- /** Start a wait; the returned function ends it (idempotent). */
289
- begin(): () => void;
290
- /** Age in ms of the oldest open wait (0 when none). */
291
- oldestMs(): number;
292
- }
293
- export interface ProdRuntime {
294
- readonly opts: ProdGatewayOptions;
295
- readonly table: RouteTable;
296
- /** Presented key → service. Replaced in place by `setServiceKeys` (same Map identity). */
297
- readonly keyToProject: ReadonlyMap<string, string>;
298
- /** The key the gateway stamps as `x-internal-token` on a request it forwards to `service`. */
299
- serviceKeyOf(service: string): string | undefined;
300
- readonly upstreamWaits: UpstreamWaits;
301
- readonly versionHeader: string;
302
- readonly accessLog: boolean;
303
- readonly corsCredentialOrigins: ReadonlySet<string>;
304
- }
305
- export type ProdGatewayPhase = 'onRequest' | 'beforeAuth' | 'afterAuth' | 'beforeForward' | 'onResponse' | 'onError' | 'onUpgrade';
306
- export type ProdHookHandler = (ctx: ProdHookContext) => void | Promise<void>;
307
- export interface ProdGatewayHooks {
308
- onRequest?: ProdHookHandler[];
309
- beforeAuth?: ProdHookHandler[];
310
- afterAuth?: ProdHookHandler[];
311
- beforeForward?: ProdHookHandler[];
312
- onResponse?: ProdHookHandler[];
313
- onError?: ProdHookHandler[];
314
- onUpgrade?: ProdHookHandler[];
315
- }
316
- /** Context passed to every prod hook — a typed view over the in-flight request. */
317
- export interface ProdHookContext {
318
- /** Raw node request (header mutation flows downstream to the upstream). */
319
- readonly req: http.IncomingMessage;
320
- /** The Fastify request (absent on a WebSocket upgrade). */
321
- readonly request?: FastifyRequest;
322
- /** The Fastify reply (absent on a WebSocket upgrade). */
323
- readonly reply?: FastifyReply;
324
- /** The raw upgrade socket (present only on a WebSocket upgrade). */
325
- readonly socket?: import('node:net').Socket;
326
- route?: Route;
327
- caller?: string;
328
- claims?: Record<string, unknown>;
329
- version?: string;
330
- readonly trace?: GwTrace;
331
- error?: Error;
332
- status?: number;
333
- sendError(status: number, reason: import('../gateway-errors').GatewayErrorReason, detail?: string): void;
334
- responded(): boolean;
335
- }
@@ -1 +0,0 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});
@@ -1,23 +0,0 @@
1
- import * as net from 'node:net';
2
- import type * as http from 'node:http';
3
- import type { RouteLimits } from './route-limits';
4
- import type { ProdRuntime } from './types';
5
- import type { Observability } from './observability';
6
- import type { EdgeAuth } from './auth';
7
- import type { UpstreamLayer } from './upstream';
8
- import type { HooksLayer } from './hooks';
9
- import type { RolloutLayer } from './rollout';
10
- export interface UpgradeDeps {
11
- rt: ProdRuntime;
12
- obs: Observability;
13
- auth: EdgeAuth;
14
- upstream: UpstreamLayer;
15
- hooks: HooksLayer;
16
- rollout: RolloutLayer;
17
- routeLimits: RouteLimits;
18
- }
19
- export type UpgradeListener = ((req: http.IncomingMessage, socket: net.Socket, head: Buffer) => void) & {
20
- /** Destroy every live tunnel and pending handshake — `stop()` calls it so a WebSocket cannot pin the drain. */
21
- closeAll(): void;
22
- };
23
- export declare function createUpgrade(deps: UpgradeDeps): UpgradeListener;
@@ -1,16 +0,0 @@
1
- "use strict";var be=Object.defineProperty;var V=(l,s)=>be(l,"name",{value:s,configurable:!0});var ve=Object.defineProperty,d=V((l,s)=>ve(l,"name",{value:s,configurable:!0}),"d");Object.defineProperty(exports,"__esModule",{value:!0}),exports.createUpgrade=createUpgrade;const tslib_1=require("tslib"),node_crypto_1=require("node:crypto"),net=tslib_1.__importStar(require("node:net")),tls=tslib_1.__importStar(require("node:tls")),manifest_1=require("../manifest"),client_ip_1=require("../client-ip"),gateway_errors_1=require("../gateway-errors"),edge_1=require("./edge"),trust_1=require("./trust"),validHeaderValue=d(l=>/^[\t\x20-\x7e\x80-\xff]*$/.test(l),"validHeaderValue"),validToken=d(l=>/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(l),"validToken"),WS_GUID="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",WS_KEY=/^[A-Za-z0-9+/]{22}==$/,acceptFor=d(l=>(0,node_crypto_1.createHash)("sha1").update(l+WS_GUID).digest("base64"),"acceptFor"),OWN_LINES=new Set(["host","connection"]),DEFAULT_TUNNEL_IDLE_MS=6e5,DEFAULT_MAX_PENDING_PER_CLIENT=32,DEFAULT_MAX_TUNNELS_PER_SERVICE=4096,MAX_HEAD_BYTES=64*1024,HANDSHAKE_TIMEOUT_MS=3e4;function createUpgrade(l){const{rt:s,obs:c,auth:X,upstream:ge,hooks:u,rollout:_,routeLimits:le}=l,fe=Math.max(1,s.opts.upgrades?.maxPendingPerClient??DEFAULT_MAX_PENDING_PER_CLIENT),Y=Math.max(1,s.opts.upgrades?.maxTunnelsPerService??DEFAULT_MAX_TUNNELS_PER_SERVICE),he=Math.max(1,Math.floor(s.opts.upgrades?.maxTunnelsPerClient??Math.max(1,Y/4))),Z=Math.max(0,s.opts.upgrades?.idleMs??DEFAULT_TUNNEL_IDLE_MS),H=new Map,U=new Map,L=new Map,v=new Set,x=d((e,t,i)=>{const p=(e.get(t)??0)+i;p>0?e.set(t,p):e.delete(t)},"bump"),h=d((e,t,i,p)=>{c.emit("warning",`gateway upgrade rejected (${t})${i?` for ${i}`:""}`,`gateway-upgrade:${i??"(none)"}:${t}`,{kind:"gateway-upgrade-rejected",reason:t,...i?{project:i}:{},...p}),e.destroy()},"reject"),w=d((e,t,i="")=>{try{e.end(`HTTP/1.1 ${t}\r
2
- ${i}Connection: close\r
3
- Content-Length: 0\r
4
- \r
5
- `)}catch{e.destroy()}},"refuse"),we=d(async(e,t,i)=>{const p={...e.headers};(0,trust_1.stripTrust)(e),delete e.headers["x-status-token"],(0,gateway_errors_1.ensureRequestId)(e);const o=u.any?u.upgradeContext(e,t,void 0):void 0;if(o&&u.has("onRequest")&&(await u.run("onRequest",o),o.responded()))return;if(e.method==="TRACE"||e.method==="TRACK"){w(t,"405 Method Not Allowed");return}const J=(0,edge_1.parseHost)(e.headers.host);if(!J){w(t,"400 Bad Request");return}const P=J.name,T=(0,edge_1.canonicalize)(e.url??"/");if(T===void 0){h(t,"bad-path");return}const N=T.policy;e.url=T.path+T.query;const r=(0,manifest_1.matchRoute)(s.table.routes,P,N+T.query);if(!r){h(t,"no-route",void 0,{host:P});return}o&&(o.route=r);const q=e.socket?.remoteAddress??"",R=_.clientIpOf(e,q),ye=_.proxyKind(e,q);_.dropProxySecret(e),(0,trust_1.stripProxyClaims)(e.headers,ye,_.proxyHeaders);const m=(0,client_ip_1.limiterKey)(R);if(s.opts.rateLimiter){const a=await s.opts.rateLimiter.check(m);if(!a.allowed){c.emit("warning",`gateway upgrade rate-limited for ${r.service}`,`gateway-upgrade:${r.service}:rate-limited`,{kind:"gateway-upgrade-rejected",reason:"rate-limited",project:r.service}),w(t,"429 Too Many Requests",`Retry-After: ${Math.ceil(a.retryAfterMs/1e3)}\r
6
- `);return}}if(r.internal&&s.opts.internalPeers?.length&&!(0,client_ip_1.addressIn)(R,s.opts.internalPeers)){h(t,"no-route",void 0,{host:P});return}const Q=(0,edge_1.hdr)(e.headers["sec-websocket-key"])??"",me=e.headers["transfer-encoding"]!==void 0||e.headers["content-length"]!==void 0&&e.headers["content-length"]!=="0";if(e.method!=="GET"||String(e.headers.upgrade??"").toLowerCase()!=="websocket"||(0,edge_1.hdr)(e.headers["sec-websocket-version"])!=="13"||!WS_KEY.test(Q)||me){c.emit("warning",`gateway upgrade refused for ${r.service}: not a WebSocket handshake`,`gateway-upgrade:${r.service}:not-websocket`,{kind:"gateway-upgrade-rejected",reason:"not-websocket",project:r.service,upgrade:String(e.headers.upgrade??"").slice(0,40),method:e.method}),w(t,"400 Bad Request");return}if(o&&u.has("beforeAuth")&&(await u.run("beforeAuth",o),o.responded()))return;const I=r.internal?void 0:s.opts.identify?.(e),C=I instanceof Promise?await I:I;if(t.destroyed)return;let D;if(r.internal){const a=X.internal(e,r,void 0);if(!a.ok){h(t,"auth-failed",r.service);return}D=a.caller,o&&(o.caller=D)}else{if(!X.public(e,r,N,C,R,void 0).ok){h(t,"auth-failed",r.service);return}if(o&&(o.claims=C),o&&u.has("afterAuth")&&(await u.run("afterAuth",o),o.responded()))return}const ee=le.check(r,N,{ip:m,tenant:C?.tid,user:C?.sub}),re=ee?await ee:void 0;if(re){c.emit("warning",`gateway upgrade rate-limited for ${r.service} (route limit)`,`gateway-upgrade:${r.service}:route-limited`,{kind:"gateway-upgrade-rejected",reason:"route-limited",project:r.service}),w(t,"429 Too Many Requests",`Retry-After: ${Math.max(1,Math.ceil(re.retryAfterMs/1e3))}\r
7
- `);return}if((0,trust_1.countHop)(e)===void 0){h(t,"loop",r.service);return}e.headers["x-forwarded-for"]=_.forwardedFor(e,q),e.headers["x-forwarded-proto"]=_.forwardedProto(e,q,s.opts.tls?"https":"http"),e.headers["x-forwarded-host"]=e.headers.host??P,e.headers["x-real-ip"]=R;const te=s.serviceKeyOf(r.service);if(te&&(e.headers["x-internal-token"]=te),r.prependPrefix){const a=e.url??"/",n=r.prependPrefix;a!==n&&!a.startsWith(n+"/")&&(e.url=n+a)}const $e=(0,edge_1.hdr)(e.headers[s.versionHeader]),M=await ge.resolveUpstream(r,void 0,$e);if(!M||!("url"in M)){h(t,"no-upstream",r.service);return}const y=new URL(M.url),ae=y.pathname.replace(/\/+$/,"");if(ae&&(e.url=ae+(e.url??"/")),o&&(o.version=M.version),o&&u.has("beforeForward")&&(await u.run("beforeForward",o),o.responded())||o&&u.has("onUpgrade")&&(await u.run("onUpgrade",o),o.responded())||t.destroyed)return;const oe=e.method??"GET",O=e.url??"/";if(!validToken(oe)||!validHeaderValue(O)||O.includes(" ")){h(t,"bad-request-line",r.service);return}const F=[`${oe} ${O} HTTP/1.1`,`Host: ${y.host}`,"Connection: Upgrade"];for(let a=0;a<e.rawHeaders.length;a+=2){const n=e.rawHeaders[a],f=e.rawHeaders[a+1]??"",k=n.toLowerCase();if(OWN_LINES.has(k))continue;const j=e.headers[k];if(!(j===void 0||j!==p[k])){if(!validToken(n)||!validHeaderValue(f)){h(t,"bad-header",r.service,{header:k});return}F.push(`${n}: ${f}`)}}for(const a of Object.keys(e.headers)){const n=e.headers[a];if(!(OWN_LINES.has(a)||n===void 0||n===p[a])){for(const f of Array.isArray(n)?n:[n])if(!(typeof f!="string"||f==="")){if(!validToken(a)||!validHeaderValue(f)){h(t,"bad-identity-value",r.service,{header:a});return}F.push(`${a}: ${f}`)}}}if((H.get(m)??0)>=fe){c.emit("warning",`gateway upgrade refused for ${r.service}: too many pending upgrades from one client`,`gateway-upgrade:${r.service}:pending-cap`,{kind:"gateway-upgrade-rejected",reason:"pending-cap",project:r.service}),w(t,"429 Too Many Requests",`Retry-After: 1\r
8
- `);return}if((L.get(m)??0)>=he){c.emit("warning",`gateway upgrade refused for ${r.service}: one client holds its share of live tunnels`,`gateway-upgrade:${r.service}:client-tunnel-cap`,{kind:"gateway-upgrade-rejected",reason:"client-tunnel-cap",project:r.service}),w(t,"429 Too Many Requests",`Retry-After: 5\r
9
- `);return}if((U.get(r.service)??0)>=Y){c.emit("warning",`gateway upgrade refused for ${r.service}: live tunnel ceiling reached`,`gateway-upgrade:${r.service}:tunnel-cap`,{kind:"gateway-upgrade-rejected",reason:"tunnel-cap",project:r.service}),w(t,"503 Service Unavailable",`Retry-After: 5\r
10
- `);return}i?.length&&c.emit("warning",`gateway upgrade for ${r.service}: client sent ${i.length} byte(s) before the 101`,`gateway-upgrade:${r.service}:head-before-101`,{kind:"gateway-upgrade-anomaly",reason:"head-before-101",project:r.service,bytes:i.length});const B=y.protocol==="https:"||y.protocol==="wss:",se=Number(y.port)||(B?443:80),$=s.opts.undici,g=B?tls.connect({port:se,host:y.hostname,...net.isIP(y.hostname)?{}:{servername:y.hostname},rejectUnauthorized:$?.rejectUnauthorized??!1,...$?.cert?{cert:$.cert}:{},...$?.key?{key:$.key}:{},...$?.ca?{ca:$.ca}:{}}):net.connect(se,y.hostname);v.add(t),x(H,m,1);let ne=!0;const z=d(()=>{ne&&(ne=!1,x(H,m,-1))},"endPending");let E=!1,A=!1;const ie=d(()=>{z(),E&&(E=!1,x(U,r.service,-1),x(L,m,-1)),v.delete(t),g.destroy(),t.destroy()},"teardown"),b=d(a=>{if(A){ie();return}A=!0,clearTimeout(K),c.emit("warning",`gateway upgrade failed (${a}) for ${r.service}`,`gateway-upgrade:${r.service}:${a}`,{kind:"gateway-upgrade-rejected",reason:a,project:r.service}),ie()},"abort"),K=setTimeout(()=>b("handshake-timeout"),HANDSHAKE_TIMEOUT_MS);K.unref?.(),g.on("error",()=>b("upstream-error")),t.on("error",()=>b("client-error")),t.on("close",()=>{E||!A?b("client-closed"):(z(),v.delete(t))}),g.on(B?"secureConnect":"connect",()=>{g.write(F.join(`\r
11
- `)+`\r
12
- \r
13
- `)});const de=[];let ce=0;const ue=d(a=>{if(A)return;de.push(a),ce+=a.length;const n=Buffer.concat(de),f=n.indexOf(`\r
14
- \r
15
- `);if(f===-1){ce>MAX_HEAD_BYTES&&b("oversized-response-head");return}A=!0,clearTimeout(K),g.off("data",ue),z();const k=n.subarray(0,f).toString("latin1").split(`\r
16
- `),j=Number(/^HTTP\/1\.[01] (\d{3})/.exec(k[0]??"")?.[1]);if(j!==101){c.emit("warning",`gateway upgrade refused upstream (${j||"malformed"}) for ${r.service}`,`gateway-upgrade:${r.service}:upstream-refused`,{kind:"gateway-upgrade-rejected",reason:"upstream-refused",project:r.service,status:j||0}),v.delete(t),t.end(n.subarray(0,f+4)),g.destroy();return}const S=new Map;for(const W of k.slice(1)){const G=W.indexOf(":");if(G>0){const pe=W.slice(0,G).trim().toLowerCase();S.has(pe)||S.set(pe,W.slice(G+1).trim())}}if((S.get("upgrade")??"").toLowerCase()!=="websocket"||S.get("sec-websocket-accept")!==acceptFor(Q)){c.emit("warning",`gateway upgrade for ${r.service}: the upstream's 101 does not answer the WebSocket handshake`,`gateway-upgrade:${r.service}:upstream-bad-101`,{kind:"gateway-upgrade-rejected",reason:"upstream-bad-101",project:r.service,upgrade:(S.get("upgrade")??"").slice(0,40)}),v.delete(t),w(t,"502 Bad Gateway"),g.destroy();return}c.recordEdge(r,0,101,D,M.version),E=!0,x(U,r.service,1),x(L,m,1),Z>0&&(t.setTimeout(Z),t.once("timeout",()=>b("idle"))),t.write(n),i?.length&&g.write(i),g.pipe(t),t.pipe(g)},"onHead");g.on("data",ue),g.on("close",()=>{(!A||E)&&b("upstream-closed")})},"run");return Object.assign(d((e,t,i)=>{t.on("error",()=>{}),we(e,t,i).catch(p=>{c.emit("error",`gateway upgrade error: ${p?.message??String(p)}`,"gateway-upgrade:(none):exception",{kind:"gateway-upgrade-rejected",reason:"exception",error:p?.message??String(p)});try{t.destroy()}catch{}})},"listener"),{closeAll(){for(const e of[...v])try{e.destroy()}catch{}v.clear()}})}V(createUpgrade,"createUpgrade"),d(createUpgrade,"createUpgrade");
@@ -1,33 +0,0 @@
1
- /**
2
- * What a failed proxy hop says about the UPSTREAM — the classification reply-from's `onError` needs before it may
3
- * eject an endpoint (PG3-18).
4
- *
5
- * The handler used to call `pods.drop` for EVERY error, including undici refusing to build the request at all — a
6
- * request the upstream never saw, whose cause was a header the client chose. Four anonymous requests ejected every
7
- * endpoint of a service (30 s, doubling to 5 min): a client edited the pool's view of health. Now:
8
- * - {@link refusedBeforeDispatch}: undici refused the request itself (`invalid … header`, `… not supported`). The
9
- * client's fault → 400, and never an ejection.
10
- * - {@link upstreamTransportFailure}: positive evidence about the upstream (refused / reset / unreachable / DNS /
11
- * timeout / TLS). The only errors that eject.
12
- * - anything else: 502, no ejection — not knowing is not evidence.
13
- *
14
- * reply-from wraps undici's errors: ENOTFOUND → `FST_REPLY_FROM_SERVICE_UNAVAILABLE`, headers timeout →
15
- * `FST_REPLY_FROM_GATEWAY_TIMEOUT`, `ECONNRESET` / `UND_ERR_SOCKET` / `UND_ERR_CONNECT_TIMEOUT` keep their code, and
16
- * everything else (ECONNREFUSED and the validation errors alike) becomes `FST_REPLY_FROM_INTERNAL_SERVER_ERROR` with
17
- * the original message — so the message is what tells those two apart.
18
- */
19
- import type * as http from 'node:http';
20
- export interface ProxyError {
21
- code?: string;
22
- message?: string;
23
- }
24
- export declare const refusedBeforeDispatch: (e: ProxyError | undefined) => boolean;
25
- export declare const upstreamTransportFailure: (e: ProxyError | undefined) => boolean;
26
- /**
27
- * Did the CALLER end this exchange (issues/closed/prod-gateway-4-03)? An inbound request destroyed before it was
28
- * complete, or a response / socket already gone, means the hop failed from the client's side — and that failure
29
- * reaches reply-from spelled exactly like an upstream reset (`ECONNRESET`). It is no evidence about the upstream, so
30
- * it must never eject one: a single abandoned upload used to take the live endpoint out for 30 s (doubling to
31
- * 5 min), which moved every other caller onto whatever cohort was left.
32
- */
33
- export declare const clientWentAway: (req: http.IncomingMessage, res: http.ServerResponse) => boolean;
@@ -1 +0,0 @@
1
- "use strict";var _=Object.defineProperty;var r=(e,t)=>_(e,"name",{value:t,configurable:!0});var T=Object.defineProperty,E=r((e,t)=>T(e,"name",{value:t,configurable:!0}),"E");Object.defineProperty(exports,"__esModule",{value:!0}),exports.clientWentAway=exports.upstreamTransportFailure=exports.refusedBeforeDispatch=void 0;const REFUSED_MESSAGE=/^(invalid [\w-]+ header|invalid header key|[\w-]+ header not supported|duplicate [\w-]+ header|invalid request (path|method)|(path|method) must be )/i,refusedBeforeDispatch=E(e=>!!e&&(e.code==="UND_ERR_INVALID_ARG"||e.code==="UND_ERR_NOT_SUPPORTED"||REFUSED_MESSAGE.test(e.message??"")),"refusedBeforeDispatch");exports.refusedBeforeDispatch=refusedBeforeDispatch;const TRANSPORT_CODES=new Set(["FST_REPLY_FROM_SERVICE_UNAVAILABLE","FST_REPLY_FROM_GATEWAY_TIMEOUT","FST_REPLY_FROM_TIMEOUT","FST_REPLY_FROM_HTTP_REQUEST_TIMEOUT","FST_REPLY_FROM_HTTP2_REQUEST_TIMEOUT","FST_REPLY_FROM_HTTP2_SESSION_TIMEOUT","ECONNRESET","ECONNREFUSED","UND_ERR_SOCKET","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_CLOSED"]),TRANSPORT_MESSAGE=/\b(ECONNREFUSED|ECONNRESET|EHOSTUNREACH|ENETUNREACH|EHOSTDOWN|ETIMEDOUT|EAI_AGAIN|ENOTFOUND|EPIPE|ECONNABORTED|ERR_HTTP2_\w+|ERR_TLS_\w+)\b|other side closed|socket hang up|certificate|self[- ]signed/i,upstreamTransportFailure=E(e=>!!e&&!(0,exports.refusedBeforeDispatch)(e)&&(TRANSPORT_CODES.has(e.code??"")||TRANSPORT_MESSAGE.test(e.message??"")),"upstreamTransportFailure");exports.upstreamTransportFailure=upstreamTransportFailure;const clientWentAway=E((e,t)=>e.destroyed&&!e.complete||t.destroyed||e.socket?.destroyed===!0,"clientWentAway");exports.clientWentAway=clientWentAway;
@@ -1,14 +0,0 @@
1
- /**
2
- * Per-request upstream resolution: a direct manifest `upstream`, or a pooled
3
- * pod pick (health-steered, version-pinned) with scale-from-zero via the
4
- * PodProvider. Shared by the HTTP handler and the WS upgrade.
5
- */
6
- import type { Route, Upstream } from '../manifest';
7
- import type { GwTrace, ProdGatewayOptions } from './types';
8
- import type { Observability } from './observability';
9
- export interface UpstreamLayer {
10
- /** `allowDrained` marks a version the GATEWAY chose (ABAC rule / sticky bucket) rather than one
11
- * the client asked for — only the former may land on a drained (weight-0) cohort. */
12
- resolveUpstream(route: Route, trace: GwTrace | undefined, pinned?: string, allowDrained?: boolean): Promise<Upstream | undefined>;
13
- }
14
- export declare function createUpstream(opts: ProdGatewayOptions, obs: Observability): UpstreamLayer;
@@ -1 +0,0 @@
1
- "use strict";var v=Object.defineProperty;var p=(e,t)=>v(e,"name",{value:t,configurable:!0});var u=Object.defineProperty,s=p((e,t)=>u(e,"name",{value:t,configurable:!0}),"s");Object.defineProperty(exports,"__esModule",{value:!0}),exports.createUpstream=createUpstream;function createUpstream(e,t){return{resolveUpstream:s(async(r,o,i,n)=>{if(r.upstream)return{url:r.upstream};const c={...i?{version:i}:{},...n?{allowDrained:!0}:{},...e.healthChecker?{isHealthy:s(l=>e.healthChecker.isHealthy(l),"isHealthy")}:{}};let a=e.pods?.pick(r.service,c);return!a&&e.pods?.ensureUp&&(t.step(o,"ensure-up",{project:r.service}),await e.pods.ensureUp(r.service)&&(a=e.pods.pick(r.service,c))),a},"resolveUpstream")}}p(createUpstream,"createUpstream"),s(createUpstream,"createUpstream");
@@ -1,54 +0,0 @@
1
- import { type ManifestProvider, type PodProvider, type RouteManifest, type VersionCohort, type TargetRule } from './manifest';
2
- /** A service's rollout spec: optional targeting rules + the weighted cohorts. */
3
- export interface RolloutSpec {
4
- rules?: TargetRule[];
5
- cohorts: VersionCohort[];
6
- }
7
- /** Per-service rollout table — a flat URL list, a bare cohort array (no rules), or a full spec. */
8
- export type RolloutTable = Record<string, string[] | VersionCohort[] | RolloutSpec>;
9
- /** Is this endpoints table a ROLLOUT table (cohorts / a full spec) rather than flat `{svc:[url]}`?
10
- * BOTH documented rollout shapes count — `{svc:[{version,weight,urls}]}` and the targeted
11
- * `{svc:{rules,cohorts}}`. Checks EVERY entry, not just the first, so a mixed file classifies
12
- * correctly (a flat entry compiles to a synthetic single cohort, so mixing is well-defined). */
13
- export declare const isRolloutShape: (eps: Record<string, unknown>) => boolean;
14
- /** A fixed set of manifests (tests, single-shot config). */
15
- export declare function staticManifestProvider(manifests: RouteManifest[]): ManifestProvider;
16
- /**
17
- * Watch a manifests JSON file; atomically swap the in-memory set on a valid
18
- * change, reject and keep last-good on a bad one. `watch` notifies subscribers
19
- * with the new set. Poll fallback covers editors/atomic-rename + platforms
20
- * where fs.watch is unreliable.
21
- */
22
- export declare function fileManifestProvider(filePath: string, opts?: {
23
- pollMs?: number;
24
- onError?: (e: unknown) => void;
25
- }): ManifestProvider & {
26
- stop: () => void;
27
- };
28
- /**
29
- * Rollout-aware pod provider: each service is a set of VERSION COHORTS, and
30
- * `pick` splits traffic across them by weight (smooth weighted round-robin —
31
- * a 90/10 canary interleaves, never bursts) and round-robins endpoints WITHIN
32
- * the chosen cohort. `pick(svc, {version})` pins a cohort (sticky canary /
33
- * debugging). `update` swaps weights/cohorts live — a rollout ramps
34
- * (10→25→50→100) or rolls back without redeploying the gateway. The returned
35
- * Upstream carries `version` so the gateway can surface which cohort served.
36
- */
37
- export declare function rolloutPodProvider(table: RolloutTable, opts?: {
38
- onError?: (e: unknown) => void;
39
- }): PodProvider & {
40
- update: (next: RolloutTable) => void;
41
- };
42
- /**
43
- * Flat single-version load balancing — the common case (no rollout in
44
- * progress). A thin wrapper over `rolloutPodProvider` with one synthetic
45
- * cohort per service, so the rollout path is the only code path. The synthetic
46
- * version is STRIPPED from the result: flat LB carries no `version`, so a
47
- * response only gets `x-lensmcp-version` (and a `rollout` trace step) when a
48
- * genuine multi-cohort rollout served it.
49
- */
50
- export declare function endpointsPodProvider(endpoints: Record<string, string[]>, opts?: {
51
- onError?: (e: unknown) => void;
52
- }): PodProvider & {
53
- update: (next: Record<string, string[]>) => void;
54
- };
@@ -1 +0,0 @@
1
- "use strict";var L=Object.defineProperty;var w=(t,o)=>L(t,"name",{value:o,configurable:!0});var P=Object.defineProperty,n=w((t,o)=>P(t,"name",{value:o,configurable:!0}),"n");Object.defineProperty(exports,"__esModule",{value:!0}),exports.isRolloutShape=void 0,exports.staticManifestProvider=staticManifestProvider,exports.fileManifestProvider=fileManifestProvider,exports.rolloutPodProvider=rolloutPodProvider,exports.endpointsPodProvider=endpointsPodProvider;const node_fs_1=require("node:fs"),manifest_1=require("./manifest"),FLAT="_flat",isCohortList=n(t=>Array.isArray(t)&&t.every(o=>!!o&&typeof o=="object"&&Array.isArray(o.urls)),"isCohortList"),isUrlList=n(t=>Array.isArray(t)&&t.every(o=>typeof o=="string"),"isUrlList"),isSpec=n(t=>!!t&&typeof t=="object"&&!Array.isArray(t)&&isCohortList(t.cohorts),"isSpec"),isRolloutShape=n(t=>Object.values(t).some(o=>isSpec(o)||isCohortList(o)&&o.length>0),"isRolloutShape");exports.isRolloutShape=isRolloutShape;const isValidEntry=n(t=>isSpec(t)||isCohortList(t)||isUrlList(t),"isValidEntry"),toSpec=n(t=>Array.isArray(t)?isUrlList(t)?{rules:[],cohorts:[{version:FLAT,weight:1,urls:t}]}:{rules:[],cohorts:t}:{rules:t.rules??[],cohorts:t.cohorts??[]},"toSpec");function staticManifestProvider(t){return{list:n(()=>t,"list")}}w(staticManifestProvider,"staticManifestProvider"),n(staticManifestProvider,"staticManifestProvider");function parseManifests(t){let o;try{o=JSON.parse(t)}catch{return}const l=Array.isArray(o)?o:o?.manifests;if(Array.isArray(l))return l.some(d=>(0,manifest_1.manifestDefects)(d).length===0)?l:void 0}w(parseManifests,"parseManifests"),n(parseManifests,"parseManifests");function fileManifestProvider(t,o={}){const l=o.onError??(()=>{});let d=[],M=-1;const m=new Set,S=n(()=>{if(!(0,node_fs_1.existsSync)(t))return;let u;try{u=(0,node_fs_1.statSync)(t).mtimeMs}catch{return}if(u===M)return;let k;try{k=(0,node_fs_1.readFileSync)(t,"utf8")}catch(e){l(e);return}const s=parseManifests(k);if(!s){l(new Error(`[gateway] rejecting invalid manifest file ${t} \u2014 keeping last-good`));return}M=u,d=s;for(const e of m)try{e(d)}catch(r){l(r)}},"reload");S();let b;try{b=(0,node_fs_1.watch)(t,{persistent:!1},()=>S())}catch{}const A=setInterval(S,o.pollMs??1e3);return A.unref?.(),{list:n(()=>d,"list"),watch:n(u=>(m.add(u),()=>m.delete(u)),"watch"),stop:n(()=>{try{b?.close()}catch{}clearInterval(A)},"stop")}}w(fileManifestProvider,"fileManifestProvider"),n(fileManifestProvider,"fileManifestProvider");function rolloutPodProvider(t,o={}){const l=new Map,d=o.onError??(()=>{}),M=n(s=>({cohorts:s.cohorts.map(e=>({...e,urls:e.urls.slice()})),select:(0,manifest_1.smoothWeightedSelector)(s.cohorts.map(e=>e.weight)),rr:s.cohorts.map(()=>-1),rules:s.rules??[]}),"build"),m=n(s=>{const e=new Map,r=[];for(const[c,a]of Object.entries(s??{})){const f=n(()=>{const p=l.get(c);p&&e.set(c,p),r.push(c)},"keepLastGood");if(!isValidEntry(a)){f();continue}try{e.set(c,M(toSpec(a)))}catch{f()}}r.length&&d(new Error(`[gateway] rollout config: ignoring invalid entr${r.length>1?"ies":"y"} for ${r.join(", ")} \u2014 keeping last-good`));for(const[c,a]of e)for(const f of a.rules)for(const p of(0,manifest_1.regexSources)(f.when)){const v=(0,manifest_1.unsafeRegex)(p);v&&d(new Error(`[gateway] rollout config: ${c} rule ${f.name??"(unnamed)"} has a regex the edge will not run (${v}) \u2014 it never matches: ${p.slice(0,80)}`))}l.clear();for(const[c,a]of e)l.set(c,a)},"load");m(t);const S=n(s=>s.cohorts.findIndex(e=>e.urls.length>0),"firstNonEmpty"),b=3e4,A=3e5,u=new Map,k=n(s=>{const e=u.get(s);return!!e&&Date.now()<e.until},"isEjected");return{pick(s,e){const r=l.get(s);if(!r||r.cohorts.length===0)return;const c=e?.isHealthy,a=c||u.size>0?i=>!k(i)&&(c?c(i):!0):void 0,f=n((i,h)=>{const x=r.cohorts[i];if(!x||x.urls.length===0)return;const j=x.urls.length;for(let $=0;$<j;$++){r.rr[i]=(r.rr[i]+1)%j;const _=x.urls[r.rr[i]];if(!h||h(_))return _}},"pickUrl"),p=n(i=>i.urls.length>0&&(e?.allowDrained===!0||i.weight>0),"pinnable"),v=e?.version?r.cohorts.findIndex(i=>i.version===e.version&&p(i)):-1;if(v>=0){const i=f(v,a)??f(v);if(i===void 0)return;const h=r.cohorts[v].version;return h===FLAT?{url:i}:{url:i,version:h}}let g=r.select();(!r.cohorts[g]||r.cohorts[g].urls.length===0)&&(g=S(r));let y=f(g,a);if(y===void 0&&a)for(let i=0;i<r.cohorts.length;i++){if(!(r.cohorts[i].weight>0))continue;const h=f(i,a);if(h!==void 0){g=i,y=h;break}}if(y===void 0&&(y=f(g)),y===void 0)return;const E=r.cohorts[g]?.version;return E===void 0||E===FLAT?{url:y}:{url:y,version:E}},endpoints(){const s=new Set;for(const e of l.values())for(const r of e.cohorts)for(const c of r.urls)s.add(c);return[...s]},resolveVersion(s,e){const r=l.get(s);return r&&r.rules.length?(0,manifest_1.pickTargetedVersion)(r.rules,e):void 0},bucket(s,e){const r=l.get(s);if(!r||r.cohorts.length===0)return;const c=r.cohorts[(0,manifest_1.bucketByWeight)(`${e}:${s}`,r.cohorts.map(a=>a.weight))];return c&&c.version!==FLAT?{version:c.version}:void 0},ensureUp:n(async()=>!0,"ensureUp"),drop(s,e){if(!("url"in e))return;const r=Date.now(),c=u.get(e.url),a=c&&r<c.until+A?c.strikes+1:1;u.set(e.url,{until:r+Math.min(b*2**(a-1),A),strikes:a})},update:m}}w(rolloutPodProvider,"rolloutPodProvider"),n(rolloutPodProvider,"rolloutPodProvider");function endpointsPodProvider(t,o={}){const l=rolloutPodProvider(t,o);return{...l,resolveVersion:n(()=>{},"resolveVersion"),bucket:n(()=>{},"bucket"),update:n(d=>l.update(d),"update")}}w(endpointsPodProvider,"endpointsPodProvider"),n(endpointsPodProvider,"endpointsPodProvider");
@@ -1,68 +0,0 @@
1
- /**
2
- * Registry-backed gateway config — true zero-touch discovery. Instead of a
3
- * mounted file, the manifests + rollout cohorts live in a shared registry
4
- * (Redis here; k8s ConfigMap/Endpoints can drop in behind `RegistrySource`).
5
- * A service deploy / the `lensmcp rollout --redis` CD helper writes its keys and
6
- * publishes a change; the gateway re-reads and live-swaps its route table +
7
- * cohorts in ~instant — no gateway redeploy, no file mounts.
8
- *
9
- * The cluster lib stays dependency-light: `redisRegistrySource` works against a
10
- * minimal injected `RedisLike` (ioredis satisfies it; the prod entry wires the
11
- * real client, tests pass a fake). See docs/design/targeted-rollout.md and
12
- * docs/design/prod-gateway.md (§Distribution).
13
- */
14
- import { type RolloutTable } from './providers-prod';
15
- import { type ManifestProvider, type PodProvider, type RouteManifest } from './manifest';
16
- /** A change-notifying source of the gateway's full config (manifests + rollout). */
17
- export interface RegistrySource {
18
- /** Read the current snapshot. `rejected` names every entry the source refused to hand on, and why. */
19
- read(): Promise<{
20
- manifests: RouteManifest[];
21
- endpoints: RolloutTable;
22
- rejected?: string[];
23
- }>;
24
- /** Subscribe to change notifications; returns an unsubscribe. Optional. */
25
- watch?(onChange: () => void): Promise<() => void>;
26
- /** Release any held connections. */
27
- stop?(): void;
28
- }
29
- /** The minimal Redis surface `redisRegistrySource` uses (ioredis satisfies it). */
30
- export interface RedisLike {
31
- keys(pattern: string): Promise<string[]>;
32
- mget(...keys: string[]): Promise<(string | null)[]>;
33
- set(key: string, value: string): Promise<unknown>;
34
- del(key: string): Promise<unknown>;
35
- publish(channel: string, message: string): Promise<unknown>;
36
- duplicate(): RedisLike;
37
- subscribe(channel: string): Promise<unknown>;
38
- on(event: 'message', cb: (channel: string, message: string) => void): void;
39
- quit(): Promise<unknown>;
40
- }
41
- export declare const DEFAULT_REGISTRY_PREFIX = "lensmcp:gw";
42
- export declare const manifestKey: (prefix: string, service: string) => string;
43
- export declare const rolloutKey: (prefix: string, service: string) => string;
44
- export declare const changeChannel: (prefix: string) => string;
45
- /**
46
- * Redis-backed source. Per-service keys (so a deploy touches only its own key,
47
- * no read-modify-write races): `<prefix>:manifest:<svc>` (a RouteManifest) and
48
- * `<prefix>:rollout:<svc>` (a VersionCohort[] | RolloutSpec). Writers publish
49
- * `<prefix>:changed` after a SET; the gateway re-reads on the message.
50
- */
51
- export declare function redisRegistrySource(client: RedisLike, opts?: {
52
- prefix?: string;
53
- }): RegistrySource;
54
- /**
55
- * Compose a ManifestProvider + PodProvider over a RegistrySource. Both refresh
56
- * together on every change (source.watch) and on a poll fallback. Call
57
- * `start()` (awaits the first read so the route table is warm) before handing
58
- * the providers to `startProdGateway`.
59
- */
60
- export declare function createRegistryProviders(source: RegistrySource, opts?: {
61
- pollMs?: number;
62
- onError?: (e: unknown) => void;
63
- }): {
64
- manifests: ManifestProvider;
65
- pods: PodProvider;
66
- start(): Promise<void>;
67
- stop(): void;
68
- };
@@ -1,2 +0,0 @@
1
- "use strict";var v=Object.defineProperty;var g=(e,r)=>v(e,"name",{value:r,configurable:!0});var m=Object.defineProperty,a=g((e,r)=>m(e,"name",{value:r,configurable:!0}),"a");Object.defineProperty(exports,"__esModule",{value:!0}),exports.changeChannel=exports.rolloutKey=exports.manifestKey=exports.DEFAULT_REGISTRY_PREFIX=void 0,exports.redisRegistrySource=redisRegistrySource,exports.createRegistryProviders=createRegistryProviders;const providers_prod_1=require("./providers-prod"),manifest_1=require("./manifest");exports.DEFAULT_REGISTRY_PREFIX="lensmcp:gw";const manifestKey=a((e,r)=>`${e}:manifest:${r}`,"manifestKey");exports.manifestKey=manifestKey;const rolloutKey=a((e,r)=>`${e}:rollout:${r}`,"rolloutKey");exports.rolloutKey=rolloutKey;const changeChannel=a(e=>`${e}:changed`,"changeChannel");exports.changeChannel=changeChannel;function parseManifest(e,r){let s;try{s=JSON.parse(e)}catch{return{rejected:"not JSON"}}const n=(0,manifest_1.manifestDefects)(s);if(n.length)return{rejected:n.slice(0,3).join("; ")};const o=s;return o.service!==r?{rejected:`it describes service \xAB${o.service}\xBB \u2014 a manifest is published under its own service's key`}:{manifest:o}}g(parseManifest,"parseManifest"),a(parseManifest,"parseManifest");function redisRegistrySource(e,r={}){const s=r.prefix??exports.DEFAULT_REGISTRY_PREFIX;let n;const o=`${s}:rollout:`;return{async read(){const c=`${s}:manifest:`,u=await e.keys(`${c}*`),l=[],d=[];if(u.length){const h=await e.mget(...u);u.forEach((i,p)=>{const y=h[p];if(!y)return;const w=parseManifest(y,i.slice(c.length));"manifest"in w?l.push(w.manifest):d.push(`${i}: ${w.rejected}`)})}const f=await e.keys(`${o}*`),t={};if(f.length){const h=await e.mget(...f);f.forEach((i,p)=>{const y=h[p];if(y)try{t[i.slice(o.length)]=JSON.parse(y)}catch{}})}return{manifests:l,endpoints:t,...d.length?{rejected:d}:{}}},async watch(c){return n=e.duplicate(),await n.subscribe((0,exports.changeChannel)(s)),n.on("message",()=>c()),async()=>{try{await n?.quit()}catch{}}},stop(){n?.quit().catch(()=>{})}}}g(redisRegistrySource,"redisRegistrySource"),a(redisRegistrySource,"redisRegistrySource");function createRegistryProviders(e,r={}){const s=r.onError??(()=>{});let n=[];const o=new Set,c=(0,providers_prod_1.rolloutPodProvider)({},{onError:s});let u,l,d="";const f=a(async()=>{let t;try{t=await e.read()}catch(i){s(i);return}const h=(t.rejected??[]).join(`
2
- `);if(h!==d){d=h;for(const i of t.rejected??[])s(new Error(`[gateway] registry entry refused \u2014 ${i}`))}if(n.length>0&&t.manifests.length===0){s(new Error("[gateway] registry read came back EMPTY while serving routes \u2014 keeping last-good (set the registry to a single manifest to drain deliberately)"));return}n=t.manifests,(Object.keys(t.endpoints).length>0||n.length===0)&&c.update(t.endpoints);for(const i of o)try{i(n)}catch(p){s(p)}},"refresh");return{manifests:{list:a(()=>n,"list"),watch:a(t=>(o.add(t),()=>o.delete(t)),"watch")},pods:c,async start(){if(await f(),e.watch)try{u=await e.watch(()=>{f()})}catch(t){s(t)}l=setInterval(()=>{f()},r.pollMs??5e3),l.unref?.()},stop(){u?.(),l&&clearInterval(l),e.stop?.()}}}g(createRegistryProviders,"createRegistryProviders"),a(createRegistryProviders,"createRegistryProviders");