@pgxsinkit/server 0.3.0 → 0.5.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/LICENSE +21 -0
- package/dist/circuits/edge.d.ts.map +1 -1
- package/dist/events/consumer.d.ts +40 -0
- package/dist/events/consumer.d.ts.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +47 -11
- package/dist/index.js.map +6 -6
- package/package.json +3 -2
- package/skills/deploying/SKILL.md +10 -1
- package/src/circuits/edge.ts +28 -3
- package/src/events/consumer.ts +79 -0
- package/src/index.ts +1 -0
- package/src/mutations/plpgsql-apply.ts +2 -2
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@pgxsinkit/server",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0",
|
|
4
4
|
"keywords": [
|
|
5
5
|
"tanstack-intent"
|
|
6
6
|
],
|
|
@@ -13,6 +13,7 @@
|
|
|
13
13
|
"dist",
|
|
14
14
|
"src",
|
|
15
15
|
"README.md",
|
|
16
|
+
"LICENSE",
|
|
16
17
|
"skills"
|
|
17
18
|
],
|
|
18
19
|
"type": "module",
|
|
@@ -31,7 +32,7 @@
|
|
|
31
32
|
"build": "bun --cwd ../.. run build:public-packages"
|
|
32
33
|
},
|
|
33
34
|
"dependencies": {
|
|
34
|
-
"@pgxsinkit/contracts": "0.
|
|
35
|
+
"@pgxsinkit/contracts": "0.5.0"
|
|
35
36
|
},
|
|
36
37
|
"peerDependencies": {
|
|
37
38
|
"drizzle-orm": "1.0.0-rc.4"
|
|
@@ -15,7 +15,7 @@ description: >-
|
|
|
15
15
|
metadata:
|
|
16
16
|
type: task
|
|
17
17
|
library: "@pgxsinkit/server"
|
|
18
|
-
library_version: "0.
|
|
18
|
+
library_version: "0.5.0"
|
|
19
19
|
source: https://pgxsinkit.github.io/start/deploying-the-server/
|
|
20
20
|
---
|
|
21
21
|
|
|
@@ -257,6 +257,7 @@ const consumer = defineEventConsumer({
|
|
|
257
257
|
});
|
|
258
258
|
},
|
|
259
259
|
onDeadLetter: (report) => alert(report), // the runner ALSO warn-logs every one, unconditionally
|
|
260
|
+
onPoll: (report) => (lastPollAt = report.at), // fires after EVERY read — your liveness heartbeat
|
|
260
261
|
});
|
|
261
262
|
consumer.start();
|
|
262
263
|
process.on("SIGTERM", () => void consumer.stop()); // graceful: no new reads, in-flight callbacks awaited
|
|
@@ -283,6 +284,14 @@ process.on("SIGTERM", () => void consumer.stop()); // graceful: no new reads, in
|
|
|
283
284
|
no library-owned DLQ table. Requeue is a deliberate act (`requeueDeadLetter`), never automatic.
|
|
284
285
|
- One runner hosts many streams (independent loops each), so a small deployment runs one process and a large
|
|
285
286
|
one splits `streams` across processes. Construction is query-free: the first statement is the first poll.
|
|
287
|
+
- **Answer the liveness probe from `onPoll`, never from the callback.** The callback fires only on delivered
|
|
288
|
+
batches, so on an idle queue it goes silent — a probe wired to it reports a perfectly healthy runner as
|
|
289
|
+
dead. `onPoll` fires after **every** read (productive or empty, and in the `drainOnce` mode too) with
|
|
290
|
+
`{ stream, delivered, empty, fault, at }`: record `at` and let the probe fail when it is older than a few
|
|
291
|
+
idle ceilings. `fault: true` marks a read that failed (queue/database fault, or an unreadable body) — the
|
|
292
|
+
loop backs off and carries on, so treat it as queue health, not liveness. It fires on the read, before
|
|
293
|
+
delivery, so a slow callback never delays the beat, and a hook that throws is caught and warn-logged once
|
|
294
|
+
per runner rather than taking the loop down.
|
|
286
295
|
|
|
287
296
|
**3b. No long-lived compute at all? `drainOnce()` on a schedule.** On a platform whose only server-side unit
|
|
288
297
|
is a per-request function (managed Supabase, say), there is nowhere to put `start()` — and the queue would
|
package/src/circuits/edge.ts
CHANGED
|
@@ -330,12 +330,29 @@ export function createStreamGate(options: StreamGateOptions) {
|
|
|
330
330
|
|
|
331
331
|
const init: RequestInit = { method: request.method, headers: forwarded, signal: request.signal };
|
|
332
332
|
|
|
333
|
+
// A downstream that walks away mid-long-poll (a client's clean `stop()`/unsubscribe) aborts
|
|
334
|
+
// `request.signal`, and the forwarded fetch rejects with an AbortError. That is the cancellation
|
|
335
|
+
// working as designed, not a failure — but left to propagate it surfaced as a 500 plus a raw
|
|
336
|
+
// DOMException in every consumer's error log, once per stream, at every clean shutdown. Nothing
|
|
337
|
+
// is ever delivered on an aborted request, so answer the mount's await with 499 (client closed
|
|
338
|
+
// request) and stay quiet. A rejection with the signal NOT aborted is a real failure and still
|
|
339
|
+
// propagates.
|
|
340
|
+
const upstreamFetch = async (): Promise<Response> => {
|
|
341
|
+
try {
|
|
342
|
+
return await doFetch(upstreamUrl, init);
|
|
343
|
+
} catch (error) {
|
|
344
|
+
if (request.signal.aborted) return new Response(null, { status: 499 });
|
|
345
|
+
throw error;
|
|
346
|
+
}
|
|
347
|
+
};
|
|
348
|
+
|
|
333
349
|
// The pass-through path hands back the upstream Response OBJECT, untouched. Not "an equivalent
|
|
334
350
|
// response" — the same one, so a shape that declares no transform pays nothing for the existence
|
|
335
351
|
// of this stage and keeps whatever caching headers durable-streams answered with.
|
|
336
|
-
if (transform == null || entry == null) return
|
|
352
|
+
if (transform == null || entry == null) return upstreamFetch();
|
|
337
353
|
|
|
338
|
-
const upstream = await
|
|
354
|
+
const upstream = await upstreamFetch();
|
|
355
|
+
if (upstream.status === 499) return upstream;
|
|
339
356
|
const headers = rewrittenEgressHeaders(upstream.headers);
|
|
340
357
|
|
|
341
358
|
// 204 long-poll timeouts, 304s, upstream errors, and HEAD probes: nothing to rewrite, but they
|
|
@@ -350,7 +367,15 @@ export function createStreamGate(options: StreamGateOptions) {
|
|
|
350
367
|
return new Response(upstream.body, { status: upstream.status, statusText: upstream.statusText, headers });
|
|
351
368
|
}
|
|
352
369
|
|
|
353
|
-
|
|
370
|
+
// The body read can abort the same way the fetch can (the poll delivered headers, the client
|
|
371
|
+
// left before the body finished) — same cancellation, same quiet answer.
|
|
372
|
+
let parsed: unknown;
|
|
373
|
+
try {
|
|
374
|
+
parsed = (await upstream.json()) as unknown;
|
|
375
|
+
} catch (error) {
|
|
376
|
+
if (request.signal.aborted) return new Response(null, { status: 499 });
|
|
377
|
+
throw error;
|
|
378
|
+
}
|
|
354
379
|
const isBatch = Array.isArray(parsed);
|
|
355
380
|
const envelopes = (isBatch ? parsed : [parsed]) as ProxiedEnvelope[];
|
|
356
381
|
|
package/src/events/consumer.ts
CHANGED
|
@@ -22,6 +22,11 @@ import {
|
|
|
22
22
|
* shutdown. Construction stays query-free — the FIRST statement this runner sends is the first poll inside
|
|
23
23
|
* `start()`.
|
|
24
24
|
*
|
|
25
|
+
* Because the app owns the process, it also owns the health endpoint — so the runner reports the one thing
|
|
26
|
+
* that endpoint cannot see from outside: {@link DefineEventConsumerOptions.onPoll} fires after EVERY read,
|
|
27
|
+
* productive or empty, in both pacing modes. Beat a liveness probe from that, never from `callback`, which
|
|
28
|
+
* by design says nothing at all while the queue is idle.
|
|
29
|
+
*
|
|
25
30
|
* One runner hosts many Event streams: each gets its own independent loop (a poison event or slow callback in
|
|
26
31
|
* one stream must never head-of-line-block another), so small deployments run one process and large ones split
|
|
27
32
|
* `streams` across processes.
|
|
@@ -153,6 +158,31 @@ export interface EventDeadLetterReport {
|
|
|
153
158
|
cause?: unknown;
|
|
154
159
|
}
|
|
155
160
|
|
|
161
|
+
/**
|
|
162
|
+
* What {@link DefineEventConsumerOptions.onPoll} is told after each read — the host's liveness heartbeat.
|
|
163
|
+
*
|
|
164
|
+
* One report per read the runner performs, productive or not, in BOTH pacing modes. `delivered` counts the
|
|
165
|
+
* sub-batches that read returned (the queue's unit: one message, one callback invocation), and `empty` is
|
|
166
|
+
* exactly `delivered === 0` — including on a faulted read, which is why `fault` is a separate flag rather
|
|
167
|
+
* than something to infer from the counts.
|
|
168
|
+
*/
|
|
169
|
+
export interface EventPollReport {
|
|
170
|
+
/** The Event stream that was read. Each stream has its own loop, so each beats on its own cadence. */
|
|
171
|
+
readonly stream: string;
|
|
172
|
+
/** Sub-batches this read returned. `0` on an empty or faulted read. */
|
|
173
|
+
readonly delivered: number;
|
|
174
|
+
/** `delivered === 0` — nothing came back from this read. */
|
|
175
|
+
readonly empty: boolean;
|
|
176
|
+
/**
|
|
177
|
+
* The read itself FAILED: a queue/database fault, or a message body that could not be parsed (which fails
|
|
178
|
+
* the whole read). The runner backs off and carries on either way — a fault never ends a loop — so a host
|
|
179
|
+
* watching the heartbeat still sees it turning, and this is what tells it the queue is unhealthy.
|
|
180
|
+
*/
|
|
181
|
+
readonly fault: boolean;
|
|
182
|
+
/** When the read settled, from the runner's own clock (`Date.now` unless one is injected). */
|
|
183
|
+
readonly at: number;
|
|
184
|
+
}
|
|
185
|
+
|
|
156
186
|
/**
|
|
157
187
|
* The deterministic seam the runner waits on. `signal` is aborted by `stop()`, so a stopping runner never
|
|
158
188
|
* lingers for a full idle ceiling. Injected only by tests; production uses an abortable `setTimeout`.
|
|
@@ -233,6 +263,17 @@ export interface DefineEventConsumerOptions<TRegistry extends SyncTableRegistry>
|
|
|
233
263
|
* the ADR's requirement and a hook that swallows (or throws) must not be able to make a dead letter silent.
|
|
234
264
|
*/
|
|
235
265
|
onDeadLetter?: (report: EventDeadLetterReport) => void;
|
|
266
|
+
/**
|
|
267
|
+
* Notified after EVERY read the runner performs — productive or empty, in both pacing modes — which makes it
|
|
268
|
+
* the host's **liveness heartbeat**. The {@link DefineEventConsumerOptions.callback} fires only on delivered
|
|
269
|
+
* batches, so on an idle queue it goes quiet and a liveness/readiness probe answering from it would report a
|
|
270
|
+
* healthy runner as dead; beat from this instead and treat `fault` as the queue-health signal.
|
|
271
|
+
*
|
|
272
|
+
* It fires on the READ, before the batch is delivered, so a slow callback cannot delay the heartbeat. A hook
|
|
273
|
+
* that THROWS can never take a loop down: the throw is caught, warn-logged ONCE per runner (a hook that
|
|
274
|
+
* throws every poll must not drown the log), and the loop carries on.
|
|
275
|
+
*/
|
|
276
|
+
onPoll?: (report: EventPollReport) => void;
|
|
236
277
|
/** @internal The injectable wait — the deterministic seam the pacing tests drive. Defaults to `setTimeout`. */
|
|
237
278
|
sleep?: EventConsumerSleep;
|
|
238
279
|
/** @internal The injectable clock `drainOnce` measures its budget against. Defaults to `Date.now`. */
|
|
@@ -408,6 +449,34 @@ export function defineEventConsumer<TRegistry extends SyncTableRegistry>(
|
|
|
408
449
|
*/
|
|
409
450
|
let drainStats: { delivered: number; deadLettered: number } | null = null;
|
|
410
451
|
|
|
452
|
+
// ─── The per-read heartbeat ──────────────────────────────────────────────────────────────────────────
|
|
453
|
+
/** Latched once the `onPoll` hook has thrown: the warn is per RUNNER, not per poll (see the option's doc). */
|
|
454
|
+
let pollHookFailed = false;
|
|
455
|
+
/**
|
|
456
|
+
* Beat once for one completed read. Called from BOTH pacing modes and from the fault paths, so a host
|
|
457
|
+
* watching this sees every turn of every loop; `empty` is derived here so the two modes cannot disagree
|
|
458
|
+
* about what an empty read is.
|
|
459
|
+
*/
|
|
460
|
+
const reportPoll = (stream: string, delivered: number, fault: boolean): void => {
|
|
461
|
+
if (!options.onPoll) {
|
|
462
|
+
return;
|
|
463
|
+
}
|
|
464
|
+
try {
|
|
465
|
+
options.onPoll({ stream, delivered, empty: delivered === 0, fault, at: now() });
|
|
466
|
+
} catch (error) {
|
|
467
|
+
// A liveness hook that throws must never be able to stop the loop it is observing — that would turn a
|
|
468
|
+
// reporting bug into an outage. Loud once, then silent: it typically throws on EVERY poll.
|
|
469
|
+
if (!pollHookFailed) {
|
|
470
|
+
pollHookFailed = true;
|
|
471
|
+
console.warn(
|
|
472
|
+
"pgxsinkit: the `onPoll` hook threw; the event consumer carries on regardless (this is warned once " +
|
|
473
|
+
"per runner, not once per poll)",
|
|
474
|
+
error,
|
|
475
|
+
);
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
};
|
|
479
|
+
|
|
411
480
|
// ─── Dead-lettering (ADR-0053 decision 7: the loudness lives HERE) ───────────────────────────────────
|
|
412
481
|
const reportDeadLetter = (report: EventDeadLetterReport): void => {
|
|
413
482
|
// Unconditional, and deliberately not the client report surface's "warn only when nobody subscribed"
|
|
@@ -644,11 +713,17 @@ export function defineEventConsumer<TRegistry extends SyncTableRegistry>(
|
|
|
644
713
|
let productive = false;
|
|
645
714
|
try {
|
|
646
715
|
const messages = await queue.readBatch(stream, { visibilityTimeoutSeconds, maxMessages: batchSize });
|
|
716
|
+
// Beat on the READ, before delivery, so a slow callback cannot delay the heartbeat. `processDelivered`
|
|
717
|
+
// never throws, so this iteration can produce exactly one report: this one, or the fault one below.
|
|
718
|
+
reportPoll(stream, messages.length, false);
|
|
647
719
|
if (messages.length > 0) {
|
|
648
720
|
productive = true;
|
|
649
721
|
await processDelivered(stream, messages, () => stopping);
|
|
650
722
|
}
|
|
651
723
|
} catch (error) {
|
|
724
|
+
// The read did not complete. An unparseable body fails the WHOLE read exactly as a queue fault does,
|
|
725
|
+
// so both beat the same way: nothing delivered, `fault: true`, and the loop carries on.
|
|
726
|
+
reportPoll(stream, 0, true);
|
|
652
727
|
if (error instanceof MalformedEventQueueMessageError) {
|
|
653
728
|
// The endpoint is the only writer of these queues and it writes contract-shaped bodies, so this is a
|
|
654
729
|
// hand-inserted or corrupted message. It fails the WHOLE read, so it must go on sight or it wedges
|
|
@@ -716,7 +791,11 @@ export function defineEventConsumer<TRegistry extends SyncTableRegistry>(
|
|
|
716
791
|
let messages: readonly DeliveredEventMessage[];
|
|
717
792
|
try {
|
|
718
793
|
messages = await queue.readBatch(stream, { visibilityTimeoutSeconds, maxMessages: batchSize });
|
|
794
|
+
// The heartbeat covers this pacing mode too — a scheduled drain is exactly the deployment whose
|
|
795
|
+
// host most wants to know a pass actually reached the queue.
|
|
796
|
+
reportPoll(stream, messages.length, false);
|
|
719
797
|
} catch (error) {
|
|
798
|
+
reportPoll(stream, 0, true);
|
|
720
799
|
if (error instanceof MalformedEventQueueMessageError) {
|
|
721
800
|
// Same policy as the loop: it fails the WHOLE read, so it goes on sight and the stream stays
|
|
722
801
|
// pending for the re-read that fetches the rest of the batch.
|
package/src/index.ts
CHANGED
|
@@ -554,7 +554,7 @@ function resolveGrantExecuteRoles(grantExecuteTo: readonly string[] | undefined)
|
|
|
554
554
|
* - **A default (NULL) `proacl` explodes to nothing.** That is why the unconditional
|
|
555
555
|
* `REVOKE ALL … FROM PUBLIC` is emitted FIRST: revoking materializes the previously-implicit ACL
|
|
556
556
|
* (`NULL` → `{owner=X/owner}`), so by the time this block runs the catalog states the truth. Pinned by
|
|
557
|
-
* the
|
|
557
|
+
* the pgwasm unit lane, and by the integration lane against a real cluster.
|
|
558
558
|
* - **Grantee `0` is PUBLIC**, which has no role name (`pg_get_userbyid(0)` returns a placeholder
|
|
559
559
|
* string), so it is revoked by the `FROM PUBLIC` spelling rather than by name.
|
|
560
560
|
*
|
|
@@ -610,7 +610,7 @@ $$;`;
|
|
|
610
610
|
* `anon`/`authenticated`/`service_role` trio via default privileges; because the artifact begins with
|
|
611
611
|
* `DROP FUNCTION`, EVERY install recreates that exposure. So the revokes are emitted unconditionally
|
|
612
612
|
* (convergence must not depend on install history), the Supabase-trio ones through the shared
|
|
613
|
-
* role-existence guard so the artifact stays portable to
|
|
613
|
+
* role-existence guard so the artifact stays portable to pgwasm and plain-Postgres lanes.
|
|
614
614
|
*
|
|
615
615
|
* Those named revokes are the READABLE fast path — a reviewer sees the two known exposures closed in
|
|
616
616
|
* plain SQL. The guarantee is {@link buildApplyFunctionAclConvergerSql}, which then revokes EVERY
|