@pgxsinkit/client 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.
Files changed (94) hide show
  1. package/README.md +2 -1
  2. package/dist/boot-report.d.ts +5 -2
  3. package/dist/boot-report.d.ts.map +1 -1
  4. package/dist/circuits/envelope-to-change.d.ts +35 -0
  5. package/dist/circuits/envelope-to-change.d.ts.map +1 -0
  6. package/dist/circuits/group-sync.d.ts +123 -0
  7. package/dist/circuits/group-sync.d.ts.map +1 -0
  8. package/dist/circuits/shape-group.d.ts +77 -0
  9. package/dist/circuits/shape-group.d.ts.map +1 -0
  10. package/dist/circuits/stream-inbox.d.ts +126 -0
  11. package/dist/circuits/stream-inbox.d.ts.map +1 -0
  12. package/dist/circuits/stream-source.d.ts +90 -0
  13. package/dist/circuits/stream-source.d.ts.map +1 -0
  14. package/dist/circuits/subscription-client.d.ts +143 -0
  15. package/dist/circuits/subscription-client.d.ts.map +1 -0
  16. package/dist/circuits/sync-engine.d.ts +131 -0
  17. package/dist/circuits/sync-engine.d.ts.map +1 -0
  18. package/dist/debug.d.ts +0 -10
  19. package/dist/debug.d.ts.map +1 -1
  20. package/dist/export-dump.d.ts.map +1 -1
  21. package/dist/index.d.ts +47 -19
  22. package/dist/index.d.ts.map +1 -1
  23. package/dist/index.js +6258 -6443
  24. package/dist/index.js.map +26 -26
  25. package/dist/local-tables.d.ts +1 -1
  26. package/dist/local-tables.d.ts.map +1 -1
  27. package/dist/schema.d.ts.map +1 -1
  28. package/dist/sync/apply.d.ts +13 -21
  29. package/dist/sync/apply.d.ts.map +1 -1
  30. package/dist/sync/copy.d.ts +8 -8
  31. package/dist/sync/fold.d.ts +40 -0
  32. package/dist/sync/fold.d.ts.map +1 -0
  33. package/dist/sync/metadata-tables.d.ts +25 -1
  34. package/dist/sync/metadata-tables.d.ts.map +1 -1
  35. package/dist/sync/subscription-state.d.ts +21 -2
  36. package/dist/sync/subscription-state.d.ts.map +1 -1
  37. package/dist/sync/types.d.ts +9 -129
  38. package/dist/sync/types.d.ts.map +1 -1
  39. package/dist/testing.js +3 -3
  40. package/dist/testing.js.map +2 -2
  41. package/dist/worker/attach-sync-client.d.ts +3 -1
  42. package/dist/worker/attach-sync-client.d.ts.map +1 -1
  43. package/dist/worker/define-sync-worker.d.ts +17 -1
  44. package/dist/worker/define-sync-worker.d.ts.map +1 -1
  45. package/dist/worker/engine-control.d.ts +53 -0
  46. package/dist/worker/engine-control.d.ts.map +1 -1
  47. package/package.json +4 -5
  48. package/skills/core/SKILL.md +72 -55
  49. package/skills/operating/SKILL.md +120 -120
  50. package/src/boot-report.ts +4 -3
  51. package/src/circuits/envelope-to-change.ts +102 -0
  52. package/src/circuits/group-sync.ts +1047 -0
  53. package/src/circuits/shape-group.ts +158 -0
  54. package/src/circuits/stream-inbox.ts +225 -0
  55. package/src/circuits/stream-source.ts +165 -0
  56. package/src/circuits/subscription-client.ts +353 -0
  57. package/src/circuits/sync-engine.ts +641 -0
  58. package/src/debug.ts +1 -85
  59. package/src/export-dump.ts +3 -2
  60. package/src/index.ts +290 -273
  61. package/src/lazy-guard.ts +1 -1
  62. package/src/local-tables.ts +9 -2
  63. package/src/schema.ts +2 -11
  64. package/src/sync/apply.ts +72 -110
  65. package/src/sync/copy.ts +15 -15
  66. package/src/sync/fold.ts +94 -0
  67. package/src/sync/metadata-tables.ts +42 -1
  68. package/src/sync/subscription-state.ts +21 -3
  69. package/src/sync/types.ts +13 -141
  70. package/src/testing.ts +2 -2
  71. package/src/worker/attach-sync-client.ts +8 -1
  72. package/src/worker/define-sync-worker.ts +122 -13
  73. package/src/worker/engine-control.ts +89 -0
  74. package/dist/read-stream-stall.d.ts +0 -54
  75. package/dist/read-stream-stall.d.ts.map +0 -1
  76. package/dist/shape-sync.d.ts +0 -207
  77. package/dist/shape-sync.d.ts.map +0 -1
  78. package/dist/sync/index.d.ts +0 -32
  79. package/dist/sync/index.d.ts.map +0 -1
  80. package/dist/sync/nudge.d.ts +0 -49
  81. package/dist/sync/nudge.d.ts.map +0 -1
  82. package/dist/sync/shape-inbox.d.ts +0 -215
  83. package/dist/sync/shape-inbox.d.ts.map +0 -1
  84. package/dist/sync/tags.d.ts +0 -142
  85. package/dist/sync/tags.d.ts.map +0 -1
  86. package/dist/sync-auth.d.ts +0 -53
  87. package/dist/sync-auth.d.ts.map +0 -1
  88. package/src/read-stream-stall.ts +0 -102
  89. package/src/shape-sync.ts +0 -533
  90. package/src/sync/index.ts +0 -1124
  91. package/src/sync/nudge.ts +0 -110
  92. package/src/sync/shape-inbox.ts +0 -566
  93. package/src/sync/tags.ts +0 -390
  94. package/src/sync-auth.ts +0 -117
@@ -1,142 +0,0 @@
1
- import type { ChangeMessage, MovePattern, Row } from "@electric-sql/client";
2
- import type { PGliteInterface, Transaction } from "@electric-sql/pglite";
3
- import type { ApplyTarget } from "../local-tables";
4
- /**
5
- * Electric **tagged-subquery** reconciliation (ADR-0023). A shape whose `where` contains a subquery
6
- * (membership-style row filters: `container_id IN (SELECT … FROM memberships WHERE member = $sub)`)
7
- * streams two extra things the plain change path ignores:
8
- *
9
- * - every change message carries `headers.tags` — the **reasons** the row is in the shape (one tag per
10
- * grant/membership), plus `removed_tags` on an update;
11
- * - a **`move-out` `EventMessage`** carries `patterns: { pos, value }[]` — "the tag whose component at
12
- * index `pos` equals `value` is withdrawn", i.e. that grant was revoked.
13
- *
14
- * A row leaves the shape only when it has **no remaining tag**. The engine drops the `EventMessage`
15
- * today, so a removed member keeps the revoked rows. This module persists each row's tag-set in one
16
- * metadata table and evicts rows whose last tag is withdrawn — closing the move-out gap without an
17
- * Electric change.
18
- *
19
- * Tag storage is a single metadata table keyed by the synced table + a canonical primary-key JSON:
20
- * `shape_row_tags(shape_table, pk_json, tag)`. It is created in `migrateSubscriptionMetadataTables`.
21
- */
22
- /**
23
- * The pgxsinkit-owned metadata schema (ADR-0009 decision 6) the tag store + subscription state live in.
24
- * The sync engine defaults its `metadataSchema` to this, and `createSyncClient` never overrides it — so
25
- * the desync path (which is outside the engine) can key the tag store by this same constant.
26
- */
27
- export declare const DEFAULT_METADATA_SCHEMA = "pgxsinkit";
28
- /**
29
- * Validate the metadata schema name at engine construction. The name is interpolated RAW into two
30
- * positions a double-quoted identifier cannot cover:
31
- * - GUC space — `SET LOCAL <schema>.syncing` (sync/index.ts) and `SET <schema>.syncing = false`
32
- * (the metadata migration). GUC grammar takes a `namespace.name` of bare identifiers; it does not
33
- * accept a quoted identifier the way a table/column position does, so the name cannot be safely
34
- * quoted there.
35
- * - the `CREATE SCHEMA <schema>` DDL identifier position.
36
- * Rather than trust arbitrary caller input in those raw positions, restrict the name to a bare
37
- * lowercase identifier and reject uppercase/exotic names outright. The default "pgxsinkit" passes.
38
- */
39
- export declare function assertValidMetadataSchema(metadataSchema: string): void;
40
- /**
41
- * The tag store's schema-qualified identifier, derived from the `shape_row_tags` pgTable config
42
- * (ADR-0029 D3 — single source; no parallel name string). The store itself is provisioned by
43
- * `migrateSubscriptionMetadataTables`, which renders that same pgTable.
44
- */
45
- export declare function shapeRowTagsTableName(metadataSchema: string): string;
46
- /**
47
- * The SESSION (`pg_temp`) tag store's qualified identifier (ADR-0042), derived from the session
48
- * `shape_row_tags` pgTable config — the same relation name, in `pg_temp`. Used by the scope-blind
49
- * {@link buildClearShapeTagsSql} so a desync/discard clears an ephemeral shape's tags wherever they live.
50
- */
51
- export declare function shapeRowTagsSessionTableName(): string;
52
- /** The `shape_table` key for the tag store: the synced table, schema-qualified (defaults `public`). */
53
- export declare function shapeTableId(schema: string | undefined, table: string): string;
54
- /**
55
- * Static SQL to drop a shape's tag-set, **guarded** by `to_regclass` so it is a no-op when the tag store
56
- * does not exist. Used by `buildDesyncTableSql` (ADR-0023 Slice 2), which may be exec'd standalone (a
57
- * caller/test that builds the local schema without booting the sync engine that creates the store). The
58
- * engine's own `clearShapeTags` runs inside a commit where the store is guaranteed present, so it is not
59
- * guarded.
60
- */
61
- export declare function buildClearShapeTagsSql(shapeTable: string, metadataSchema?: string): string;
62
- /**
63
- * Canonical primary-key JSON for a synced row — the tag store's per-row key. Built from the **mapped**
64
- * value (synced-table column names), with pk columns sorted so the string is stable, and `bigint`
65
- * rendered as a string (JSON has no bigint). Reversible via `JSON.parse` for the eviction DELETE.
66
- */
67
- export declare function serializeRowPk(value: Row<unknown>, primaryKey: readonly string[]): string;
68
- /**
69
- * Split a composite `MoveTag` into its positional columns. A tag for a shape with N subquery conditions
70
- * is the per-condition grant values joined by `/` (an absent condition is an empty column) — e.g. a
71
- * two-condition shape yields `"<grantHash>/1//"` and `"//<grantHash>/<grantHash>"`. `\/` is a literal
72
- * `/`, `\\` a literal `\`. A single-condition shape's tag has no separator → `[tag]`.
73
- *
74
- * (The `MovePattern.pos` indexes into THIS split — confirmed against Electric 1.7.4 wire messages,
75
- * ADR-0023. The upstream type doc mentions `|`; the actual column separator on the wire is `/`.)
76
- */
77
- export declare function splitTagComponents(tag: string): string[];
78
- /**
79
- * Whether a tag is withdrawn by a `move-out` event. A revoked grant can appear at more than one column
80
- * of the shape's tag structure (one position per subquery condition that references it), so the event
81
- * enumerates those positions and a tag is withdrawn if it carries the value at **any** of them. A row
82
- * is then evicted only once **every** tag keeping it in the shape has been withdrawn (the caller's
83
- * empty-tag-set check) — so a row held by an independent second grant survives. Empty pattern set
84
- * matches nothing.
85
- */
86
- export declare function tagMatchesPatterns(tag: string, patterns: readonly MovePattern[]): boolean;
87
- interface TagSyncOptions {
88
- pg: PGliteInterface | Transaction;
89
- metadataSchema: string;
90
- shapeTable: string;
91
- messages: ChangeMessage<Row<unknown>>[];
92
- primaryKey: string[];
93
- /** ADR-0042: route the tag DML to the SESSION (`pg_temp`) store for an ephemeral group. */
94
- sessionScoped?: boolean;
95
- }
96
- /**
97
- * Maintain the tag-set for a shape from its drained change batch (ADR-0023). For a subquery shape every
98
- * change carries `headers.tags` (the row's current full reason-set), so insert/update **replace** the
99
- * row's tags; a delete drops them. `removed_tags` (without `tags`) deletes just those. A non-subquery
100
- * shape carries no `tags`, so this is a no-op for it. Runs before the data apply and the move-out
101
- * eviction in the same commit, so an add-then-remove within one batch resolves correctly.
102
- */
103
- export declare function applyShapeTagSync({ pg, metadataSchema, shapeTable, messages, primaryKey, sessionScoped, }: TagSyncOptions): Promise<void>;
104
- /**
105
- * Record (union) a **move-in** row's tags without clearing the tags the row already carries (ADR-0024).
106
- * A move-in ADDS a reason a row is in the shape, so — unlike a regular change, whose `tags` is the
107
- * authoritative full reason-set and therefore REPLACES (see {@link applyShapeTagSync}) — a move-in must
108
- * not drop tags from an independent grant. Inserting with `ON CONFLICT DO NOTHING` is correct whether
109
- * Electric sends the row's full reason-set or only the newly-added grant on a move-in, so move-out
110
- * eviction afterwards stays correct under multi-grant without depending on the move-in's tag cardinality.
111
- * A row with no `tags` (a non-subquery shape) is a no-op.
112
- */
113
- export declare function addShapeRowTags({ pg, metadataSchema, shapeTable, messages, primaryKey, sessionScoped, }: TagSyncOptions): Promise<void>;
114
- interface MoveOutOptions {
115
- pg: PGliteInterface | Transaction;
116
- metadataSchema: string;
117
- shapeTable: string;
118
- /** The resolved apply target for the synced table the evicted rows are deleted from (ADR-0029 D1). */
119
- target: ApplyTarget;
120
- /** One entry per buffered `move-out` event, each its own pattern set. */
121
- patternSets: MovePattern[][];
122
- debug: boolean;
123
- /** ADR-0042: route the tag reads/evictions to the SESSION (`pg_temp`) store for an ephemeral group. */
124
- sessionScoped?: boolean;
125
- }
126
- /**
127
- * Apply buffered `move-out` events for a shape (ADR-0023): withdraw the matched tag from every row that
128
- * carries it, then evict the synced rows left with **no** remaining tag — so a row held by two grants
129
- * survives losing one. Eviction goes through the tested bulk-delete path, so it fires the reconcile
130
- * trigger and the read-model/overlay stays consistent. Returns the number of rows evicted.
131
- */
132
- export declare function applyShapeMoveOut({ pg, metadataSchema, shapeTable, target, patternSets, debug, sessionScoped, }: MoveOutOptions): Promise<number>;
133
- /** Drop a shape's entire tag-set — for a `must-refetch`/read-cache rebuild, before the re-snapshot (ADR-0023 Slice 2). */
134
- export declare function clearShapeTags({ pg, metadataSchema, shapeTable, sessionScoped, }: {
135
- pg: PGliteInterface | Transaction;
136
- metadataSchema: string;
137
- shapeTable: string;
138
- /** ADR-0042: clear the SESSION (`pg_temp`) tag store for an ephemeral group's must-refetch rebuild. */
139
- sessionScoped?: boolean;
140
- }): Promise<void>;
141
- export {};
142
- //# sourceMappingURL=tags.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"tags.d.ts","sourceRoot":"","sources":["../../src/sync/tags.ts"],"names":[],"mappings":"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"}
@@ -1,53 +0,0 @@
1
- import type { ExternalHeadersRecord, ShapeStreamOptions } from "@electric-sql/client";
2
- /** The per-shape error handler shape Electric expects (`ShapeStreamOptions.onError`). */
3
- type ShapeStreamErrorHandler = NonNullable<ShapeStreamOptions["onError"]>;
4
- /**
5
- * Read-path identity (ADR-0013). The two ingress points must share **one** token lifecycle: the
6
- * write path already calls `getAuthToken` fresh on every flush, so the read path must too — never
7
- * freezing a JWT at boot, which wedges a long-lived offline-first session the instant the token
8
- * expires.
9
- *
10
- * `buildAuthShapeHeaders` returns the read-path `Authorization` header as an **async function**.
11
- * Electric resolves header-value functions on every request *and every retry*
12
- * (`ExternalHeadersRecord` allows `string | (() => string | Promise<string>)`), so each shape fetch
13
- * presents a fresh token. This is the client mirror of ADR-0003's server-side one-identity decision.
14
- *
15
- * The provider contract (documented in `docs/architecture.md`): `getAuthToken` is now called per
16
- * request by both paths and **must be refresh-deduping** — return the cached valid token and refresh
17
- * single-flight, so an N-shape consistency group does not trigger N refreshes.
18
- */
19
- /**
20
- * Build the read-path shape headers: the optional async `Authorization` (per ADR-0013) **plus** any
21
- * caller-supplied static `requestHeaders`. The static headers are spread first so the toolkit-owned
22
- * `Authorization` always wins; they exist for deployment-gateway credentials the toolkit is otherwise
23
- * agnostic about — e.g. a Supabase `apikey` header the platform function gateway expects. Emitted
24
- * whenever *either* a token provider or static headers are present, so a credential-only consumer
25
- * (no per-request token) still sends its headers.
26
- */
27
- export declare function buildShapeHeaders(input: {
28
- getAuthToken?: () => Promise<string | undefined>;
29
- requestHeaders?: Record<string, string>;
30
- }): ExternalHeadersRecord;
31
- /** Token-only convenience over {@link buildShapeHeaders}; retained for callers that pass a provider. */
32
- export declare function buildAuthShapeHeaders(getAuthToken: () => Promise<string | undefined>, requestHeaders?: Record<string, string>): ExternalHeadersRecord;
33
- /**
34
- * The per-shape `ShapeStreamOptions.onError` handler for the read path. It is the only place that can
35
- * request a retry (the `MultiShapeStream.subscribe` `onError` is notification-only), so it owns BOTH
36
- * read-path identity (ADR-0013) and read-stream error surfacing (#4):
37
- *
38
- * - **auth (401/403)** → `onAuthError` + return `{}` (retry): Electric re-issues the request,
39
- * re-resolving the async Authorization header ({@link buildAuthShapeHeaders}) for a *fresh* token.
40
- * Never return `void` here — that stops the stream permanently, wrong for offline-first: a dead
41
- * session must keep retrying (jittered backoff bounds the cost) so sync resumes the instant re-auth
42
- * makes the token valid again. The optional `onAuthError` surfaces a distinct "re-login" status.
43
- * - **any other error** → `onReadStreamError` (so the runtime can move to a `degraded` status instead
44
- * of silently believing the read path is live), then retry transient faults ({@link
45
- * isRetryableStreamError}: 5xx/429/network → `{}`) or stop a structural 4xx (return `undefined`). A
46
- * later successful fetch (`onSyncActivity`) clears the degraded status back to live.
47
- */
48
- export declare function createShapeErrorHandler(options?: {
49
- onAuthError?: () => void;
50
- onReadStreamError?: (error: Error) => void;
51
- }): ShapeStreamErrorHandler;
52
- export {};
53
- //# sourceMappingURL=sync-auth.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"sync-auth.d.ts","sourceRoot":"","sources":["../src/sync-auth.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,qBAAqB,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAEtF,yFAAyF;AACzF,KAAK,uBAAuB,GAAG,WAAW,CAAC,kBAAkB,CAAC,SAAS,CAAC,CAAC,CAAC;AAE1E;;;;;;;;;;;;;;GAcG;AACH;;;;;;;GAOG;AACH,wBAAgB,iBAAiB,CAAC,KAAK,EAAE;IACvC,YAAY,CAAC,EAAE,MAAM,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAAC;IACjD,cAAc,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CACzC,GAAG,qBAAqB,CAYxB;AAED,wGAAwG;AACxG,wBAAgB,qBAAqB,CACnC,YAAY,EAAE,MAAM,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,EAC/C,cAAc,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GACtC,qBAAqB,CAEvB;AAuCD;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,uBAAuB,CACrC,OAAO,GAAE;IAAE,WAAW,CAAC,EAAE,MAAM,IAAI,CAAC;IAAC,iBAAiB,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAA;CAAO,GACrF,uBAAuB,CASzB"}
@@ -1,102 +0,0 @@
1
- import { BackoffDefaults, type BackoffOptions } from "@electric-sql/client";
2
-
3
- /**
4
- * The read path's OUTAGE seam (board ADR-0010 "offline return").
5
- *
6
- * Every shape fetch runs inside Electric's `createFetchWithBackoff`, which retries a failed attempt
7
- * **forever** (`maxRetries: Infinity` — "clients may go offline and come back") and only re-throws a
8
- * non-retryable 4xx. A network-level failure therefore never escapes that wrapper: `ShapeStream.onError`
9
- * is never called, so neither is `onReadStreamError`, and a runtime keying off those alone reports
10
- * `syncing` for as long as the machine stays offline. `backoffOptions.onFailedAttempt` is the ONLY signal
11
- * Electric surfaces from inside the loop, and it is what this probe turns into a runtime status change.
12
- *
13
- * The two seams PARTITION the failures, they do not overlap:
14
- *
15
- * - **Retried inside the wrapper** (a rejected request — the offline case, with no HTTP status at all — a
16
- * 5xx, or a 429) → nobody else will ever hear about it. This probe's `onStalled`.
17
- * - **Escapes the wrapper** (any other 4xx: 401/403 auth, 404/409/… structural) → `ShapeStream.onError`,
18
- * i.e. `createShapeErrorHandler` → `onAuthError` / `onReadStreamError`, which own it and carry a real
19
- * error message. Deliberately NOT reported here, so a rejected token still surfaces as the more
20
- * actionable `auth-needed` and an expired handle's 409 stays the recovery it is.
21
- * - **A deliberate abort** — a stream teardown, a hidden tab (`PAUSE_STREAM`), a live-request timeout, a
22
- * system wake, and the live-tail nudge's `forceDisconnectAndRefresh` all abort the in-flight request,
23
- * and Electric calls `onFailedAttempt` for the resulting `AbortError` like any other. None is an
24
- * outage; counting them would report "connection needed" for backgrounding a tab.
25
- *
26
- * `onFailedAttempt` carries no arguments, so the classification is made one layer down, in the
27
- * `fetchClient` this probe supplies: it records how the attempt that just settled would be treated by the
28
- * very next lines of Electric's own catch block. Recovery needs nothing here — the runtime clears a
29
- * stream-degraded status on the next delivered batch (`onSyncActivity`), which a resumed stream produces
30
- * on its first successful poll.
31
- */
32
- export interface ReadStreamStallProbe {
33
- /** Pass as `ShapeStreamOptions.backoffOptions` — Electric's defaults plus the failed-attempt hook. */
34
- backoffOptions: BackoffOptions;
35
- /** Pass as `ShapeStreamOptions.fetchClient` — the innermost transport, wrapped to classify each attempt. */
36
- fetchClient: typeof fetch;
37
- }
38
-
39
- /**
40
- * The CALL signature of `fetch`, without the runtime-specific statics (Bun's global carries `preconnect`).
41
- * A ShapeStream only ever invokes its `fetchClient` as a plain call, so this is the honest contract for a
42
- * transport being wrapped — and it is what lets a test inject a failing one.
43
- */
44
- type FetchLike = (request: Parameters<typeof fetch>[0], init?: Parameters<typeof fetch>[1]) => Promise<Response>;
45
-
46
- /**
47
- * Would Electric SWALLOW this response status and retry it inside the backoff loop? Mirrors the branch in
48
- * `createFetchWithBackoff`: a 4xx is re-thrown (and reaches `onError`) unless it is the one retryable
49
- * status, 429; everything else — 5xx above all — is retried where no other seam can see it.
50
- */
51
- function isRetriedInsideBackoff(status: number): boolean {
52
- return status === 429 || status < 400 || status >= 500;
53
- }
54
-
55
- export function createReadStreamStallProbe(input: {
56
- /**
57
- * Notified per failed attempt that Electric will retry internally, never for an escaping 4xx and never
58
- * for a deliberate abort. Fires repeatedly while an outage lasts — Electric retries forever — so the
59
- * consumer owns the transition/dedup, not this probe.
60
- */
61
- onStalled: () => void;
62
- /** The transport to wrap. Defaults to the global `fetch`; a test injects the failure here. */
63
- fetchClient?: FetchLike;
64
- }): ReadStreamStallProbe {
65
- const transport = input.fetchClient;
66
- // How the attempt that just settled will be treated by Electric's catch block. Written by the fetch
67
- // wrapper and read by `onFailedAttempt`, which Electric invokes in the catch of the very call that just
68
- // settled — no await sits between the two, so the pairing holds. Per-probe (one probe per shape), so a
69
- // sibling shape's traffic can never answer for this one.
70
- let lastAttemptRetried = false;
71
- const fetchClient = (async (request: Parameters<typeof fetch>[0], init?: Parameters<typeof fetch>[1]) => {
72
- try {
73
- const response = await (transport ? transport(request, init) : fetch(request, init));
74
- // The server answered. `ok` means no failed attempt at all; otherwise the backoff wrapper turns it
75
- // into a `FetchError` and either swallows it (5xx/429 — ours) or re-throws it (4xx — `onError`'s).
76
- lastAttemptRetried = !response.ok && isRetriedInsideBackoff(response.status);
77
- return response;
78
- } catch (error) {
79
- // A rejection: a transport fault (retried forever — the outage) unless the request was deliberately
80
- // aborted, which Electric turns into a `FetchBackoffAbortError` rather than a retry.
81
- lastAttemptRetried = init?.signal?.aborted !== true;
82
- throw error;
83
- }
84
- // `typeof fetch` (Bun's global) carries a `preconnect` member the wrapper neither has nor needs — the
85
- // ShapeStream only ever invokes fetchClient as a plain fetch — so the shape-compatible cast is safe.
86
- }) as typeof fetch;
87
-
88
- return {
89
- fetchClient,
90
- // `ShapeStream` uses `options.backoffOptions ?? BackoffDefaults` — it SPREADS, it does not merge — so
91
- // a partial object would blank Electric's timings. Spreading `BackoffDefaults` keeps them (1000 /
92
- // 32000 / 2, `maxRetries: Infinity`) and tracks upstream if they ever move: adding this callback is
93
- // behaviour-neutral for retrying.
94
- backoffOptions: {
95
- ...BackoffDefaults,
96
- onFailedAttempt: () => {
97
- if (!lastAttemptRetried) return;
98
- input.onStalled();
99
- },
100
- },
101
- };
102
- }