@vrplatform/kysely 1.3.45-stage.119 → 1.3.45-stage.1259

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 (89) hide show
  1. package/build/.data.tar +2 -2
  2. package/build/main/control-plane/index.d.ts +28 -6
  3. package/build/main/control-plane/index.js.map +1 -1
  4. package/build/main/index.d.ts +38 -2
  5. package/build/main/index.js +271 -55
  6. package/build/main/index.js.map +1 -1
  7. package/build/main/local/index.js +115 -8
  8. package/build/main/local/index.js.map +1 -1
  9. package/build/main/migration-source.d.ts +4 -0
  10. package/build/main/migration-source.js +37 -0
  11. package/build/main/migration-source.js.map +1 -0
  12. package/build/main/postgres-error.d.ts +3 -3
  13. package/build/main/postgres-error.js +4 -3
  14. package/build/main/postgres-error.js.map +1 -1
  15. package/build/main/query/listing/status.js +6 -2
  16. package/build/main/query/listing/status.js.map +1 -1
  17. package/build/main/query/tenant/status.d.ts +1 -1
  18. package/build/main/query/tenant/status.js +5 -2
  19. package/build/main/query/tenant/status.js.map +1 -1
  20. package/build/main/regional.d.ts +1 -0
  21. package/build/main/regional.js +1 -0
  22. package/build/main/regional.js.map +1 -1
  23. package/build/main/test/index.d.ts +25 -2
  24. package/build/main/test/index.js +40 -8
  25. package/build/main/test/index.js.map +1 -1
  26. package/build/main/v1.generated.d.ts +195 -19
  27. package/build/main/v1.generated.js.map +1 -1
  28. package/build/migrations-v2/0000000000033-plaid-connect-session-telemetry.ts +31 -0
  29. package/build/migrations-v2/0000000000033-reservation-issue-seed-bucket-index.ts +19 -0
  30. package/build/migrations-v2/0000000000034-retire-recent-classification-indexes.ts +29 -0
  31. package/build/migrations-v2/0000000000035-core-change-autovacuum.ts +24 -0
  32. package/build/migrations-v2/0000000000036-journal-entry-inactive-reason-constraint.ts +33 -0
  33. package/build/migrations-v2/0000000000037-journal-entry-inactive-reasons.ts +19 -0
  34. package/build/migrations-v2/0000000000038-journal-entry-group-inactive-reason.ts +14 -0
  35. package/build/migrations-v2/0000000000039-reservation-guest-breakdown.ts +19 -0
  36. package/build/migrations-v2/0000000000040-csv-import-source-identity-index.ts +23 -0
  37. package/build/migrations-v2/0000000000041-payment-returns.ts +38 -0
  38. package/build/migrations-v2/0000000000042-operation-resource-types.ts +609 -0
  39. package/build/migrations-v2/0000000000043-reservation-journal-freshness.ts +149 -0
  40. package/build/migrations-v2/0000000000044-reservation-journal-freshness-backfill.ts +254 -0
  41. package/build/migrations-v2/0000000000045-reservation-journal-freshness-revision-repair.ts +83 -0
  42. package/build/migrations-v2/0000000000046-materialized-reservation-journal-operations.ts +709 -0
  43. package/build/migrations-v2/0000000000047-public-audit-completion.ts +77 -0
  44. package/build/migrations-v2/0000000000048-reservation-journal-full-refresh-repair.ts +136 -0
  45. package/build/migrations-v2/0000000000049-queued-journal-operation-failures.ts +60 -0
  46. package/build/migrations-v2/0000000000050-connection-oauth-state.ts +43 -0
  47. package/build/migrations-v2/0000000000051-owner-statement-email-delivery.ts +134 -0
  48. package/build/migrations-v2/0000000000052-fee-journal-lock-skip-operations.ts +59 -0
  49. package/build/migrations-v2/0000000000053-fee-journal-lock-skip-null-attempt.ts +44 -0
  50. package/build/migrations-v2/0000000000054-journal-refresh-issue-codes.ts +16 -0
  51. package/build/migrations-v2/0000000000055-tenant-billing-subscription.ts +8 -0
  52. package/build/migrations-v2/0000000000056-journal-operation-failure-precedence.ts +306 -0
  53. package/build/migrations-v2/0000000000057-journal-invalidation-failure-code.ts +28 -0
  54. package/build/migrations-v2/0000000000058-journal-invalidation-locked-failure.ts +16 -0
  55. package/build/migrations-v2/0000000000059-billing-active-listing-cross-region-partner.ts +135 -0
  56. package/build/migrations-v2/0000000000060-accounting-integrity-change-driven.ts +99 -0
  57. package/build/migrations-v2/0000000000061-tenant-pending-onboarding-status.ts +37 -0
  58. package/build/migrations-v2/0000000000062-statement-payout-operations.ts +16 -0
  59. package/build/migrations-v2/0000000000063-missing-account-assignments-issue-code.ts +13 -0
  60. package/build/migrations-v2/0000000000064-journal-invalidation-source-lookup-index.ts +26 -0
  61. package/build/migrations-v2/0000000000065-hasura-connection-event-credentials.ts +42 -0
  62. package/build/migrations-v2/0000000000066-recurring-fee-listing-subscription-match-by.ts +51 -0
  63. package/build/module/control-plane/index.d.ts +28 -6
  64. package/build/module/control-plane/index.js.map +1 -1
  65. package/build/module/index.d.ts +38 -2
  66. package/build/module/index.js +269 -55
  67. package/build/module/index.js.map +1 -1
  68. package/build/module/local/index.js +115 -8
  69. package/build/module/local/index.js.map +1 -1
  70. package/build/module/migration-source.d.ts +4 -0
  71. package/build/module/migration-source.js +34 -0
  72. package/build/module/migration-source.js.map +1 -0
  73. package/build/module/postgres-error.d.ts +3 -3
  74. package/build/module/postgres-error.js +4 -3
  75. package/build/module/postgres-error.js.map +1 -1
  76. package/build/module/query/listing/status.js +6 -2
  77. package/build/module/query/listing/status.js.map +1 -1
  78. package/build/module/query/tenant/status.d.ts +1 -1
  79. package/build/module/query/tenant/status.js +5 -2
  80. package/build/module/query/tenant/status.js.map +1 -1
  81. package/build/module/regional.d.ts +1 -0
  82. package/build/module/regional.js +1 -0
  83. package/build/module/regional.js.map +1 -1
  84. package/build/module/test/index.d.ts +25 -2
  85. package/build/module/test/index.js +39 -8
  86. package/build/module/test/index.js.map +1 -1
  87. package/build/module/v1.generated.d.ts +195 -19
  88. package/build/module/v1.generated.js.map +1 -1
  89. package/package.json +9 -7
@@ -17,17 +17,24 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
17
17
  return (mod && mod.__esModule) ? mod : { "default": mod };
18
18
  };
19
19
  Object.defineProperty(exports, "__esModule", { value: true });
20
+ exports.retryPostgresLockFailure = retryPostgresLockFailure;
20
21
  exports.useKysely = useKysely;
22
+ exports.usePostgres = usePostgres;
21
23
  exports.useAsyncPostgres = useAsyncPostgres;
22
24
  exports.useAsyncKysely = useAsyncKysely;
25
+ exports.useAsyncNeonWebSocketKysely = useAsyncNeonWebSocketKysely;
26
+ exports.useControlPlaneKysely = useControlPlaneKysely;
23
27
  exports.useAsyncControlPlaneKysely = useAsyncControlPlaneKysely;
24
28
  exports.forceCloseAllPostgres = forceCloseAllPostgres;
25
29
  const exponential_backoff_1 = require("exponential-backoff");
30
+ const serverless_1 = require("@neondatabase/serverless");
31
+ const kysely_1 = require("kysely");
26
32
  const kysely_postgres_js_1 = require("kysely-postgres-js");
27
33
  const postgres_1 = __importDefault(require("postgres"));
28
34
  const control_plane_1 = require("./control-plane");
29
35
  const error_1 = require("./error");
30
36
  const plugins_1 = require("./plugins");
37
+ const postgres_error_1 = require("./postgres-error");
31
38
  __exportStar(require("./error"), exports);
32
39
  __exportStar(require("./isomorphic"), exports);
33
40
  __exportStar(require("./postgres-error"), exports);
@@ -40,24 +47,149 @@ const retryableMessages = [
40
47
  'CONNECT_TIMEOUT',
41
48
  'Idle connection closed by Hyperdrive.',
42
49
  'server_login_retry',
50
+ 'Timed out while creating a new server connection.',
43
51
  ];
44
52
  const postgresRetryAttempts = 3;
53
+ /**
54
+ * Parameter types PostgreSQL described per statement signature (PRO-18871).
55
+ * Postgres.js describes a statement in a round trip of its own before it can
56
+ * execute it when a parameter type is unknown, and a Worker request always
57
+ * starts on new connections. The patched driver reads and fills this map
58
+ * through its `statement_types` option and then parses, describes, binds and
59
+ * executes a known statement in one round trip. It forgets a statement's
60
+ * types when the statement fails, so a schema change is described again.
61
+ */
62
+ class StatementTypes extends Map {
63
+ set(signature, types) {
64
+ if (!this.has(signature) && this.size >= 2000) {
65
+ this.delete(this.keys().next().value);
66
+ }
67
+ return super.set(signature, types);
68
+ }
69
+ }
70
+ /** Kept for the isolate's lifetime, one map per Hyperdrive database. */
71
+ const hyperdriveStatementTypes = {
72
+ controlPlane: new StatementTypes(),
73
+ regional: new StatementTypes(),
74
+ };
45
75
  function isRetryableConnectionError(error) {
46
76
  const message = error instanceof Error ? error.message : String(error);
47
77
  return retryableMessages.some((retryable) => message.includes(retryable));
48
78
  }
49
- function retryPostgres(operation, retry) {
50
- return (0, exponential_backoff_1.backOff)(operation, {
51
- numOfAttempts: postgresRetryAttempts,
52
- startingDelay: (0, utils_1.parseDuration)('1s'),
53
- maxDelay: (0, utils_1.parseDuration)('5s'),
54
- retry: (error, attemptNumber) => attemptNumber < postgresRetryAttempts && retry(error, attemptNumber),
55
- });
79
+ function isConnectionReset(error) {
80
+ return (error instanceof Error && 'code' in error && error.code === 'ECONNRESET');
81
+ }
82
+ function isRetryableConnectionAcquisitionError(error) {
83
+ return (isRetryableConnectionError(error) ||
84
+ isConnectionReset(error) ||
85
+ (error instanceof Error &&
86
+ (error.message === 'connection attempt failed' ||
87
+ ('code' in error && error.code === 'CONNECTION_DESTROYED'))));
88
+ }
89
+ function isQueryRetryDiagnosticError(error) {
90
+ const message = error instanceof Error ? error.message : String(error);
91
+ return (isRetryableConnectionError(error) ||
92
+ isConnectionReset(error) ||
93
+ message === 'Egress connection severed outside of Hyperdrive' ||
94
+ message === 'Network connection lost.' ||
95
+ message === 'Node shutting down' ||
96
+ message === 'Node shutting down.' ||
97
+ message === 'shutting down');
98
+ }
99
+ async function retryPostgres(operation, retry, diagnostic) {
100
+ let attemptCount = 0;
101
+ let retried = false;
102
+ let lastError;
103
+ const emitDiagnostic = (outcome) => {
104
+ if (!diagnostic)
105
+ return;
106
+ diagnostic.emit({
107
+ attemptCount,
108
+ dataRegion: diagnostic.dataRegion,
109
+ errorClass: lastError instanceof Error
110
+ ? 'code' in lastError && typeof lastError.code === 'string'
111
+ ? lastError.code
112
+ : lastError.constructor.name
113
+ : 'unknown',
114
+ operationKind: diagnostic.operationKind,
115
+ outcome,
116
+ repositoryName: diagnostic.repositoryName,
117
+ });
118
+ };
119
+ try {
120
+ return await (0, exponential_backoff_1.backOff)(async () => {
121
+ attemptCount++;
122
+ return await operation();
123
+ }, {
124
+ numOfAttempts: postgresRetryAttempts,
125
+ startingDelay: (0, utils_1.parseDuration)('1s'),
126
+ maxDelay: (0, utils_1.parseDuration)('5s'),
127
+ // Scheduled chunk fan-outs open many connections at once; full jitter
128
+ // keeps their retries from reconnecting in lockstep.
129
+ jitter: 'full',
130
+ async retry(error, attemptNumber) {
131
+ lastError = error;
132
+ const shouldRetry = attemptNumber < postgresRetryAttempts &&
133
+ (await retry(error, attemptNumber));
134
+ if (shouldRetry && diagnostic) {
135
+ retried = true;
136
+ emitDiagnostic('retrying');
137
+ }
138
+ return shouldRetry;
139
+ },
140
+ });
141
+ }
142
+ catch (error) {
143
+ lastError = error;
144
+ if (diagnostic?.shouldEmit(error)) {
145
+ emitDiagnostic(retried && attemptCount === postgresRetryAttempts
146
+ ? 'exhausted'
147
+ : 'notRetryable');
148
+ }
149
+ throw error;
150
+ }
151
+ }
152
+ /**
153
+ * Replays a complete database operation after a PostgreSQL deadlock (40P01)
154
+ * or lock timeout (55P03), using the same three-attempt jittered budget as
155
+ * connection retries. The operation must own its transaction and must not
156
+ * contain external side effects such as partner API writes.
157
+ */
158
+ function retryPostgresLockFailure(operation) {
159
+ return retryPostgres(operation, (error) => (0, postgres_error_1.isPostgresError)(error, { code: '40P01' }) ||
160
+ (0, postgres_error_1.isPostgresError)(error, { code: '55P03' }));
56
161
  }
57
162
  class RetryingPostgresJSDialect extends kysely_postgres_js_1.PostgresJSDialect {
58
- constructor(config) {
163
+ constructor(config, retryDiagnostic, closeOnScriptTimeout) {
59
164
  super(config);
60
165
  this.config = config;
166
+ this.retryDiagnostic = retryDiagnostic;
167
+ this.closeOnScriptTimeout = closeOnScriptTimeout;
168
+ }
169
+ /** Ends the run when a script's database operation gets no answer (PRO-19037). */
170
+ async withScriptDeadline(operation) {
171
+ if (!this.closeOnScriptTimeout)
172
+ return await operation();
173
+ let timer;
174
+ try {
175
+ return await Promise.race([
176
+ operation(),
177
+ new Promise((_, reject) => {
178
+ timer = setTimeout(() => {
179
+ console.error('Postgres operation timed out', {
180
+ timeoutMs: scriptQueryTimeoutMs,
181
+ });
182
+ this.closeOnScriptTimeout?.();
183
+ reject(new error_1.KyselyError('Postgres operation timed out', {
184
+ timeoutMs: scriptQueryTimeoutMs,
185
+ }));
186
+ }, scriptQueryTimeoutMs);
187
+ }),
188
+ ]);
189
+ }
190
+ finally {
191
+ clearTimeout(timer);
192
+ }
61
193
  }
62
194
  createDriver() {
63
195
  const driver = new kysely_postgres_js_1.PostgresJSDriver(this.config);
@@ -76,20 +208,37 @@ class RetryingPostgresJSDialect extends kysely_postgres_js_1.PostgresJSDialect {
76
208
  inTransaction: false,
77
209
  };
78
210
  const connection = {
79
- executeQuery: (compiledQuery) => retryPostgres(() => state.connection.executeQuery(compiledQuery), async (error) => {
80
- const message = error instanceof Error ? error.message : String(error);
81
- if (state.inTransaction ||
82
- (!isRetryableConnectionError(error) &&
83
- (compiledQuery.query.kind !== 'SelectQueryNode' ||
84
- (message !==
85
- 'Egress connection severed outside of Hyperdrive' &&
86
- message !== 'Network connection lost.')))) {
87
- return false;
88
- }
89
- // Postgres.js already ejects a severed reserved connection.
90
- // Acquire a new reservation before replaying the safe read.
91
- state.connection = await driver.acquireConnection();
92
- return true;
211
+ executeQuery: (compiledQuery) => this.withScriptDeadline(() => {
212
+ const operationKind = state.inTransaction
213
+ ? 'transaction'
214
+ : compiledQuery.query.kind === 'SelectQueryNode'
215
+ ? 'select'
216
+ : 'mutation';
217
+ return retryPostgres(() => state.connection.executeQuery(compiledQuery), async (error) => {
218
+ const message = error instanceof Error ? error.message : String(error);
219
+ if (state.inTransaction ||
220
+ (!isRetryableConnectionError(error) &&
221
+ (compiledQuery.query.kind !== 'SelectQueryNode' ||
222
+ (!isConnectionReset(error) &&
223
+ message !==
224
+ 'Egress connection severed outside of Hyperdrive' &&
225
+ message !== 'Network connection lost.' &&
226
+ message !== 'Node shutting down' &&
227
+ message !== 'Node shutting down.' &&
228
+ message !== 'shutting down')))) {
229
+ return false;
230
+ }
231
+ // Postgres.js already ejects a severed reserved connection.
232
+ // Acquire a new reservation before replaying the safe read.
233
+ state.connection = await driver.acquireConnection();
234
+ return true;
235
+ }, this.retryDiagnostic
236
+ ? {
237
+ ...this.retryDiagnostic,
238
+ operationKind,
239
+ shouldEmit: isQueryRetryDiagnosticError,
240
+ }
241
+ : undefined);
93
242
  }),
94
243
  streamQuery: (compiledQuery, chunkSize) => {
95
244
  if (chunkSize === undefined) {
@@ -105,7 +254,7 @@ class RetryingPostgresJSDialect extends kysely_postgres_js_1.PostgresJSDialect {
105
254
  const state = getConnection(connection);
106
255
  state.inTransaction = true;
107
256
  try {
108
- await driver.beginTransaction(state.connection, settings);
257
+ await this.withScriptDeadline(() => driver.beginTransaction(state.connection, settings));
109
258
  }
110
259
  catch (error) {
111
260
  state.inTransaction = false;
@@ -115,7 +264,7 @@ class RetryingPostgresJSDialect extends kysely_postgres_js_1.PostgresJSDialect {
115
264
  commitTransaction: async (connection) => {
116
265
  const state = getConnection(connection);
117
266
  try {
118
- await driver.commitTransaction(state.connection);
267
+ await this.withScriptDeadline(() => driver.commitTransaction(state.connection));
119
268
  }
120
269
  finally {
121
270
  state.inTransaction = false;
@@ -124,15 +273,15 @@ class RetryingPostgresJSDialect extends kysely_postgres_js_1.PostgresJSDialect {
124
273
  rollbackTransaction: async (connection) => {
125
274
  const state = getConnection(connection);
126
275
  try {
127
- await driver.rollbackTransaction(state.connection);
276
+ await this.withScriptDeadline(() => driver.rollbackTransaction(state.connection));
128
277
  }
129
278
  finally {
130
279
  state.inTransaction = false;
131
280
  }
132
281
  },
133
- savepoint: (connection, savepointName, compileQuery) => driver.savepoint(getConnection(connection).connection, savepointName, compileQuery),
134
- rollbackToSavepoint: (connection, savepointName, compileQuery) => driver.rollbackToSavepoint(getConnection(connection).connection, savepointName, compileQuery),
135
- releaseSavepoint: (connection, savepointName, compileQuery) => driver.releaseSavepoint(getConnection(connection).connection, savepointName, compileQuery),
282
+ savepoint: (connection, savepointName, compileQuery) => this.withScriptDeadline(() => driver.savepoint(getConnection(connection).connection, savepointName, compileQuery)),
283
+ rollbackToSavepoint: (connection, savepointName, compileQuery) => this.withScriptDeadline(() => driver.rollbackToSavepoint(getConnection(connection).connection, savepointName, compileQuery)),
284
+ releaseSavepoint: (connection, savepointName, compileQuery) => this.withScriptDeadline(() => driver.releaseSavepoint(getConnection(connection).connection, savepointName, compileQuery)),
136
285
  releaseConnection: async (connection) => {
137
286
  await driver.releaseConnection(getConnection(connection).connection);
138
287
  connections.delete(connection);
@@ -143,16 +292,37 @@ class RetryingPostgresJSDialect extends kysely_postgres_js_1.PostgresJSDialect {
143
292
  }
144
293
  function useKysely(postgres, options) {
145
294
  console.debug('Creating Kysely instance');
295
+ const emitRetryDiagnostic = options?.onRetryDiagnostic ??
296
+ (options?.repositoryName
297
+ ? (diagnostic) => console.warn('Postgres operation retry diagnostic', diagnostic)
298
+ : undefined);
146
299
  const reserveConnection = postgres.reserve.bind(postgres);
147
300
  postgres.reserve = async () => {
148
- const connection = await retryPostgres(reserveConnection, isRetryableConnectionError);
301
+ const connection = await retryPostgres(reserveConnection, isRetryableConnectionAcquisitionError, emitRetryDiagnostic
302
+ ? {
303
+ dataRegion: options?.dataRegion,
304
+ emit: emitRetryDiagnostic,
305
+ operationKind: 'acquisition',
306
+ repositoryName: options?.repositoryName,
307
+ shouldEmit: isRetryableConnectionAcquisitionError,
308
+ }
309
+ : undefined);
149
310
  if (options?.hyperdrive) {
150
311
  const unsafe = connection.unsafe;
151
312
  connection.unsafe = (query, parameters, queryOptions) => unsafe(query, parameters, { ...queryOptions, prepare: true });
152
313
  }
153
314
  return connection;
154
315
  };
155
- const kysely = (0, plugins_1.getKysely)(new RetryingPostgresJSDialect({ postgres }), {
316
+ const kysely = (0, plugins_1.getKysely)(new RetryingPostgresJSDialect({ postgres }, emitRetryDiagnostic
317
+ ? {
318
+ dataRegion: options?.dataRegion,
319
+ emit: emitRetryDiagnostic,
320
+ repositoryName: options?.repositoryName,
321
+ shouldEmit: isQueryRetryDiagnosticError,
322
+ }
323
+ : undefined, options?.script
324
+ ? () => void postgres.end({ timeout: 0 }).catch(() => undefined)
325
+ : undefined), {
156
326
  repositoryName: options?.repositoryName,
157
327
  log: options?.log,
158
328
  });
@@ -165,44 +335,77 @@ function useKysely(postgres, options) {
165
335
  };
166
336
  return kysely;
167
337
  }
338
+ const scriptQueryTimeoutMs = (0, utils_1.parseDuration)('1h');
168
339
  let _connections = [];
340
+ function usePostgres(connectionString, opt) {
341
+ const ssl = opt?.forceDisableSSL !== true && !opt?.hyperdrive;
342
+ const sql = (0, postgres_1.default)(connectionString, {
343
+ ssl: ssl ? 'require' : false,
344
+ target_session_attrs: 'read-write',
345
+ // Named prepared statements: PRO-17965 (Hyperdrive and Crunchy PgBouncer).
346
+ prepare: true,
347
+ ...(opt?.hyperdrive
348
+ ? {
349
+ max: 5,
350
+ // Retire idle clients before Hyperdrive can close them asynchronously.
351
+ idle_timeout: 10,
352
+ statement_types: hyperdriveStatementTypes[opt.hyperdrive],
353
+ }
354
+ : {
355
+ connect_timeout: 10,
356
+ idle_timeout: 60,
357
+ ...(opt?.script ? { keep_alive: 10 } : {}),
358
+ }),
359
+ });
360
+ if (opt?.onReserve) {
361
+ const { onReserve } = opt;
362
+ const reserve = sql.reserve.bind(sql);
363
+ // Innermost wrapper: it times each open or reuse of a connection, the
364
+ // startup probe too, and is not part of the retry loop (PRO-18952).
365
+ sql.reserve = async () => {
366
+ const startedAtEpochMs = Date.now();
367
+ const startedAt = performance.now();
368
+ try {
369
+ return await reserve();
370
+ }
371
+ finally {
372
+ onReserve({
373
+ durationMs: performance.now() - startedAt,
374
+ startedAtEpochMs,
375
+ });
376
+ }
377
+ };
378
+ }
379
+ // statement_timeout/lock_timeout are role-level settings on the cluster
380
+ // (ALTER ROLE application SET ...) so they cover every pooled
381
+ // connection; per-session SETs here only ever applied to one of them
382
+ _connections.push(sql);
383
+ return sql;
384
+ }
169
385
  async function useAsyncPostgres(connectionString, opt) {
170
386
  const delayMs = 2500;
171
387
  const probe = opt?.probe === true;
172
388
  const retries = probe ? (opt?.retries === false ? 0 : opt?.retries || 3) : 1;
173
- const ssl = opt?.forceDisableSSL !== true && opt?.hyperdrive !== true;
174
389
  const url = new URL(connectionString);
175
- console.debug(`Creating Postgres connection with probe=${probe}, ${retries} attempts, ssl=${ssl}, and port=${url.port}`);
390
+ console.debug(`Creating Postgres connection with probe=${probe}, ${retries} attempts, ssl=${opt?.forceDisableSSL !== true && !opt?.hyperdrive}, and port=${url.port}`);
176
391
  if (_connections.length > 0)
177
392
  console.warn(`We already have ${_connections.length} Postgres connections`);
178
393
  for (let attempt = 1; attempt <= retries; attempt++) {
394
+ let sql;
179
395
  try {
180
- const sql = (0, postgres_1.default)(connectionString, {
181
- ssl: ssl ? 'require' : false,
182
- target_session_attrs: 'read-write',
183
- // enable prepare statements, pgbouncer on crunchy allows for prepared statements
184
- prepare: true,
185
- ...(opt?.hyperdrive
186
- ? {
187
- max: 5,
188
- // Retire idle clients before Hyperdrive can close them asynchronously.
189
- idle_timeout: 10,
190
- }
191
- : {
192
- connect_timeout: 10,
193
- idle_timeout: 60,
194
- }),
195
- });
396
+ sql = usePostgres(connectionString, opt);
196
397
  if (probe) {
197
- await sql `select 1`;
398
+ // Opening a connection already checks that the session is writable
399
+ // and loads the array types; a probe query would add a round trip.
400
+ (await sql.reserve()).release();
198
401
  }
199
- // statement_timeout/lock_timeout are role-level settings on the cluster
200
- // (ALTER ROLE application SET ...) so they cover every pooled
201
- // connection; per-session SETs here only ever applied to one of them
202
- _connections.push(sql);
203
402
  return sql;
204
403
  }
205
404
  catch (err) {
405
+ if (sql) {
406
+ await sql.end({ timeout: 0 }).catch(() => undefined);
407
+ _connections.splice(_connections.indexOf(sql), 1);
408
+ }
206
409
  if (attempt === retries)
207
410
  throw err;
208
411
  console.warn(`Postgres connection failed (attempt ${attempt}), retrying...`);
@@ -216,9 +419,22 @@ async function useAsyncKysely(connectionString, opt) {
216
419
  const sql = await useAsyncPostgres(connectionString, opt);
217
420
  return useKysely(sql, opt);
218
421
  }
422
+ async function useAsyncNeonWebSocketKysely(connectionString, opt) {
423
+ const pool = new serverless_1.Pool({ connectionString, max: 5 });
424
+ const kysely = (0, plugins_1.getKysely)(new kysely_1.PostgresDialect({ pool }), opt ?? {});
425
+ kysely.destroy = async () => {
426
+ console.debug('Closing Neon WebSocket Kysely connection');
427
+ await pool.end();
428
+ };
429
+ if (opt?.probe)
430
+ await pool.query('select 1');
431
+ return kysely;
432
+ }
433
+ function useControlPlaneKysely(postgres, options) {
434
+ return (0, control_plane_1.withControlPlaneSchema)(useKysely(postgres, options), 'public');
435
+ }
219
436
  async function useAsyncControlPlaneKysely(connectionString, opt) {
220
- const sql = await useAsyncPostgres(connectionString, opt);
221
- return (0, control_plane_1.withControlPlaneSchema)(useKysely(sql, opt), 'public');
437
+ return useControlPlaneKysely(await useAsyncPostgres(connectionString, opt), opt);
222
438
  }
223
439
  async function forceCloseAllPostgres(timeoutMs = 5000) {
224
440
  await Promise.race([
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"src/","sources":["index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;AAqLA,8BA8BC;AAGD,4CAmDC;AAED,wCAMC;AAED,gEAMC;AAED,sDAUC;AArSD,6DAA8C;AAQ9C,2DAI4B;AAC5B,wDAA8C;AAC9C,mDAA8E;AAC9E,mCAAsC;AACtC,uCAAsC;AAGtC,0CAAwB;AACxB,+CAA6B;AAC7B,mDAAiC;AACjC,0CAAwB;AACxB,6CAA2B;AAC3B,gDAA8B;AAE9B,6CAAkD;AAelD,MAAM,iBAAiB,GAAG;IACxB,mBAAmB;IACnB,iBAAiB;IACjB,uCAAuC;IACvC,oBAAoB;CACrB,CAAC;AACF,MAAM,qBAAqB,GAAG,CAAC,CAAC;AAEhC,SAAS,0BAA0B,CAAC,KAAc;IAChD,MAAM,OAAO,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IACvE,OAAO,iBAAiB,CAAC,IAAI,CAAC,CAAC,SAAS,EAAE,EAAE,CAAC,OAAO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BAA0B,CAC9C,gBAAwB,EACxB,GAAwB;IAExB,MAAM,GAAG,GAAG,MAAM,gBAAgB,CAAC,gBAAgB,EAAE,GAAG,CAAC,CAAC;IAC1D,OAAO,IAAA,sCAAsB,EAAC,SAAS,CAAiB,GAAG,EAAE,GAAG,CAAC,EAAE,QAAQ,CAAC,CAAC;AAC/E,CAAC;AAEM,KAAK,UAAU,qBAAqB,CAAC,SAAS,GAAG,IAAI;IAC1D,MAAM,OAAO,CAAC,IAAI,CAAC;QACjB,OAAO,CAAC,GAAG,CACT,YAAY,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,EAAE,CACtB,EAAE,CAAC,GAAG,CAAC,EAAE,OAAO,EAAE,SAAS,GAAG,IAAI,EAAE,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAC7D,CACF;QACD,IAAI,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,UAAU,CAAC,GAAG,EAAE,SAAS,GAAG,IAAI,CAAC,CAAC;KACxD,CAAC,CAAC;IACH,YAAY,GAAG,EAAE,CAAC;AACpB,CAAC","sourcesContent":["import { backOff } from 'exponential-backoff';\nimport type {\n DatabaseConnection,\n Driver,\n Kysely as K,\n LogConfig,\n Transaction as T,\n} from 'kysely';\nimport {\n PostgresJSDialect,\n type PostgresJSDialectConfig,\n PostgresJSDriver,\n} from 'kysely-postgres-js';\nimport postgres, { type Sql } from 'postgres';\nimport { type ControlPlaneDB, withControlPlaneSchema } from './control-plane';\nimport { KyselyError } from './error';\nimport { getKysely } from './plugins';\n\nexport type { Insertable, LogEvent } from 'kysely';\nexport * from './error';\nexport * from './isomorphic';\nexport * from './postgres-error';\nexport * from './query';\nexport * from './regional';\nexport * from './transaction';\n\nimport { parseDuration } from '@vrplatform/utils';\nimport type { DB } from './v1.generated';\n\ntype KyselyOpts = {\n hyperdrive?: true;\n repositoryName?: string;\n log?: true | LogConfig;\n};\n\ntype PgOpt = {\n forceDisableSSL?: boolean;\n probe?: true;\n retries?: false | number;\n} & Pick<KyselyOpts, 'hyperdrive'>;\n\nconst retryableMessages = [\n 'CONNECTION_CLOSED',\n 'CONNECT_TIMEOUT',\n 'Idle connection closed by Hyperdrive.',\n 'server_login_retry',\n];\nconst postgresRetryAttempts = 3;\n\nfunction isRetryableConnectionError(error: unknown) {\n const message = error instanceof Error ? error.message : String(error);\n return retryableMessages.some((retryable) => message.includes(retryable));\n}\n\nfunction retryPostgres<T>(\n operation: () => Promise<T>,\n retry: (error: unknown, attemptNumber: number) => boolean | Promise<boolean>\n) {\n return backOff(operation, {\n numOfAttempts: postgresRetryAttempts,\n startingDelay: parseDuration('1s'),\n maxDelay: parseDuration('5s'),\n retry: (error, attemptNumber) =>\n attemptNumber < postgresRetryAttempts && retry(error, attemptNumber),\n });\n}\n\nclass RetryingPostgresJSDialect extends PostgresJSDialect {\n constructor(private readonly config: PostgresJSDialectConfig) {\n super(config);\n }\n\n override createDriver(): Driver {\n const driver = new PostgresJSDriver(this.config);\n const connections = new WeakMap<\n DatabaseConnection,\n { connection: DatabaseConnection; inTransaction: boolean }\n >();\n const getConnection = (connection: DatabaseConnection) => {\n const state = connections.get(connection);\n if (!state) throw new Error('Postgres connection state is unavailable');\n return state;\n };\n\n return {\n init: () => driver.init(),\n acquireConnection: async () => {\n const state = {\n connection: await driver.acquireConnection(),\n inTransaction: false,\n };\n const connection: DatabaseConnection = {\n executeQuery: (compiledQuery) =>\n retryPostgres(\n () => state.connection.executeQuery(compiledQuery),\n async (error) => {\n const message =\n error instanceof Error ? error.message : String(error);\n if (\n state.inTransaction ||\n (!isRetryableConnectionError(error) &&\n (compiledQuery.query.kind !== 'SelectQueryNode' ||\n (message !==\n 'Egress connection severed outside of Hyperdrive' &&\n message !== 'Network connection lost.')))\n ) {\n return false;\n }\n\n // Postgres.js already ejects a severed reserved connection.\n // Acquire a new reservation before replaying the safe read.\n state.connection = await driver.acquireConnection();\n return true;\n }\n ),\n streamQuery: (compiledQuery, chunkSize) => {\n if (chunkSize === undefined) {\n throw new Error('Postgres stream chunk size is required');\n }\n return state.connection.streamQuery(compiledQuery, chunkSize);\n },\n };\n connections.set(connection, state);\n return connection;\n },\n beginTransaction: async (connection, settings) => {\n const state = getConnection(connection);\n state.inTransaction = true;\n try {\n await driver.beginTransaction(state.connection, settings);\n } catch (error) {\n state.inTransaction = false;\n throw error;\n }\n },\n commitTransaction: async (connection) => {\n const state = getConnection(connection);\n try {\n await driver.commitTransaction(state.connection);\n } finally {\n state.inTransaction = false;\n }\n },\n rollbackTransaction: async (connection) => {\n const state = getConnection(connection);\n try {\n await driver.rollbackTransaction(state.connection);\n } finally {\n state.inTransaction = false;\n }\n },\n savepoint: (connection, savepointName, compileQuery) =>\n driver.savepoint(\n getConnection(connection).connection,\n savepointName,\n compileQuery\n ),\n rollbackToSavepoint: (connection, savepointName, compileQuery) =>\n driver.rollbackToSavepoint(\n getConnection(connection).connection,\n savepointName,\n compileQuery\n ),\n releaseSavepoint: (connection, savepointName, compileQuery) =>\n driver.releaseSavepoint(\n getConnection(connection).connection,\n savepointName,\n compileQuery\n ),\n releaseConnection: async (connection) => {\n await driver.releaseConnection(getConnection(connection).connection);\n connections.delete(connection);\n },\n destroy: () => driver.destroy(),\n };\n }\n}\n\nexport type Kysely = K<DB>;\nexport type ControlPlaneKysely = K<ControlPlaneDB>;\nexport type ControlPlaneTransaction = T<ControlPlaneDB>;\nexport function useKysely<Database = DB>(postgres: Sql, options?: KyselyOpts) {\n console.debug('Creating Kysely instance');\n const reserveConnection = postgres.reserve.bind(postgres);\n postgres.reserve = async () => {\n const connection = await retryPostgres(\n reserveConnection,\n isRetryableConnectionError\n );\n if (options?.hyperdrive) {\n const unsafe = connection.unsafe;\n connection.unsafe = (query, parameters, queryOptions) =>\n unsafe(query, parameters, { ...queryOptions, prepare: true });\n }\n return connection;\n };\n const kysely = getKysely<Database>(\n new RetryingPostgresJSDialect({ postgres }),\n {\n repositoryName: options?.repositoryName,\n log: options?.log,\n }\n );\n kysely.destroy = async () => {\n console.debug('Closing Kysely connection');\n await postgres.end({ timeout: 5 }).catch(() => undefined);\n const index = _connections.indexOf(postgres);\n if (index !== -1) _connections.splice(index, 1);\n };\n\n return kysely;\n}\n\nlet _connections: postgres.Sql[] = [];\nexport async function useAsyncPostgres(connectionString: string, opt?: PgOpt) {\n const delayMs = 2500;\n const probe = opt?.probe === true;\n const retries = probe ? (opt?.retries === false ? 0 : opt?.retries || 3) : 1;\n const ssl = opt?.forceDisableSSL !== true && opt?.hyperdrive !== true;\n const url = new URL(connectionString);\n\n console.debug(\n `Creating Postgres connection with probe=${probe}, ${retries} attempts, ssl=${ssl}, and port=${url.port}`\n );\n if (_connections.length > 0)\n console.warn(`We already have ${_connections.length} Postgres connections`);\n\n for (let attempt = 1; attempt <= retries; attempt++) {\n try {\n const sql = postgres(connectionString, {\n ssl: ssl ? 'require' : false,\n target_session_attrs: 'read-write',\n // enable prepare statements, pgbouncer on crunchy allows for prepared statements\n prepare: true,\n ...(opt?.hyperdrive\n ? {\n max: 5,\n // Retire idle clients before Hyperdrive can close them asynchronously.\n idle_timeout: 10,\n }\n : {\n connect_timeout: 10,\n idle_timeout: 60,\n }),\n });\n\n if (probe) {\n await sql`select 1`;\n }\n // statement_timeout/lock_timeout are role-level settings on the cluster\n // (ALTER ROLE application SET ...) so they cover every pooled\n // connection; per-session SETs here only ever applied to one of them\n\n _connections.push(sql);\n return sql;\n } catch (err) {\n if (attempt === retries) throw err;\n console.warn(\n `Postgres connection failed (attempt ${attempt}), retrying...`\n );\n console.error('error', err);\n await new Promise((res) => setTimeout(res, delayMs));\n }\n }\n throw new KyselyError('Unable to connect to Postgres');\n}\n\nexport async function useAsyncKysely(\n connectionString: string,\n opt?: PgOpt & KyselyOpts\n) {\n const sql = await useAsyncPostgres(connectionString, opt);\n return useKysely(sql, opt);\n}\n\nexport async function useAsyncControlPlaneKysely(\n connectionString: string,\n opt?: PgOpt & KyselyOpts\n) {\n const sql = await useAsyncPostgres(connectionString, opt);\n return withControlPlaneSchema(useKysely<ControlPlaneDB>(sql, opt), 'public');\n}\n\nexport async function forceCloseAllPostgres(timeoutMs = 5000) {\n await Promise.race([\n Promise.all(\n _connections.map((pg) =>\n pg.end({ timeout: timeoutMs / 1000 }).catch(() => undefined)\n )\n ),\n new Promise((res) => setTimeout(res, timeoutMs + 1000)),\n ]);\n _connections = [];\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"src/","sources":["index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;AAsNA,4DAOC;AAsLD,8BA0DC;AAID,kCA8CC;AAED,4CAoCC;AAED,wCAMC;AAED,kEAYC;AAED,sDAKC;AAED,gEAQC;AAED,sDAUC;AAxlBD,6DAA8C;AAC9C,yDAAgD;AAQhD,mCAAyC;AACzC,2DAI4B;AAC5B,wDAA8C;AAC9C,mDAA8E;AAC9E,mCAAsC;AACtC,uCAAsC;AACtC,qDAAmD;AAGnD,0CAAwB;AACxB,+CAA6B;AAC7B,mDAAiC;AACjC,0CAAwB;AACxB,6CAA2B;AAC3B,gDAA8B;AAE9B,6CAAkD;AA2ClD,MAAM,iBAAiB,GAAG;IACxB,mBAAmB;IACnB,iBAAiB;IACjB,uCAAuC;IACvC,oBAAoB;IACpB,mDAAmD;CACpD,CAAC;AACF,MAAM,qBAAqB,GAAG,CAAC,CAAC;AAEhC;;;;;;;;GAQG;AACH,MAAM,cAAe,SAAQ,GAAqB;IACvC,GAAG,CAAC,SAAiB,EAAE,KAAe;QAC7C,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,SAAS,CAAC,IAAI,IAAI,CAAC,IAAI,IAAI,IAAI,EAAE,CAAC;YAC9C,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC,IAAI,EAAE,CAAC,KAAM,CAAC,CAAC;QACzC,CAAC;QACD,OAAO,KAAK,CAAC,GAAG,CAAC,SAAS,EAAE,KAAK,CAAC,CAAC;IACrC,CAAC;CACF;AAED,wEAAwE;AAC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B,CAAC,gBAAgB,EAAE,GAAG,CAAC,EAC7C,GAAG,CACJ,CAAC;AACJ,CAAC;AAEM,KAAK,UAAU,qBAAqB,CAAC,SAAS,GAAG,IAAI;IAC1D,MAAM,OAAO,CAAC,IAAI,CAAC;QACjB,OAAO,CAAC,GAAG,CACT,YAAY,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,EAAE,CACtB,EAAE,CAAC,GAAG,CAAC,EAAE,OAAO,EAAE,SAAS,GAAG,IAAI,EAAE,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAC7D,CACF;QACD,IAAI,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,UAAU,CAAC,GAAG,EAAE,SAAS,GAAG,IAAI,CAAC,CAAC;KACxD,CAAC,CAAC;IACH,YAAY,GAAG,EAAE,CAAC;AACpB,CAAC","sourcesContent":["import { backOff } from 'exponential-backoff';\nimport { Pool } from '@neondatabase/serverless';\nimport type {\n DatabaseConnection,\n Driver,\n Kysely as K,\n LogConfig,\n Transaction as T,\n} from 'kysely';\nimport { PostgresDialect } from 'kysely';\nimport {\n PostgresJSDialect,\n type PostgresJSDialectConfig,\n PostgresJSDriver,\n} from 'kysely-postgres-js';\nimport postgres, { type Sql } from 'postgres';\nimport { type ControlPlaneDB, withControlPlaneSchema } from './control-plane';\nimport { KyselyError } from './error';\nimport { getKysely } from './plugins';\nimport { isPostgresError } from './postgres-error';\n\nexport type { Insertable, LogEvent } from 'kysely';\nexport * from './error';\nexport * from './isomorphic';\nexport * from './postgres-error';\nexport * from './query';\nexport * from './regional';\nexport * from './transaction';\n\nimport { parseDuration } from '@vrplatform/utils';\nimport type { TenantDataRegion } from './regional';\nimport type { DB } from './v1.generated';\n\n/** The database a Worker reaches through its Hyperdrive binding. */\ntype HyperdriveDatabase = 'controlPlane' | 'regional';\n\ntype KyselyOpts = {\n dataRegion?: TenantDataRegion;\n hyperdrive?: HyperdriveDatabase;\n /** Called after every connection reservation, including the startup probe. */\n onReserve?: (timing: {\n durationMs: number;\n startedAtEpochMs: number;\n }) => void;\n onRetryDiagnostic?: (diagnostic: PostgresRetryDiagnostic) => void;\n repositoryName?: string;\n log?: true | LogConfig;\n /**\n * Scripts and repairs (PRO-19037). Probes an idle TCP connection after 10 s.\n * A query, commit, begin, rollback or savepoint with no answer for an hour,\n * longer than any statement timeout a script sets, fails the run and closes\n * the Postgres client that issued it. Backstop for a connection the kernel\n * keeps open while the peer never answers.\n */\n script?: true;\n};\n\ntype PostgresRetryDiagnostic = {\n attemptCount: number;\n dataRegion?: TenantDataRegion;\n errorClass: string;\n operationKind: 'acquisition' | 'mutation' | 'select' | 'transaction';\n outcome: 'exhausted' | 'notRetryable' | 'retrying';\n repositoryName?: string;\n};\n\ntype PgOpt = {\n forceDisableSSL?: boolean;\n probe?: true;\n retries?: false | number;\n} & Pick<KyselyOpts, 'hyperdrive' | 'onReserve' | 'script'>;\n\nconst retryableMessages = [\n 'CONNECTION_CLOSED',\n 'CONNECT_TIMEOUT',\n 'Idle connection closed by Hyperdrive.',\n 'server_login_retry',\n 'Timed out while creating a new server connection.',\n];\nconst postgresRetryAttempts = 3;\n\n/**\n * Parameter types PostgreSQL described per statement signature (PRO-18871).\n * Postgres.js describes a statement in a round trip of its own before it can\n * execute it when a parameter type is unknown, and a Worker request always\n * starts on new connections. The patched driver reads and fills this map\n * through its `statement_types` option and then parses, describes, binds and\n * executes a known statement in one round trip. It forgets a statement's\n * types when the statement fails, so a schema change is described again.\n */\nclass StatementTypes extends Map<string, number[]> {\n override set(signature: string, types: number[]) {\n if (!this.has(signature) && this.size >= 2000) {\n this.delete(this.keys().next().value!);\n }\n return super.set(signature, types);\n }\n}\n\n/** Kept for the isolate's lifetime, one map per Hyperdrive database. */\nconst hyperdriveStatementTypes: Record<HyperdriveDatabase, StatementTypes> = {\n controlPlane: new StatementTypes(),\n regional: new StatementTypes(),\n};\n\nfunction isRetryableConnectionError(error: unknown) {\n const message = error instanceof Error ? error.message : String(error);\n return retryableMessages.some((retryable) => message.includes(retryable));\n}\n\nfunction isConnectionReset(error: unknown) {\n return (\n error instanceof Error && 'code' in error && error.code === 'ECONNRESET'\n );\n}\n\nfunction isRetryableConnectionAcquisitionError(error: unknown) {\n return (\n isRetryableConnectionError(error) ||\n isConnectionReset(error) ||\n (error instanceof Error &&\n (error.message === 'connection attempt failed' ||\n ('code' in error && error.code === 'CONNECTION_DESTROYED')))\n );\n}\n\nfunction isQueryRetryDiagnosticError(error: unknown) {\n const message = error instanceof Error ? error.message : String(error);\n return (\n isRetryableConnectionError(error) ||\n isConnectionReset(error) ||\n message === 'Egress connection severed outside of Hyperdrive' ||\n message === 'Network connection lost.' ||\n message === 'Node shutting down' ||\n message === 'Node shutting down.' ||\n message === 'shutting down'\n );\n}\n\nasync function retryPostgres<T>(\n operation: () => Promise<T>,\n retry: (error: unknown, attemptNumber: number) => boolean | Promise<boolean>,\n diagnostic?: Omit<\n PostgresRetryDiagnostic,\n 'attemptCount' | 'errorClass' | 'outcome'\n > & {\n emit: (diagnostic: PostgresRetryDiagnostic) => void;\n shouldEmit: (error: unknown) => boolean;\n }\n) {\n let attemptCount = 0;\n let retried = false;\n let lastError: unknown;\n const emitDiagnostic = (outcome: PostgresRetryDiagnostic['outcome']) => {\n if (!diagnostic) return;\n diagnostic.emit({\n attemptCount,\n dataRegion: diagnostic.dataRegion,\n errorClass:\n lastError instanceof Error\n ? 'code' in lastError && typeof lastError.code === 'string'\n ? lastError.code\n : lastError.constructor.name\n : 'unknown',\n operationKind: diagnostic.operationKind,\n outcome,\n repositoryName: diagnostic.repositoryName,\n });\n };\n try {\n return await backOff(\n async () => {\n attemptCount++;\n return await operation();\n },\n {\n numOfAttempts: postgresRetryAttempts,\n startingDelay: parseDuration('1s'),\n maxDelay: parseDuration('5s'),\n // Scheduled chunk fan-outs open many connections at once; full jitter\n // keeps their retries from reconnecting in lockstep.\n jitter: 'full',\n async retry(error, attemptNumber) {\n lastError = error;\n const shouldRetry =\n attemptNumber < postgresRetryAttempts &&\n (await retry(error, attemptNumber));\n if (shouldRetry && diagnostic) {\n retried = true;\n emitDiagnostic('retrying');\n }\n return shouldRetry;\n },\n }\n );\n } catch (error) {\n lastError = error;\n if (diagnostic?.shouldEmit(error)) {\n emitDiagnostic(\n retried && attemptCount === postgresRetryAttempts\n ? 'exhausted'\n : 'notRetryable'\n );\n }\n throw error;\n }\n}\n\n/**\n * Replays a complete database operation after a PostgreSQL deadlock (40P01)\n * or lock timeout (55P03), using the same three-attempt jittered budget as\n * connection retries. The operation must own its transaction and must not\n * contain external side effects such as partner API writes.\n */\nexport function retryPostgresLockFailure<T>(operation: () => Promise<T>) {\n return retryPostgres(\n operation,\n (error) =>\n isPostgresError(error, { code: '40P01' }) ||\n isPostgresError(error, { code: '55P03' })\n );\n}\n\nclass RetryingPostgresJSDialect extends PostgresJSDialect {\n constructor(\n private readonly config: PostgresJSDialectConfig,\n private readonly retryDiagnostic?: Omit<\n PostgresRetryDiagnostic,\n 'attemptCount' | 'errorClass' | 'operationKind' | 'outcome'\n > & {\n emit: (diagnostic: PostgresRetryDiagnostic) => void;\n shouldEmit: (error: unknown) => boolean;\n },\n private readonly closeOnScriptTimeout?: () => void\n ) {\n super(config);\n }\n\n /** Ends the run when a script's database operation gets no answer (PRO-19037). */\n private async withScriptDeadline<T>(operation: () => Promise<T>) {\n if (!this.closeOnScriptTimeout) return await operation();\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n operation(),\n new Promise<never>((_, reject) => {\n timer = setTimeout(() => {\n console.error('Postgres operation timed out', {\n timeoutMs: scriptQueryTimeoutMs,\n });\n this.closeOnScriptTimeout?.();\n reject(\n new KyselyError('Postgres operation timed out', {\n timeoutMs: scriptQueryTimeoutMs,\n })\n );\n }, scriptQueryTimeoutMs);\n }),\n ]);\n } finally {\n clearTimeout(timer);\n }\n }\n\n override createDriver(): Driver {\n const driver = new PostgresJSDriver(this.config);\n const connections = new WeakMap<\n DatabaseConnection,\n { connection: DatabaseConnection; inTransaction: boolean }\n >();\n const getConnection = (connection: DatabaseConnection) => {\n const state = connections.get(connection);\n if (!state) throw new Error('Postgres connection state is unavailable');\n return state;\n };\n\n return {\n init: () => driver.init(),\n acquireConnection: async () => {\n const state = {\n connection: await driver.acquireConnection(),\n inTransaction: false,\n };\n const connection: DatabaseConnection = {\n executeQuery: (compiledQuery) =>\n this.withScriptDeadline(() => {\n const operationKind = state.inTransaction\n ? 'transaction'\n : compiledQuery.query.kind === 'SelectQueryNode'\n ? 'select'\n : 'mutation';\n return retryPostgres(\n () => state.connection.executeQuery(compiledQuery),\n async (error) => {\n const message =\n error instanceof Error ? error.message : String(error);\n if (\n state.inTransaction ||\n (!isRetryableConnectionError(error) &&\n (compiledQuery.query.kind !== 'SelectQueryNode' ||\n (!isConnectionReset(error) &&\n message !==\n 'Egress connection severed outside of Hyperdrive' &&\n message !== 'Network connection lost.' &&\n message !== 'Node shutting down' &&\n message !== 'Node shutting down.' &&\n message !== 'shutting down')))\n ) {\n return false;\n }\n\n // Postgres.js already ejects a severed reserved connection.\n // Acquire a new reservation before replaying the safe read.\n state.connection = await driver.acquireConnection();\n return true;\n },\n this.retryDiagnostic\n ? {\n ...this.retryDiagnostic,\n operationKind,\n shouldEmit: isQueryRetryDiagnosticError,\n }\n : undefined\n );\n }),\n streamQuery: (compiledQuery, chunkSize) => {\n if (chunkSize === undefined) {\n throw new Error('Postgres stream chunk size is required');\n }\n return state.connection.streamQuery(compiledQuery, chunkSize);\n },\n };\n connections.set(connection, state);\n return connection;\n },\n beginTransaction: async (connection, settings) => {\n const state = getConnection(connection);\n state.inTransaction = true;\n try {\n await this.withScriptDeadline(() =>\n driver.beginTransaction(state.connection, settings)\n );\n } catch (error) {\n state.inTransaction = false;\n throw error;\n }\n },\n commitTransaction: async (connection) => {\n const state = getConnection(connection);\n try {\n await this.withScriptDeadline(() =>\n driver.commitTransaction(state.connection)\n );\n } finally {\n state.inTransaction = false;\n }\n },\n rollbackTransaction: async (connection) => {\n const state = getConnection(connection);\n try {\n await this.withScriptDeadline(() =>\n driver.rollbackTransaction(state.connection)\n );\n } finally {\n state.inTransaction = false;\n }\n },\n savepoint: (connection, savepointName, compileQuery) =>\n this.withScriptDeadline(() =>\n driver.savepoint(\n getConnection(connection).connection,\n savepointName,\n compileQuery\n )\n ),\n rollbackToSavepoint: (connection, savepointName, compileQuery) =>\n this.withScriptDeadline(() =>\n driver.rollbackToSavepoint(\n getConnection(connection).connection,\n savepointName,\n compileQuery\n )\n ),\n releaseSavepoint: (connection, savepointName, compileQuery) =>\n this.withScriptDeadline(() =>\n driver.releaseSavepoint(\n getConnection(connection).connection,\n savepointName,\n compileQuery\n )\n ),\n releaseConnection: async (connection) => {\n await driver.releaseConnection(getConnection(connection).connection);\n connections.delete(connection);\n },\n destroy: () => driver.destroy(),\n };\n }\n}\n\nexport type Kysely = K<DB>;\nexport type ControlPlaneKysely = K<ControlPlaneDB>;\nexport type ControlPlaneTransaction = T<ControlPlaneDB>;\nexport function useKysely<Database = DB>(postgres: Sql, options?: KyselyOpts) {\n console.debug('Creating Kysely instance');\n const emitRetryDiagnostic =\n options?.onRetryDiagnostic ??\n (options?.repositoryName\n ? (diagnostic: PostgresRetryDiagnostic) =>\n console.warn('Postgres operation retry diagnostic', diagnostic)\n : undefined);\n const reserveConnection = postgres.reserve.bind(postgres);\n postgres.reserve = async () => {\n const connection = await retryPostgres(\n reserveConnection,\n isRetryableConnectionAcquisitionError,\n emitRetryDiagnostic\n ? {\n dataRegion: options?.dataRegion,\n emit: emitRetryDiagnostic,\n operationKind: 'acquisition',\n repositoryName: options?.repositoryName,\n shouldEmit: isRetryableConnectionAcquisitionError,\n }\n : undefined\n );\n if (options?.hyperdrive) {\n const unsafe = connection.unsafe;\n connection.unsafe = (query, parameters, queryOptions) =>\n unsafe(query, parameters, { ...queryOptions, prepare: true });\n }\n return connection;\n };\n const kysely = getKysely<Database>(\n new RetryingPostgresJSDialect(\n { postgres },\n emitRetryDiagnostic\n ? {\n dataRegion: options?.dataRegion,\n emit: emitRetryDiagnostic,\n repositoryName: options?.repositoryName,\n shouldEmit: isQueryRetryDiagnosticError,\n }\n : undefined,\n options?.script\n ? () => void postgres.end({ timeout: 0 }).catch(() => undefined)\n : undefined\n ),\n {\n repositoryName: options?.repositoryName,\n log: options?.log,\n }\n );\n kysely.destroy = async () => {\n console.debug('Closing Kysely connection');\n await postgres.end({ timeout: 5 }).catch(() => undefined);\n const index = _connections.indexOf(postgres);\n if (index !== -1) _connections.splice(index, 1);\n };\n\n return kysely;\n}\n\nconst scriptQueryTimeoutMs = parseDuration('1h');\nlet _connections: postgres.Sql[] = [];\nexport function usePostgres(\n connectionString: string,\n opt?: Pick<PgOpt, 'forceDisableSSL' | 'hyperdrive' | 'onReserve' | 'script'>\n) {\n const ssl = opt?.forceDisableSSL !== true && !opt?.hyperdrive;\n const sql = postgres(connectionString, {\n ssl: ssl ? 'require' : false,\n target_session_attrs: 'read-write',\n // Named prepared statements: PRO-17965 (Hyperdrive and Crunchy PgBouncer).\n prepare: true,\n ...(opt?.hyperdrive\n ? {\n max: 5,\n // Retire idle clients before Hyperdrive can close them asynchronously.\n idle_timeout: 10,\n statement_types: hyperdriveStatementTypes[opt.hyperdrive],\n }\n : {\n connect_timeout: 10,\n idle_timeout: 60,\n ...(opt?.script ? { keep_alive: 10 } : {}),\n }),\n });\n if (opt?.onReserve) {\n const { onReserve } = opt;\n const reserve = sql.reserve.bind(sql);\n // Innermost wrapper: it times each open or reuse of a connection, the\n // startup probe too, and is not part of the retry loop (PRO-18952).\n sql.reserve = async () => {\n const startedAtEpochMs = Date.now();\n const startedAt = performance.now();\n try {\n return await reserve();\n } finally {\n onReserve({\n durationMs: performance.now() - startedAt,\n startedAtEpochMs,\n });\n }\n };\n }\n // statement_timeout/lock_timeout are role-level settings on the cluster\n // (ALTER ROLE application SET ...) so they cover every pooled\n // connection; per-session SETs here only ever applied to one of them\n _connections.push(sql);\n return sql;\n}\n\nexport async function useAsyncPostgres(connectionString: string, opt?: PgOpt) {\n const delayMs = 2500;\n const probe = opt?.probe === true;\n const retries = probe ? (opt?.retries === false ? 0 : opt?.retries || 3) : 1;\n const url = new URL(connectionString);\n\n console.debug(\n `Creating Postgres connection with probe=${probe}, ${retries} attempts, ssl=${opt?.forceDisableSSL !== true && !opt?.hyperdrive}, and port=${url.port}`\n );\n if (_connections.length > 0)\n console.warn(`We already have ${_connections.length} Postgres connections`);\n\n for (let attempt = 1; attempt <= retries; attempt++) {\n let sql: Sql | undefined;\n try {\n sql = usePostgres(connectionString, opt);\n if (probe) {\n // Opening a connection already checks that the session is writable\n // and loads the array types; a probe query would add a round trip.\n (await sql.reserve()).release();\n }\n return sql;\n } catch (err) {\n if (sql) {\n await sql.end({ timeout: 0 }).catch(() => undefined);\n _connections.splice(_connections.indexOf(sql), 1);\n }\n if (attempt === retries) throw err;\n console.warn(\n `Postgres connection failed (attempt ${attempt}), retrying...`\n );\n console.error('error', err);\n await new Promise((res) => setTimeout(res, delayMs));\n }\n }\n throw new KyselyError('Unable to connect to Postgres');\n}\n\nexport async function useAsyncKysely(\n connectionString: string,\n opt?: PgOpt & KyselyOpts\n) {\n const sql = await useAsyncPostgres(connectionString, opt);\n return useKysely(sql, opt);\n}\n\nexport async function useAsyncNeonWebSocketKysely(\n connectionString: string,\n opt?: Pick<PgOpt, 'probe'> & KyselyOpts\n) {\n const pool = new Pool({ connectionString, max: 5 });\n const kysely = getKysely<DB>(new PostgresDialect({ pool }), opt ?? {});\n kysely.destroy = async () => {\n console.debug('Closing Neon WebSocket Kysely connection');\n await pool.end();\n };\n if (opt?.probe) await pool.query('select 1');\n return kysely;\n}\n\nexport function useControlPlaneKysely(postgres: Sql, options?: KyselyOpts) {\n return withControlPlaneSchema(\n useKysely<ControlPlaneDB>(postgres, options),\n 'public'\n );\n}\n\nexport async function useAsyncControlPlaneKysely(\n connectionString: string,\n opt?: PgOpt & KyselyOpts\n) {\n return useControlPlaneKysely(\n await useAsyncPostgres(connectionString, opt),\n opt\n );\n}\n\nexport async function forceCloseAllPostgres(timeoutMs = 5000) {\n await Promise.race([\n Promise.all(\n _connections.map((pg) =>\n pg.end({ timeout: timeoutMs / 1000 }).catch(() => undefined)\n )\n ),\n new Promise((res) => setTimeout(res, timeoutMs + 1000)),\n ]);\n _connections = [];\n}\n"]}