@vrplatform/kysely 1.3.45-391 → 1.3.45-39120281816

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 (115) hide show
  1. package/build/.data.tar +2 -2
  2. package/build/main/camel-case/index.d.ts +4 -4
  3. package/build/main/camel-case/index.js +2 -1
  4. package/build/main/camel-case/index.js.map +1 -1
  5. package/build/main/connect-handoff.d.ts +12 -0
  6. package/build/main/connect-handoff.js +73 -0
  7. package/build/main/connect-handoff.js.map +1 -0
  8. package/build/main/control-plane/index.d.ts +19 -1
  9. package/build/main/control-plane/index.js +10 -0
  10. package/build/main/control-plane/index.js.map +1 -1
  11. package/build/main/index.d.ts +38 -2
  12. package/build/main/index.js +323 -58
  13. package/build/main/index.js.map +1 -1
  14. package/build/main/isomorphic.d.ts +1 -1
  15. package/build/main/isomorphic.js +2 -1
  16. package/build/main/isomorphic.js.map +1 -1
  17. package/build/main/local/generate.js +4 -3
  18. package/build/main/local/generate.js.map +1 -1
  19. package/build/main/local/index.js +3 -0
  20. package/build/main/local/index.js.map +1 -1
  21. package/build/main/migration-source.d.ts +4 -0
  22. package/build/main/migration-source.js +45 -0
  23. package/build/main/migration-source.js.map +1 -0
  24. package/build/main/pganalyze-comment-plugin/comment-transformer.js +3 -1
  25. package/build/main/pganalyze-comment-plugin/comment-transformer.js.map +1 -1
  26. package/build/main/query/listing/status.js +6 -2
  27. package/build/main/query/listing/status.js.map +1 -1
  28. package/build/main/query/tenant/status.d.ts +1 -6
  29. package/build/main/query/tenant/status.js +4 -12
  30. package/build/main/query/tenant/status.js.map +1 -1
  31. package/build/main/regional.d.ts +1 -0
  32. package/build/main/regional.js +1 -0
  33. package/build/main/regional.js.map +1 -1
  34. package/build/main/test/index.js +4 -3
  35. package/build/main/test/index.js.map +1 -1
  36. package/build/main/v1.generated.d.ts +255 -19
  37. package/build/main/v1.generated.js.map +1 -1
  38. package/build/migrations-v2/0000000000033-plaid-connect-session-telemetry.ts +31 -0
  39. package/build/migrations-v2/0000000000049-queued-journal-operation-failures.ts +60 -0
  40. package/build/migrations-v2/0000000000050-connection-oauth-state.ts +43 -0
  41. package/build/migrations-v2/0000000000051-owner-statement-email-delivery.ts +134 -0
  42. package/build/migrations-v2/0000000000052-fee-journal-lock-skip-operations.ts +59 -0
  43. package/build/migrations-v2/0000000000053-fee-journal-lock-skip-null-attempt.ts +44 -0
  44. package/build/migrations-v2/0000000000054-journal-refresh-issue-codes.ts +16 -0
  45. package/build/migrations-v2/0000000000055-tenant-billing-subscription.ts +8 -0
  46. package/build/migrations-v2/0000000000056-journal-operation-failure-precedence.ts +306 -0
  47. package/build/migrations-v2/0000000000057-journal-invalidation-failure-code.ts +28 -0
  48. package/build/migrations-v2/0000000000058-journal-invalidation-locked-failure.ts +16 -0
  49. package/build/migrations-v2/0000000000059-billing-active-listing-cross-region-partner.ts +135 -0
  50. package/build/migrations-v2/0000000000060-accounting-integrity-change-driven.ts +99 -0
  51. package/build/migrations-v2/0000000000061-tenant-pending-onboarding-status.ts +37 -0
  52. package/build/migrations-v2/0000000000062-statement-payout-operations.ts +16 -0
  53. package/build/migrations-v2/0000000000063-missing-account-assignments-issue-code.ts +13 -0
  54. package/build/migrations-v2/0000000000064-journal-invalidation-source-lookup-index.ts +26 -0
  55. package/build/migrations-v2/0000000000065-hasura-connection-event-credentials.ts +42 -0
  56. package/build/migrations-v2/0000000000066-recurring-fee-listing-subscription-match-by.ts +51 -0
  57. package/build/migrations-v2/0000000000067-connection-credential-metadata.ts +60 -0
  58. package/build/migrations-v2/0000000000068-connection-credential-version.ts +34 -0
  59. package/build/migrations-v2/0000000000069-owner-statement-contact-email-delivery.ts +84 -0
  60. package/build/migrations-v2/0000000000070-payment-writer-compatibility.ts +69 -0
  61. package/build/migrations-v2/0000000000071-payments.ts +532 -0
  62. package/build/migrations-v2/0000000000072-journal-entry-payment-index.ts +21 -0
  63. package/build/migrations-v2/0000000000073-batch-invalidation-operation-registration.ts +74 -0
  64. package/build/migrations-v2/0000000000074-owner-statement-email-history.ts +34 -0
  65. package/build/migrations-v2/0000000000075-tenant-deletion-lookup-indexes.ts +46 -0
  66. package/build/migrations-v2/0000000000076-tenant-onboarding-not-null.ts +23 -0
  67. package/build/migrations-v2/0000000000077-payment-writer-statement-attachment.ts +92 -0
  68. package/build/migrations-v2/0000000000078-trigger-timeout-indexes.ts +44 -0
  69. package/build/migrations-v2/0000000000079-core-change-tenant-statistics.ts +26 -0
  70. package/build/migrations-v2/0000000000080-drop-legacy-tracking-event.ts +60 -0
  71. package/build/migrations-v2/0000000000081-recurring-fee-planner-operation-status.ts +35 -0
  72. package/build/migrations-v2/0000000000082-reservation-search-trigram-indexes.ts +54 -0
  73. package/build/migrations-v2/0000000000083-journal-entry-deposit-lookup-index.ts +31 -0
  74. package/build/migrations-v2/0000000000084-journal-entry-reservation-revenue-indexes.ts +39 -0
  75. package/build/migrations-v2/0000000000085-owner-statement-link-email-template.ts +23 -0
  76. package/build/migrations-v2/0000000000086-contact-payment-setup.ts +72 -0
  77. package/build/migrations-v2/0000000000087-address-delete-fk-indexes.ts +30 -0
  78. package/build/migrations-v2/0000000000088-owner-statement-email-switch.ts +76 -0
  79. package/build/module/camel-case/index.d.ts +4 -4
  80. package/build/module/camel-case/index.js +3 -2
  81. package/build/module/camel-case/index.js.map +1 -1
  82. package/build/module/connect-handoff.d.ts +12 -0
  83. package/build/module/connect-handoff.js +70 -0
  84. package/build/module/connect-handoff.js.map +1 -0
  85. package/build/module/control-plane/index.d.ts +19 -1
  86. package/build/module/control-plane/index.js +9 -0
  87. package/build/module/control-plane/index.js.map +1 -1
  88. package/build/module/index.d.ts +38 -2
  89. package/build/module/index.js +322 -58
  90. package/build/module/index.js.map +1 -1
  91. package/build/module/isomorphic.d.ts +1 -1
  92. package/build/module/isomorphic.js +1 -1
  93. package/build/module/isomorphic.js.map +1 -1
  94. package/build/module/local/generate.js +4 -3
  95. package/build/module/local/generate.js.map +1 -1
  96. package/build/module/local/index.js +3 -0
  97. package/build/module/local/index.js.map +1 -1
  98. package/build/module/migration-source.d.ts +4 -0
  99. package/build/module/migration-source.js +42 -0
  100. package/build/module/migration-source.js.map +1 -0
  101. package/build/module/pganalyze-comment-plugin/comment-transformer.js +3 -1
  102. package/build/module/pganalyze-comment-plugin/comment-transformer.js.map +1 -1
  103. package/build/module/query/listing/status.js +6 -2
  104. package/build/module/query/listing/status.js.map +1 -1
  105. package/build/module/query/tenant/status.d.ts +1 -6
  106. package/build/module/query/tenant/status.js +4 -11
  107. package/build/module/query/tenant/status.js.map +1 -1
  108. package/build/module/regional.d.ts +1 -0
  109. package/build/module/regional.js +1 -0
  110. package/build/module/regional.js.map +1 -1
  111. package/build/module/test/index.js +4 -3
  112. package/build/module/test/index.js.map +1 -1
  113. package/build/module/v1.generated.d.ts +255 -19
  114. package/build/module/v1.generated.js.map +1 -1
  115. package/package.json +8 -6
@@ -17,10 +17,13 @@ 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;
23
25
  exports.useAsyncNeonWebSocketKysely = useAsyncNeonWebSocketKysely;
26
+ exports.useControlPlaneKysely = useControlPlaneKysely;
24
27
  exports.useAsyncControlPlaneKysely = useAsyncControlPlaneKysely;
25
28
  exports.forceCloseAllPostgres = forceCloseAllPostgres;
26
29
  const exponential_backoff_1 = require("exponential-backoff");
@@ -31,6 +34,8 @@ const postgres_1 = __importDefault(require("postgres"));
31
34
  const control_plane_1 = require("./control-plane");
32
35
  const error_1 = require("./error");
33
36
  const plugins_1 = require("./plugins");
37
+ const postgres_error_1 = require("./postgres-error");
38
+ __exportStar(require("./connect-handoff"), exports);
34
39
  __exportStar(require("./error"), exports);
35
40
  __exportStar(require("./isomorphic"), exports);
36
41
  __exportStar(require("./postgres-error"), exports);
@@ -43,27 +48,177 @@ const retryableMessages = [
43
48
  'CONNECT_TIMEOUT',
44
49
  'Idle connection closed by Hyperdrive.',
45
50
  'server_login_retry',
51
+ 'Timed out while creating a new server connection.',
52
+ // Neon rejects the login before any statement runs (PRO-19169).
53
+ 'Failed to acquire permit to connect to the database',
46
54
  ];
47
55
  const postgresRetryAttempts = 3;
56
+ /**
57
+ * Parameter types PostgreSQL described per statement signature (PRO-18871).
58
+ * Postgres.js describes a statement in a round trip of its own before it can
59
+ * execute it when a parameter type is unknown, and a Worker request always
60
+ * starts on new connections. The patched driver reads and fills this map
61
+ * through its `statement_types` option and then parses, describes, binds and
62
+ * executes a known statement in one round trip. It forgets a statement's
63
+ * types when the statement fails, so a schema change is described again.
64
+ */
65
+ class StatementTypes extends Map {
66
+ set(signature, types) {
67
+ if (!this.has(signature) && this.size >= 2000) {
68
+ this.delete(this.keys().next().value);
69
+ }
70
+ return super.set(signature, types);
71
+ }
72
+ }
73
+ /** Kept for the isolate's lifetime, one map per Hyperdrive database. */
74
+ const hyperdriveStatementTypes = {
75
+ controlPlane: new StatementTypes(),
76
+ regional: new StatementTypes(),
77
+ };
48
78
  function isRetryableConnectionError(error) {
49
79
  const message = error instanceof Error ? error.message : String(error);
50
80
  return retryableMessages.some((retryable) => message.includes(retryable));
51
81
  }
82
+ function isNodeShuttingDown(error) {
83
+ return (error instanceof Error &&
84
+ (error.message === 'Node shutting down' ||
85
+ error.message === 'Node shutting down.' ||
86
+ error.message === 'shutting down'));
87
+ }
52
88
  function isConnectionReset(error) {
53
89
  return (error instanceof Error && 'code' in error && error.code === 'ECONNRESET');
54
90
  }
55
- function retryPostgres(operation, retry) {
56
- return (0, exponential_backoff_1.backOff)(operation, {
57
- numOfAttempts: postgresRetryAttempts,
58
- startingDelay: (0, utils_1.parseDuration)('1s'),
59
- maxDelay: (0, utils_1.parseDuration)('5s'),
60
- retry: (error, attemptNumber) => attemptNumber < postgresRetryAttempts && retry(error, attemptNumber),
61
- });
91
+ function isRetryableConnectionAcquisitionError(error) {
92
+ return (isRetryableConnectionError(error) ||
93
+ isConnectionReset(error) ||
94
+ // Hyperdrive refuses any new connection while its node shuts down
95
+ // (PRO-19168).
96
+ isNodeShuttingDown(error) ||
97
+ (error instanceof Error &&
98
+ (error.message === 'connection attempt failed' ||
99
+ // Opening a connection happens before any statement runs, so the
100
+ // open is safe to retry (PRO-18866).
101
+ error.message === 'Egress connection severed outside of Hyperdrive' ||
102
+ error.message === 'Network connection lost.' ||
103
+ ('code' in error && error.code === 'CONNECTION_DESTROYED'))));
104
+ }
105
+ /**
106
+ * Postgres.js closes a reserved connection when its socket dies, whether the
107
+ * statement in flight fails with `CONNECTION_CLOSED` or with the socket error.
108
+ * A statement sent to it afterwards is never answered: it throws in a timer
109
+ * callback or is silently never written (PRO-17710). A destroyed connection
110
+ * rejects at once, so it needs no guard.
111
+ */
112
+ function isConnectionClosed(error) {
113
+ return (isConnectionReset(error) ||
114
+ (error instanceof Error &&
115
+ 'code' in error &&
116
+ (error.code === 'CONNECTION_CLOSED' ||
117
+ error.code === 'EPIPE' ||
118
+ error.code === 'ETIMEDOUT')));
119
+ }
120
+ function isQueryRetryDiagnosticError(error) {
121
+ const message = error instanceof Error ? error.message : String(error);
122
+ return (isRetryableConnectionError(error) ||
123
+ isConnectionReset(error) ||
124
+ message === 'Egress connection severed outside of Hyperdrive' ||
125
+ message === 'Network connection lost.' ||
126
+ isNodeShuttingDown(error));
127
+ }
128
+ async function retryPostgres(operation, retry, diagnostic) {
129
+ let attemptCount = 0;
130
+ let retried = false;
131
+ let lastError;
132
+ const emitDiagnostic = (outcome) => {
133
+ if (!diagnostic)
134
+ return;
135
+ diagnostic.emit({
136
+ attemptCount,
137
+ dataRegion: diagnostic.dataRegion,
138
+ errorClass: lastError instanceof Error
139
+ ? 'code' in lastError && typeof lastError.code === 'string'
140
+ ? lastError.code
141
+ : lastError.constructor.name
142
+ : 'unknown',
143
+ operationKind: diagnostic.operationKind,
144
+ outcome,
145
+ repositoryName: diagnostic.repositoryName,
146
+ });
147
+ };
148
+ try {
149
+ return await (0, exponential_backoff_1.backOff)(async () => {
150
+ attemptCount++;
151
+ return await operation();
152
+ }, {
153
+ numOfAttempts: postgresRetryAttempts,
154
+ startingDelay: (0, utils_1.parseDuration)('1s'),
155
+ maxDelay: (0, utils_1.parseDuration)('5s'),
156
+ // Scheduled chunk fan-outs open many connections at once; full jitter
157
+ // keeps their retries from reconnecting in lockstep.
158
+ jitter: 'full',
159
+ async retry(error, attemptNumber) {
160
+ lastError = error;
161
+ const shouldRetry = attemptNumber < postgresRetryAttempts &&
162
+ (await retry(error, attemptNumber));
163
+ if (shouldRetry && diagnostic) {
164
+ retried = true;
165
+ emitDiagnostic('retrying');
166
+ }
167
+ return shouldRetry;
168
+ },
169
+ });
170
+ }
171
+ catch (error) {
172
+ lastError = error;
173
+ if (diagnostic?.shouldEmit(error)) {
174
+ emitDiagnostic(retried && attemptCount === postgresRetryAttempts
175
+ ? 'exhausted'
176
+ : 'notRetryable');
177
+ }
178
+ throw error;
179
+ }
180
+ }
181
+ /**
182
+ * Replays a complete database operation after a PostgreSQL deadlock (40P01)
183
+ * or lock timeout (55P03), using the same three-attempt jittered budget as
184
+ * connection retries. The operation must own its transaction and must not
185
+ * contain external side effects such as partner API writes.
186
+ */
187
+ function retryPostgresLockFailure(operation) {
188
+ return retryPostgres(operation, (error) => (0, postgres_error_1.isPostgresError)(error, { code: '40P01' }) ||
189
+ (0, postgres_error_1.isPostgresError)(error, { code: '55P03' }));
62
190
  }
63
191
  class RetryingPostgresJSDialect extends kysely_postgres_js_1.PostgresJSDialect {
64
- constructor(config) {
192
+ constructor(config, retryDiagnostic, closeOnScriptTimeout) {
65
193
  super(config);
66
194
  this.config = config;
195
+ this.retryDiagnostic = retryDiagnostic;
196
+ this.closeOnScriptTimeout = closeOnScriptTimeout;
197
+ }
198
+ /** Ends the run when a script's database operation gets no answer (PRO-19037). */
199
+ async withScriptDeadline(operation) {
200
+ if (!this.closeOnScriptTimeout)
201
+ return await operation();
202
+ let timer;
203
+ try {
204
+ return await Promise.race([
205
+ operation(),
206
+ new Promise((_, reject) => {
207
+ timer = setTimeout(() => {
208
+ console.error('Postgres operation timed out', {
209
+ timeoutMs: scriptQueryTimeoutMs,
210
+ });
211
+ this.closeOnScriptTimeout?.();
212
+ reject(new error_1.KyselyError('Postgres operation timed out', {
213
+ timeoutMs: scriptQueryTimeoutMs,
214
+ }));
215
+ }, scriptQueryTimeoutMs);
216
+ }),
217
+ ]);
218
+ }
219
+ finally {
220
+ clearTimeout(timer);
221
+ }
67
222
  }
68
223
  createDriver() {
69
224
  const driver = new kysely_postgres_js_1.PostgresJSDriver(this.config);
@@ -82,22 +237,46 @@ class RetryingPostgresJSDialect extends kysely_postgres_js_1.PostgresJSDialect {
82
237
  inTransaction: false,
83
238
  };
84
239
  const connection = {
85
- executeQuery: (compiledQuery) => retryPostgres(() => state.connection.executeQuery(compiledQuery), async (error) => {
86
- const message = error instanceof Error ? error.message : String(error);
87
- if (state.inTransaction ||
88
- (!isRetryableConnectionError(error) &&
89
- (compiledQuery.query.kind !== 'SelectQueryNode' ||
90
- (!isConnectionReset(error) &&
91
- message !==
92
- 'Egress connection severed outside of Hyperdrive' &&
93
- message !== 'Network connection lost.' &&
94
- message !== 'Node shutting down')))) {
95
- return false;
96
- }
97
- // Postgres.js already ejects a severed reserved connection.
98
- // Acquire a new reservation before replaying the safe read.
99
- state.connection = await driver.acquireConnection();
100
- return true;
240
+ executeQuery: (compiledQuery) => this.withScriptDeadline(() => {
241
+ const operationKind = state.inTransaction
242
+ ? 'transaction'
243
+ : compiledQuery.query.kind === 'SelectQueryNode'
244
+ ? 'select'
245
+ : 'mutation';
246
+ return retryPostgres(() => {
247
+ if (state.lost)
248
+ return Promise.reject(state.lost);
249
+ return state.connection
250
+ .executeQuery(compiledQuery)
251
+ .catch((error) => {
252
+ if (isConnectionClosed(error))
253
+ state.lost = error;
254
+ throw error;
255
+ });
256
+ }, async (error) => {
257
+ const message = error instanceof Error ? error.message : String(error);
258
+ if (state.inTransaction ||
259
+ (!isRetryableConnectionError(error) &&
260
+ (compiledQuery.query.kind !== 'SelectQueryNode' ||
261
+ (!isConnectionReset(error) &&
262
+ message !==
263
+ 'Egress connection severed outside of Hyperdrive' &&
264
+ message !== 'Network connection lost.' &&
265
+ !isNodeShuttingDown(error))))) {
266
+ return false;
267
+ }
268
+ // Postgres.js already ejects a severed reserved connection.
269
+ // Acquire a new reservation before replaying the safe read.
270
+ state.connection = await driver.acquireConnection();
271
+ state.lost = undefined;
272
+ return true;
273
+ }, this.retryDiagnostic
274
+ ? {
275
+ ...this.retryDiagnostic,
276
+ operationKind,
277
+ shouldEmit: isQueryRetryDiagnosticError,
278
+ }
279
+ : undefined);
101
280
  }),
102
281
  streamQuery: (compiledQuery, chunkSize) => {
103
282
  if (chunkSize === undefined) {
@@ -113,17 +292,21 @@ class RetryingPostgresJSDialect extends kysely_postgres_js_1.PostgresJSDialect {
113
292
  const state = getConnection(connection);
114
293
  state.inTransaction = true;
115
294
  try {
116
- await driver.beginTransaction(state.connection, settings);
295
+ await this.withScriptDeadline(() => driver.beginTransaction(state.connection, settings));
117
296
  }
118
297
  catch (error) {
119
298
  state.inTransaction = false;
299
+ if (isConnectionClosed(error))
300
+ state.lost = error;
120
301
  throw error;
121
302
  }
122
303
  },
123
304
  commitTransaction: async (connection) => {
124
305
  const state = getConnection(connection);
125
306
  try {
126
- await driver.commitTransaction(state.connection);
307
+ if (state.lost)
308
+ throw state.lost;
309
+ await this.withScriptDeadline(() => driver.commitTransaction(state.connection));
127
310
  }
128
311
  finally {
129
312
  state.inTransaction = false;
@@ -132,18 +315,44 @@ class RetryingPostgresJSDialect extends kysely_postgres_js_1.PostgresJSDialect {
132
315
  rollbackTransaction: async (connection) => {
133
316
  const state = getConnection(connection);
134
317
  try {
135
- await driver.rollbackTransaction(state.connection);
318
+ // PostgreSQL rolls the transaction back when its session ends, and a
319
+ // statement on the closed connection would never be answered.
320
+ if (state.lost)
321
+ return;
322
+ await this.withScriptDeadline(() => driver.rollbackTransaction(state.connection));
136
323
  }
137
324
  finally {
138
325
  state.inTransaction = false;
139
326
  }
140
327
  },
141
- savepoint: (connection, savepointName, compileQuery) => driver.savepoint(getConnection(connection).connection, savepointName, compileQuery),
142
- rollbackToSavepoint: (connection, savepointName, compileQuery) => driver.rollbackToSavepoint(getConnection(connection).connection, savepointName, compileQuery),
143
- releaseSavepoint: (connection, savepointName, compileQuery) => driver.releaseSavepoint(getConnection(connection).connection, savepointName, compileQuery),
328
+ savepoint: (connection, savepointName, compileQuery) => this.withScriptDeadline(() => {
329
+ const state = getConnection(connection);
330
+ if (state.lost)
331
+ throw state.lost;
332
+ return driver.savepoint(state.connection, savepointName, compileQuery);
333
+ }),
334
+ rollbackToSavepoint: (connection, savepointName, compileQuery) => this.withScriptDeadline(() => {
335
+ const state = getConnection(connection);
336
+ if (state.lost)
337
+ throw state.lost;
338
+ return driver.rollbackToSavepoint(state.connection, savepointName, compileQuery);
339
+ }),
340
+ releaseSavepoint: (connection, savepointName, compileQuery) => this.withScriptDeadline(() => {
341
+ const state = getConnection(connection);
342
+ if (state.lost)
343
+ throw state.lost;
344
+ return driver.releaseSavepoint(state.connection, savepointName, compileQuery);
345
+ }),
144
346
  releaseConnection: async (connection) => {
145
- await driver.releaseConnection(getConnection(connection).connection);
347
+ const state = getConnection(connection);
146
348
  connections.delete(connection);
349
+ // Releasing a closed connection would put it back in the open pool,
350
+ // and the next statement on it would hang. Postgres.js reconnects
351
+ // from the closed pool on demand, and a failed reconnect is a
352
+ // retryable CONNECT_TIMEOUT.
353
+ if (state.lost)
354
+ return;
355
+ await driver.releaseConnection(state.connection);
147
356
  },
148
357
  destroy: () => driver.destroy(),
149
358
  };
@@ -151,16 +360,37 @@ class RetryingPostgresJSDialect extends kysely_postgres_js_1.PostgresJSDialect {
151
360
  }
152
361
  function useKysely(postgres, options) {
153
362
  console.debug('Creating Kysely instance');
363
+ const emitRetryDiagnostic = options?.onRetryDiagnostic ??
364
+ (options?.repositoryName
365
+ ? (diagnostic) => console.warn('Postgres operation retry diagnostic', diagnostic)
366
+ : undefined);
154
367
  const reserveConnection = postgres.reserve.bind(postgres);
155
368
  postgres.reserve = async () => {
156
- const connection = await retryPostgres(reserveConnection, (error) => isRetryableConnectionError(error) || isConnectionReset(error));
369
+ const connection = await retryPostgres(reserveConnection, isRetryableConnectionAcquisitionError, emitRetryDiagnostic
370
+ ? {
371
+ dataRegion: options?.dataRegion,
372
+ emit: emitRetryDiagnostic,
373
+ operationKind: 'acquisition',
374
+ repositoryName: options?.repositoryName,
375
+ shouldEmit: isRetryableConnectionAcquisitionError,
376
+ }
377
+ : undefined);
157
378
  if (options?.hyperdrive) {
158
379
  const unsafe = connection.unsafe;
159
380
  connection.unsafe = (query, parameters, queryOptions) => unsafe(query, parameters, { ...queryOptions, prepare: true });
160
381
  }
161
382
  return connection;
162
383
  };
163
- const kysely = (0, plugins_1.getKysely)(new RetryingPostgresJSDialect({ postgres }), {
384
+ const kysely = (0, plugins_1.getKysely)(new RetryingPostgresJSDialect({ postgres }, emitRetryDiagnostic
385
+ ? {
386
+ dataRegion: options?.dataRegion,
387
+ emit: emitRetryDiagnostic,
388
+ repositoryName: options?.repositoryName,
389
+ shouldEmit: isQueryRetryDiagnosticError,
390
+ }
391
+ : undefined, options?.script
392
+ ? () => void postgres.end({ timeout: 0 }).catch(() => undefined)
393
+ : undefined), {
164
394
  repositoryName: options?.repositoryName,
165
395
  log: options?.log,
166
396
  });
@@ -173,44 +403,77 @@ function useKysely(postgres, options) {
173
403
  };
174
404
  return kysely;
175
405
  }
406
+ const scriptQueryTimeoutMs = (0, utils_1.parseDuration)('1h');
176
407
  let _connections = [];
408
+ function usePostgres(connectionString, opt) {
409
+ const ssl = opt?.forceDisableSSL !== true && !opt?.hyperdrive;
410
+ const sql = (0, postgres_1.default)(connectionString, {
411
+ ssl: ssl ? 'require' : false,
412
+ target_session_attrs: 'read-write',
413
+ // Named prepared statements: PRO-17965 (Hyperdrive and Crunchy PgBouncer).
414
+ prepare: true,
415
+ ...(opt?.hyperdrive
416
+ ? {
417
+ max: 5,
418
+ // Retire idle clients before Hyperdrive can close them asynchronously.
419
+ idle_timeout: 10,
420
+ statement_types: hyperdriveStatementTypes[opt.hyperdrive],
421
+ }
422
+ : {
423
+ connect_timeout: 10,
424
+ idle_timeout: 60,
425
+ ...(opt?.script ? { keep_alive: 10 } : {}),
426
+ }),
427
+ });
428
+ if (opt?.onReserve) {
429
+ const { onReserve } = opt;
430
+ const reserve = sql.reserve.bind(sql);
431
+ // Innermost wrapper: it times each open or reuse of a connection, the
432
+ // startup probe too, and is not part of the retry loop (PRO-18952).
433
+ sql.reserve = async () => {
434
+ const startedAtEpochMs = Date.now();
435
+ const startedAt = performance.now();
436
+ try {
437
+ return await reserve();
438
+ }
439
+ finally {
440
+ onReserve({
441
+ durationMs: performance.now() - startedAt,
442
+ startedAtEpochMs,
443
+ });
444
+ }
445
+ };
446
+ }
447
+ // statement_timeout/lock_timeout are role-level settings on the cluster
448
+ // (ALTER ROLE application SET ...) so they cover every pooled
449
+ // connection; per-session SETs here only ever applied to one of them
450
+ _connections.push(sql);
451
+ return sql;
452
+ }
177
453
  async function useAsyncPostgres(connectionString, opt) {
178
454
  const delayMs = 2500;
179
455
  const probe = opt?.probe === true;
180
456
  const retries = probe ? (opt?.retries === false ? 0 : opt?.retries || 3) : 1;
181
- const ssl = opt?.forceDisableSSL !== true && opt?.hyperdrive !== true;
182
457
  const url = new URL(connectionString);
183
- console.debug(`Creating Postgres connection with probe=${probe}, ${retries} attempts, ssl=${ssl}, and port=${url.port}`);
458
+ console.debug(`Creating Postgres connection with probe=${probe}, ${retries} attempts, ssl=${opt?.forceDisableSSL !== true && !opt?.hyperdrive}, and port=${url.port}`);
184
459
  if (_connections.length > 0)
185
460
  console.warn(`We already have ${_connections.length} Postgres connections`);
186
461
  for (let attempt = 1; attempt <= retries; attempt++) {
462
+ let sql;
187
463
  try {
188
- const sql = (0, postgres_1.default)(connectionString, {
189
- ssl: ssl ? 'require' : false,
190
- target_session_attrs: 'read-write',
191
- // enable prepare statements, pgbouncer on crunchy allows for prepared statements
192
- prepare: true,
193
- ...(opt?.hyperdrive
194
- ? {
195
- max: 5,
196
- // Retire idle clients before Hyperdrive can close them asynchronously.
197
- idle_timeout: 10,
198
- }
199
- : {
200
- connect_timeout: 10,
201
- idle_timeout: 60,
202
- }),
203
- });
464
+ sql = usePostgres(connectionString, opt);
204
465
  if (probe) {
205
- await sql `select 1`;
466
+ // Opening a connection already checks that the session is writable
467
+ // and loads the array types; a probe query would add a round trip.
468
+ (await sql.reserve()).release();
206
469
  }
207
- // statement_timeout/lock_timeout are role-level settings on the cluster
208
- // (ALTER ROLE application SET ...) so they cover every pooled
209
- // connection; per-session SETs here only ever applied to one of them
210
- _connections.push(sql);
211
470
  return sql;
212
471
  }
213
472
  catch (err) {
473
+ if (sql) {
474
+ await sql.end({ timeout: 0 }).catch(() => undefined);
475
+ _connections.splice(_connections.indexOf(sql), 1);
476
+ }
214
477
  if (attempt === retries)
215
478
  throw err;
216
479
  console.warn(`Postgres connection failed (attempt ${attempt}), retrying...`);
@@ -235,9 +498,11 @@ async function useAsyncNeonWebSocketKysely(connectionString, opt) {
235
498
  await pool.query('select 1');
236
499
  return kysely;
237
500
  }
501
+ function useControlPlaneKysely(postgres, options) {
502
+ return (0, control_plane_1.withControlPlaneSchema)(useKysely(postgres, options), 'public');
503
+ }
238
504
  async function useAsyncControlPlaneKysely(connectionString, opt) {
239
- const sql = await useAsyncPostgres(connectionString, opt);
240
- return (0, control_plane_1.withControlPlaneSchema)(useKysely(sql, opt), 'public');
505
+ return useControlPlaneKysely(await useAsyncPostgres(connectionString, opt), opt);
241
506
  }
242
507
  async function forceCloseAllPostgres(timeoutMs = 5000) {
243
508
  await Promise.race([
@@ -1 +1 @@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IAAI,wBAAe,CAAC,EAAE,IAAI,EAAE,CAAC,EAAE,GAAG,IAAI,EAAE,CAAC,CAAC;IACvE,MAAM,CAAC,OAAO,GAAG,KAAK,IAAI,EAAE;QAC1B,OAAO,CAAC,KAAK,CAAC,0CAA0C,CAAC,CAAC;QAC1D,MAAM,IAAI,CAAC,GAAG,EAAE,CAAC;IACnB,CAAC,CAAC;IACF,IAAI,GAAG,EAAE,KAAK;QAAE,MAAM,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;IAC7C,OAAO,MAAM,CAAC;AAChB,CAAC;AAEM,KAAK,UAAU,0BAA0B,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 { 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';\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 isConnectionReset(error: unknown) {\n return (\n error instanceof Error && 'code' in error && error.code === 'ECONNRESET'\n );\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 (!isConnectionReset(error) &&\n message !==\n 'Egress connection severed outside of Hyperdrive' &&\n message !== 'Network connection lost.' &&\n message !== 'Node 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 ),\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 (error) => isRetryableConnectionError(error) || isConnectionReset(error)\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 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 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":";;;;;;;;;;;;;;;;;;;AA2PA,4DAOC;AAiND,8BA0DC;AAID,kCA8CC;AAED,4CAoCC;AAED,wCAMC;AAED,kEAYC;AAED,sDAKC;AAED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,CAAC;AACJ,CAAC;AAEM,KAAK,UAAU,0BAA0B,CAC9C,gBAAwB,EACxB,GAAwB;IAExB,OAAO,qBAAqB,CAC1B,MAAM,gBAAgB,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 CompiledQuery,\n DatabaseConnection,\n Driver,\n Kysely as K,\n LogConfig,\n QueryResult,\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 './connect-handoff';\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 // Neon rejects the login before any statement runs (PRO-19169).\n 'Failed to acquire permit to connect to the database',\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 isNodeShuttingDown(error: unknown) {\n return (\n error instanceof Error &&\n (error.message === 'Node shutting down' ||\n error.message === 'Node shutting down.' ||\n error.message === 'shutting down')\n );\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 // Hyperdrive refuses any new connection while its node shuts down\n // (PRO-19168).\n isNodeShuttingDown(error) ||\n (error instanceof Error &&\n (error.message === 'connection attempt failed' ||\n // Opening a connection happens before any statement runs, so the\n // open is safe to retry (PRO-18866).\n error.message === 'Egress connection severed outside of Hyperdrive' ||\n error.message === 'Network connection lost.' ||\n ('code' in error && error.code === 'CONNECTION_DESTROYED')))\n );\n}\n\n/**\n * Postgres.js closes a reserved connection when its socket dies, whether the\n * statement in flight fails with `CONNECTION_CLOSED` or with the socket error.\n * A statement sent to it afterwards is never answered: it throws in a timer\n * callback or is silently never written (PRO-17710). A destroyed connection\n * rejects at once, so it needs no guard.\n */\nfunction isConnectionClosed(error: unknown): error is Error {\n return (\n isConnectionReset(error) ||\n (error instanceof Error &&\n 'code' in error &&\n (error.code === 'CONNECTION_CLOSED' ||\n error.code === 'EPIPE' ||\n error.code === 'ETIMEDOUT'))\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 isNodeShuttingDown(error)\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 type ConnectionState = {\n connection: Awaited<ReturnType<typeof driver.acquireConnection>>;\n inTransaction: boolean;\n /** Set once the reserved connection reported that its socket closed. */\n lost?: Error;\n };\n const connections = new WeakMap<DatabaseConnection, ConnectionState>();\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: ConnectionState = {\n connection: await driver.acquireConnection(),\n inTransaction: false,\n };\n const connection: DatabaseConnection = {\n executeQuery: <R>(compiledQuery: CompiledQuery) =>\n this.withScriptDeadline(() => {\n const operationKind = state.inTransaction\n ? 'transaction'\n : compiledQuery.query.kind === 'SelectQueryNode'\n ? 'select'\n : 'mutation';\n return retryPostgres<QueryResult<R>>(\n () => {\n if (state.lost) return Promise.reject(state.lost);\n return state.connection\n .executeQuery<R>(compiledQuery)\n .catch((error) => {\n if (isConnectionClosed(error)) state.lost = error;\n throw error;\n });\n },\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 !isNodeShuttingDown(error))))\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 state.lost = undefined;\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 if (isConnectionClosed(error)) state.lost = error;\n throw error;\n }\n },\n commitTransaction: async (connection) => {\n const state = getConnection(connection);\n try {\n if (state.lost) throw state.lost;\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 // PostgreSQL rolls the transaction back when its session ends, and a\n // statement on the closed connection would never be answered.\n if (state.lost) return;\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 const state = getConnection(connection);\n if (state.lost) throw state.lost;\n return driver.savepoint(\n state.connection,\n savepointName,\n compileQuery\n );\n }),\n rollbackToSavepoint: (connection, savepointName, compileQuery) =>\n this.withScriptDeadline(() => {\n const state = getConnection(connection);\n if (state.lost) throw state.lost;\n return driver.rollbackToSavepoint(\n state.connection,\n savepointName,\n compileQuery\n );\n }),\n releaseSavepoint: (connection, savepointName, compileQuery) =>\n this.withScriptDeadline(() => {\n const state = getConnection(connection);\n if (state.lost) throw state.lost;\n return driver.releaseSavepoint(\n state.connection,\n savepointName,\n compileQuery\n );\n }),\n releaseConnection: async (connection) => {\n const state = getConnection(connection);\n connections.delete(connection);\n // Releasing a closed connection would put it back in the open pool,\n // and the next statement on it would hang. Postgres.js reconnects\n // from the closed pool on demand, and a failed reconnect is a\n // retryable CONNECT_TIMEOUT.\n if (state.lost) return;\n await driver.releaseConnection(state.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"]}
@@ -8,5 +8,5 @@ export type DatabaseKysely<Database> = K<Database>;
8
8
  export type DatabaseTransaction<Database> = T<Database>;
9
9
  export type Transaction = DatabaseTransaction<DB>;
10
10
  export type ControlledTransaction<S extends string[] = string[]> = CT<DB, S>;
11
- export { sql } from 'kysely';
11
+ export { PostgresQueryCompiler, sql } from 'kysely';
12
12
  export type Kysely = DatabaseKysely<DB>;