@pgxsinkit/server 0.2.7 → 0.3.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.
- package/README.md +7 -4
- package/dist/circuits/compile.d.ts +66 -0
- package/dist/circuits/compile.d.ts.map +1 -0
- package/dist/circuits/edge.d.ts +188 -0
- package/dist/circuits/edge.d.ts.map +1 -0
- package/dist/circuits/engine-client.d.ts +111 -0
- package/dist/circuits/engine-client.d.ts.map +1 -0
- package/dist/circuits/index.d.ts +7 -0
- package/dist/circuits/index.d.ts.map +1 -0
- package/dist/circuits/stream-token.d.ts +138 -0
- package/dist/circuits/stream-token.d.ts.map +1 -0
- package/dist/circuits/subscribe.d.ts +280 -0
- package/dist/circuits/subscribe.d.ts.map +1 -0
- package/dist/circuits/wire.d.ts +70 -0
- package/dist/circuits/wire.d.ts.map +1 -0
- package/dist/index.d.ts +36 -10
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +801 -286
- package/dist/index.js.map +12 -8
- package/dist/mutations/plpgsql-apply.d.ts +1 -1
- package/package.json +2 -2
- package/skills/deploying/SKILL.md +74 -38
- package/src/circuits/compile.ts +301 -0
- package/src/circuits/edge.ts +386 -0
- package/src/circuits/engine-client.ts +195 -0
- package/src/circuits/index.ts +6 -0
- package/src/circuits/stream-token.ts +224 -0
- package/src/circuits/subscribe.ts +832 -0
- package/src/circuits/wire.ts +71 -0
- package/src/index.ts +136 -31
- package/src/mutations/plpgsql-apply.ts +1 -1
- package/src/router.ts +2 -2
- package/dist/electric-proxy.d.ts +0 -48
- package/dist/electric-proxy.d.ts.map +0 -1
- package/src/electric-proxy.ts +0 -474
|
@@ -0,0 +1,386 @@
|
|
|
1
|
+
import { getTableConfig } from "drizzle-orm/pg-core";
|
|
2
|
+
|
|
3
|
+
import type { PredicateValue, RowTransform, RowTransformContext, SyncTableRegistry } from "@pgxsinkit/contracts";
|
|
4
|
+
|
|
5
|
+
import { resolveEntryByShapeKey } from "./compile";
|
|
6
|
+
import { findGrant, verifyStreamToken, type StreamGrant } from "./stream-token";
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* The live entitlement set the edge checks a shared-tier read against (ADR-0055 decision 7).
|
|
10
|
+
*
|
|
11
|
+
* An interface, not an implementation, because the source is a Circuits subscription over the
|
|
12
|
+
* membership relations themselves — freshness is engine propagation, not a cache TTL, and there is
|
|
13
|
+
* no database on the read path.
|
|
14
|
+
*/
|
|
15
|
+
export interface EntitlementSet {
|
|
16
|
+
/**
|
|
17
|
+
* Whether the entitlement set can be trusted right now. False while the subscription is catching
|
|
18
|
+
* up, degraded, or stale.
|
|
19
|
+
*
|
|
20
|
+
* The edge denies when this is false. An unavailable entitlement set is never a permit — the
|
|
21
|
+
* failure mode of the alternative is a disclosure, and the failure mode of this one is a subject
|
|
22
|
+
* retrying a read.
|
|
23
|
+
*/
|
|
24
|
+
readonly ready: boolean;
|
|
25
|
+
/** Whether `subject` may read `shapeKey` at `scope`. */
|
|
26
|
+
permits(subject: string, shapeKey: string, scope: readonly PredicateValue[]): boolean;
|
|
27
|
+
/**
|
|
28
|
+
* Every scope of `shapeKey` that `subject` holds, each an ordered tuple matching the shape's
|
|
29
|
+
* declared scope columns.
|
|
30
|
+
*
|
|
31
|
+
* This is what lets a client subscribe by shape alone (ADR-0055 decision 6): it names
|
|
32
|
+
* `offering_content`, and the control plane answers with one stream per offering the subject can
|
|
33
|
+
* actually read. The alternative — the client naming scopes — makes it restate something only this
|
|
34
|
+
* set knows, so its every answer is either redundant or wrong.
|
|
35
|
+
*
|
|
36
|
+
* Enumeration and `permits` must agree: a scope returned here that `permits` would refuse is a
|
|
37
|
+
* grant the edge then rejects on every read.
|
|
38
|
+
*/
|
|
39
|
+
scopesFor(subject: string, shapeKey: string): readonly (readonly PredicateValue[])[];
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* The entitlement set cannot be consulted right now — it is catching up, degraded, or stale.
|
|
44
|
+
*
|
|
45
|
+
* An OUTAGE, and thrown rather than reported per subscription for exactly the reason an engine fault
|
|
46
|
+
* is: a client told "not entitled" clears that scope and unsubscribes (ADR-0055 decision 6), so
|
|
47
|
+
* relaying an unavailable set as a denial would turn a transient control-plane condition into
|
|
48
|
+
* client-side data loss. The routes map it to 503, which is a status a client retries through.
|
|
49
|
+
*
|
|
50
|
+
* The EDGE does not throw this. A read arriving while the set is unavailable is denied (see
|
|
51
|
+
* {@link EntitlementSet.ready}) and a denied read is not a revocation — it is a request the client
|
|
52
|
+
* makes again.
|
|
53
|
+
*/
|
|
54
|
+
export class EntitlementsUnavailableError extends Error {
|
|
55
|
+
constructor() {
|
|
56
|
+
super(
|
|
57
|
+
"[pgxsinkit] the entitlement set is unavailable — it is catching up, degraded or stale; " +
|
|
58
|
+
"shared-tier subscriptions cannot be decided right now",
|
|
59
|
+
);
|
|
60
|
+
this.name = "EntitlementsUnavailableError";
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export interface StreamGateOptions {
|
|
65
|
+
/** Verifies the stream token. Minted by the control plane in the same process. */
|
|
66
|
+
key: CryptoKey;
|
|
67
|
+
/**
|
|
68
|
+
* The registry the granted shapes are declared in — REQUIRED, unlike every other option here.
|
|
69
|
+
*
|
|
70
|
+
* The gate needs it to answer one question per read: does this shape declare a
|
|
71
|
+
* `serverProjection.rowTransform`, and must its bytes therefore be rewritten before they reach the
|
|
72
|
+
* client (ADR-0055 decision 5)? A gate that cannot see the registry cannot know, so it would proxy
|
|
73
|
+
* a transform shape's raw rows — including the `serverOnlyColumns` fetched solely for the transform
|
|
74
|
+
* — with nothing anywhere reporting a discrepancy. Making it required is what makes that mount
|
|
75
|
+
* impossible to write, which is why it is not optional "for deployments with no transform shape":
|
|
76
|
+
* the leak arrives on the day someone adds the first one, in a file nobody was editing.
|
|
77
|
+
*/
|
|
78
|
+
registry: SyncTableRegistry;
|
|
79
|
+
/**
|
|
80
|
+
* The live entitlement set backing the shared tier. Optional for the same reason it is optional on
|
|
81
|
+
* the control plane: a deployment whose registry declares no shared shape has nothing to ask it.
|
|
82
|
+
* Absent, a shared-tier grant is DENIED rather than waved through — the two sides then agree that
|
|
83
|
+
* an unconfigured entitlement set can never permit.
|
|
84
|
+
*/
|
|
85
|
+
entitlements?: EntitlementSet;
|
|
86
|
+
/**
|
|
87
|
+
* Base URL of the durable-streams server, with whatever stream prefix it is mounted under — the
|
|
88
|
+
* same value the engine is given as `ELECTRIC_CIRCUITS_DS_URL`, since both address the same paths.
|
|
89
|
+
*/
|
|
90
|
+
durableStreamsUrl: string;
|
|
91
|
+
/**
|
|
92
|
+
* Deployment-supplied runtime params, handed to an egress `rowTransform` as its context's `params`
|
|
93
|
+
* — the same values `SubscribeOptions.params` hands to `rowFilter.customPredicate`. A deployment
|
|
94
|
+
* that configures them on one side and not the other gives its registry two different runtime
|
|
95
|
+
* environments for one shape, so mount both from the same source.
|
|
96
|
+
*/
|
|
97
|
+
params?: Record<string, unknown>;
|
|
98
|
+
/** Injected for tests; defaults to the ambient `fetch`. */
|
|
99
|
+
fetch?: typeof fetch;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* What DECIDING one read needs: the signing key, plus the entitlement set the shared tier is checked
|
|
104
|
+
* against.
|
|
105
|
+
*
|
|
106
|
+
* Spelled as the gate's options with everything else relaxed to optional, rather than as
|
|
107
|
+
* {@link StreamGateOptions} itself, because a caller that wants only the decision — a mount that
|
|
108
|
+
* proxies for itself, a test pinning the authorization rules — has no gate to configure, and
|
|
109
|
+
* requiring it to invent a `registry` and a `durableStreamsUrl` would demand values the answer
|
|
110
|
+
* provably does not depend on.
|
|
111
|
+
*/
|
|
112
|
+
export type StreamAuthorizationOptions = Pick<StreamGateOptions, "key" | "entitlements"> &
|
|
113
|
+
Partial<Omit<StreamGateOptions, "key" | "entitlements">>;
|
|
114
|
+
|
|
115
|
+
export type GateDecision =
|
|
116
|
+
| {
|
|
117
|
+
allow: true;
|
|
118
|
+
grant: StreamGrant;
|
|
119
|
+
/**
|
|
120
|
+
* The token's subject. Carried on the decision because the egress transform stage needs it and
|
|
121
|
+
* re-verifying the token to recover it would pay for a second HMAC on every rewritten read —
|
|
122
|
+
* the verification that established it already happened here.
|
|
123
|
+
*/
|
|
124
|
+
subject: string;
|
|
125
|
+
}
|
|
126
|
+
| { allow: false; reason: string };
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Authorize one read of one stream path.
|
|
130
|
+
*
|
|
131
|
+
* Two checks, and they are not redundant. The token is a capability bounded by its TTL, which is the
|
|
132
|
+
* only bound available when a hit-serving CDN sits in front and the request never reaches us. The
|
|
133
|
+
* entitlement lookup is live, and bounds revocation by propagation latency instead whenever the
|
|
134
|
+
* request does reach us. Which one binds is a property of the deployment, not of this code.
|
|
135
|
+
*
|
|
136
|
+
* A private-tier grant has no scope to check, so the token is the whole authorization and its TTL is
|
|
137
|
+
* the whole revocation bound. That is the same bound a CDN-fronted shared read has, and it is worth
|
|
138
|
+
* stating rather than leaving to be inferred.
|
|
139
|
+
*/
|
|
140
|
+
export async function authorizeStreamRead(
|
|
141
|
+
options: StreamAuthorizationOptions,
|
|
142
|
+
token: string | null,
|
|
143
|
+
path: string,
|
|
144
|
+
now: number,
|
|
145
|
+
): Promise<GateDecision> {
|
|
146
|
+
if (token == null || token === "") return { allow: false, reason: "no stream token" };
|
|
147
|
+
|
|
148
|
+
const verified = await verifyStreamToken(options.key, token, now);
|
|
149
|
+
if (!verified.ok) return { allow: false, reason: verified.reason };
|
|
150
|
+
|
|
151
|
+
const grant = findGrant(verified.claims, path);
|
|
152
|
+
if (grant == null) return { allow: false, reason: "token grants no such stream" };
|
|
153
|
+
|
|
154
|
+
const subject = verified.claims.sub;
|
|
155
|
+
if (grant.scope === undefined) return { allow: true, grant, subject };
|
|
156
|
+
|
|
157
|
+
const entitlements = options.entitlements;
|
|
158
|
+
if (entitlements === undefined) {
|
|
159
|
+
return { allow: false, reason: "shared-tier grant, but this deployment configured no entitlement set" };
|
|
160
|
+
}
|
|
161
|
+
if (!entitlements.ready) return { allow: false, reason: "entitlements unavailable" };
|
|
162
|
+
if (!entitlements.permits(subject, grant.shapeKey, grant.scope)) {
|
|
163
|
+
return { allow: false, reason: "not entitled to this scope" };
|
|
164
|
+
}
|
|
165
|
+
return { allow: true, grant, subject };
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* Read the stream token off a request.
|
|
170
|
+
*
|
|
171
|
+
* `Authorization`, never a query parameter, and this is a correctness condition rather than a
|
|
172
|
+
* convention: the cache key is the URL, so a token in the URL gives every subscriber a distinct key
|
|
173
|
+
* and destroys precisely the sharing the shared tier exists for. A cache must also be configured not
|
|
174
|
+
* to vary on this header — which it can only do if the header is where the token is.
|
|
175
|
+
*/
|
|
176
|
+
export function readStreamToken(request: Request): string | null {
|
|
177
|
+
const header = request.headers.get("authorization");
|
|
178
|
+
if (header == null) return null;
|
|
179
|
+
const [scheme, value] = header.split(" ");
|
|
180
|
+
return scheme?.toLowerCase() === "bearer" && value ? value : null;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* The response headers a browser must be allowed to READ off a stream-edge response.
|
|
185
|
+
*
|
|
186
|
+
* CORS lets script see only a short safelist of response headers (`cache-control`, `content-language`,
|
|
187
|
+
* `content-length`, `content-type`, `expires`, `last-modified`, `pragma`). Every header the
|
|
188
|
+
* durable-streams protocol answers with is outside it, so a CROSS-ORIGIN reader sees NONE of them
|
|
189
|
+
* unless the mount names them on `Access-Control-Expose-Headers`.
|
|
190
|
+
*
|
|
191
|
+
* The failure that follows is silent and expensive rather than loud. `@durable-streams/client` drives
|
|
192
|
+
* its entire read loop off these headers — verified by grepping the installed 0.2.6 dist
|
|
193
|
+
* (`@durable-streams/client/dist/index.js`, mirrored in its shipped `src/`): `Stream-Next-Offset`,
|
|
194
|
+
* `Stream-Cursor` and `Stream-Closed` are read per response, `Stream-Up-To-Date` is a presence check
|
|
195
|
+
* (`headers.has`, which is why it is easy to miss), `stream-sse-data-encoding` decides SSE payload
|
|
196
|
+
* decoding, and `etag` is read on the stream-metadata path. Stripped of them, the client never learns
|
|
197
|
+
* an offset: it re-requests `offset=-1` forever and never switches to a live long poll, which presents
|
|
198
|
+
* as a hot loop of hundreds of requests per second per shape with no error raised anywhere.
|
|
199
|
+
*
|
|
200
|
+
* `Stream-Seq`, `Stream-TTL` and `Stream-Expires-At` are request headers in that client version. They
|
|
201
|
+
* are named here anyway because this list is a statement about the ds protocol's response namespace
|
|
202
|
+
* rather than about which subset one client version happens to read today — exposing a header a
|
|
203
|
+
* response never carries is inert, while omitting one that it does carry wedges the reader. The
|
|
204
|
+
* `Producer-*` headers are deliberately absent: they belong to the write path, which does not come
|
|
205
|
+
* through this gate.
|
|
206
|
+
*
|
|
207
|
+
* EVERY mount of `createStreamGate` must put these on `Access-Control-Expose-Headers` of the ACTUAL
|
|
208
|
+
* (non-preflight) response. The gate cannot do it itself — it forwards the upstream response's
|
|
209
|
+
* headers (verbatim for an ordinary shape, minus the caching ones for a rewritten one), and an
|
|
210
|
+
* exposure list is meaningless without the `Access-Control-Allow-Origin` decision that only the mount
|
|
211
|
+
* owns.
|
|
212
|
+
*/
|
|
213
|
+
export const STREAM_READ_EXPOSED_HEADERS: readonly string[] = [
|
|
214
|
+
"stream-next-offset",
|
|
215
|
+
"stream-up-to-date",
|
|
216
|
+
"stream-cursor",
|
|
217
|
+
"stream-closed",
|
|
218
|
+
"stream-seq",
|
|
219
|
+
"stream-ttl",
|
|
220
|
+
"stream-expires-at",
|
|
221
|
+
"stream-sse-data-encoding",
|
|
222
|
+
"etag",
|
|
223
|
+
];
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* A durable-streams long-poll body as the transform stage handles it.
|
|
227
|
+
*
|
|
228
|
+
* Deliberately NOT `StreamEnvelope`: the gate is a proxy, and typing the body as the contract would
|
|
229
|
+
* assert that the edge validates a wire form it only ever forwards. All it needs to know is that an
|
|
230
|
+
* envelope may carry a `value` object — a delete envelope is key-only, so it has nothing to rewrite
|
|
231
|
+
* and nothing to disclose.
|
|
232
|
+
*/
|
|
233
|
+
interface ProxiedEnvelope {
|
|
234
|
+
value?: unknown;
|
|
235
|
+
[key: string]: unknown;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/**
|
|
239
|
+
* The response headers a rewritten body may be answered with.
|
|
240
|
+
*
|
|
241
|
+
* `cache-control: private, no-store` is the governing invariant, not a precaution: a transform makes
|
|
242
|
+
* the bytes a function of the SUBJECT, so nothing between this edge and the browser that requested
|
|
243
|
+
* them may share or store them. `etag` goes for the same reason — an upstream validator describes the
|
|
244
|
+
* bytes durable-streams holds, not the ones we just produced, and honouring it would let a
|
|
245
|
+
* revalidation return another subject's rewrite. `content-length` and `content-encoding` describe a
|
|
246
|
+
* body that no longer exists: the length changed under the rewrite, and `fetch` already decoded what
|
|
247
|
+
* it handed us.
|
|
248
|
+
*
|
|
249
|
+
* Everything else is kept VERBATIM — every `stream-*` header and the content type. The client's whole
|
|
250
|
+
* read loop drives off them (see {@link STREAM_READ_EXPOSED_HEADERS}); an edge that dropped
|
|
251
|
+
* `stream-next-offset` while rewriting would present as a hot loop, not as a redaction bug.
|
|
252
|
+
*/
|
|
253
|
+
function rewrittenEgressHeaders(upstream: Headers): Headers {
|
|
254
|
+
const headers = new Headers(upstream);
|
|
255
|
+
headers.delete("content-length");
|
|
256
|
+
headers.delete("content-encoding");
|
|
257
|
+
headers.delete("etag");
|
|
258
|
+
headers.set("cache-control", "private, no-store");
|
|
259
|
+
return headers;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/** Whether this read asks for SSE framing, by either of the two ways the ds protocol expresses it. */
|
|
263
|
+
function asksForSse(request: Request): boolean {
|
|
264
|
+
return (
|
|
265
|
+
new URL(request.url).searchParams.get("live") === "sse" ||
|
|
266
|
+
(request.headers.get("accept") ?? "").includes("text/event-stream")
|
|
267
|
+
);
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/**
|
|
271
|
+
* The edge: gate, then proxy bytes — rewriting them only for the shapes that declare a rewrite.
|
|
272
|
+
*
|
|
273
|
+
* There is no per-read FILTERING here at all, and no per-read rewriting for shapes that declare none.
|
|
274
|
+
* Predicates were resolved at shape creation, so what remains for almost every read is a decision and
|
|
275
|
+
* a copy — which is why this can sit in the TypeScript control-plane process without CPU being the
|
|
276
|
+
* axis that decides where it belongs.
|
|
277
|
+
*
|
|
278
|
+
* A shape that declares `serverProjection.rowTransform` is the one exception: it is rewritten HERE,
|
|
279
|
+
* per request, with the subject taken from the stream token, and answered `private, no-store`. This
|
|
280
|
+
* is the rewriting origin ADR-0055 decision 5 names, confined to the shapes that incur it — a
|
|
281
|
+
* transform shape gives up CDN shareability and SSE framing, and every other shape gives up nothing.
|
|
282
|
+
* The transform's `serverOnlyColumns` are fetched by the engine so the transform can read them and
|
|
283
|
+
* are stripped here, after it runs, to the columns the client's local table declares.
|
|
284
|
+
*
|
|
285
|
+
* The claims a transform sees at the edge are `{ sub }` and nothing else: a stream token carries the
|
|
286
|
+
* subject, not the JWT it was minted from, and re-deriving richer claims per read would put an auth
|
|
287
|
+
* provider call on the read path this whole topology exists to keep off it. A transform that needs
|
|
288
|
+
* more than the subject is therefore NOT expressible at egress — put the subject-dependent part in
|
|
289
|
+
* the shape's private `rowFilter.customPredicate`, which is compiled at subscribe time from the full
|
|
290
|
+
* verified claims.
|
|
291
|
+
*/
|
|
292
|
+
export function createStreamGate(options: StreamGateOptions) {
|
|
293
|
+
const doFetch = options.fetch ?? fetch;
|
|
294
|
+
const base = options.durableStreamsUrl.replace(/\/+$/, "");
|
|
295
|
+
|
|
296
|
+
return async function handleStreamRead(request: Request, path: string, now: number): Promise<Response> {
|
|
297
|
+
const decision = await authorizeStreamRead(options, readStreamToken(request), path, now);
|
|
298
|
+
if (!decision.allow) {
|
|
299
|
+
return new Response(JSON.stringify({ error: decision.reason }), {
|
|
300
|
+
status: 403,
|
|
301
|
+
headers: { "content-type": "application/json" },
|
|
302
|
+
});
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
// Resolved by shapeKey, exactly as the control plane resolved it to create the shape, so the edge
|
|
306
|
+
// and the control plane cannot disagree about which declaration governs this stream.
|
|
307
|
+
const entry = resolveEntryByShapeKey(options.registry, decision.grant.shapeKey);
|
|
308
|
+
const transform: RowTransform | undefined = entry?.serverProjection?.rowTransform;
|
|
309
|
+
|
|
310
|
+
// Refused BEFORE the upstream fetch: the rewrite needs a whole JSON body per response, and SSE
|
|
311
|
+
// delivers a frame stream instead. Parsing that would mean a second body parser for a mode no
|
|
312
|
+
// pgxsinkit client uses, so the mode is declined rather than half-supported.
|
|
313
|
+
if (transform != null && asksForSse(request)) {
|
|
314
|
+
return new Response(
|
|
315
|
+
JSON.stringify({ error: "this shape is rewritten at egress and is served as JSON long-poll only" }),
|
|
316
|
+
{ status: 406, headers: { "content-type": "application/json" } },
|
|
317
|
+
);
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
// Forward the ds protocol's own query string untouched — offsets and the live flag are the
|
|
321
|
+
// protocol's, not ours, and rewriting them is how a proxy ends up owning a contract it does not
|
|
322
|
+
// define. The token does NOT travel on: durable-streams has no read authorization in any
|
|
323
|
+
// implementation, so it would only be an unread secret sitting in another service's logs.
|
|
324
|
+
const upstreamUrl = new URL(`${base}/${path}`);
|
|
325
|
+
upstreamUrl.search = new URL(request.url).search;
|
|
326
|
+
|
|
327
|
+
const forwarded = new Headers(request.headers);
|
|
328
|
+
forwarded.delete("authorization");
|
|
329
|
+
forwarded.delete("host");
|
|
330
|
+
|
|
331
|
+
const init: RequestInit = { method: request.method, headers: forwarded, signal: request.signal };
|
|
332
|
+
|
|
333
|
+
// The pass-through path hands back the upstream Response OBJECT, untouched. Not "an equivalent
|
|
334
|
+
// response" — the same one, so a shape that declares no transform pays nothing for the existence
|
|
335
|
+
// of this stage and keeps whatever caching headers durable-streams answered with.
|
|
336
|
+
if (transform == null || entry == null) return doFetch(upstreamUrl, init);
|
|
337
|
+
|
|
338
|
+
const upstream = await doFetch(upstreamUrl, init);
|
|
339
|
+
const headers = rewrittenEgressHeaders(upstream.headers);
|
|
340
|
+
|
|
341
|
+
// 204 long-poll timeouts, 304s, upstream errors, and HEAD probes: nothing to rewrite, but they
|
|
342
|
+
// are still answers about a subject-dependent stream, so they leave with the same no-store,
|
|
343
|
+
// no-etag posture. HEAD belongs here because it answers `application/json` with NO body — parsing
|
|
344
|
+
// it would throw on a request that is only asking for the headers.
|
|
345
|
+
if (
|
|
346
|
+
request.method === "HEAD" ||
|
|
347
|
+
upstream.status !== 200 ||
|
|
348
|
+
!(upstream.headers.get("content-type") ?? "").includes("application/json")
|
|
349
|
+
) {
|
|
350
|
+
return new Response(upstream.body, { status: upstream.status, statusText: upstream.statusText, headers });
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
const parsed = (await upstream.json()) as unknown;
|
|
354
|
+
const isBatch = Array.isArray(parsed);
|
|
355
|
+
const envelopes = (isBatch ? parsed : [parsed]) as ProxiedEnvelope[];
|
|
356
|
+
|
|
357
|
+
// The client keep-set: the columns the LOCAL table declares, computed once per request. Stripping
|
|
358
|
+
// to it after the transform runs is what keeps `serverOnlyColumns` — fetched by the engine solely
|
|
359
|
+
// so the transform could read them — off the client wire, and it also drops any key a transform
|
|
360
|
+
// invented, so an egress rewrite can never widen the shape the client's schema was built for.
|
|
361
|
+
const keep = new Set(getTableConfig(entry.localTable).columns.map((column) => column.name));
|
|
362
|
+
const context: RowTransformContext = {
|
|
363
|
+
claims: { sub: decision.subject },
|
|
364
|
+
...(options.params ? { params: options.params } : {}),
|
|
365
|
+
};
|
|
366
|
+
|
|
367
|
+
const rewritten = envelopes.map((envelope) => {
|
|
368
|
+
const value = envelope?.value;
|
|
369
|
+
if (value == null || typeof value !== "object") return envelope;
|
|
370
|
+
const transformed = transform(value as Record<string, unknown>, context);
|
|
371
|
+
const stripped: Record<string, unknown> = {};
|
|
372
|
+
for (const [column, cell] of Object.entries(transformed)) {
|
|
373
|
+
if (keep.has(column)) stripped[column] = cell;
|
|
374
|
+
}
|
|
375
|
+
return { ...envelope, value: stripped };
|
|
376
|
+
});
|
|
377
|
+
|
|
378
|
+
// Answered in the shape it arrived in. A ds long-poll body is an array, and the single-object case
|
|
379
|
+
// is only defensive — re-emitting it as an array would corrupt a body the client can parse today.
|
|
380
|
+
return new Response(JSON.stringify(isBatch ? rewritten : rewritten[0]), {
|
|
381
|
+
status: upstream.status,
|
|
382
|
+
statusText: upstream.statusText,
|
|
383
|
+
headers,
|
|
384
|
+
});
|
|
385
|
+
};
|
|
386
|
+
}
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
import type { CircuitsShapeHandle, CreateShapeRequest } from "./wire";
|
|
2
|
+
|
|
3
|
+
export interface CircuitsEngineOptions {
|
|
4
|
+
/** Base URL of the Circuits engine's control API, e.g. `http://circuits-engine:4000`. */
|
|
5
|
+
baseUrl: string;
|
|
6
|
+
/** Injected for tests; defaults to the ambient `fetch`. */
|
|
7
|
+
fetch?: typeof fetch;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* An engine call that did not return 2xx, carrying the status so a caller can map it to its own.
|
|
12
|
+
*
|
|
13
|
+
* The one status with a MEANING rather than a severity is **409**: a create whose `subscription` id
|
|
14
|
+
* is already held by a different shape (fork ADR-0008 — one name, one shape). It is the caller's
|
|
15
|
+
* conflict, not an outage, and no retry changes it; match it as `error.status === 409` and re-subscribe
|
|
16
|
+
* under a fresh id. Everything else is either a request this client built wrong (4xx) or an engine
|
|
17
|
+
* that could not answer (5xx), and both propagate as a 503 to the client.
|
|
18
|
+
*/
|
|
19
|
+
export class CircuitsEngineError extends Error {
|
|
20
|
+
readonly status: number;
|
|
21
|
+
readonly body: string;
|
|
22
|
+
|
|
23
|
+
constructor(status: number, body: string, message: string) {
|
|
24
|
+
super(message);
|
|
25
|
+
this.name = "CircuitsEngineError";
|
|
26
|
+
this.status = status;
|
|
27
|
+
this.body = body;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* The control plane's client for the Circuits engine.
|
|
33
|
+
*
|
|
34
|
+
* Only the shape LIFECYCLE goes through here. Reads never do: they terminate on durable-streams,
|
|
35
|
+
* which is the whole point of the native topology — the engine is asked once, at subscribe time,
|
|
36
|
+
* for a stream to follow, and is then out of the read path entirely.
|
|
37
|
+
*/
|
|
38
|
+
export function createCircuitsEngineClient(options: CircuitsEngineOptions) {
|
|
39
|
+
const doFetch = options.fetch ?? fetch;
|
|
40
|
+
const base = options.baseUrl.replace(/\/+$/, "");
|
|
41
|
+
|
|
42
|
+
async function call(path: string, init: RequestInit): Promise<unknown> {
|
|
43
|
+
const headers = new Headers(init.headers);
|
|
44
|
+
headers.set("content-type", "application/json");
|
|
45
|
+
const response = await doFetch(`${base}${path}`, { ...init, headers });
|
|
46
|
+
const body = await response.text();
|
|
47
|
+
if (!response.ok) {
|
|
48
|
+
throw new CircuitsEngineError(
|
|
49
|
+
response.status,
|
|
50
|
+
body,
|
|
51
|
+
`[pgxsinkit] circuits engine ${init.method ?? "GET"} ${path} → ${response.status}: ${body}`,
|
|
52
|
+
);
|
|
53
|
+
}
|
|
54
|
+
return body === "" ? undefined : JSON.parse(body);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
return {
|
|
58
|
+
/**
|
|
59
|
+
* Register a shape and get the stream to follow — **and renew that registration**.
|
|
60
|
+
*
|
|
61
|
+
* There is deliberately no `renewShape`: a renewal IS this call, repeated with the same
|
|
62
|
+
* `request.subscription` on the same definition (fork ADR-0008). The engine answers the same
|
|
63
|
+
* handle, counts nothing extra, and moves the lease forward. That is also why a create whose
|
|
64
|
+
* response was lost can simply be sent again, and why the control plane's token re-mint can renew
|
|
65
|
+
* every live claim without a second route.
|
|
66
|
+
*
|
|
67
|
+
* Two outcomes a caller must distinguish:
|
|
68
|
+
* - **409** ({@link CircuitsEngineError.status}) — the id names a DIFFERENT shape already. One
|
|
69
|
+
* name, one shape; nothing was taken, and a retry will not change it.
|
|
70
|
+
* - a **different handle** — the claim had lapsed or the shape was evicted, so this call
|
|
71
|
+
* re-subscribed rather than renewed. The stream the old grant named is not this one (ADR-0007).
|
|
72
|
+
*
|
|
73
|
+
* The engine shares by definition: two identical bodies collapse onto one maintained stream and
|
|
74
|
+
* return the same handle. Nothing here has to check for that or cache against it — which is
|
|
75
|
+
* exactly why the shared tier's predicate must be GENERATED. Two subscribers in one scope produce
|
|
76
|
+
* identical bodies only because neither's identity reached the predicate; they are still two
|
|
77
|
+
* distinct subscriptions, because each names its own claim.
|
|
78
|
+
*
|
|
79
|
+
* The answer is VALIDATED, not cast, for the same reason {@link replicationState} validates the
|
|
80
|
+
* barrier: an engine that acknowledges a create without saying which subscription it recorded or
|
|
81
|
+
* how long that subscription lives cannot be renewed or released by id at all, and defaulting
|
|
82
|
+
* either field would invent a lease this control plane was never promised.
|
|
83
|
+
*/
|
|
84
|
+
async createShape(request: CreateShapeRequest): Promise<CircuitsShapeHandle> {
|
|
85
|
+
const body = (await call("/shapes", {
|
|
86
|
+
method: "POST",
|
|
87
|
+
body: JSON.stringify(request),
|
|
88
|
+
})) as Partial<CircuitsShapeHandle> | null;
|
|
89
|
+
if (body === null || typeof body !== "object") throw unusableCreate("the body", body);
|
|
90
|
+
if (typeof body.shapeId !== "string") throw unusableCreate("shapeId", body.shapeId);
|
|
91
|
+
if (typeof body.streamPath !== "string") throw unusableCreate("streamPath", body.streamPath);
|
|
92
|
+
if (typeof body.subscription !== "string" || body.subscription === "") {
|
|
93
|
+
throw unusableCreate("subscription", body.subscription);
|
|
94
|
+
}
|
|
95
|
+
if (typeof body.leaseSeconds !== "number") throw unusableCreate("leaseSeconds", body.leaseSeconds);
|
|
96
|
+
return body as CircuitsShapeHandle;
|
|
97
|
+
},
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Release ONE named subscription's claim on a shape (`DELETE /shapes/{id}?subscription=…`).
|
|
101
|
+
*
|
|
102
|
+
* **Idempotent**, and that is the whole point of naming the claim: releasing one that is already
|
|
103
|
+
* gone is a no-op `200` rather than a decrement that steals another subscriber's. A caller whose
|
|
104
|
+
* response was lost may simply send it again.
|
|
105
|
+
*
|
|
106
|
+
* There is no anonymous form here. The engine still accepts a bare `DELETE /shapes/{id}` as a
|
|
107
|
+
* legacy refcount decrement, but it carries no claim identity and is not retry-safe, so this
|
|
108
|
+
* client never issues one.
|
|
109
|
+
*
|
|
110
|
+
* The shape itself survives its other subscribers and then follows the engine's retention
|
|
111
|
+
* lifecycle (idle → dormant → evicted); this is a release, not a delete.
|
|
112
|
+
*/
|
|
113
|
+
async releaseShape(shapeId: string, subscription: string): Promise<void> {
|
|
114
|
+
const query = `?subscription=${encodeURIComponent(subscription)}`;
|
|
115
|
+
await call(`/shapes/${encodeURIComponent(shapeId)}${query}`, { method: "DELETE" });
|
|
116
|
+
},
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* The engine's convergence barrier (ADR-0056): where replication is, how many
|
|
120
|
+
* computed-but-undelivered subquery flips remain, and how many flip batches the engine gave up
|
|
121
|
+
* on.
|
|
122
|
+
*
|
|
123
|
+
* The engine answers a `sync` field beside these and it is deliberately NOT read: it is the
|
|
124
|
+
* `__el_sync` sentinel watermark — an i64 the engine's conformance harness bumps and waits on as
|
|
125
|
+
* a global quiescence fence — which no pgxsinkit database ever writes, so it is 0 everywhere and
|
|
126
|
+
* says nothing about convergence.
|
|
127
|
+
*
|
|
128
|
+
* `pendingFlips > 0` means a revocation has been computed and not yet written to any stream,
|
|
129
|
+
* which no wire-format watermark can see. That is the term the Electric wire could not express
|
|
130
|
+
* at all, and the reason the barrier is read out of band rather than inferred from a position.
|
|
131
|
+
*
|
|
132
|
+
* `flipFailures > 0` means a batch was **abandoned** after exhausting its propagation retries:
|
|
133
|
+
* those membership effects are gone rather than late. The engine keeps the abandoned batch's
|
|
134
|
+
* `pendingFlips` count held — so the waiting terms never falsely read converged — and latches
|
|
135
|
+
* itself degraded: `/v1/health` answers 503, so do its membership-bearing routes, and a reaper
|
|
136
|
+
* deletes every subquery shape stream. Recovery is an operator restart.
|
|
137
|
+
*
|
|
138
|
+
* The answer is VALIDATED, not cast. An engine that does not report both counters cannot answer
|
|
139
|
+
* the question this barrier asks, and defaulting a missing term to zero would manufacture a
|
|
140
|
+
* converged reading out of an engine that never claimed one.
|
|
141
|
+
*/
|
|
142
|
+
async replicationState(): Promise<CircuitsReplicationState> {
|
|
143
|
+
const body = (await call("/replication/lsn", { method: "GET" })) as Partial<CircuitsReplicationState>;
|
|
144
|
+
if (body === null || typeof body !== "object") throw unusableBarrier("the body", body);
|
|
145
|
+
if (body.lsn !== null && typeof body.lsn !== "string") throw unusableBarrier("lsn", body.lsn);
|
|
146
|
+
if (typeof body.pendingFlips !== "number") throw unusableBarrier("pendingFlips", body.pendingFlips);
|
|
147
|
+
if (typeof body.flipFailures !== "number") throw unusableBarrier("flipFailures", body.flipFailures);
|
|
148
|
+
return { lsn: body.lsn, pendingFlips: body.pendingFlips, flipFailures: body.flipFailures };
|
|
149
|
+
},
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* An engine whose barrier this client cannot read is not a degraded engine — it is the wrong engine,
|
|
155
|
+
* and saying so is the point. Silently tolerating the omission would leave a gate claiming to check a
|
|
156
|
+
* term nothing reports.
|
|
157
|
+
*/
|
|
158
|
+
function unusableBarrier(field: string, value: unknown): Error {
|
|
159
|
+
return new Error(
|
|
160
|
+
`[pgxsinkit] the engine's GET /replication/lsn answered with an unusable \`${field}\` (${JSON.stringify(value)}). ` +
|
|
161
|
+
`This client requires an engine reporting the whole convergence barrier — \`lsn\`, \`pendingFlips\` and ` +
|
|
162
|
+
`\`flipFailures\` (ADR-0056 decision 3); the engine at this URL is not the one this client targets.`,
|
|
163
|
+
);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* An engine whose create answer this client cannot read is not a degraded engine — it is the wrong
|
|
168
|
+
* engine, exactly as {@link unusableBarrier} says of the barrier. A create that does not name the
|
|
169
|
+
* subscription it was recorded under, or the window that subscription must be renewed within, leaves
|
|
170
|
+
* a claim nothing can renew and nothing can release by id; defaulting either would manufacture a
|
|
171
|
+
* lease the engine never granted.
|
|
172
|
+
*/
|
|
173
|
+
function unusableCreate(field: string, value: unknown): Error {
|
|
174
|
+
return new Error(
|
|
175
|
+
`[pgxsinkit] the engine's POST /shapes answered with an unusable \`${field}\` (${JSON.stringify(value)}). ` +
|
|
176
|
+
`This client requires an engine that records every shape claim under a named, leased subscription — ` +
|
|
177
|
+
`\`shapeId\`, \`streamPath\`, \`subscription\` and \`leaseSeconds\` (fork ADR-0008); the engine at this ` +
|
|
178
|
+
`URL is not the one this client targets.`,
|
|
179
|
+
);
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
export type CircuitsEngineClient = ReturnType<typeof createCircuitsEngineClient>;
|
|
183
|
+
|
|
184
|
+
/** What `GET /replication/lsn` answers that this client reads — these fields exactly, no more. */
|
|
185
|
+
export interface CircuitsReplicationState {
|
|
186
|
+
/** The ingest head — where the replication tailer has read to. */
|
|
187
|
+
lsn: string | null;
|
|
188
|
+
pendingFlips: number;
|
|
189
|
+
/**
|
|
190
|
+
* Flip batches the engine abandoned after exhausting their retries. Non-zero means membership
|
|
191
|
+
* effects were **lost**, not delayed: the batch's pending count stays held, the engine is latched
|
|
192
|
+
* degraded, and only a restart clears it.
|
|
193
|
+
*/
|
|
194
|
+
flipFailures: number;
|
|
195
|
+
}
|