@vrplatform/kysely 1.3.45-stage.6066 → 1.3.45-stage.607
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/.data.tar +0 -0
- package/build/main/control-plane/index.d.ts +312 -0
- package/build/main/control-plane/index.js.map +1 -1
- package/build/main/index.d.ts +13 -2
- package/build/main/index.js +217 -23
- package/build/main/index.js.map +1 -1
- package/build/main/local/generate.js +2 -0
- package/build/main/local/generate.js.map +1 -1
- package/build/main/local/index.js +110 -8
- package/build/main/local/index.js.map +1 -1
- package/build/main/postgres-error.d.ts +3 -3
- package/build/main/postgres-error.js +4 -3
- package/build/main/postgres-error.js.map +1 -1
- package/build/main/query/listing/status.js +2 -6
- package/build/main/query/listing/status.js.map +1 -1
- package/build/main/query/tenant/status.d.ts +1 -1
- package/build/main/query/tenant/status.js +6 -4
- package/build/main/query/tenant/status.js.map +1 -1
- package/build/main/regional.d.ts +1 -0
- package/build/main/regional.js +1 -0
- package/build/main/regional.js.map +1 -1
- package/build/main/test/index.d.ts +23 -3
- package/build/main/test/index.js +35 -13
- package/build/main/test/index.js.map +1 -1
- package/build/main/v1.generated.d.ts +560 -8
- package/build/main/v1.generated.js.map +1 -1
- package/build/migrations-v2/0000000000015-durable-flow-events.ts +163 -0
- package/build/migrations-v2/0000000000016-billing-listing-facts.ts +539 -0
- package/build/migrations-v2/0000000000016-managed-team-access.ts +34 -0
- package/build/migrations-v2/0000000000017-drop-trial-until.ts +42 -0
- package/build/migrations-v2/0000000000017-webhook-secret-reencryption-failures.ts +18 -0
- package/build/migrations-v2/0000000000018-accounting-integrity-monitoring.ts +276 -0
- package/build/migrations-v2/0000000000018-durable-flow-event-sensitive-input.ts +28 -0
- package/build/migrations-v2/0000000000019-accounting-integrity-run-shards.ts +26 -0
- package/build/migrations-v2/0000000000019-asynchronous-operations.ts +736 -0
- package/build/migrations-v2/0000000000020-accounting-integrity-case-classification.ts +52 -0
- package/build/migrations-v2/0000000000021-payment-line-classification-monitor-indexes.ts +31 -0
- package/build/migrations-v2/0000000000022-accounting-integrity-controlled-repairs.ts +281 -0
- package/build/migrations-v2/0000000000023-line-classification-usage.ts +325 -0
- package/build/migrations-v2/0000000000024-tenant-region-migration.ts +108 -0
- package/build/migrations-v2/0000000000025-partner-ach-denial-default.ts +30 -0
- package/build/migrations-v2/0000000000026-line-classification-usage-capture.ts +399 -0
- package/build/migrations-v2/0000000000027-payout-replacement-chain.ts +27 -0
- package/build/migrations-v2/0000000000028-accounting-integrity-operator-workflow.ts +108 -0
- package/build/migrations-v2/0000000000029-accounting-integrity-definition-artifacts.ts +40 -0
- package/build/migrations-v2/0000000000030-accounting-integrity-review-metadata-compatibility.ts +49 -0
- package/build/migrations-v2/0000000000031-ui-permission-role-simplification.ts +70 -0
- package/build/migrations-v2/0000000000032-tenant-delete-ownership-cascades.ts +44 -0
- package/build/migrations-v2/0000000000033-reservation-issue-seed-bucket-index.ts +19 -0
- package/build/migrations-v2/0000000000034-retire-recent-classification-indexes.ts +29 -0
- package/build/migrations-v2/0000000000035-core-change-autovacuum.ts +24 -0
- package/build/migrations-v2/0000000000036-journal-entry-inactive-reason-constraint.ts +33 -0
- package/build/migrations-v2/0000000000037-journal-entry-inactive-reasons.ts +19 -0
- package/build/migrations-v2/0000000000038-journal-entry-group-inactive-reason.ts +14 -0
- package/build/migrations-v2/0000000000039-reservation-guest-breakdown.ts +19 -0
- package/build/migrations-v2/0000000000040-csv-import-source-identity-index.ts +23 -0
- package/build/migrations-v2/0000000000041-payment-returns.ts +38 -0
- package/build/migrations-v2/0000000000042-operation-resource-types.ts +609 -0
- package/build/migrations-v2/0000000000043-reservation-journal-freshness.ts +149 -0
- package/build/migrations-v2/0000000000044-reservation-journal-freshness-backfill.ts +254 -0
- package/build/migrations-v2/0000000000045-reservation-journal-freshness-revision-repair.ts +83 -0
- package/build/migrations-v2/0000000000046-materialized-reservation-journal-operations.ts +709 -0
- package/build/migrations-v2/0000000000047-public-audit-completion.ts +77 -0
- package/build/migrations-v2/0000000000048-reservation-journal-full-refresh-repair.ts +136 -0
- package/build/migrations-v2/0000000000049-queued-journal-operation-failures.ts +60 -0
- package/build/migrations-v2/0000000000050-connection-oauth-state.ts +43 -0
- package/build/migrations-v2/0000000000051-owner-statement-email-delivery.ts +134 -0
- package/build/migrations-v2/0000000000052-fee-journal-lock-skip-operations.ts +59 -0
- package/build/migrations-v2/0000000000053-fee-journal-lock-skip-null-attempt.ts +44 -0
- package/build/migrations-v2/0000000000054-journal-refresh-issue-codes.ts +16 -0
- package/build/migrations-v2/0000000000055-tenant-billing-subscription.ts +8 -0
- package/build/module/control-plane/index.d.ts +312 -0
- package/build/module/control-plane/index.js.map +1 -1
- package/build/module/index.d.ts +13 -2
- package/build/module/index.js +219 -24
- package/build/module/index.js.map +1 -1
- package/build/module/local/generate.js +2 -0
- package/build/module/local/generate.js.map +1 -1
- package/build/module/local/index.js +110 -8
- package/build/module/local/index.js.map +1 -1
- package/build/module/postgres-error.d.ts +3 -3
- package/build/module/postgres-error.js +4 -3
- package/build/module/postgres-error.js.map +1 -1
- package/build/module/query/listing/status.js +2 -6
- package/build/module/query/listing/status.js.map +1 -1
- package/build/module/query/tenant/status.d.ts +1 -1
- package/build/module/query/tenant/status.js +6 -4
- package/build/module/query/tenant/status.js.map +1 -1
- package/build/module/regional.d.ts +1 -0
- package/build/module/regional.js +1 -0
- package/build/module/regional.js.map +1 -1
- package/build/module/test/index.d.ts +23 -3
- package/build/module/test/index.js +34 -13
- package/build/module/test/index.js.map +1 -1
- package/build/module/v1.generated.d.ts +560 -8
- package/build/module/v1.generated.js.map +1 -1
- package/package.json +4 -2
package/build/module/index.js
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { backOff } from 'exponential-backoff';
|
|
2
|
-
import {
|
|
2
|
+
import { Pool } from '@neondatabase/serverless';
|
|
3
|
+
import { PostgresDialect } from 'kysely';
|
|
4
|
+
import { PostgresJSDialect, PostgresJSDriver, } from 'kysely-postgres-js';
|
|
3
5
|
import postgres from 'postgres';
|
|
4
6
|
import { withControlPlaneSchema } from './control-plane';
|
|
5
7
|
import { KyselyError } from './error';
|
|
@@ -15,31 +17,211 @@ const retryableMessages = [
|
|
|
15
17
|
'CONNECTION_CLOSED',
|
|
16
18
|
'CONNECT_TIMEOUT',
|
|
17
19
|
'Idle connection closed by Hyperdrive.',
|
|
20
|
+
'server_login_retry',
|
|
18
21
|
];
|
|
22
|
+
const postgresRetryAttempts = 3;
|
|
23
|
+
function isRetryableConnectionError(error) {
|
|
24
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
25
|
+
return retryableMessages.some((retryable) => message.includes(retryable));
|
|
26
|
+
}
|
|
27
|
+
function isConnectionReset(error) {
|
|
28
|
+
return (error instanceof Error && 'code' in error && error.code === 'ECONNRESET');
|
|
29
|
+
}
|
|
30
|
+
function isRetryableConnectionAcquisitionError(error) {
|
|
31
|
+
return (isRetryableConnectionError(error) ||
|
|
32
|
+
isConnectionReset(error) ||
|
|
33
|
+
(error instanceof Error &&
|
|
34
|
+
(error.message === 'connection attempt failed' ||
|
|
35
|
+
('code' in error && error.code === 'CONNECTION_DESTROYED'))));
|
|
36
|
+
}
|
|
37
|
+
function isQueryRetryDiagnosticError(error) {
|
|
38
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
39
|
+
return (isRetryableConnectionError(error) ||
|
|
40
|
+
isConnectionReset(error) ||
|
|
41
|
+
message === 'Egress connection severed outside of Hyperdrive' ||
|
|
42
|
+
message === 'Network connection lost.' ||
|
|
43
|
+
message === 'Node shutting down' ||
|
|
44
|
+
message === 'Node shutting down.');
|
|
45
|
+
}
|
|
46
|
+
async function retryPostgres(operation, retry, diagnostic) {
|
|
47
|
+
let attemptCount = 0;
|
|
48
|
+
let retried = false;
|
|
49
|
+
const emitDiagnostic = (outcome) => {
|
|
50
|
+
if (!diagnostic)
|
|
51
|
+
return;
|
|
52
|
+
diagnostic.emit({
|
|
53
|
+
attemptCount,
|
|
54
|
+
dataRegion: diagnostic.dataRegion,
|
|
55
|
+
operationKind: diagnostic.operationKind,
|
|
56
|
+
outcome,
|
|
57
|
+
repositoryName: diagnostic.repositoryName,
|
|
58
|
+
});
|
|
59
|
+
};
|
|
60
|
+
try {
|
|
61
|
+
return await backOff(async () => {
|
|
62
|
+
attemptCount++;
|
|
63
|
+
return await operation();
|
|
64
|
+
}, {
|
|
65
|
+
numOfAttempts: postgresRetryAttempts,
|
|
66
|
+
startingDelay: parseDuration('1s'),
|
|
67
|
+
maxDelay: parseDuration('5s'),
|
|
68
|
+
async retry(error, attemptNumber) {
|
|
69
|
+
const shouldRetry = attemptNumber < postgresRetryAttempts &&
|
|
70
|
+
(await retry(error, attemptNumber));
|
|
71
|
+
if (shouldRetry && diagnostic) {
|
|
72
|
+
retried = true;
|
|
73
|
+
emitDiagnostic('retrying');
|
|
74
|
+
}
|
|
75
|
+
return shouldRetry;
|
|
76
|
+
},
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
catch (error) {
|
|
80
|
+
if (diagnostic?.shouldEmit(error)) {
|
|
81
|
+
emitDiagnostic(retried && attemptCount === postgresRetryAttempts
|
|
82
|
+
? 'exhausted'
|
|
83
|
+
: 'notRetryable');
|
|
84
|
+
}
|
|
85
|
+
throw error;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
class RetryingPostgresJSDialect extends PostgresJSDialect {
|
|
89
|
+
config;
|
|
90
|
+
retryDiagnostic;
|
|
91
|
+
constructor(config, retryDiagnostic) {
|
|
92
|
+
super(config);
|
|
93
|
+
this.config = config;
|
|
94
|
+
this.retryDiagnostic = retryDiagnostic;
|
|
95
|
+
}
|
|
96
|
+
createDriver() {
|
|
97
|
+
const driver = new PostgresJSDriver(this.config);
|
|
98
|
+
const connections = new WeakMap();
|
|
99
|
+
const getConnection = (connection) => {
|
|
100
|
+
const state = connections.get(connection);
|
|
101
|
+
if (!state)
|
|
102
|
+
throw new Error('Postgres connection state is unavailable');
|
|
103
|
+
return state;
|
|
104
|
+
};
|
|
105
|
+
return {
|
|
106
|
+
init: () => driver.init(),
|
|
107
|
+
acquireConnection: async () => {
|
|
108
|
+
const state = {
|
|
109
|
+
connection: await driver.acquireConnection(),
|
|
110
|
+
inTransaction: false,
|
|
111
|
+
};
|
|
112
|
+
const connection = {
|
|
113
|
+
executeQuery: (compiledQuery) => {
|
|
114
|
+
const operationKind = state.inTransaction
|
|
115
|
+
? 'transaction'
|
|
116
|
+
: compiledQuery.query.kind === 'SelectQueryNode'
|
|
117
|
+
? 'select'
|
|
118
|
+
: 'mutation';
|
|
119
|
+
return retryPostgres(() => state.connection.executeQuery(compiledQuery), async (error) => {
|
|
120
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
121
|
+
if (state.inTransaction ||
|
|
122
|
+
(!isRetryableConnectionError(error) &&
|
|
123
|
+
(compiledQuery.query.kind !== 'SelectQueryNode' ||
|
|
124
|
+
(!isConnectionReset(error) &&
|
|
125
|
+
message !==
|
|
126
|
+
'Egress connection severed outside of Hyperdrive' &&
|
|
127
|
+
message !== 'Network connection lost.' &&
|
|
128
|
+
message !== 'Node shutting down' &&
|
|
129
|
+
message !== 'Node shutting down.')))) {
|
|
130
|
+
return false;
|
|
131
|
+
}
|
|
132
|
+
// Postgres.js already ejects a severed reserved connection.
|
|
133
|
+
// Acquire a new reservation before replaying the safe read.
|
|
134
|
+
state.connection = await driver.acquireConnection();
|
|
135
|
+
return true;
|
|
136
|
+
}, this.retryDiagnostic
|
|
137
|
+
? {
|
|
138
|
+
...this.retryDiagnostic,
|
|
139
|
+
operationKind,
|
|
140
|
+
shouldEmit: isQueryRetryDiagnosticError,
|
|
141
|
+
}
|
|
142
|
+
: undefined);
|
|
143
|
+
},
|
|
144
|
+
streamQuery: (compiledQuery, chunkSize) => {
|
|
145
|
+
if (chunkSize === undefined) {
|
|
146
|
+
throw new Error('Postgres stream chunk size is required');
|
|
147
|
+
}
|
|
148
|
+
return state.connection.streamQuery(compiledQuery, chunkSize);
|
|
149
|
+
},
|
|
150
|
+
};
|
|
151
|
+
connections.set(connection, state);
|
|
152
|
+
return connection;
|
|
153
|
+
},
|
|
154
|
+
beginTransaction: async (connection, settings) => {
|
|
155
|
+
const state = getConnection(connection);
|
|
156
|
+
state.inTransaction = true;
|
|
157
|
+
try {
|
|
158
|
+
await driver.beginTransaction(state.connection, settings);
|
|
159
|
+
}
|
|
160
|
+
catch (error) {
|
|
161
|
+
state.inTransaction = false;
|
|
162
|
+
throw error;
|
|
163
|
+
}
|
|
164
|
+
},
|
|
165
|
+
commitTransaction: async (connection) => {
|
|
166
|
+
const state = getConnection(connection);
|
|
167
|
+
try {
|
|
168
|
+
await driver.commitTransaction(state.connection);
|
|
169
|
+
}
|
|
170
|
+
finally {
|
|
171
|
+
state.inTransaction = false;
|
|
172
|
+
}
|
|
173
|
+
},
|
|
174
|
+
rollbackTransaction: async (connection) => {
|
|
175
|
+
const state = getConnection(connection);
|
|
176
|
+
try {
|
|
177
|
+
await driver.rollbackTransaction(state.connection);
|
|
178
|
+
}
|
|
179
|
+
finally {
|
|
180
|
+
state.inTransaction = false;
|
|
181
|
+
}
|
|
182
|
+
},
|
|
183
|
+
savepoint: (connection, savepointName, compileQuery) => driver.savepoint(getConnection(connection).connection, savepointName, compileQuery),
|
|
184
|
+
rollbackToSavepoint: (connection, savepointName, compileQuery) => driver.rollbackToSavepoint(getConnection(connection).connection, savepointName, compileQuery),
|
|
185
|
+
releaseSavepoint: (connection, savepointName, compileQuery) => driver.releaseSavepoint(getConnection(connection).connection, savepointName, compileQuery),
|
|
186
|
+
releaseConnection: async (connection) => {
|
|
187
|
+
await driver.releaseConnection(getConnection(connection).connection);
|
|
188
|
+
connections.delete(connection);
|
|
189
|
+
},
|
|
190
|
+
destroy: () => driver.destroy(),
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
}
|
|
19
194
|
export function useKysely(postgres, options) {
|
|
20
195
|
console.debug('Creating Kysely instance');
|
|
21
|
-
const
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
}
|
|
196
|
+
const emitRetryDiagnostic = options?.onRetryDiagnostic ??
|
|
197
|
+
(options?.repositoryName
|
|
198
|
+
? (diagnostic) => console.warn('Postgres operation retry diagnostic', diagnostic)
|
|
199
|
+
: undefined);
|
|
200
|
+
const reserveConnection = postgres.reserve.bind(postgres);
|
|
201
|
+
postgres.reserve = async () => {
|
|
202
|
+
const connection = await retryPostgres(reserveConnection, isRetryableConnectionAcquisitionError, emitRetryDiagnostic
|
|
203
|
+
? {
|
|
204
|
+
dataRegion: options?.dataRegion,
|
|
205
|
+
emit: emitRetryDiagnostic,
|
|
206
|
+
operationKind: 'acquisition',
|
|
207
|
+
repositoryName: options?.repositoryName,
|
|
208
|
+
shouldEmit: isRetryableConnectionAcquisitionError,
|
|
209
|
+
}
|
|
210
|
+
: undefined);
|
|
211
|
+
if (options?.hyperdrive) {
|
|
212
|
+
const unsafe = connection.unsafe;
|
|
213
|
+
connection.unsafe = (query, parameters, queryOptions) => unsafe(query, parameters, { ...queryOptions, prepare: true });
|
|
214
|
+
}
|
|
215
|
+
return connection;
|
|
216
|
+
};
|
|
217
|
+
const kysely = getKysely(new RetryingPostgresJSDialect({ postgres }, emitRetryDiagnostic
|
|
218
|
+
? {
|
|
219
|
+
dataRegion: options?.dataRegion,
|
|
220
|
+
emit: emitRetryDiagnostic,
|
|
221
|
+
repositoryName: options?.repositoryName,
|
|
222
|
+
shouldEmit: isQueryRetryDiagnosticError,
|
|
223
|
+
}
|
|
224
|
+
: undefined), {
|
|
43
225
|
repositoryName: options?.repositoryName,
|
|
44
226
|
log: options?.log,
|
|
45
227
|
});
|
|
@@ -63,8 +245,9 @@ export async function useAsyncPostgres(connectionString, opt) {
|
|
|
63
245
|
if (_connections.length > 0)
|
|
64
246
|
console.warn(`We already have ${_connections.length} Postgres connections`);
|
|
65
247
|
for (let attempt = 1; attempt <= retries; attempt++) {
|
|
248
|
+
let sql;
|
|
66
249
|
try {
|
|
67
|
-
|
|
250
|
+
sql = postgres(connectionString, {
|
|
68
251
|
ssl: ssl ? 'require' : false,
|
|
69
252
|
target_session_attrs: 'read-write',
|
|
70
253
|
// enable prepare statements, pgbouncer on crunchy allows for prepared statements
|
|
@@ -90,6 +273,7 @@ export async function useAsyncPostgres(connectionString, opt) {
|
|
|
90
273
|
return sql;
|
|
91
274
|
}
|
|
92
275
|
catch (err) {
|
|
276
|
+
await sql?.end({ timeout: 0 }).catch(() => undefined);
|
|
93
277
|
if (attempt === retries)
|
|
94
278
|
throw err;
|
|
95
279
|
console.warn(`Postgres connection failed (attempt ${attempt}), retrying...`);
|
|
@@ -103,6 +287,17 @@ export async function useAsyncKysely(connectionString, opt) {
|
|
|
103
287
|
const sql = await useAsyncPostgres(connectionString, opt);
|
|
104
288
|
return useKysely(sql, opt);
|
|
105
289
|
}
|
|
290
|
+
export async function useAsyncNeonWebSocketKysely(connectionString, opt) {
|
|
291
|
+
const pool = new Pool({ connectionString, max: 5 });
|
|
292
|
+
const kysely = getKysely(new PostgresDialect({ pool }), opt ?? {});
|
|
293
|
+
kysely.destroy = async () => {
|
|
294
|
+
console.debug('Closing Neon WebSocket Kysely connection');
|
|
295
|
+
await pool.end();
|
|
296
|
+
};
|
|
297
|
+
if (opt?.probe)
|
|
298
|
+
await pool.query('select 1');
|
|
299
|
+
return kysely;
|
|
300
|
+
}
|
|
106
301
|
export async function useAsyncControlPlaneKysely(connectionString, opt) {
|
|
107
302
|
const sql = await useAsyncPostgres(connectionString, opt);
|
|
108
303
|
return withControlPlaneSchema(useKysely(sql, opt), 'public');
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":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,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 { Kysely as K, LogConfig, Transaction as T } from 'kysely';\nimport { PostgresJSDialect } 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 repositoryName?: string;\n log?: true | LogConfig;\n};\n\ntype PgOpt = {\n forceDisableSSL?: boolean;\n hyperdrive?: true;\n probe?: true;\n retries?: false | number;\n};\n\nconst retryableMessages = [\n 'CONNECTION_CLOSED',\n 'CONNECT_TIMEOUT',\n 'Idle connection closed by Hyperdrive.',\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 kysely = getKysely<Database>(\n new PostgresJSDialect({\n postgres,\n onReserveConnection: async (connection) => {\n const executeQuery = connection.executeQuery.bind(connection);\n connection.executeQuery = (arg) =>\n backOff(async () => await executeQuery(arg), {\n numOfAttempts: 3,\n startingDelay: parseDuration('1s'),\n maxDelay: parseDuration('5s'),\n retry: (error) => {\n const message =\n error instanceof Error ? error.message : String(error);\n if (\n retryableMessages.some((m) => message?.includes(m)) ||\n (arg.query.kind === 'SelectQueryNode' &&\n (message ===\n 'Egress connection severed outside of Hyperdrive' ||\n message === 'Network connection lost.'))\n ) {\n return true;\n }\n return false;\n },\n });\n },\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\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":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAC;AAC9C,OAAO,EAAE,IAAI,EAAE,MAAM,0BAA0B,CAAC;AAQhD,OAAO,EAAE,eAAe,EAAE,MAAM,QAAQ,CAAC;AACzC,OAAO,EACL,iBAAiB,EAEjB,gBAAgB,GACjB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,QAAsB,MAAM,UAAU,CAAC;AAC9C,OAAO,EAAuB,sBAAsB,EAAE,MAAM,iBAAiB,CAAC;AAC9E,OAAO,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;AACtC,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAGtC,cAAc,SAAS,CAAC;AACxB,cAAc,cAAc,CAAC;AAC7B,cAAc,kBAAkB,CAAC;AACjC,cAAc,SAAS,CAAC;AACxB,cAAc,YAAY,CAAC;AAC3B,cAAc,eAAe,CAAC;AAE9B,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AA0BlD,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,KAA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AM,CAAC;AAChB,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,0BAA0B,CAC9C,gBAAwB,EACxB,GAAwB;IAExB,MAAM,GAAG,GAAG,MAAM,gBAAgB,CAAC,gBAAgB,EAAE,GAAG,CAAC,CAAC;IAC1D,OAAO,sBAAsB,CAAC,SAAS,CAAiB,GAAG,EAAE,GAAG,CAAC,EAAE,QAAQ,CAAC,CAAC;AAC/E,CAAC;AAED,MAAM,CAAC,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 { TenantDataRegion } from './regional';\nimport type { DB } from './v1.generated';\n\ntype KyselyOpts = {\n dataRegion?: TenantDataRegion;\n hyperdrive?: true;\n onRetryDiagnostic?: (diagnostic: PostgresRetryDiagnostic) => void;\n repositoryName?: string;\n log?: true | LogConfig;\n};\n\ntype PostgresRetryDiagnostic = {\n attemptCount: number;\n dataRegion?: TenantDataRegion;\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'>;\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 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 );\n}\n\nasync function retryPostgres<T>(\n operation: () => Promise<T>,\n retry: (error: unknown, attemptNumber: number) => boolean | Promise<boolean>,\n diagnostic?: Omit<PostgresRetryDiagnostic, 'attemptCount' | 'outcome'> & {\n emit: (diagnostic: PostgresRetryDiagnostic) => void;\n shouldEmit: (error: unknown) => boolean;\n }\n) {\n let attemptCount = 0;\n let retried = false;\n const emitDiagnostic = (outcome: PostgresRetryDiagnostic['outcome']) => {\n if (!diagnostic) return;\n diagnostic.emit({\n attemptCount,\n dataRegion: diagnostic.dataRegion,\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 async retry(error, attemptNumber) {\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 if (diagnostic?.shouldEmit(error)) {\n emitDiagnostic(\n retried && attemptCount === postgresRetryAttempts\n ? 'exhausted'\n : 'notRetryable'\n );\n }\n throw error;\n }\n}\n\nclass RetryingPostgresJSDialect extends PostgresJSDialect {\n constructor(\n private readonly config: PostgresJSDialectConfig,\n private readonly retryDiagnostic?: Omit<\n PostgresRetryDiagnostic,\n 'attemptCount' | 'operationKind' | 'outcome'\n > & {\n emit: (diagnostic: PostgresRetryDiagnostic) => void;\n shouldEmit: (error: unknown) => boolean;\n }\n ) {\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 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 ) {\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 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 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 ),\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 let sql: Sql | undefined;\n try {\n 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 await sql?.end({ timeout: 0 }).catch(() => undefined);\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"]}
|
|
@@ -13,6 +13,7 @@ async function normalizeGeneratedTypes(root) {
|
|
|
13
13
|
const current = await Bun.file(outFile).text();
|
|
14
14
|
const next = current
|
|
15
15
|
.replace('export type Timestamp = ColumnType<Date, Date | string, Date | string>;', 'export type Timestamp = ColumnType<Date | string, Date | string, Date | string>;')
|
|
16
|
+
.replace(' managedTeamAccess: Generated<string>;\n', ' managedTeamAccess: Generated<"all" | "assigned">;\n')
|
|
16
17
|
.replace(' slug: string;\n', ' slug: Generated<string>;\n');
|
|
17
18
|
if (next !== current) {
|
|
18
19
|
await Bun.write(outFile, next);
|
|
@@ -32,6 +33,7 @@ async function migrate(root, client) {
|
|
|
32
33
|
async function migrateKysely(root, kysely) {
|
|
33
34
|
console.log('init migrating kysely ....');
|
|
34
35
|
const migrator = new Migrator({
|
|
36
|
+
allowUnorderedMigrations: true,
|
|
35
37
|
db: kysely,
|
|
36
38
|
migrationTableSchema: appMigrationEpoch.tableSchema,
|
|
37
39
|
migrationTableName: appMigrationEpoch.tableName,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generate.js","sourceRoot":"src/","sources":["local/generate.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,IAAI,EAAE,EAAE,MAAM,SAAS,CAAC;AACzC,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAC1C,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAClC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAC9C,OAAO,EAAE,qBAAqB,EAAe,QAAQ,EAAE,MAAM,QAAQ,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AAC,CAAC;IAC1C,MAAM,MAAM,GAAG,SAAS,CAAC,OAAO,EAAE;QAChC,cAAc,EAAE,cAAc;QAC9B,GAAG,EAAE,SAAS;KACf,CAAC,CAAC;IAEH,MAAM,eAAe,GAAG,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IACpD,MAAM,CAAC,OAAO,GAAG,KAAK,IAAI,EAAE;QAC1B,IAAI,WAAW;YAAE,OAAO;QACxB,WAAW,GAAG,IAAI,CAAC;QACnB,yCAAyC;QACzC,MAAM,eAAe,EAAE,CAAC;QACxB,cAAc;QACd,0EAA0E;QAC1E,IAAI;IACN,CAAC,CAAC;IAEF,iFAAiF;IAEjF,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import { promises as fs } from 'node:fs';\nimport { exists } from 'node:fs/promises';\nimport * as path from 'node:path';\nimport { join } from 'node:path';\nimport { PGlite } from '@electric-sql/pglite';\nimport { FileMigrationProvider, type Kysely, Migrator } from 'kysely';\nimport codegen from 'kysely-codegen';\nimport { PGliteDialect } from 'kysely-pglite-dialect';\nimport { appMigrationEpoch } from '../migration';\nimport { getKysely } from '../plugins';\nimport type { DB } from '../v1.generated';\n\nasync function normalizeGeneratedTypes(root: string) {\n const outFile = path.join(root, 'src/v1.generated.ts');\n const current = await Bun.file(outFile).text();\n const next = current\n .replace(\n 'export type Timestamp = ColumnType<Date, Date | string, Date | string>;',\n 'export type Timestamp = ColumnType<Date | string, Date | string, Date | string>;'\n )\n .replace(' slug: string;\\n', ' slug: Generated<string>;\\n');\n\n if (next !== current) {\n await Bun.write(outFile, next);\n }\n}\n\nasync function migrate(root: string, client: PGlite) {\n console.log('migrating pglite ....');\n const glob = new Bun.Glob('initial/*.sql');\n for await (const migration of glob.scan(root)) {\n const raw = await Bun.file(join(root, migration)).text();\n // `pg_dump` (v17+) prepends `\\restrict`/`\\unrestrict` psql meta commands\n // which PostgreSQL-compatible parsers (like PGlite) cannot execute.\n const sanitized = raw.replace(/^\\s*\\\\(?:un)?restrict.*$/gim, '');\n await client.exec(sanitized);\n }\n}\n\nasync function migrateKysely(root: string, kysely: Kysely<DB>) {\n console.log('init migrating kysely ....');\n const migrator = new Migrator({\n db: kysely,\n migrationTableSchema: appMigrationEpoch.tableSchema,\n migrationTableName: appMigrationEpoch.tableName,\n migrationLockTableName: appMigrationEpoch.lockTableName,\n provider: new FileMigrationProvider({\n fs,\n path,\n // This needs to be an absolute path.\n migrationFolder: path.join(root, appMigrationEpoch.folder),\n }),\n });\n\n console.log('migrating kysely ....');\n const { error, results } = await migrator.migrateToLatest().catch(() => {\n console.error('failed to migrate');\n process.exit(1);\n });\n\n for (const it of results ?? []) {\n if (it.status === 'Success') {\n console.log(`migration \"${it.migrationName}\" was executed successfully`);\n } else if (it.status === 'Error') {\n console.error(`failed to execute migration \"${it.migrationName}\"`);\n }\n }\n\n if (error) {\n console.error('failed to migrate');\n console.error(error);\n process.exit(1);\n }\n}\n\nasync function generateDump(root: string, dumpPath: string) {\n const dataExists = await exists(dumpPath).catch(() => false);\n if (!dataExists) {\n console.log('Creating initial dump');\n const main = new PGlite();\n await migrate(root, main).catch(async (err) => {\n console.error('failed to migrate initial dump');\n await Bun.write(\n '../logs/migrate-initial-dump.json',\n JSON.stringify(err as any, null, 2)\n );\n process.exit(1);\n });\n const dialect = new PGliteDialect(main);\n const kysely = getKysely(dialect, {\n repositoryName: 'localTesting',\n log: undefined,\n });\n await migrateKysely(root, kysely).catch(() => {\n console.error('failed to migrate kysely');\n process.exit(1);\n });\n await codegen\n .generate({\n db: kysely,\n outFile: path.join(root, 'src/v1.generated.ts'),\n defaultSchemas: ['xxx'],\n camelCase: true,\n dialect: codegen.getDialect('postgres'),\n })\n .catch(() => {\n console.error('failed to generate kysely');\n process.exit(1);\n });\n await normalizeGeneratedTypes(root);\n const content = await main.dumpDataDir('none').catch(() => {\n console.error('failed to dump data');\n process.exit(1);\n });\n await Bun.write(dumpPath, content).catch(() => {\n console.error('failed to write dump');\n process.exit(1);\n });\n return content;\n }\n return Bun.file(dumpPath);\n}\n\nexport async function createLocalKysely(root: string, dumpPath: string) {\n let isDestroyed = false;\n //const now = performance.now();\n\n const dump = await generateDump(root, dumpPath);\n\n const pglite = new PGlite({ loadDataDir: dump });\n // warm up\n await pglite.sql`SELECT 1`;\n const dialect = new PGliteDialect(pglite);\n const kysely = getKysely(dialect, {\n repositoryName: 'localTesting',\n log: undefined,\n });\n\n const originalDestroy = kysely.destroy.bind(kysely);\n kysely.destroy = async () => {\n if (isDestroyed) return;\n isDestroyed = true;\n // const destroyTime = performance.now();\n await originalDestroy();\n //console.log(\n // `Database destroyed: ${Math.round(performance.now() - destroyTime)}ms`\n //);\n };\n\n // console.log(`Database initialized: ${Math.round(performance.now() - now)}ms`);\n\n return kysely;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"generate.js","sourceRoot":"src/","sources":["local/generate.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,IAAI,EAAE,EAAE,MAAM,SAAS,CAAC;AACzC,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAC1C,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAClC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAC9C,OAAO,EAAE,qBAAqB,EAAe,QAAQ,EAAE,MAAM,QAAQ,CAAC;AACtE,OAAO,OAAO,MAAM,gBAAgB,CAAC;AACrC,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AACtD,OAAO,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAC;AACjD,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAGvC,KAAK,UAAU,uBAAuB,CAAC,IAAY;IACjD,MAAM,OAAO,GAAG,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,qBAAqB,CAAC,CAAC;IACvD,MAAM,OAAO,GAAG,MAAM,GAAG,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,OAAO;QACxB,WAAW,GAAG,IAAI,CAAC;QACnB,yCAAyC;QACzC,MAAM,eAAe,EAAE,CAAC;QACxB,cAAc;QACd,0EAA0E;QAC1E,IAAI;IACN,CAAC,CAAC;IAEF,iFAAiF;IAEjF,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import { promises as fs } from 'node:fs';\nimport { exists } from 'node:fs/promises';\nimport * as path from 'node:path';\nimport { join } from 'node:path';\nimport { PGlite } from '@electric-sql/pglite';\nimport { FileMigrationProvider, type Kysely, Migrator } from 'kysely';\nimport codegen from 'kysely-codegen';\nimport { PGliteDialect } from 'kysely-pglite-dialect';\nimport { appMigrationEpoch } from '../migration';\nimport { getKysely } from '../plugins';\nimport type { DB } from '../v1.generated';\n\nasync function normalizeGeneratedTypes(root: string) {\n const outFile = path.join(root, 'src/v1.generated.ts');\n const current = await Bun.file(outFile).text();\n const next = current\n .replace(\n 'export type Timestamp = ColumnType<Date, Date | string, Date | string>;',\n 'export type Timestamp = ColumnType<Date | string, Date | string, Date | string>;'\n )\n .replace(\n ' managedTeamAccess: Generated<string>;\\n',\n ' managedTeamAccess: Generated<\"all\" | \"assigned\">;\\n'\n )\n .replace(' slug: string;\\n', ' slug: Generated<string>;\\n');\n\n if (next !== current) {\n await Bun.write(outFile, next);\n }\n}\n\nasync function migrate(root: string, client: PGlite) {\n console.log('migrating pglite ....');\n const glob = new Bun.Glob('initial/*.sql');\n for await (const migration of glob.scan(root)) {\n const raw = await Bun.file(join(root, migration)).text();\n // `pg_dump` (v17+) prepends `\\restrict`/`\\unrestrict` psql meta commands\n // which PostgreSQL-compatible parsers (like PGlite) cannot execute.\n const sanitized = raw.replace(/^\\s*\\\\(?:un)?restrict.*$/gim, '');\n await client.exec(sanitized);\n }\n}\n\nasync function migrateKysely(root: string, kysely: Kysely<DB>) {\n console.log('init migrating kysely ....');\n const migrator = new Migrator({\n allowUnorderedMigrations: true,\n db: kysely,\n migrationTableSchema: appMigrationEpoch.tableSchema,\n migrationTableName: appMigrationEpoch.tableName,\n migrationLockTableName: appMigrationEpoch.lockTableName,\n provider: new FileMigrationProvider({\n fs,\n path,\n // This needs to be an absolute path.\n migrationFolder: path.join(root, appMigrationEpoch.folder),\n }),\n });\n\n console.log('migrating kysely ....');\n const { error, results } = await migrator.migrateToLatest().catch(() => {\n console.error('failed to migrate');\n process.exit(1);\n });\n\n for (const it of results ?? []) {\n if (it.status === 'Success') {\n console.log(`migration \"${it.migrationName}\" was executed successfully`);\n } else if (it.status === 'Error') {\n console.error(`failed to execute migration \"${it.migrationName}\"`);\n }\n }\n\n if (error) {\n console.error('failed to migrate');\n console.error(error);\n process.exit(1);\n }\n}\n\nasync function generateDump(root: string, dumpPath: string) {\n const dataExists = await exists(dumpPath).catch(() => false);\n if (!dataExists) {\n console.log('Creating initial dump');\n const main = new PGlite();\n await migrate(root, main).catch(async (err) => {\n console.error('failed to migrate initial dump');\n await Bun.write(\n '../logs/migrate-initial-dump.json',\n JSON.stringify(err as any, null, 2)\n );\n process.exit(1);\n });\n const dialect = new PGliteDialect(main);\n const kysely = getKysely(dialect, {\n repositoryName: 'localTesting',\n log: undefined,\n });\n await migrateKysely(root, kysely).catch(() => {\n console.error('failed to migrate kysely');\n process.exit(1);\n });\n await codegen\n .generate({\n db: kysely,\n outFile: path.join(root, 'src/v1.generated.ts'),\n defaultSchemas: ['xxx'],\n camelCase: true,\n dialect: codegen.getDialect('postgres'),\n })\n .catch(() => {\n console.error('failed to generate kysely');\n process.exit(1);\n });\n await normalizeGeneratedTypes(root);\n const content = await main.dumpDataDir('none').catch(() => {\n console.error('failed to dump data');\n process.exit(1);\n });\n await Bun.write(dumpPath, content).catch(() => {\n console.error('failed to write dump');\n process.exit(1);\n });\n return content;\n }\n return Bun.file(dumpPath);\n}\n\nexport async function createLocalKysely(root: string, dumpPath: string) {\n let isDestroyed = false;\n //const now = performance.now();\n\n const dump = await generateDump(root, dumpPath);\n\n const pglite = new PGlite({ loadDataDir: dump });\n // warm up\n await pglite.sql`SELECT 1`;\n const dialect = new PGliteDialect(pglite);\n const kysely = getKysely(dialect, {\n repositoryName: 'localTesting',\n log: undefined,\n });\n\n const originalDestroy = kysely.destroy.bind(kysely);\n kysely.destroy = async () => {\n if (isDestroyed) return;\n isDestroyed = true;\n // const destroyTime = performance.now();\n await originalDestroy();\n //console.log(\n // `Database destroyed: ${Math.round(performance.now() - destroyTime)}ms`\n //);\n };\n\n // console.log(`Database initialized: ${Math.round(performance.now() - now)}ms`);\n\n return kysely;\n}\n"]}
|
|
@@ -11,6 +11,7 @@ export const root = path.join(__dirname, '../..');
|
|
|
11
11
|
export const dumpPath = path.join(root, '.data.tar');
|
|
12
12
|
async function migrateToLatest(kysely) {
|
|
13
13
|
const migrator = new Migrator({
|
|
14
|
+
allowUnorderedMigrations: true,
|
|
14
15
|
db: kysely,
|
|
15
16
|
migrationTableSchema: appMigrationEpoch.tableSchema,
|
|
16
17
|
migrationTableName: appMigrationEpoch.tableName,
|
|
@@ -26,17 +27,68 @@ async function migrateToLatest(kysely) {
|
|
|
26
27
|
throw error;
|
|
27
28
|
}
|
|
28
29
|
}
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
30
|
+
// Every spec file used to replay this identical bootstrap - migrations, the
|
|
31
|
+
// schema surgery, and the control-plane seed copies - against a freshly loaded
|
|
32
|
+
// snapshot, which measured ~345ms per file against ~185ms for the snapshot load
|
|
33
|
+
// alone. None of it depends on the caller, so it runs once and is cached as a
|
|
34
|
+
// prepared snapshot keyed by everything that determines its content.
|
|
35
|
+
const preparedDumpPrefix = '.data.prepared.';
|
|
36
|
+
let preparedDumpPromise;
|
|
37
|
+
async function preparedDumpKey() {
|
|
38
|
+
const [snapshot, appMigrations, controlPlaneMigrations] = await Promise.all([
|
|
39
|
+
fs.stat(dumpPath),
|
|
40
|
+
fs.readdir(path.join(root, appMigrationEpoch.folder)),
|
|
41
|
+
fs.readdir(path.join(root, 'control-plane-migrations')),
|
|
42
|
+
]);
|
|
43
|
+
const hasher = new Bun.CryptoHasher('sha256');
|
|
44
|
+
hasher.update(`${snapshot.size}:${snapshot.mtimeMs}`);
|
|
45
|
+
hasher.update(appMigrations.sort().join(','));
|
|
46
|
+
hasher.update(controlPlaneMigrations.sort().join(','));
|
|
47
|
+
// Source of the bootstrap itself, so editing the surgery rebuilds the
|
|
48
|
+
// snapshot. Read through toString() rather than the file: this module is also
|
|
49
|
+
// published as CommonJS, where import.meta is a compile error.
|
|
50
|
+
for (const step of [
|
|
51
|
+
buildPreparedDump,
|
|
52
|
+
migrateToLatest,
|
|
53
|
+
ensureDigestFunction,
|
|
54
|
+
ensureGenRandomBytesFunction,
|
|
55
|
+
]) {
|
|
56
|
+
hasher.update(step.toString());
|
|
57
|
+
}
|
|
58
|
+
return hasher.digest('hex').slice(0, 16);
|
|
59
|
+
}
|
|
60
|
+
async function resolvePreparedDump() {
|
|
61
|
+
const key = await preparedDumpKey();
|
|
62
|
+
const target = path.join(root, `${preparedDumpPrefix}${key}.tar`);
|
|
63
|
+
const cached = Bun.file(target);
|
|
64
|
+
if (await cached.exists()) {
|
|
65
|
+
return cached;
|
|
66
|
+
}
|
|
67
|
+
const content = await buildPreparedDump();
|
|
68
|
+
// Sibling workers build this concurrently on a cold cache; rename is atomic,
|
|
69
|
+
// so a reader never observes a half-written snapshot.
|
|
70
|
+
const staging = `${target}.${process.pid}.tmp`;
|
|
71
|
+
await Bun.write(staging, content);
|
|
72
|
+
await fs.rename(staging, target);
|
|
73
|
+
// Only finished snapshots: a sibling worker's staging file also carries the
|
|
74
|
+
// prefix, and removing it would break its rename.
|
|
75
|
+
const current = path.basename(target);
|
|
76
|
+
for (const entry of await fs.readdir(root)) {
|
|
77
|
+
if (entry.startsWith(preparedDumpPrefix) &&
|
|
78
|
+
entry.endsWith('.tar') &&
|
|
79
|
+
entry !== current) {
|
|
80
|
+
await fs.rm(path.join(root, entry), { force: true });
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
return content;
|
|
84
|
+
}
|
|
85
|
+
async function buildPreparedDump() {
|
|
33
86
|
const pglite = new PGlite({
|
|
34
|
-
loadDataDir:
|
|
87
|
+
loadDataDir: Bun.file(dumpPath),
|
|
35
88
|
});
|
|
36
89
|
const dialect = new PGliteDialect(pglite);
|
|
37
90
|
const kysely = getKysely(dialect, {
|
|
38
|
-
repositoryName:
|
|
39
|
-
log: args?.log,
|
|
91
|
+
repositoryName: 'localTestingPrepare',
|
|
40
92
|
});
|
|
41
93
|
await ensureDigestFunction(kysely);
|
|
42
94
|
await ensureGenRandomBytesFunction(kysely);
|
|
@@ -46,7 +98,7 @@ export async function useLocalKysely(args = {}) {
|
|
|
46
98
|
await sql `create schema public`.execute(kysely);
|
|
47
99
|
await sql `create schema core`.execute(kysely);
|
|
48
100
|
const controlPlaneBootstrapKysely = getKysely(dialect, {
|
|
49
|
-
repositoryName:
|
|
101
|
+
repositoryName: 'localTestingPrepare/control-plane-bootstrap',
|
|
50
102
|
});
|
|
51
103
|
const controlPlaneMigrator = new Migrator({
|
|
52
104
|
db: controlPlaneBootstrapKysely,
|
|
@@ -63,6 +115,7 @@ export async function useLocalKysely(args = {}) {
|
|
|
63
115
|
if (controlPlaneMigrationError) {
|
|
64
116
|
throw controlPlaneMigrationError;
|
|
65
117
|
}
|
|
118
|
+
await sql `alter table core.flow set schema public`.execute(controlPlaneBootstrapKysely);
|
|
66
119
|
await sql `alter table core.issue_message_overwrite set schema public`.execute(controlPlaneBootstrapKysely);
|
|
67
120
|
await sql `drop schema core`.execute(controlPlaneBootstrapKysely);
|
|
68
121
|
await sql `alter schema public rename to control_plane`.execute(controlPlaneBootstrapKysely);
|
|
@@ -82,9 +135,39 @@ export async function useLocalKysely(args = {}) {
|
|
|
82
135
|
'control_plane.build_unique_tenant_slug(text,uuid)'::regprocedure
|
|
83
136
|
) into definition;
|
|
84
137
|
execute replace(definition, 'public.', 'control_plane.');
|
|
138
|
+
|
|
139
|
+
select pg_get_functiondef(
|
|
140
|
+
'control_plane.refresh_operation_state(uuid)'::regprocedure
|
|
141
|
+
) into definition;
|
|
142
|
+
execute replace(definition, 'public.', 'control_plane.');
|
|
143
|
+
|
|
144
|
+
select pg_get_functiondef(
|
|
145
|
+
'control_plane.refresh_destructive_job_operation()'::regprocedure
|
|
146
|
+
) into definition;
|
|
147
|
+
execute replace(definition, 'public.', 'control_plane.');
|
|
85
148
|
end;
|
|
86
149
|
$$;
|
|
87
150
|
`.execute(controlPlaneBootstrapKysely);
|
|
151
|
+
// The canonical VRPlatform tenant. Production code falls back to this exact id
|
|
152
|
+
// in getCalculatedBillingPartnerId, so specs need it to exist without each of
|
|
153
|
+
// them creating - and mutating - their own copy of a shared singleton.
|
|
154
|
+
await kysely
|
|
155
|
+
.insertInto('public.tenant')
|
|
156
|
+
.values({
|
|
157
|
+
id: '7bfec41f-aa3f-4602-95d2-f7996e4f0e59',
|
|
158
|
+
name: 'VRPlatform',
|
|
159
|
+
type: 'partner',
|
|
160
|
+
status: 'active',
|
|
161
|
+
isActive: true,
|
|
162
|
+
isGeneralLedger: false,
|
|
163
|
+
isOnboarding: false,
|
|
164
|
+
partnerId: null,
|
|
165
|
+
billingPartnerId: null,
|
|
166
|
+
defaultCurrency: 'usd',
|
|
167
|
+
statementStartAt: new Date('2020-01-01T00:00:00Z'),
|
|
168
|
+
})
|
|
169
|
+
.onConflict((oc) => oc.column('id').doNothing())
|
|
170
|
+
.execute();
|
|
88
171
|
await sql `
|
|
89
172
|
insert into control_plane.app (
|
|
90
173
|
authentication,
|
|
@@ -240,6 +323,25 @@ export async function useLocalKysely(args = {}) {
|
|
|
240
323
|
from public.token
|
|
241
324
|
on conflict (id) do nothing;
|
|
242
325
|
`.execute(controlPlaneBootstrapKysely);
|
|
326
|
+
const content = await pglite.dumpDataDir('none');
|
|
327
|
+
await kysely.destroy();
|
|
328
|
+
return content;
|
|
329
|
+
}
|
|
330
|
+
export async function useLocalKysely(args = {}) {
|
|
331
|
+
let isDestroyed = false;
|
|
332
|
+
preparedDumpPromise ??= resolvePreparedDump();
|
|
333
|
+
const pglite = new PGlite({
|
|
334
|
+
loadDataDir: await preparedDumpPromise,
|
|
335
|
+
});
|
|
336
|
+
// The constructor is lazy. The bootstrap this replaced forced the snapshot to
|
|
337
|
+
// load before returning, so keep that contract: a returned handle is usable,
|
|
338
|
+
// and a bad snapshot fails here instead of inside an unrelated test.
|
|
339
|
+
await pglite.waitReady;
|
|
340
|
+
const dialect = new PGliteDialect(pglite);
|
|
341
|
+
const kysely = getKysely(dialect, {
|
|
342
|
+
repositoryName: args?.repositoryName ?? 'localTesting',
|
|
343
|
+
log: args?.log,
|
|
344
|
+
});
|
|
243
345
|
const controlPlaneKysely = withControlPlaneSchema(getKysely(dialect, {
|
|
244
346
|
repositoryName: `${args.repositoryName ?? 'localTesting'}/control-plane`,
|
|
245
347
|
log: args.log,
|