@pgxsinkit/client 0.5.1 → 0.6.0-rc.1

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/dist/index.js CHANGED
@@ -528,10 +528,10 @@ function buildLocalIndexStatements(entry, syncedTable, projectedColumns) {
528
528
  function buildOverlayNonMembershipTest(primaryKeyColumns, overlayTable) {
529
529
  const key = primaryKeyColumns.length === 1 ? `t.${primaryKeyColumns[0]}` : `(${primaryKeyColumns.map((column) => `t.${column}`).join(", ")})`;
530
530
  return [
531
- `WHERE ${key} NOT IN (`,
531
+ `WHERE (${key} NOT IN (`,
532
532
  ` SELECT ${primaryKeyColumns.map((column) => `o.${column}`).join(", ")}`,
533
533
  ` FROM ${overlayTable} AS o`,
534
- ")"
534
+ ")) IS TRUE"
535
535
  ];
536
536
  }
537
537
  function buildTableColumnSql(columns, primaryKeyColumns, localSchema) {
@@ -2072,8 +2072,106 @@ function envelopeToChange(target, envelope) {
2072
2072
  }
2073
2073
  var PK_SEPARATOR = "\x1F";
2074
2074
 
2075
+ // packages/client/src/retry-after.ts
2076
+ function parseRetryAfterMs(headerValue, nowMs) {
2077
+ if (headerValue == null) {
2078
+ return null;
2079
+ }
2080
+ const trimmed = headerValue.trim();
2081
+ if (trimmed === "") {
2082
+ return null;
2083
+ }
2084
+ if (/^\d+$/.test(trimmed)) {
2085
+ return Number(trimmed) * 1000;
2086
+ }
2087
+ const parsedDate = Date.parse(trimmed);
2088
+ if (Number.isNaN(parsedDate)) {
2089
+ return null;
2090
+ }
2091
+ return Math.max(0, parsedDate - nowMs);
2092
+ }
2093
+
2094
+ // packages/client/src/circuits/long-poll.ts
2095
+ function readRequestUrl(streamUrl, position) {
2096
+ const url = new URL(streamUrl);
2097
+ url.searchParams.set("offset", position.offset);
2098
+ if (position.longPoll)
2099
+ url.searchParams.set("live", "long-poll");
2100
+ if (position.cursor !== null)
2101
+ url.searchParams.set("cursor", position.cursor);
2102
+ return url.toString();
2103
+ }
2104
+ function classifyStatus(status) {
2105
+ if (status === 401 || status === 403)
2106
+ return "token-rejected";
2107
+ if (status === 429 || status >= 500)
2108
+ return "retry";
2109
+ return "terminal";
2110
+ }
2111
+ async function failedRead(response, url) {
2112
+ const body = (await response.text().catch(() => "")).trim();
2113
+ const reason = body.length > 200 ? `${body.slice(0, 200)}\u2026` : body;
2114
+ return new StreamReadError(`[pgxsinkit] stream read failed: HTTP ${response.status} at ${url}${reason ? `: ${reason}` : ""}`, response.status);
2115
+ }
2116
+ async function readResponse(response, url, requestedOffset) {
2117
+ const headers = response.headers;
2118
+ const offset = headers.get("stream-next-offset");
2119
+ if (!offset) {
2120
+ throw new StreamReadError(`[pgxsinkit] stream response carried no Stream-Next-Offset (${url}). A cross-origin edge must expose ` + "the stream-* headers on Access-Control-Expose-Headers (STREAM_READ_EXPOSED_HEADERS).", response.status);
2121
+ }
2122
+ const body = response.status === 204 ? "" : (await response.text()).trim();
2123
+ let envelopes = [];
2124
+ if (body !== "") {
2125
+ try {
2126
+ envelopes = JSON.parse(body);
2127
+ } catch {
2128
+ envelopes = null;
2129
+ }
2130
+ }
2131
+ if (!Array.isArray(envelopes)) {
2132
+ throw new StreamReadError(`[pgxsinkit] stream response body is not a JSON array (${url})`, response.status);
2133
+ }
2134
+ const upToDate = headers.has("stream-up-to-date");
2135
+ const closed = headers.get("stream-closed")?.toLowerCase() === "true";
2136
+ if (envelopes.length === 0 && offset === requestedOffset && !upToDate && !closed) {
2137
+ throw new StreamReadError(`[pgxsinkit] stream response neither advanced the offset nor reached the tail (${url}). Is the edge ` + "exposing Stream-Up-To-Date (STREAM_READ_EXPOSED_HEADERS)?", response.status);
2138
+ }
2139
+ return { envelopes, offset, cursor: headers.get("stream-cursor"), upToDate, closed };
2140
+ }
2141
+ function retryDelayMs(attempt, retryAfterMs, random) {
2142
+ const ceiling = Math.min(100 * 1.3 ** (attempt - 1), 60000);
2143
+ return Math.round(Math.max(retryAfterMs ?? 0, random() * ceiling));
2144
+ }
2145
+ function sleep(ms, signal) {
2146
+ return new Promise((resolve) => {
2147
+ if (signal.aborted) {
2148
+ resolve();
2149
+ return;
2150
+ }
2151
+ const onAbort = () => {
2152
+ clearTimeout(timer);
2153
+ resolve();
2154
+ };
2155
+ const timer = setTimeout(() => {
2156
+ signal.removeEventListener("abort", onAbort);
2157
+ resolve();
2158
+ }, ms);
2159
+ signal.addEventListener("abort", onAbort, { once: true });
2160
+ });
2161
+ }
2162
+ var StreamReadError;
2163
+ var init_long_poll = __esm(() => {
2164
+ StreamReadError = class StreamReadError extends Error {
2165
+ status;
2166
+ constructor(message, status) {
2167
+ super(message);
2168
+ this.name = "StreamReadError";
2169
+ this.status = status;
2170
+ }
2171
+ };
2172
+ });
2173
+
2075
2174
  // packages/client/src/circuits/stream-source.ts
2076
- import { stream } from "@durable-streams/client";
2077
2175
  function createTokenRecovery(onTokenRejected) {
2078
2176
  let recovering = false;
2079
2177
  return async (error) => {
@@ -2089,47 +2187,134 @@ function createTokenRecovery(onTokenRejected) {
2089
2187
  return { headers: { authorization: `Bearer ${fresh}` } };
2090
2188
  };
2091
2189
  }
2092
- async function readShapeStream(options, onBatch, onEnd) {
2093
- const response = await stream({
2094
- url: options.url,
2095
- offset: options.offset ?? STREAM_START,
2096
- live: options.live ?? true,
2097
- headers: { authorization: async () => `Bearer ${await options.token()}` },
2098
- ...options.onTokenRejected ? { onError: createTokenRecovery(options.onTokenRejected) } : {},
2099
- ...options.signal ? { signal: options.signal } : {},
2100
- ...options.fetch ? { fetch: options.fetch } : {}
2101
- });
2190
+ function readShapeStream(options, onBatch, onEnd) {
2191
+ return readShapeStreamWith({}, options, onBatch, onEnd);
2192
+ }
2193
+ function readShapeStreamWith(internals, options, onBatch, onEnd) {
2194
+ const wait = internals.wait ?? sleep;
2195
+ const random = internals.random ?? Math.random;
2196
+ const send = options.fetch ?? ((input, init) => fetch(input, init));
2102
2197
  const live = options.live ?? true;
2198
+ const stop = new AbortController;
2199
+ const signal = stop.signal;
2200
+ const forwardAbort = () => stop.abort();
2201
+ options.signal?.addEventListener("abort", forwardAbort, { once: true });
2202
+ if (options.signal?.aborted)
2203
+ stop.abort();
2103
2204
  let closedByCaller = false;
2104
2205
  let endReported = false;
2105
2206
  const reportEnd = (error) => {
2207
+ options.signal?.removeEventListener("abort", forwardAbort);
2106
2208
  if (endReported || closedByCaller)
2107
2209
  return;
2108
2210
  endReported = true;
2109
2211
  onEnd?.(error);
2110
2212
  };
2111
- const unsubscribe = response.subscribeJson(async (batch) => {
2112
- await onBatch({
2113
- envelopes: batch.items,
2114
- offset: String(batch.offset),
2115
- upToDate: batch.upToDate
2116
- });
2117
- if (batch.streamClosed === true || !live && batch.upToDate)
2118
- reportEnd(null);
2119
- });
2120
- response.closed.then(() => {
2121
- if (options.signal?.aborted)
2122
- reportEnd(null);
2123
- }, (error) => reportEnd(error instanceof Error ? error : new Error(String(error))));
2124
- return {
2213
+ async function request(position) {
2214
+ const url = readRequestUrl(options.url, position);
2215
+ const recover = options.onTokenRejected ? createTokenRecovery(options.onTokenRejected) : null;
2216
+ let reminted = null;
2217
+ let attempt = 0;
2218
+ for (;; ) {
2219
+ if (signal.aborted)
2220
+ return null;
2221
+ const authorization = reminted ?? `Bearer ${await options.token()}`;
2222
+ reminted = null;
2223
+ let response;
2224
+ try {
2225
+ response = await send(url, { method: "GET", headers: { authorization }, signal });
2226
+ if (response.ok)
2227
+ return await readResponse(response, url, position.offset);
2228
+ } catch (error) {
2229
+ if (signal.aborted)
2230
+ return null;
2231
+ if (error instanceof StreamReadError)
2232
+ throw error;
2233
+ await wait(retryDelayMs(++attempt, null, random), signal);
2234
+ continue;
2235
+ }
2236
+ const verdict = classifyStatus(response.status);
2237
+ if (verdict === "retry") {
2238
+ await response.body?.cancel().catch(() => {});
2239
+ const retryAfterMs = parseRetryAfterMs(response.headers.get("retry-after"), Date.now());
2240
+ await wait(retryDelayMs(++attempt, retryAfterMs, random), signal);
2241
+ continue;
2242
+ }
2243
+ const failure = await failedRead(response, url);
2244
+ if (verdict === "token-rejected") {
2245
+ const retry = await recover?.(failure);
2246
+ if (retry) {
2247
+ reminted = retry.headers.authorization;
2248
+ continue;
2249
+ }
2250
+ }
2251
+ throw failure;
2252
+ }
2253
+ }
2254
+ let position = { offset: options.offset ?? STREAM_START, cursor: null, longPoll: false };
2255
+ let first = null;
2256
+ const subscription = {
2125
2257
  close: () => {
2126
2258
  closedByCaller = true;
2127
- unsubscribe();
2259
+ options.signal?.removeEventListener("abort", forwardAbort);
2260
+ stop.abort();
2128
2261
  }
2129
2262
  };
2263
+ const opened = (async () => {
2264
+ try {
2265
+ first = await request(position);
2266
+ if (first === null) {
2267
+ throw new StreamReadError(`[pgxsinkit] stream read of ${options.url} was aborted before its first response`);
2268
+ }
2269
+ return subscription;
2270
+ } catch (error) {
2271
+ options.signal?.removeEventListener("abort", forwardAbort);
2272
+ throw error;
2273
+ }
2274
+ })();
2275
+ async function deliver() {
2276
+ let response = first;
2277
+ try {
2278
+ for (;; ) {
2279
+ if (signal.aborted)
2280
+ return null;
2281
+ const last = response.closed || !live && response.upToDate;
2282
+ let ahead = null;
2283
+ if (!last) {
2284
+ position = {
2285
+ offset: response.offset,
2286
+ cursor: response.cursor ?? position.cursor,
2287
+ longPoll: live && response.upToDate
2288
+ };
2289
+ ahead = request(position);
2290
+ ahead.catch(() => {});
2291
+ }
2292
+ await onBatch({ envelopes: response.envelopes, offset: response.offset, upToDate: response.upToDate });
2293
+ if (ahead === null)
2294
+ return null;
2295
+ const next = await ahead;
2296
+ if (next === null)
2297
+ return null;
2298
+ response = next;
2299
+ }
2300
+ } catch (error) {
2301
+ if (signal.aborted)
2302
+ return null;
2303
+ stop.abort();
2304
+ return error instanceof Error ? error : new Error(String(error));
2305
+ }
2306
+ }
2307
+ opened.then(() => {
2308
+ return;
2309
+ }).then(async () => reportEnd(await deliver()), () => {
2310
+ return;
2311
+ });
2312
+ return opened;
2130
2313
  }
2131
2314
  var STREAM_START = "-1";
2132
- var init_stream_source = () => {};
2315
+ var init_stream_source = __esm(() => {
2316
+ init_long_poll();
2317
+ });
2133
2318
 
2134
2319
  // packages/client/src/circuits/shape-group.ts
2135
2320
  function createShapeGroup(options) {
@@ -3257,23 +3442,6 @@ function buildRequestHeaders(bearerToken, requestHeaders) {
3257
3442
  function classifyEventBatchFailure(httpStatus) {
3258
3443
  return httpStatus != null && AUTH_STATUSES.has(httpStatus) ? "auth" : "retryable";
3259
3444
  }
3260
- function parseRetryAfterMs(headerValue, nowMs) {
3261
- if (headerValue == null) {
3262
- return null;
3263
- }
3264
- const trimmed = headerValue.trim();
3265
- if (trimmed === "") {
3266
- return null;
3267
- }
3268
- if (/^\d+$/.test(trimmed)) {
3269
- return Number(trimmed) * 1000;
3270
- }
3271
- const parsedDate = Date.parse(trimmed);
3272
- if (Number.isNaN(parsedDate)) {
3273
- return null;
3274
- }
3275
- return Math.max(0, parsedDate - nowMs);
3276
- }
3277
3445
  function computeEventBackoffMs(attempt, options, random) {
3278
3446
  const baseMs = options.baseMs ?? DEFAULT_EVENT_BACKOFF_BASE_MS;
3279
3447
  const ceilingMs = options.ceilingMs ?? DEFAULT_EVENT_BACKOFF_CEILING_MS;
@@ -4120,7 +4288,7 @@ async function drainJournalForExport(deps, timeoutMs) {
4120
4288
  if (nowMs2() - drainStartPerf >= timeoutMs) {
4121
4289
  throw new DataExportDrainError("timeout", diagnostics);
4122
4290
  }
4123
- await sleep(DRAIN_POLL_INTERVAL_MS);
4291
+ await sleep2(DRAIN_POLL_INTERVAL_MS);
4124
4292
  }
4125
4293
  }
4126
4294
  function buildArtefactCommentHeader(tableNames, escapeHatch) {
@@ -4178,7 +4346,7 @@ async function performDataExport(deps, options = {}) {
4178
4346
  };
4179
4347
  return { file, report };
4180
4348
  }
4181
- var DEFAULT_DRAIN_TIMEOUT_MS = 15000, DRAIN_POLL_INTERVAL_MS = 50, DataExportDrainError, hasNonDrainableRows = (diagnostics) => diagnostics.failedCount > 0 || diagnostics.quarantinedCount > 0 || diagnostics.conflictedCount > 0, isFullyDrained = (diagnostics) => diagnostics.pendingCount === 0 && diagnostics.sendingCount === 0 && diagnostics.ackedCount === 0 && !hasNonDrainableRows(diagnostics), sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
4349
+ var DEFAULT_DRAIN_TIMEOUT_MS = 15000, DRAIN_POLL_INTERVAL_MS = 50, DataExportDrainError, hasNonDrainableRows = (diagnostics) => diagnostics.failedCount > 0 || diagnostics.quarantinedCount > 0 || diagnostics.conflictedCount > 0, isFullyDrained = (diagnostics) => diagnostics.pendingCount === 0 && diagnostics.sendingCount === 0 && diagnostics.ackedCount === 0 && !hasNonDrainableRows(diagnostics), sleep2 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
4182
4350
  var init_export_data = __esm(() => {
4183
4351
  init_export_dump();
4184
4352
  DataExportDrainError = class DataExportDrainError extends Error {
@@ -7099,6 +7267,7 @@ var init_store_build = __esm(() => {
7099
7267
  "StorageBuildMismatchError",
7100
7268
  "BuildMismatchError",
7101
7269
  "DataFormatMismatchError",
7270
+ "PostgresVersionMismatchError",
7102
7271
  "BuildMarkerUnreadableError"
7103
7272
  ]);
7104
7273
  });
@@ -11828,6 +11997,7 @@ async function createSyncClient(options) {
11828
11997
  hadStored: storedFingerprint != null
11829
11998
  });
11830
11999
  await pgwasm.exec(generateDurableLocalSchemaSql(options.registry));
12000
+ await pgwasm.refreshArrayTypes();
11831
12001
  await writeStoredLocalSchemaFingerprint(pgwasm, options.registry, currentFingerprint);
11832
12002
  bootReportBuilder.setSchemaFastPath({ skipped: false, fingerprintMatch: false });
11833
12003
  }
@@ -12760,4 +12930,4 @@ export {
12760
12930
  wrapLiveQueryForMaterialization
12761
12931
  };
12762
12932
 
12763
- //# debugId=E3BAB3EDFFA8367464756E2164756E21
12933
+ //# debugId=4F9DD6FD8DD671E164756E2164756E21