@dbos-inc/kysely-datasource 5.2.11 → 5.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +7 -2
- package/dist/index.js.map +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/package.json +1 -1
- package/index.ts +0 -379
- package/jest.config.js +0 -8
- package/tests/config.test.ts +0 -51
- package/tests/datasource.test.ts +0 -803
- package/tests/esm-consumer.mts +0 -13
- package/tests/esmtypes.test.ts +0 -27
- package/tests/test-helpers.ts +0 -24
- package/tests/tsconfig.esmcheck.json +0 -11
- package/tsconfig.json +0 -9
package/package.json
CHANGED
package/index.ts
DELETED
|
@@ -1,379 +0,0 @@
|
|
|
1
|
-
/* eslint-disable @typescript-eslint/no-explicit-any */
|
|
2
|
-
// using https://kysely.dev/
|
|
3
|
-
import { DBOS, FunctionName } from '@dbos-inc/dbos-sdk';
|
|
4
|
-
import {
|
|
5
|
-
type DataSourceTransactionHandler,
|
|
6
|
-
isPGRetriableTransactionError,
|
|
7
|
-
DBOSError,
|
|
8
|
-
DBOSStepAlreadyRecordedError,
|
|
9
|
-
DBOSWorkflowConflictError,
|
|
10
|
-
assertStillOwnsWorkflow,
|
|
11
|
-
replayRecordedStep,
|
|
12
|
-
registerTransaction,
|
|
13
|
-
runTransaction,
|
|
14
|
-
DBOSDataSource,
|
|
15
|
-
registerDataSource,
|
|
16
|
-
DataSourceMigrationOptions,
|
|
17
|
-
DataSourceSQLExecutor,
|
|
18
|
-
initializeDataSourceSchemaPG,
|
|
19
|
-
migrateDataSourcePG,
|
|
20
|
-
verifyDataSourcePG,
|
|
21
|
-
} from '@dbos-inc/dbos-sdk/datasource';
|
|
22
|
-
import { AsyncLocalStorage } from 'async_hooks';
|
|
23
|
-
import { Kysely, sql, Transaction, IsolationLevel, PostgresDialect } from 'kysely';
|
|
24
|
-
import { Pool, PoolConfig } from 'pg';
|
|
25
|
-
import { SuperJSON } from 'superjson';
|
|
26
|
-
|
|
27
|
-
export interface transaction_completion {
|
|
28
|
-
workflow_id: string;
|
|
29
|
-
function_num: number;
|
|
30
|
-
output: string | null;
|
|
31
|
-
error: string | null;
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
// Define a database interface for tables used in this datasource
|
|
35
|
-
interface DBOSKyselyTables {
|
|
36
|
-
'dbos.transaction_completion': transaction_completion;
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
export interface TransactionConfig {
|
|
40
|
-
name?: string;
|
|
41
|
-
isolationLevel?: IsolationLevel;
|
|
42
|
-
readOnly?: boolean;
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
interface KyselyDataSourceContext<DB> {
|
|
46
|
-
client: Transaction<DB>;
|
|
47
|
-
owner: KyselyTransactionHandler;
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
const asyncLocalCtx = new AsyncLocalStorage();
|
|
51
|
-
|
|
52
|
-
function kyselyExecutor(db: Kysely<any>): DataSourceSQLExecutor {
|
|
53
|
-
return async (text) => (await sql.raw<Record<string, unknown>>(text).execute(db)).rows;
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
class KyselyTransactionHandler implements DataSourceTransactionHandler {
|
|
57
|
-
#kyselyDBField: Kysely<DBOSKyselyTables>;
|
|
58
|
-
readonly schemaName: string;
|
|
59
|
-
readonly poolConfig: PoolConfig | undefined;
|
|
60
|
-
|
|
61
|
-
constructor(
|
|
62
|
-
readonly name: string,
|
|
63
|
-
poolConfigOrKysely: PoolConfig | Kysely<any>,
|
|
64
|
-
schemaName: string = 'dbos',
|
|
65
|
-
private readonly options: DataSourceMigrationOptions = {},
|
|
66
|
-
) {
|
|
67
|
-
this.schemaName = schemaName;
|
|
68
|
-
|
|
69
|
-
if (poolConfigOrKysely instanceof Kysely) {
|
|
70
|
-
this.#kyselyDBField = poolConfigOrKysely as Kysely<DBOSKyselyTables>;
|
|
71
|
-
} else {
|
|
72
|
-
this.poolConfig = poolConfigOrKysely;
|
|
73
|
-
this.#kyselyDBField = new Kysely<DBOSKyselyTables>({
|
|
74
|
-
dialect: new PostgresDialect({
|
|
75
|
-
pool: new Pool(poolConfigOrKysely),
|
|
76
|
-
}),
|
|
77
|
-
});
|
|
78
|
-
}
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
async initialize(): Promise<void> {
|
|
82
|
-
if (this.poolConfig) {
|
|
83
|
-
const kyselyDB = this.#kyselyDBField;
|
|
84
|
-
this.#kyselyDBField = new Kysely<DBOSKyselyTables>({
|
|
85
|
-
dialect: new PostgresDialect({
|
|
86
|
-
pool: new Pool(this.poolConfig),
|
|
87
|
-
}),
|
|
88
|
-
});
|
|
89
|
-
await kyselyDB?.destroy();
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
if (this.options.runMigrations === false) {
|
|
93
|
-
await verifyDataSourcePG(kyselyExecutor(this.#kyselyDBField), this.schemaName, this.name);
|
|
94
|
-
return;
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
try {
|
|
98
|
-
await this.#kyselyDBField
|
|
99
|
-
.transaction()
|
|
100
|
-
.execute((trx) => migrateDataSourcePG(kyselyExecutor(trx), this.schemaName));
|
|
101
|
-
} catch (err) {
|
|
102
|
-
throw new Error(
|
|
103
|
-
`In initialization of 'KyselyDataSource' ${this.name}: The '${this.schemaName}' transaction schema could not be migrated: ${(err as Error).message}. This should be added to your database migrations.
|
|
104
|
-
See: https://docs.dbos.dev/typescript/tutorials/transaction-tutorial#installing-the-dbos-schema`,
|
|
105
|
-
);
|
|
106
|
-
}
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
async destroy(): Promise<void> {
|
|
110
|
-
await this.#kyselyDBField.destroy();
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
get #kyselyDB() {
|
|
114
|
-
if (!this.#kyselyDBField) {
|
|
115
|
-
throw new Error(`DataSource ${this.name} is not initialized.`);
|
|
116
|
-
}
|
|
117
|
-
return this.#kyselyDBField;
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
async deleteCheckpoints(workflowID: string, startStep: number, beforeCommit?: () => Promise<void>): Promise<void> {
|
|
121
|
-
await this.#kyselyDB.transaction().execute(async (client) => {
|
|
122
|
-
await client
|
|
123
|
-
.deleteFrom('dbos.transaction_completion')
|
|
124
|
-
.where('workflow_id', '=', workflowID)
|
|
125
|
-
.where('function_num', '>=', startStep)
|
|
126
|
-
.execute();
|
|
127
|
-
await beforeCommit?.();
|
|
128
|
-
});
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
async #checkExecution(
|
|
132
|
-
workflowID: string,
|
|
133
|
-
stepID: number,
|
|
134
|
-
): Promise<{ output: string | null } | { error: string } | undefined> {
|
|
135
|
-
const result = await this.#kyselyDB
|
|
136
|
-
.selectFrom('dbos.transaction_completion')
|
|
137
|
-
.select(['output', 'error'])
|
|
138
|
-
.where('workflow_id', '=', workflowID)
|
|
139
|
-
.where('function_num', '=', stepID)
|
|
140
|
-
.executeTakeFirst();
|
|
141
|
-
if (result === undefined) {
|
|
142
|
-
return undefined;
|
|
143
|
-
}
|
|
144
|
-
const { output, error } = result;
|
|
145
|
-
return error !== null ? { error } : { output };
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
async #recordError(workflowID: string, stepID: number, error: string): Promise<void> {
|
|
149
|
-
const inserted = await this.#kyselyDB
|
|
150
|
-
.insertInto('dbos.transaction_completion')
|
|
151
|
-
.values({
|
|
152
|
-
workflow_id: workflowID,
|
|
153
|
-
function_num: stepID,
|
|
154
|
-
error,
|
|
155
|
-
output: null,
|
|
156
|
-
})
|
|
157
|
-
.onConflict((oc) => oc.columns(['workflow_id', 'function_num']).doNothing())
|
|
158
|
-
.returning('workflow_id')
|
|
159
|
-
.executeTakeFirst();
|
|
160
|
-
if (inserted === undefined) {
|
|
161
|
-
throw new DBOSStepAlreadyRecordedError(workflowID, stepID);
|
|
162
|
-
}
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
// A duplicate execution won the race, so its recorded outcome is the durable one.
|
|
166
|
-
async #replayConflictingStep<Return>(workflowID: string, stepID: number): Promise<Return> {
|
|
167
|
-
const recorded = await this.#checkExecution(workflowID, stepID);
|
|
168
|
-
if (recorded === undefined) {
|
|
169
|
-
throw new DBOSError(
|
|
170
|
-
`Step ${stepID} of workflow ${workflowID} conflicted with a concurrent execution, but no recorded outcome was found`,
|
|
171
|
-
);
|
|
172
|
-
}
|
|
173
|
-
return replayRecordedStep<Return>(recorded);
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
static async #recordOutput(
|
|
177
|
-
client: Transaction<DBOSKyselyTables>,
|
|
178
|
-
workflowID: string,
|
|
179
|
-
stepID: number,
|
|
180
|
-
output: string | null,
|
|
181
|
-
): Promise<void> {
|
|
182
|
-
const inserted = await client
|
|
183
|
-
.insertInto('dbos.transaction_completion')
|
|
184
|
-
.values({
|
|
185
|
-
workflow_id: workflowID,
|
|
186
|
-
function_num: stepID,
|
|
187
|
-
output,
|
|
188
|
-
error: null,
|
|
189
|
-
})
|
|
190
|
-
.onConflict((oc) => oc.columns(['workflow_id', 'function_num']).doNothing())
|
|
191
|
-
.returning('workflow_id')
|
|
192
|
-
.executeTakeFirst();
|
|
193
|
-
if (inserted === undefined) {
|
|
194
|
-
throw new DBOSStepAlreadyRecordedError(workflowID, stepID);
|
|
195
|
-
}
|
|
196
|
-
// Holding this step's row, so a later owner's insert waits on our commit.
|
|
197
|
-
await assertStillOwnsWorkflow(workflowID);
|
|
198
|
-
}
|
|
199
|
-
|
|
200
|
-
async invokeTransactionFunction<This, Args extends unknown[], Return>(
|
|
201
|
-
config: TransactionConfig | undefined,
|
|
202
|
-
target: This,
|
|
203
|
-
func: (this: This, ...args: Args) => Promise<Return>,
|
|
204
|
-
...args: Args
|
|
205
|
-
): Promise<Return> {
|
|
206
|
-
const workflowID = DBOS.workflowID;
|
|
207
|
-
const stepID = DBOS.stepID;
|
|
208
|
-
if (workflowID !== undefined && stepID === undefined) {
|
|
209
|
-
throw new Error('DBOS.stepID is undefined inside a workflow.');
|
|
210
|
-
}
|
|
211
|
-
|
|
212
|
-
const readOnly = config?.readOnly ?? false;
|
|
213
|
-
const saveResults = !readOnly && workflowID !== undefined;
|
|
214
|
-
|
|
215
|
-
// Retry loop if appropriate
|
|
216
|
-
let retryWaitMS = 1;
|
|
217
|
-
const backoffFactor = 1.5;
|
|
218
|
-
const maxRetryWaitMS = 2000; // Maximum wait 2 seconds.
|
|
219
|
-
|
|
220
|
-
while (true) {
|
|
221
|
-
// Check to see if this tx has already been executed
|
|
222
|
-
const previousResult = saveResults ? await this.#checkExecution(workflowID, stepID!) : undefined;
|
|
223
|
-
if (previousResult) {
|
|
224
|
-
return replayRecordedStep<Return>(previousResult);
|
|
225
|
-
}
|
|
226
|
-
|
|
227
|
-
try {
|
|
228
|
-
let trx = this.#kyselyDB.transaction();
|
|
229
|
-
if (config?.readOnly) {
|
|
230
|
-
trx = trx.setAccessMode('read only');
|
|
231
|
-
}
|
|
232
|
-
if (config?.isolationLevel) {
|
|
233
|
-
trx = trx.setIsolationLevel(config.isolationLevel);
|
|
234
|
-
}
|
|
235
|
-
const result = await trx.execute(async (client) => {
|
|
236
|
-
// execute user's transaction function
|
|
237
|
-
const result = await asyncLocalCtx.run({ client, owner: this }, async () => {
|
|
238
|
-
return (await func.call(target, ...args)) as Return;
|
|
239
|
-
});
|
|
240
|
-
|
|
241
|
-
// save the output of read/write transactions
|
|
242
|
-
if (saveResults) {
|
|
243
|
-
await KyselyTransactionHandler.#recordOutput(client, workflowID, stepID!, SuperJSON.stringify(result));
|
|
244
|
-
}
|
|
245
|
-
|
|
246
|
-
return result;
|
|
247
|
-
});
|
|
248
|
-
|
|
249
|
-
return result;
|
|
250
|
-
} catch (error) {
|
|
251
|
-
if (saveResults && error instanceof DBOSStepAlreadyRecordedError) {
|
|
252
|
-
return await this.#replayConflictingStep<Return>(workflowID, stepID!);
|
|
253
|
-
}
|
|
254
|
-
// The new owner wins; recording an error here would replay it as this step's outcome.
|
|
255
|
-
if (error instanceof DBOSWorkflowConflictError) throw error;
|
|
256
|
-
if (isPGRetriableTransactionError(error)) {
|
|
257
|
-
DBOS.span?.addEvent('TXN SERIALIZATION FAILURE', { retryWaitMillis: retryWaitMS }, performance.now());
|
|
258
|
-
await new Promise((resolve) => setTimeout(resolve, retryWaitMS));
|
|
259
|
-
retryWaitMS = Math.min(retryWaitMS * backoffFactor, maxRetryWaitMS);
|
|
260
|
-
continue;
|
|
261
|
-
} else {
|
|
262
|
-
if (saveResults) {
|
|
263
|
-
const message = SuperJSON.stringify(error);
|
|
264
|
-
try {
|
|
265
|
-
await this.#recordError(workflowID, stepID!, message);
|
|
266
|
-
} catch (recordError) {
|
|
267
|
-
if (recordError instanceof DBOSStepAlreadyRecordedError) {
|
|
268
|
-
return await this.#replayConflictingStep<Return>(workflowID, stepID!);
|
|
269
|
-
}
|
|
270
|
-
throw recordError;
|
|
271
|
-
}
|
|
272
|
-
}
|
|
273
|
-
|
|
274
|
-
throw error;
|
|
275
|
-
}
|
|
276
|
-
}
|
|
277
|
-
}
|
|
278
|
-
}
|
|
279
|
-
}
|
|
280
|
-
|
|
281
|
-
export class KyselyDataSource<DB> implements DBOSDataSource<TransactionConfig> {
|
|
282
|
-
static #getClient<DB>(p?: KyselyTransactionHandler): Kysely<DB> {
|
|
283
|
-
if (!DBOS.isInTransaction()) {
|
|
284
|
-
throw new Error('invalid use of KyselyDataSource.client outside of a DBOS transaction.');
|
|
285
|
-
}
|
|
286
|
-
const ctx = asyncLocalCtx.getStore() as KyselyDataSourceContext<DB>;
|
|
287
|
-
if (!ctx) {
|
|
288
|
-
throw new Error('invalid use of KyselyDataSource.client outside of a DBOS transaction.');
|
|
289
|
-
}
|
|
290
|
-
if (p && p !== ctx.owner) throw new Error('Request of `KyselyDataSource.client` from the wrong object.');
|
|
291
|
-
return ctx.client;
|
|
292
|
-
}
|
|
293
|
-
|
|
294
|
-
get client(): Kysely<DB> {
|
|
295
|
-
return KyselyDataSource.#getClient(this.#provider);
|
|
296
|
-
}
|
|
297
|
-
|
|
298
|
-
/**
|
|
299
|
-
* Create or migrate the DBOS transaction schema, typically with a privileged role,
|
|
300
|
-
* optionally granting `applicationRole` the minimal permissions to use it.
|
|
301
|
-
*/
|
|
302
|
-
static async initializeDBOSSchema(
|
|
303
|
-
poolConfig: PoolConfig,
|
|
304
|
-
schemaName: string = 'dbos',
|
|
305
|
-
options: { applicationRole?: string } = {},
|
|
306
|
-
) {
|
|
307
|
-
const client = new Kysely({
|
|
308
|
-
dialect: new PostgresDialect({
|
|
309
|
-
pool: new Pool(poolConfig),
|
|
310
|
-
}),
|
|
311
|
-
});
|
|
312
|
-
try {
|
|
313
|
-
await client
|
|
314
|
-
.transaction()
|
|
315
|
-
.execute((trx) => initializeDataSourceSchemaPG(kyselyExecutor(trx), schemaName, options.applicationRole));
|
|
316
|
-
} finally {
|
|
317
|
-
await client.destroy();
|
|
318
|
-
}
|
|
319
|
-
}
|
|
320
|
-
|
|
321
|
-
static async uninitializeDBOSSchema(poolConfig: PoolConfig, schemaName: string = 'dbos') {
|
|
322
|
-
const client = new Kysely({
|
|
323
|
-
dialect: new PostgresDialect({
|
|
324
|
-
pool: new Pool(poolConfig),
|
|
325
|
-
}),
|
|
326
|
-
});
|
|
327
|
-
await sql
|
|
328
|
-
.raw(
|
|
329
|
-
`DROP TABLE IF EXISTS "${schemaName}".transaction_completion; DROP SCHEMA IF EXISTS "${schemaName}" CASCADE;`,
|
|
330
|
-
)
|
|
331
|
-
.execute(client);
|
|
332
|
-
await client.destroy();
|
|
333
|
-
}
|
|
334
|
-
|
|
335
|
-
#provider: KyselyTransactionHandler;
|
|
336
|
-
|
|
337
|
-
constructor(
|
|
338
|
-
readonly name: string,
|
|
339
|
-
poolConfigOrKysely: PoolConfig | Kysely<any>,
|
|
340
|
-
schemaName: string = 'dbos',
|
|
341
|
-
options: DataSourceMigrationOptions = {},
|
|
342
|
-
) {
|
|
343
|
-
this.#provider = new KyselyTransactionHandler(name, poolConfigOrKysely, schemaName, options);
|
|
344
|
-
registerDataSource(this.#provider);
|
|
345
|
-
}
|
|
346
|
-
|
|
347
|
-
async runTransaction<R>(func: () => Promise<R>, config?: TransactionConfig) {
|
|
348
|
-
return await runTransaction(func, config?.name ?? func.name, { dsName: this.name, config });
|
|
349
|
-
}
|
|
350
|
-
|
|
351
|
-
registerTransaction<This, Args extends unknown[], Return>(
|
|
352
|
-
func: (this: This, ...args: Args) => Promise<Return>,
|
|
353
|
-
config?: TransactionConfig & FunctionName,
|
|
354
|
-
): (this: This, ...args: Args) => Promise<Return> {
|
|
355
|
-
return registerTransaction(this.name, func, config);
|
|
356
|
-
}
|
|
357
|
-
|
|
358
|
-
transaction(config?: TransactionConfig) {
|
|
359
|
-
// eslint-disable-next-line @typescript-eslint/no-this-alias
|
|
360
|
-
const ds = this;
|
|
361
|
-
return function decorator<This, Args extends unknown[], Return>(
|
|
362
|
-
target: object,
|
|
363
|
-
propertyKey: PropertyKey,
|
|
364
|
-
descriptor: TypedPropertyDescriptor<(this: This, ...args: Args) => Promise<Return>>,
|
|
365
|
-
) {
|
|
366
|
-
if (!descriptor.value) {
|
|
367
|
-
throw Error('Use of decorator when original method is undefined');
|
|
368
|
-
}
|
|
369
|
-
|
|
370
|
-
descriptor.value = ds.registerTransaction(descriptor.value, {
|
|
371
|
-
...config,
|
|
372
|
-
name: config?.name ?? String(propertyKey),
|
|
373
|
-
ctorOrProto: target,
|
|
374
|
-
});
|
|
375
|
-
|
|
376
|
-
return descriptor;
|
|
377
|
-
};
|
|
378
|
-
}
|
|
379
|
-
}
|
package/jest.config.js
DELETED
package/tests/config.test.ts
DELETED
|
@@ -1,51 +0,0 @@
|
|
|
1
|
-
import { Client, Pool, PoolClient } from 'pg';
|
|
2
|
-
import { KyselyDataSource } from '..';
|
|
3
|
-
import { dropDB, ensureDB } from './test-helpers';
|
|
4
|
-
|
|
5
|
-
const config = { user: 'postgres', database: 'kysely_ds_config_test' };
|
|
6
|
-
|
|
7
|
-
describe('KyselyDataSource.initializeDBOSSchema', () => {
|
|
8
|
-
beforeEach(async () => {
|
|
9
|
-
const client = new Client({ ...config, database: 'postgres' });
|
|
10
|
-
try {
|
|
11
|
-
await client.connect();
|
|
12
|
-
await dropDB(client, config.database, true);
|
|
13
|
-
await ensureDB(client, config.database);
|
|
14
|
-
} finally {
|
|
15
|
-
await client.end();
|
|
16
|
-
}
|
|
17
|
-
});
|
|
18
|
-
|
|
19
|
-
async function queryTxCompletionTable(client: PoolClient) {
|
|
20
|
-
const result = await client.query(
|
|
21
|
-
'SELECT workflow_id, function_num, output, error FROM dbos.transaction_completion',
|
|
22
|
-
);
|
|
23
|
-
return result.rowCount;
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
async function txCompletionTableExists(client: PoolClient) {
|
|
27
|
-
const result = await client.query<{ exists: boolean }>(
|
|
28
|
-
"SELECT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'dbos' AND table_name = 'transaction_completion');",
|
|
29
|
-
);
|
|
30
|
-
if (result.rowCount !== 1) throw new Error(`unexpected rowcount ${result.rowCount}`);
|
|
31
|
-
return result.rows[0].exists;
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
test('initializeDBOSSchema', async () => {
|
|
35
|
-
const db = new Pool(config);
|
|
36
|
-
await KyselyDataSource.initializeDBOSSchema(config);
|
|
37
|
-
|
|
38
|
-
try {
|
|
39
|
-
const client = await db.connect();
|
|
40
|
-
await expect(txCompletionTableExists(client)).resolves.toBe(true);
|
|
41
|
-
await expect(queryTxCompletionTable(client)).resolves.toEqual(0);
|
|
42
|
-
|
|
43
|
-
await KyselyDataSource.uninitializeDBOSSchema(config);
|
|
44
|
-
|
|
45
|
-
await expect(txCompletionTableExists(client)).resolves.toBe(false);
|
|
46
|
-
client.release();
|
|
47
|
-
} finally {
|
|
48
|
-
await db.end();
|
|
49
|
-
}
|
|
50
|
-
});
|
|
51
|
-
});
|