@dudousxd/nestjs-durable-store-mikro-orm 0.0.0-beta-20260701163515
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/LICENSE +21 -0
- package/dist/index.cjs +1239 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +207 -0
- package/dist/index.d.ts +207 -0
- package/dist/index.js +1206 -0
- package/dist/index.js.map +1 -0
- package/package.json +54 -0
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,1239 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
|
7
|
+
var __export = (target, all) => {
|
|
8
|
+
for (var name in all)
|
|
9
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
10
|
+
};
|
|
11
|
+
var __copyProps = (to, from, except, desc) => {
|
|
12
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
13
|
+
for (let key of __getOwnPropNames(from))
|
|
14
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
15
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
16
|
+
}
|
|
17
|
+
return to;
|
|
18
|
+
};
|
|
19
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
20
|
+
|
|
21
|
+
// src/index.ts
|
|
22
|
+
var index_exports = {};
|
|
23
|
+
__export(index_exports, {
|
|
24
|
+
BufferedSignalEntity: () => BufferedSignalEntity,
|
|
25
|
+
ENTITIES: () => ENTITIES,
|
|
26
|
+
MikroOrmStateStore: () => MikroOrmStateStore,
|
|
27
|
+
RunAttributeEntity: () => RunAttributeEntity,
|
|
28
|
+
SignalWaiterEntity: () => SignalWaiterEntity,
|
|
29
|
+
StepCheckpointEntity: () => StepCheckpointEntity,
|
|
30
|
+
WorkflowRunEntity: () => WorkflowRunEntity,
|
|
31
|
+
durableEntities: () => durableEntities,
|
|
32
|
+
ensureMikroOrmDurableSchema: () => ensureMikroOrmDurableSchema
|
|
33
|
+
});
|
|
34
|
+
module.exports = __toCommonJS(index_exports);
|
|
35
|
+
|
|
36
|
+
// src/entities.ts
|
|
37
|
+
var import_core = require("@mikro-orm/core");
|
|
38
|
+
function snakeCase(property) {
|
|
39
|
+
return property.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`);
|
|
40
|
+
}
|
|
41
|
+
__name(snakeCase, "snakeCase");
|
|
42
|
+
function columnNamer(naming) {
|
|
43
|
+
if (naming === "snake_case") return snakeCase;
|
|
44
|
+
if (naming === "preserve") return (property) => property;
|
|
45
|
+
return naming;
|
|
46
|
+
}
|
|
47
|
+
__name(columnNamer, "columnNamer");
|
|
48
|
+
var WorkflowRunEntity = class {
|
|
49
|
+
static {
|
|
50
|
+
__name(this, "WorkflowRunEntity");
|
|
51
|
+
}
|
|
52
|
+
id;
|
|
53
|
+
workflow;
|
|
54
|
+
workflowVersion;
|
|
55
|
+
status;
|
|
56
|
+
input;
|
|
57
|
+
output;
|
|
58
|
+
error;
|
|
59
|
+
wakeAt;
|
|
60
|
+
lockedBy;
|
|
61
|
+
lockedUntil;
|
|
62
|
+
awaitingDecisionTaskId;
|
|
63
|
+
recoveryAttempts;
|
|
64
|
+
tags;
|
|
65
|
+
searchAttributes;
|
|
66
|
+
priority;
|
|
67
|
+
namespace;
|
|
68
|
+
createdAt;
|
|
69
|
+
updatedAt;
|
|
70
|
+
};
|
|
71
|
+
var StepCheckpointEntity = class {
|
|
72
|
+
static {
|
|
73
|
+
__name(this, "StepCheckpointEntity");
|
|
74
|
+
}
|
|
75
|
+
runId;
|
|
76
|
+
seq;
|
|
77
|
+
name;
|
|
78
|
+
kind;
|
|
79
|
+
stepId;
|
|
80
|
+
status;
|
|
81
|
+
input;
|
|
82
|
+
output;
|
|
83
|
+
error;
|
|
84
|
+
events;
|
|
85
|
+
attempts;
|
|
86
|
+
workerGroup;
|
|
87
|
+
parallelGroup;
|
|
88
|
+
wakeAt;
|
|
89
|
+
enqueuedAt;
|
|
90
|
+
startedAt;
|
|
91
|
+
finishedAt;
|
|
92
|
+
};
|
|
93
|
+
var RunAttributeEntity = class {
|
|
94
|
+
static {
|
|
95
|
+
__name(this, "RunAttributeEntity");
|
|
96
|
+
}
|
|
97
|
+
runId;
|
|
98
|
+
key;
|
|
99
|
+
strValue;
|
|
100
|
+
numValue;
|
|
101
|
+
};
|
|
102
|
+
var SignalWaiterEntity = class {
|
|
103
|
+
static {
|
|
104
|
+
__name(this, "SignalWaiterEntity");
|
|
105
|
+
}
|
|
106
|
+
token;
|
|
107
|
+
runId;
|
|
108
|
+
seq;
|
|
109
|
+
parallelGroup;
|
|
110
|
+
};
|
|
111
|
+
var BufferedSignalEntity = class {
|
|
112
|
+
static {
|
|
113
|
+
__name(this, "BufferedSignalEntity");
|
|
114
|
+
}
|
|
115
|
+
id;
|
|
116
|
+
token;
|
|
117
|
+
payload;
|
|
118
|
+
};
|
|
119
|
+
function namespaceFilterCond(args) {
|
|
120
|
+
if (args.namespace === void 0) return {};
|
|
121
|
+
return {
|
|
122
|
+
namespace: args.namespace
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
__name(namespaceFilterCond, "namespaceFilterCond");
|
|
126
|
+
function durableEntities(options = {}) {
|
|
127
|
+
const col = columnNamer(options.naming ?? "snake_case");
|
|
128
|
+
const workflowRuns = new import_core.EntitySchema({
|
|
129
|
+
class: WorkflowRunEntity,
|
|
130
|
+
tableName: "durable_workflow_runs",
|
|
131
|
+
// Global filter: confines every read to the tenant's namespace when the store is scoped.
|
|
132
|
+
// The `cond` returns `{}` (no-op) when the `namespace` arg is `undefined`, so an unscoped
|
|
133
|
+
// (operator / control-plane) store sees all rows unchanged — existing behaviour is preserved.
|
|
134
|
+
filters: {
|
|
135
|
+
namespace: {
|
|
136
|
+
name: "namespace",
|
|
137
|
+
cond: namespaceFilterCond,
|
|
138
|
+
default: true
|
|
139
|
+
}
|
|
140
|
+
},
|
|
141
|
+
// Indexes mirror the Prisma adapter so a store swap keeps the same plan. The poller hits these
|
|
142
|
+
// every tick: `(status, wakeAt)` serves both the due-timer scan (status='suspended' AND wakeAt<=now)
|
|
143
|
+
// and, via its `status` prefix, the pending/incomplete status lookups; `(workflow, status)` serves
|
|
144
|
+
// the per-workflow timeout sweep. Without them every poll is a full scan of a table that only grows.
|
|
145
|
+
indexes: [
|
|
146
|
+
{
|
|
147
|
+
name: "durable_workflow_runs_status_wake_at_idx",
|
|
148
|
+
properties: [
|
|
149
|
+
"status",
|
|
150
|
+
"wakeAt"
|
|
151
|
+
]
|
|
152
|
+
},
|
|
153
|
+
{
|
|
154
|
+
name: "durable_workflow_runs_workflow_status_idx",
|
|
155
|
+
properties: [
|
|
156
|
+
"workflow",
|
|
157
|
+
"status"
|
|
158
|
+
]
|
|
159
|
+
},
|
|
160
|
+
{
|
|
161
|
+
name: "durable_workflow_runs_namespace_status_idx",
|
|
162
|
+
properties: [
|
|
163
|
+
"namespace",
|
|
164
|
+
"status",
|
|
165
|
+
"createdAt"
|
|
166
|
+
]
|
|
167
|
+
}
|
|
168
|
+
],
|
|
169
|
+
properties: {
|
|
170
|
+
id: {
|
|
171
|
+
type: "string",
|
|
172
|
+
primary: true,
|
|
173
|
+
fieldName: col("id")
|
|
174
|
+
},
|
|
175
|
+
workflow: {
|
|
176
|
+
type: "string",
|
|
177
|
+
fieldName: col("workflow")
|
|
178
|
+
},
|
|
179
|
+
workflowVersion: {
|
|
180
|
+
type: "string",
|
|
181
|
+
fieldName: col("workflowVersion")
|
|
182
|
+
},
|
|
183
|
+
status: {
|
|
184
|
+
type: "string",
|
|
185
|
+
fieldName: col("status")
|
|
186
|
+
},
|
|
187
|
+
input: {
|
|
188
|
+
type: "json",
|
|
189
|
+
nullable: true,
|
|
190
|
+
fieldName: col("input")
|
|
191
|
+
},
|
|
192
|
+
output: {
|
|
193
|
+
type: "json",
|
|
194
|
+
nullable: true,
|
|
195
|
+
fieldName: col("output")
|
|
196
|
+
},
|
|
197
|
+
error: {
|
|
198
|
+
type: "json",
|
|
199
|
+
nullable: true,
|
|
200
|
+
fieldName: col("error")
|
|
201
|
+
},
|
|
202
|
+
wakeAt: {
|
|
203
|
+
type: "Date",
|
|
204
|
+
nullable: true,
|
|
205
|
+
fieldName: col("wakeAt")
|
|
206
|
+
},
|
|
207
|
+
lockedBy: {
|
|
208
|
+
type: "string",
|
|
209
|
+
nullable: true,
|
|
210
|
+
fieldName: col("lockedBy")
|
|
211
|
+
},
|
|
212
|
+
lockedUntil: {
|
|
213
|
+
type: "Date",
|
|
214
|
+
nullable: true,
|
|
215
|
+
fieldName: col("lockedUntil")
|
|
216
|
+
},
|
|
217
|
+
// REMOTE turn the engine suspended on awaiting a decision; matched by completeRemoteDecision so
|
|
218
|
+
// only the currently-awaited turn's decision is applied. Nullable: cleared when a decision lands.
|
|
219
|
+
awaitingDecisionTaskId: {
|
|
220
|
+
type: "string",
|
|
221
|
+
nullable: true,
|
|
222
|
+
fieldName: col("awaitingDecisionTaskId")
|
|
223
|
+
},
|
|
224
|
+
recoveryAttempts: {
|
|
225
|
+
type: "integer",
|
|
226
|
+
nullable: true,
|
|
227
|
+
fieldName: col("recoveryAttempts")
|
|
228
|
+
},
|
|
229
|
+
tags: {
|
|
230
|
+
type: "json",
|
|
231
|
+
nullable: true,
|
|
232
|
+
fieldName: col("tags")
|
|
233
|
+
},
|
|
234
|
+
searchAttributes: {
|
|
235
|
+
type: "json",
|
|
236
|
+
nullable: true,
|
|
237
|
+
fieldName: col("searchAttributes")
|
|
238
|
+
},
|
|
239
|
+
priority: {
|
|
240
|
+
type: "integer",
|
|
241
|
+
nullable: true,
|
|
242
|
+
fieldName: col("priority")
|
|
243
|
+
},
|
|
244
|
+
namespace: {
|
|
245
|
+
type: "string",
|
|
246
|
+
default: "default",
|
|
247
|
+
fieldName: col("namespace")
|
|
248
|
+
},
|
|
249
|
+
createdAt: {
|
|
250
|
+
type: "Date",
|
|
251
|
+
fieldName: col("createdAt")
|
|
252
|
+
},
|
|
253
|
+
updatedAt: {
|
|
254
|
+
type: "Date",
|
|
255
|
+
fieldName: col("updatedAt")
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
});
|
|
259
|
+
const stepCheckpoints = new import_core.EntitySchema({
|
|
260
|
+
class: StepCheckpointEntity,
|
|
261
|
+
tableName: "durable_step_checkpoints",
|
|
262
|
+
properties: {
|
|
263
|
+
runId: {
|
|
264
|
+
type: "string",
|
|
265
|
+
primary: true,
|
|
266
|
+
fieldName: col("runId")
|
|
267
|
+
},
|
|
268
|
+
seq: {
|
|
269
|
+
type: "integer",
|
|
270
|
+
primary: true,
|
|
271
|
+
fieldName: col("seq")
|
|
272
|
+
},
|
|
273
|
+
name: {
|
|
274
|
+
type: "string",
|
|
275
|
+
fieldName: col("name")
|
|
276
|
+
},
|
|
277
|
+
kind: {
|
|
278
|
+
type: "string",
|
|
279
|
+
fieldName: col("kind")
|
|
280
|
+
},
|
|
281
|
+
stepId: {
|
|
282
|
+
type: "string",
|
|
283
|
+
fieldName: col("stepId")
|
|
284
|
+
},
|
|
285
|
+
status: {
|
|
286
|
+
type: "string",
|
|
287
|
+
fieldName: col("status")
|
|
288
|
+
},
|
|
289
|
+
input: {
|
|
290
|
+
type: "json",
|
|
291
|
+
nullable: true,
|
|
292
|
+
fieldName: col("input")
|
|
293
|
+
},
|
|
294
|
+
output: {
|
|
295
|
+
type: "json",
|
|
296
|
+
nullable: true,
|
|
297
|
+
fieldName: col("output")
|
|
298
|
+
},
|
|
299
|
+
error: {
|
|
300
|
+
type: "json",
|
|
301
|
+
nullable: true,
|
|
302
|
+
fieldName: col("error")
|
|
303
|
+
},
|
|
304
|
+
events: {
|
|
305
|
+
type: "json",
|
|
306
|
+
nullable: true,
|
|
307
|
+
fieldName: col("events")
|
|
308
|
+
},
|
|
309
|
+
attempts: {
|
|
310
|
+
type: "integer",
|
|
311
|
+
fieldName: col("attempts")
|
|
312
|
+
},
|
|
313
|
+
workerGroup: {
|
|
314
|
+
type: "string",
|
|
315
|
+
nullable: true,
|
|
316
|
+
fieldName: col("workerGroup")
|
|
317
|
+
},
|
|
318
|
+
// A ctx.gather/ctx.all fan tags every sibling step with the same group string so the dashboard
|
|
319
|
+
// renders them as one "ran in parallel" group. The core engine sets it (incl. from a remote
|
|
320
|
+
// worker's recordStep), but it was never persisted here — so the fan always rendered as N
|
|
321
|
+
// sequential singles. Nullable: only fan-out steps carry it.
|
|
322
|
+
parallelGroup: {
|
|
323
|
+
type: "string",
|
|
324
|
+
nullable: true,
|
|
325
|
+
fieldName: col("parallelGroup")
|
|
326
|
+
},
|
|
327
|
+
wakeAt: {
|
|
328
|
+
type: "Date",
|
|
329
|
+
nullable: true,
|
|
330
|
+
fieldName: col("wakeAt")
|
|
331
|
+
},
|
|
332
|
+
enqueuedAt: {
|
|
333
|
+
type: "Date",
|
|
334
|
+
nullable: true,
|
|
335
|
+
fieldName: col("enqueuedAt")
|
|
336
|
+
},
|
|
337
|
+
startedAt: {
|
|
338
|
+
type: "Date",
|
|
339
|
+
fieldName: col("startedAt")
|
|
340
|
+
},
|
|
341
|
+
finishedAt: {
|
|
342
|
+
type: "Date",
|
|
343
|
+
fieldName: col("finishedAt")
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
});
|
|
347
|
+
const runAttributes = new import_core.EntitySchema({
|
|
348
|
+
class: RunAttributeEntity,
|
|
349
|
+
tableName: "durable_run_attributes",
|
|
350
|
+
// The search-attribute EXISTS join (see the class docstring) pushes equality/range predicates down
|
|
351
|
+
// onto `(key, numValue)` / `(key, strValue)`; mirror the Prisma adapter so those scans stay indexed.
|
|
352
|
+
indexes: [
|
|
353
|
+
{
|
|
354
|
+
name: "durable_run_attributes_key_num_idx",
|
|
355
|
+
properties: [
|
|
356
|
+
"key",
|
|
357
|
+
"numValue"
|
|
358
|
+
]
|
|
359
|
+
},
|
|
360
|
+
{
|
|
361
|
+
name: "durable_run_attributes_key_str_idx",
|
|
362
|
+
properties: [
|
|
363
|
+
"key",
|
|
364
|
+
"strValue"
|
|
365
|
+
]
|
|
366
|
+
}
|
|
367
|
+
],
|
|
368
|
+
properties: {
|
|
369
|
+
runId: {
|
|
370
|
+
type: "string",
|
|
371
|
+
primary: true,
|
|
372
|
+
fieldName: col("runId")
|
|
373
|
+
},
|
|
374
|
+
key: {
|
|
375
|
+
type: "string",
|
|
376
|
+
primary: true,
|
|
377
|
+
fieldName: col("key")
|
|
378
|
+
},
|
|
379
|
+
strValue: {
|
|
380
|
+
type: "string",
|
|
381
|
+
nullable: true,
|
|
382
|
+
fieldName: col("strValue")
|
|
383
|
+
},
|
|
384
|
+
// `float`/`double` is portable across SQLite/MySQL/Postgres for numeric range scans.
|
|
385
|
+
numValue: {
|
|
386
|
+
type: "float",
|
|
387
|
+
nullable: true,
|
|
388
|
+
fieldName: col("numValue")
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
});
|
|
392
|
+
const signalWaiters = new import_core.EntitySchema({
|
|
393
|
+
class: SignalWaiterEntity,
|
|
394
|
+
tableName: "durable_signal_waiters",
|
|
395
|
+
properties: {
|
|
396
|
+
token: {
|
|
397
|
+
type: "string",
|
|
398
|
+
primary: true,
|
|
399
|
+
fieldName: col("token")
|
|
400
|
+
},
|
|
401
|
+
runId: {
|
|
402
|
+
type: "string",
|
|
403
|
+
fieldName: col("runId")
|
|
404
|
+
},
|
|
405
|
+
seq: {
|
|
406
|
+
type: "integer",
|
|
407
|
+
fieldName: col("seq")
|
|
408
|
+
},
|
|
409
|
+
// A ctx.gather_children/ctx.all child fan-out tags every awaited child with the same group; the
|
|
410
|
+
// engine threads it onto the waiter so the resolving `signal:child:` checkpoint carries it and the
|
|
411
|
+
// dashboard renders the fan as one parallel group. Nullable: only fan-out child waiters carry it.
|
|
412
|
+
parallelGroup: {
|
|
413
|
+
type: "string",
|
|
414
|
+
nullable: true,
|
|
415
|
+
fieldName: col("parallelGroup")
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
});
|
|
419
|
+
const bufferedSignals = new import_core.EntitySchema({
|
|
420
|
+
class: BufferedSignalEntity,
|
|
421
|
+
tableName: "durable_buffered_signals",
|
|
422
|
+
properties: {
|
|
423
|
+
id: {
|
|
424
|
+
type: "integer",
|
|
425
|
+
primary: true,
|
|
426
|
+
autoincrement: true,
|
|
427
|
+
fieldName: col("id")
|
|
428
|
+
},
|
|
429
|
+
token: {
|
|
430
|
+
type: "string",
|
|
431
|
+
index: true,
|
|
432
|
+
fieldName: col("token")
|
|
433
|
+
},
|
|
434
|
+
payload: {
|
|
435
|
+
type: "json",
|
|
436
|
+
nullable: true,
|
|
437
|
+
fieldName: col("payload")
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
});
|
|
441
|
+
return [
|
|
442
|
+
workflowRuns,
|
|
443
|
+
stepCheckpoints,
|
|
444
|
+
runAttributes,
|
|
445
|
+
signalWaiters,
|
|
446
|
+
bufferedSignals
|
|
447
|
+
];
|
|
448
|
+
}
|
|
449
|
+
__name(durableEntities, "durableEntities");
|
|
450
|
+
var ENTITIES = durableEntities();
|
|
451
|
+
|
|
452
|
+
// src/mikro-orm-state-store.ts
|
|
453
|
+
var import_nestjs_durable_core = require("@dudousxd/nestjs-durable-core");
|
|
454
|
+
|
|
455
|
+
// src/schema.ts
|
|
456
|
+
var import_node_crypto = require("crypto");
|
|
457
|
+
var DURABLE_TABLE_NAMES = /* @__PURE__ */ new Set([
|
|
458
|
+
"durable_workflow_runs",
|
|
459
|
+
"durable_step_checkpoints",
|
|
460
|
+
"durable_run_attributes",
|
|
461
|
+
"durable_signal_waiters",
|
|
462
|
+
"durable_buffered_signals"
|
|
463
|
+
]);
|
|
464
|
+
var MARKER_TABLE = "durable_schema_meta";
|
|
465
|
+
var MARKER_ROW_ID = "durable";
|
|
466
|
+
var SCHEMA_LOCK_NAME = "durable_schema";
|
|
467
|
+
var SCHEMA_REVISION = 1;
|
|
468
|
+
function compareStrings(a, b) {
|
|
469
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
470
|
+
}
|
|
471
|
+
__name(compareStrings, "compareStrings");
|
|
472
|
+
function targetTable(statement) {
|
|
473
|
+
const match = statement.match(/^(?:create\s+(?:unique\s+)?index\s+.+?\s+on\s+|(?:create|alter)\s+table\s+(?:if\s+not\s+exists\s+)?)[`"']?([\w$]+)[`"']?/i);
|
|
474
|
+
return match?.[1]?.toLowerCase();
|
|
475
|
+
}
|
|
476
|
+
__name(targetTable, "targetTable");
|
|
477
|
+
function isRequiredStructure(statement) {
|
|
478
|
+
return /\b(?:create\s+table|create\s+(?:unique\s+)?index|add\s+(?:column|index|constraint|key|unique|fulltext))\b/i.test(statement);
|
|
479
|
+
}
|
|
480
|
+
__name(isRequiredStructure, "isRequiredStructure");
|
|
481
|
+
function detectSqlDialect(orm) {
|
|
482
|
+
const platform = String(orm.em.getPlatform().constructor.name).toLowerCase();
|
|
483
|
+
if (platform.includes("mysql") || platform.includes("maria")) return "mysql";
|
|
484
|
+
if (platform.includes("postgre")) return "postgres";
|
|
485
|
+
if (platform.includes("sqlite") || platform.includes("libsql")) return "sqlite";
|
|
486
|
+
return "unknown";
|
|
487
|
+
}
|
|
488
|
+
__name(detectSqlDialect, "detectSqlDialect");
|
|
489
|
+
function normalizeIndexProperties(properties) {
|
|
490
|
+
if (properties === void 0) return [];
|
|
491
|
+
if (Array.isArray(properties)) return properties.map((property) => String(property));
|
|
492
|
+
return [
|
|
493
|
+
String(properties)
|
|
494
|
+
];
|
|
495
|
+
}
|
|
496
|
+
__name(normalizeIndexProperties, "normalizeIndexProperties");
|
|
497
|
+
function computeExpectedFingerprint(orm, ownedTableNames) {
|
|
498
|
+
const ownedMetadata = [
|
|
499
|
+
...orm.getMetadata().getAll().values()
|
|
500
|
+
].filter((meta) => ownedTableNames.has(meta.tableName)).sort((a, b) => compareStrings(a.tableName, b.tableName));
|
|
501
|
+
const tables = ownedMetadata.map((meta) => {
|
|
502
|
+
const columns = [
|
|
503
|
+
...meta.props
|
|
504
|
+
].map((prop) => ({
|
|
505
|
+
prop,
|
|
506
|
+
columnName: prop.fieldNames[0] ?? String(prop.name)
|
|
507
|
+
})).sort((a, b) => compareStrings(a.columnName, b.columnName)).map(({ prop, columnName }) => ({
|
|
508
|
+
name: columnName,
|
|
509
|
+
type: prop.columnTypes[0] ?? String(prop.type),
|
|
510
|
+
nullable: prop.nullable === true,
|
|
511
|
+
primary: prop.primary === true,
|
|
512
|
+
default: prop.default ?? null,
|
|
513
|
+
autoincrement: prop.autoincrement === true
|
|
514
|
+
}));
|
|
515
|
+
const indexes = [
|
|
516
|
+
...meta.indexes
|
|
517
|
+
].map((index) => ({
|
|
518
|
+
name: index.name ?? "",
|
|
519
|
+
properties: normalizeIndexProperties(index.properties)
|
|
520
|
+
})).sort((a, b) => compareStrings(a.name, b.name));
|
|
521
|
+
return {
|
|
522
|
+
tableName: meta.tableName,
|
|
523
|
+
columns,
|
|
524
|
+
indexes
|
|
525
|
+
};
|
|
526
|
+
});
|
|
527
|
+
const canonical = `${canonicalize(tables)}|collate=${String(orm.config.get("collate") ?? "")}|rev=${SCHEMA_REVISION}`;
|
|
528
|
+
return (0, import_node_crypto.createHash)("sha256").update(canonical).digest("hex");
|
|
529
|
+
}
|
|
530
|
+
__name(computeExpectedFingerprint, "computeExpectedFingerprint");
|
|
531
|
+
function canonicalize(value) {
|
|
532
|
+
if (Array.isArray(value)) {
|
|
533
|
+
return `[${value.map(canonicalize).join(",")}]`;
|
|
534
|
+
}
|
|
535
|
+
if (value !== null && typeof value === "object") {
|
|
536
|
+
const entries = Object.entries(value).sort(([a], [b]) => compareStrings(a, b));
|
|
537
|
+
return `{${entries.map(([key, val]) => `${JSON.stringify(key)}:${canonicalize(val)}`).join(",")}}`;
|
|
538
|
+
}
|
|
539
|
+
return JSON.stringify(value);
|
|
540
|
+
}
|
|
541
|
+
__name(canonicalize, "canonicalize");
|
|
542
|
+
function createMarkerTableSql() {
|
|
543
|
+
return `create table if not exists ${MARKER_TABLE} (id varchar(32) not null primary key, fingerprint varchar(64) not null, applied_at bigint not null)`;
|
|
544
|
+
}
|
|
545
|
+
__name(createMarkerTableSql, "createMarkerTableSql");
|
|
546
|
+
async function readStoredFingerprint(orm) {
|
|
547
|
+
const rows = await orm.em.getConnection().execute(`select fingerprint from ${MARKER_TABLE} where id = ?`, [
|
|
548
|
+
MARKER_ROW_ID
|
|
549
|
+
]);
|
|
550
|
+
return rows[0]?.fingerprint ?? void 0;
|
|
551
|
+
}
|
|
552
|
+
__name(readStoredFingerprint, "readStoredFingerprint");
|
|
553
|
+
async function writeFingerprint(orm, dialect, fingerprint) {
|
|
554
|
+
const upsert = dialect === "mysql" ? `insert into ${MARKER_TABLE} (id, fingerprint, applied_at) values (?, ?, ?) on duplicate key update fingerprint = values(fingerprint), applied_at = values(applied_at)` : `insert into ${MARKER_TABLE} (id, fingerprint, applied_at) values (?, ?, ?) on conflict (id) do update set fingerprint = excluded.fingerprint, applied_at = excluded.applied_at`;
|
|
555
|
+
await orm.em.getConnection().execute(upsert, [
|
|
556
|
+
MARKER_ROW_ID,
|
|
557
|
+
fingerprint,
|
|
558
|
+
Date.now()
|
|
559
|
+
]);
|
|
560
|
+
}
|
|
561
|
+
__name(writeFingerprint, "writeFingerprint");
|
|
562
|
+
async function acquireSchemaLock(orm, dialect) {
|
|
563
|
+
try {
|
|
564
|
+
if (dialect === "mysql") {
|
|
565
|
+
await orm.em.getConnection().execute(`select get_lock('${SCHEMA_LOCK_NAME}', 10)`);
|
|
566
|
+
} else if (dialect === "postgres") {
|
|
567
|
+
await orm.em.getConnection().execute(`select pg_advisory_lock(hashtext('${SCHEMA_LOCK_NAME}'))`);
|
|
568
|
+
}
|
|
569
|
+
} catch (err) {
|
|
570
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
571
|
+
console.warn(`[nestjs-durable-store-mikro-orm] could not acquire the durable-schema advisory lock (proceeding without it): ${message}`);
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
__name(acquireSchemaLock, "acquireSchemaLock");
|
|
575
|
+
async function releaseSchemaLock(orm, dialect) {
|
|
576
|
+
try {
|
|
577
|
+
if (dialect === "mysql") {
|
|
578
|
+
await orm.em.getConnection().execute(`select release_lock('${SCHEMA_LOCK_NAME}')`);
|
|
579
|
+
} else if (dialect === "postgres") {
|
|
580
|
+
await orm.em.getConnection().execute(`select pg_advisory_unlock(hashtext('${SCHEMA_LOCK_NAME}'))`);
|
|
581
|
+
}
|
|
582
|
+
} catch {
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
__name(releaseSchemaLock, "releaseSchemaLock");
|
|
586
|
+
async function ensureMikroOrmDurableSchema(orm) {
|
|
587
|
+
const dialect = detectSqlDialect(orm);
|
|
588
|
+
await orm.em.getConnection().execute(createMarkerTableSql());
|
|
589
|
+
const expected = computeExpectedFingerprint(orm, DURABLE_TABLE_NAMES);
|
|
590
|
+
const stored = await readStoredFingerprint(orm);
|
|
591
|
+
if (stored === expected) {
|
|
592
|
+
return;
|
|
593
|
+
}
|
|
594
|
+
await acquireSchemaLock(orm, dialect);
|
|
595
|
+
try {
|
|
596
|
+
if (await readStoredFingerprint(orm) === expected) {
|
|
597
|
+
return;
|
|
598
|
+
}
|
|
599
|
+
await healDurableSchema(orm);
|
|
600
|
+
await writeFingerprint(orm, dialect, expected);
|
|
601
|
+
} finally {
|
|
602
|
+
await releaseSchemaLock(orm, dialect);
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
__name(ensureMikroOrmDurableSchema, "ensureMikroOrmDurableSchema");
|
|
606
|
+
async function healDurableSchema(orm) {
|
|
607
|
+
const sql = await orm.schema.getUpdateSchemaSQL({
|
|
608
|
+
safe: true
|
|
609
|
+
});
|
|
610
|
+
const ours = sql.split(";").map((statement) => statement.trim()).filter((statement) => {
|
|
611
|
+
const table = targetTable(statement);
|
|
612
|
+
return table !== void 0 && DURABLE_TABLE_NAMES.has(table);
|
|
613
|
+
});
|
|
614
|
+
const connection = orm.em.getConnection();
|
|
615
|
+
for (const statement of ours) {
|
|
616
|
+
try {
|
|
617
|
+
await connection.execute(statement);
|
|
618
|
+
} catch (err) {
|
|
619
|
+
if (isRequiredStructure(statement)) {
|
|
620
|
+
throw err;
|
|
621
|
+
}
|
|
622
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
623
|
+
console.warn(`[nestjs-durable-store-mikro-orm] skipped a non-structural durable-schema statement that failed; the column is left as-is (functional) \u2014 repair the data out of band to converge its type. Statement: ${statement} \u2014 ${message}`);
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
await alignDurableCollation(orm);
|
|
627
|
+
}
|
|
628
|
+
__name(healDurableSchema, "healDurableSchema");
|
|
629
|
+
function isSafeSqlIdentifier(value) {
|
|
630
|
+
return /^[A-Za-z0-9_]+$/.test(value);
|
|
631
|
+
}
|
|
632
|
+
__name(isSafeSqlIdentifier, "isSafeSqlIdentifier");
|
|
633
|
+
async function alignDurableCollation(orm) {
|
|
634
|
+
const platform = String(orm.em.getPlatform().constructor.name).toLowerCase();
|
|
635
|
+
if (!platform.includes("mysql") && !platform.includes("maria")) {
|
|
636
|
+
return;
|
|
637
|
+
}
|
|
638
|
+
const collate = orm.config.get("collate");
|
|
639
|
+
if (typeof collate !== "string" || !isSafeSqlIdentifier(collate)) {
|
|
640
|
+
return;
|
|
641
|
+
}
|
|
642
|
+
const charset = collate.split("_")[0];
|
|
643
|
+
if (!charset || !isSafeSqlIdentifier(charset)) {
|
|
644
|
+
return;
|
|
645
|
+
}
|
|
646
|
+
const connection = orm.em.getConnection();
|
|
647
|
+
for (const table of DURABLE_TABLE_NAMES) {
|
|
648
|
+
try {
|
|
649
|
+
const rows = await connection.execute("select table_collation as collation from information_schema.tables where table_schema = database() and table_name = ? limit 1", [
|
|
650
|
+
table
|
|
651
|
+
]);
|
|
652
|
+
const current = rows[0]?.collation;
|
|
653
|
+
if (current == null || current === collate) {
|
|
654
|
+
continue;
|
|
655
|
+
}
|
|
656
|
+
await connection.execute(`alter table \`${table}\` convert to character set ${charset} collate ${collate}`);
|
|
657
|
+
} catch (err) {
|
|
658
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
659
|
+
console.warn(`[nestjs-durable-store-mikro-orm] could not align collation for \`${table}\` to ${collate} (left as-is): ${message}`);
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
__name(alignDurableCollation, "alignDurableCollation");
|
|
664
|
+
|
|
665
|
+
// src/mikro-orm-state-store.ts
|
|
666
|
+
var MikroOrmStateStore = class _MikroOrmStateStore {
|
|
667
|
+
static {
|
|
668
|
+
__name(this, "MikroOrmStateStore");
|
|
669
|
+
}
|
|
670
|
+
orm;
|
|
671
|
+
scopeNamespace;
|
|
672
|
+
constructor(orm, opts) {
|
|
673
|
+
this.orm = orm;
|
|
674
|
+
this.scopeNamespace = opts?.scope?.namespace;
|
|
675
|
+
}
|
|
676
|
+
/**
|
|
677
|
+
* Derive a store confined to a single tenant `scope.namespace`, sharing this store's ORM (no new
|
|
678
|
+
* connection). Turns the operator (unscoped) store into a tenant-boundary view at wiring time —
|
|
679
|
+
* used by the NestJS module's `scopeReads` option, which receives a pre-built store and can't
|
|
680
|
+
* reconstruct it. Pass `{ namespace: undefined }` for the unscoped operator view.
|
|
681
|
+
*/
|
|
682
|
+
withScope(scope) {
|
|
683
|
+
return new _MikroOrmStateStore(this.orm, {
|
|
684
|
+
scope
|
|
685
|
+
});
|
|
686
|
+
}
|
|
687
|
+
/**
|
|
688
|
+
* Create a forked EntityManager and activate the `namespace` global filter with the store's
|
|
689
|
+
* scope (if any). All read operations go through this so the tenant boundary is applied
|
|
690
|
+
* uniformly. Write operations (nativeDelete, nativeUpdate, upsert, insertMany) bypass global
|
|
691
|
+
* filters in MikroORM and are unaffected.
|
|
692
|
+
*/
|
|
693
|
+
fork() {
|
|
694
|
+
const em = this.orm.em.fork();
|
|
695
|
+
em.setFilterParams("namespace", {
|
|
696
|
+
namespace: this.scopeNamespace
|
|
697
|
+
});
|
|
698
|
+
return em;
|
|
699
|
+
}
|
|
700
|
+
async ensureSchema() {
|
|
701
|
+
await ensureMikroOrmDurableSchema(this.orm);
|
|
702
|
+
}
|
|
703
|
+
async createRun(run) {
|
|
704
|
+
const em = this.fork();
|
|
705
|
+
em.create(WorkflowRunEntity, toRunEntity(run));
|
|
706
|
+
await em.flush();
|
|
707
|
+
await this.reindexAttributes(run.id, run.searchAttributes);
|
|
708
|
+
}
|
|
709
|
+
async updateRun(runId, patch) {
|
|
710
|
+
const em = this.fork();
|
|
711
|
+
const entity = await em.findOneOrFail(WorkflowRunEntity, {
|
|
712
|
+
id: runId
|
|
713
|
+
});
|
|
714
|
+
Object.assign(entity, toRunEntity({
|
|
715
|
+
...fromRunEntity(entity),
|
|
716
|
+
...patch
|
|
717
|
+
}));
|
|
718
|
+
await em.flush();
|
|
719
|
+
if ("searchAttributes" in patch) await this.reindexAttributes(runId, patch.searchAttributes);
|
|
720
|
+
}
|
|
721
|
+
/** Rewrite a run's normalized attribute rows: delete the old set, insert the current one. Mirrors
|
|
722
|
+
* the in-memory store's reindex so the side-table always reflects the run's live searchAttributes. */
|
|
723
|
+
async reindexAttributes(runId, attributes, forked) {
|
|
724
|
+
const em = forked ?? this.fork();
|
|
725
|
+
await em.nativeDelete(RunAttributeEntity, {
|
|
726
|
+
runId
|
|
727
|
+
});
|
|
728
|
+
const rows = (0, import_nestjs_durable_core.normalizeAttributeRows)(runId, attributes);
|
|
729
|
+
if (rows.length) await em.insertMany(RunAttributeEntity, rows);
|
|
730
|
+
}
|
|
731
|
+
async getRun(runId) {
|
|
732
|
+
const em = this.fork();
|
|
733
|
+
const entity = await em.findOne(WorkflowRunEntity, {
|
|
734
|
+
id: runId
|
|
735
|
+
});
|
|
736
|
+
return entity ? fromRunEntity(entity) : null;
|
|
737
|
+
}
|
|
738
|
+
async deleteRun(runId) {
|
|
739
|
+
const em = this.fork();
|
|
740
|
+
await em.nativeDelete(StepCheckpointEntity, {
|
|
741
|
+
runId
|
|
742
|
+
});
|
|
743
|
+
await em.nativeDelete(SignalWaiterEntity, {
|
|
744
|
+
runId
|
|
745
|
+
});
|
|
746
|
+
await em.nativeDelete(RunAttributeEntity, {
|
|
747
|
+
runId
|
|
748
|
+
});
|
|
749
|
+
await em.nativeDelete(WorkflowRunEntity, {
|
|
750
|
+
id: runId
|
|
751
|
+
});
|
|
752
|
+
}
|
|
753
|
+
async pruneTerminalRuns(policy, nowMs, limit) {
|
|
754
|
+
if (policy.statuses.length === 0 || limit <= 0) return 0;
|
|
755
|
+
const em = this.fork();
|
|
756
|
+
const status = {
|
|
757
|
+
$in: policy.statuses
|
|
758
|
+
};
|
|
759
|
+
const ids = /* @__PURE__ */ new Set();
|
|
760
|
+
if (policy.maxAge != null) {
|
|
761
|
+
const cutoff = new Date(nowMs - (0, import_nestjs_durable_core.parseDuration)(policy.maxAge));
|
|
762
|
+
const rows = await em.find(WorkflowRunEntity, {
|
|
763
|
+
status,
|
|
764
|
+
updatedAt: {
|
|
765
|
+
$lt: cutoff
|
|
766
|
+
}
|
|
767
|
+
}, {
|
|
768
|
+
fields: [
|
|
769
|
+
"id"
|
|
770
|
+
],
|
|
771
|
+
orderBy: {
|
|
772
|
+
updatedAt: "asc"
|
|
773
|
+
},
|
|
774
|
+
limit
|
|
775
|
+
});
|
|
776
|
+
for (const r of rows) ids.add(r.id);
|
|
777
|
+
}
|
|
778
|
+
if (policy.maxCount != null && ids.size < limit) {
|
|
779
|
+
const rows = await em.find(WorkflowRunEntity, {
|
|
780
|
+
status
|
|
781
|
+
}, {
|
|
782
|
+
fields: [
|
|
783
|
+
"id"
|
|
784
|
+
],
|
|
785
|
+
orderBy: {
|
|
786
|
+
updatedAt: "desc",
|
|
787
|
+
id: "desc"
|
|
788
|
+
},
|
|
789
|
+
limit,
|
|
790
|
+
offset: policy.maxCount
|
|
791
|
+
});
|
|
792
|
+
for (const r of rows) {
|
|
793
|
+
ids.add(r.id);
|
|
794
|
+
if (ids.size >= limit) break;
|
|
795
|
+
}
|
|
796
|
+
}
|
|
797
|
+
if (ids.size === 0) return 0;
|
|
798
|
+
const idList = [
|
|
799
|
+
...ids
|
|
800
|
+
].slice(0, limit);
|
|
801
|
+
const runId = {
|
|
802
|
+
$in: idList
|
|
803
|
+
};
|
|
804
|
+
await em.transactional(async (tem) => {
|
|
805
|
+
await tem.nativeDelete(StepCheckpointEntity, {
|
|
806
|
+
runId
|
|
807
|
+
});
|
|
808
|
+
await tem.nativeDelete(SignalWaiterEntity, {
|
|
809
|
+
runId
|
|
810
|
+
});
|
|
811
|
+
await tem.nativeDelete(RunAttributeEntity, {
|
|
812
|
+
runId
|
|
813
|
+
});
|
|
814
|
+
await tem.nativeDelete(WorkflowRunEntity, {
|
|
815
|
+
id: runId
|
|
816
|
+
});
|
|
817
|
+
});
|
|
818
|
+
return idList.length;
|
|
819
|
+
}
|
|
820
|
+
async getCheckpoint(runId, seq) {
|
|
821
|
+
const em = this.fork();
|
|
822
|
+
const entity = await em.findOne(StepCheckpointEntity, {
|
|
823
|
+
runId,
|
|
824
|
+
seq
|
|
825
|
+
});
|
|
826
|
+
return entity ? fromCheckpointEntity(entity) : null;
|
|
827
|
+
}
|
|
828
|
+
async saveCheckpoint(checkpoint) {
|
|
829
|
+
const em = this.fork();
|
|
830
|
+
await em.upsert(StepCheckpointEntity, toCheckpointEntity(checkpoint));
|
|
831
|
+
await em.flush();
|
|
832
|
+
}
|
|
833
|
+
async transaction(work) {
|
|
834
|
+
return this.fork().transactional(async (em) => work({
|
|
835
|
+
raw: em,
|
|
836
|
+
saveCheckpoint: /* @__PURE__ */ __name(async (cp) => {
|
|
837
|
+
await em.upsert(StepCheckpointEntity, toCheckpointEntity(cp));
|
|
838
|
+
}, "saveCheckpoint")
|
|
839
|
+
}));
|
|
840
|
+
}
|
|
841
|
+
async listIncompleteRuns(namespace) {
|
|
842
|
+
const em = this.fork();
|
|
843
|
+
const rows = await em.find(WorkflowRunEntity, {
|
|
844
|
+
status: {
|
|
845
|
+
$in: [
|
|
846
|
+
"running",
|
|
847
|
+
"cancelling"
|
|
848
|
+
]
|
|
849
|
+
},
|
|
850
|
+
...namespace !== void 0 ? {
|
|
851
|
+
namespace
|
|
852
|
+
} : {}
|
|
853
|
+
});
|
|
854
|
+
return rows.map(fromRunEntity);
|
|
855
|
+
}
|
|
856
|
+
async listPendingRuns(limit, namespace) {
|
|
857
|
+
const em = this.fork();
|
|
858
|
+
const rows = await em.find(WorkflowRunEntity, {
|
|
859
|
+
status: "pending",
|
|
860
|
+
...namespace !== void 0 ? {
|
|
861
|
+
namespace
|
|
862
|
+
} : {}
|
|
863
|
+
}, {
|
|
864
|
+
orderBy: {
|
|
865
|
+
createdAt: "asc"
|
|
866
|
+
},
|
|
867
|
+
limit
|
|
868
|
+
});
|
|
869
|
+
return rows.map(fromRunEntity);
|
|
870
|
+
}
|
|
871
|
+
async listDueTimers(nowMs, namespace) {
|
|
872
|
+
const em = this.fork();
|
|
873
|
+
const rows = await em.find(WorkflowRunEntity, {
|
|
874
|
+
status: "suspended",
|
|
875
|
+
wakeAt: {
|
|
876
|
+
$ne: null,
|
|
877
|
+
$lte: new Date(nowMs)
|
|
878
|
+
},
|
|
879
|
+
...namespace !== void 0 ? {
|
|
880
|
+
namespace
|
|
881
|
+
} : {}
|
|
882
|
+
});
|
|
883
|
+
return rows.map(fromRunEntity);
|
|
884
|
+
}
|
|
885
|
+
async tryLockRun(runId, owner, leaseUntilMs, nowMs) {
|
|
886
|
+
const em = this.fork();
|
|
887
|
+
const affected = await em.nativeUpdate(WorkflowRunEntity, {
|
|
888
|
+
id: runId,
|
|
889
|
+
$or: [
|
|
890
|
+
{
|
|
891
|
+
lockedUntil: null
|
|
892
|
+
},
|
|
893
|
+
{
|
|
894
|
+
lockedUntil: {
|
|
895
|
+
$lte: new Date(nowMs)
|
|
896
|
+
}
|
|
897
|
+
}
|
|
898
|
+
]
|
|
899
|
+
}, {
|
|
900
|
+
lockedBy: owner,
|
|
901
|
+
lockedUntil: new Date(leaseUntilMs)
|
|
902
|
+
});
|
|
903
|
+
return affected === 1;
|
|
904
|
+
}
|
|
905
|
+
async releaseRunLock(runId) {
|
|
906
|
+
const em = this.fork();
|
|
907
|
+
await em.nativeUpdate(WorkflowRunEntity, {
|
|
908
|
+
id: runId
|
|
909
|
+
}, {
|
|
910
|
+
lockedBy: null,
|
|
911
|
+
lockedUntil: null
|
|
912
|
+
});
|
|
913
|
+
}
|
|
914
|
+
async renewRunLock(runId, owner, leaseUntilMs) {
|
|
915
|
+
const em = this.fork();
|
|
916
|
+
const affected = await em.nativeUpdate(WorkflowRunEntity, {
|
|
917
|
+
id: runId,
|
|
918
|
+
lockedBy: owner
|
|
919
|
+
}, {
|
|
920
|
+
lockedUntil: new Date(leaseUntilMs)
|
|
921
|
+
});
|
|
922
|
+
return affected === 1;
|
|
923
|
+
}
|
|
924
|
+
async listRuns(query) {
|
|
925
|
+
const em = this.fork();
|
|
926
|
+
const where = {};
|
|
927
|
+
if (query.workflow) where.workflow = query.workflow;
|
|
928
|
+
if (query.namespace !== void 0) where.namespace = query.namespace;
|
|
929
|
+
if (query.status && query.statuses) {
|
|
930
|
+
where.$and = [
|
|
931
|
+
{
|
|
932
|
+
status: query.status
|
|
933
|
+
},
|
|
934
|
+
{
|
|
935
|
+
status: {
|
|
936
|
+
$in: query.statuses
|
|
937
|
+
}
|
|
938
|
+
}
|
|
939
|
+
];
|
|
940
|
+
} else if (query.status) {
|
|
941
|
+
where.status = query.status;
|
|
942
|
+
} else if (query.statuses) {
|
|
943
|
+
where.status = {
|
|
944
|
+
$in: query.statuses
|
|
945
|
+
};
|
|
946
|
+
}
|
|
947
|
+
const orderBy = {
|
|
948
|
+
createdAt: "desc"
|
|
949
|
+
};
|
|
950
|
+
if (query.tag || query.attributes?.length) {
|
|
951
|
+
if (this.scopeNamespace !== void 0) where.namespace = this.scopeNamespace;
|
|
952
|
+
const quote = this.idQuote(em);
|
|
953
|
+
const cols = this.attributeColumns(em);
|
|
954
|
+
const qb = em.createQueryBuilder(WorkflowRunEntity, "r").where(where).orderBy(orderBy);
|
|
955
|
+
if (query.tag) {
|
|
956
|
+
const tagsCol = this.tagsColumn(em);
|
|
957
|
+
const pattern = `%"${query.tag.replace(/'/g, "''")}"%`;
|
|
958
|
+
const colExpr = this.jsonAsText(em, `${quote("r")}.${quote(tagsCol)}`);
|
|
959
|
+
qb.andWhere(`${colExpr} LIKE '${pattern}'`);
|
|
960
|
+
}
|
|
961
|
+
for (const f of query.attributes ?? []) {
|
|
962
|
+
qb.andWhere(this.attributeExistsSql(f, quote, "r", cols));
|
|
963
|
+
}
|
|
964
|
+
if (query.limit != null) qb.limit(query.limit);
|
|
965
|
+
if (query.offset != null) qb.offset(query.offset);
|
|
966
|
+
const rows2 = await qb.getResultList();
|
|
967
|
+
return rows2.map(fromRunEntity);
|
|
968
|
+
}
|
|
969
|
+
const rows = await em.find(WorkflowRunEntity, where, {
|
|
970
|
+
...query.limit != null ? {
|
|
971
|
+
limit: query.limit
|
|
972
|
+
} : {},
|
|
973
|
+
...query.offset != null ? {
|
|
974
|
+
offset: query.offset
|
|
975
|
+
} : {},
|
|
976
|
+
orderBy
|
|
977
|
+
});
|
|
978
|
+
return rows.map(fromRunEntity);
|
|
979
|
+
}
|
|
980
|
+
/** One attribute predicate as a raw EXISTS subquery on the side-table, correlated to the outer run
|
|
981
|
+
* alias. `<>` (ne) also excludes runs where the attribute is absent (missing-key-never-matches):
|
|
982
|
+
* EXISTS already requires a present row, so EXISTS(... <> ...) is exactly ne-with-present. Numeric
|
|
983
|
+
* operands compare the num column, everything else the str column. Identifiers are quoted per
|
|
984
|
+
* driver and operands are inlined as literals (string operands are escaped by doubling quotes). */
|
|
985
|
+
attributeExistsSql(f, quote, alias, cols) {
|
|
986
|
+
const col = (0, import_nestjs_durable_core.attributeColumnFor)(f) === "numValue" ? cols.numValue : cols.strValue;
|
|
987
|
+
const cmp = (0, import_nestjs_durable_core.sqlComparator)(f.op);
|
|
988
|
+
const operand = (0, import_nestjs_durable_core.attributeOperand)(f);
|
|
989
|
+
const literal = typeof operand === "number" ? String(operand) : `'${String(operand).replace(/'/g, "''")}'`;
|
|
990
|
+
const a = quote(cols.table);
|
|
991
|
+
const sub = quote("a");
|
|
992
|
+
const outerId = `${quote(alias)}.${quote(cols.runPk)}`;
|
|
993
|
+
return `EXISTS (SELECT 1 FROM ${a} ${sub} WHERE ${sub}.${quote(cols.runId)} = ${outerId} AND ${sub}.${quote(cols.key)} = '${f.key.replace(/'/g, "''")}' AND ${sub}.${quote(col)} ${cmp} ${literal})`;
|
|
994
|
+
}
|
|
995
|
+
/** Resolve the side-table's actual column names from MikroORM metadata, so the raw EXISTS matches
|
|
996
|
+
* the active naming strategy (underscore vs camelCase) rather than guessing. The run PK column is
|
|
997
|
+
* reused for BOTH the outer correlation and the side-table FK (they share the same fieldName). */
|
|
998
|
+
attributeColumns(em) {
|
|
999
|
+
const meta = em.getMetadata().get(RunAttributeEntity);
|
|
1000
|
+
const field = /* @__PURE__ */ __name((prop) => meta.props.find((p) => p.name === prop)?.fieldNames?.[0] ?? prop, "field");
|
|
1001
|
+
const runMeta = em.getMetadata().get(WorkflowRunEntity);
|
|
1002
|
+
const runPk = runMeta.properties.id?.fieldNames?.[0] ?? "id";
|
|
1003
|
+
return {
|
|
1004
|
+
table: meta.tableName,
|
|
1005
|
+
runId: field("runId"),
|
|
1006
|
+
runPk,
|
|
1007
|
+
key: field("key"),
|
|
1008
|
+
strValue: field("strValue"),
|
|
1009
|
+
numValue: field("numValue")
|
|
1010
|
+
};
|
|
1011
|
+
}
|
|
1012
|
+
/** Resolve the `tags` column name from metadata (per the active naming strategy), for the raw LIKE. */
|
|
1013
|
+
tagsColumn(em) {
|
|
1014
|
+
const runMeta = em.getMetadata().get(WorkflowRunEntity);
|
|
1015
|
+
return runMeta.properties.tags?.fieldNames?.[0] ?? "tags";
|
|
1016
|
+
}
|
|
1017
|
+
/** Wrap a JSON column reference so it can be `LIKE`d as text. Postgres `jsonb`/`json` rejects `LIKE`
|
|
1018
|
+
* directly (`operator does not exist: jsonb ~~ unknown`) — cast to `text`; MySQL JSON needs an
|
|
1019
|
+
* explicit `CHAR` cast; SQLite stores JSON as text already, so no cast. */
|
|
1020
|
+
jsonAsText(em, colRef) {
|
|
1021
|
+
const platform = String(em.getPlatform().constructor.name).toLowerCase();
|
|
1022
|
+
if (platform.includes("postgre")) return `${colRef}::text`;
|
|
1023
|
+
if (platform.includes("mysql") || platform.includes("mariadb")) return `CAST(${colRef} AS CHAR)`;
|
|
1024
|
+
return colRef;
|
|
1025
|
+
}
|
|
1026
|
+
/** Quote an identifier per the active SQL driver (MySQL/MariaDB backtick, others double-quote). */
|
|
1027
|
+
idQuote(em) {
|
|
1028
|
+
const platform = String(em.getPlatform().constructor.name).toLowerCase();
|
|
1029
|
+
const isMysql = platform.includes("mysql") || platform.includes("mariadb");
|
|
1030
|
+
const ch = isMysql ? "`" : '"';
|
|
1031
|
+
return (id) => `${ch}${id}${ch}`;
|
|
1032
|
+
}
|
|
1033
|
+
async listCheckpoints(runId) {
|
|
1034
|
+
const em = this.fork();
|
|
1035
|
+
const rows = await em.find(StepCheckpointEntity, {
|
|
1036
|
+
runId
|
|
1037
|
+
}, {
|
|
1038
|
+
orderBy: {
|
|
1039
|
+
seq: "asc"
|
|
1040
|
+
}
|
|
1041
|
+
});
|
|
1042
|
+
return rows.map(fromCheckpointEntity);
|
|
1043
|
+
}
|
|
1044
|
+
async getLatestCheckpointByName(runId, name) {
|
|
1045
|
+
const em = this.fork();
|
|
1046
|
+
const entity = await em.findOne(StepCheckpointEntity, {
|
|
1047
|
+
runId,
|
|
1048
|
+
name
|
|
1049
|
+
}, {
|
|
1050
|
+
orderBy: {
|
|
1051
|
+
seq: "desc"
|
|
1052
|
+
}
|
|
1053
|
+
});
|
|
1054
|
+
return entity ? fromCheckpointEntity(entity) : void 0;
|
|
1055
|
+
}
|
|
1056
|
+
async listCheckpointsByNamePrefix(runId, prefixes) {
|
|
1057
|
+
if (prefixes.length === 0) return [];
|
|
1058
|
+
const em = this.fork();
|
|
1059
|
+
const rows = await em.find(StepCheckpointEntity, {
|
|
1060
|
+
runId,
|
|
1061
|
+
$or: prefixes.map((p) => ({
|
|
1062
|
+
name: {
|
|
1063
|
+
$like: `${p}%`
|
|
1064
|
+
}
|
|
1065
|
+
}))
|
|
1066
|
+
}, {
|
|
1067
|
+
orderBy: {
|
|
1068
|
+
seq: "asc"
|
|
1069
|
+
}
|
|
1070
|
+
});
|
|
1071
|
+
return rows.map(fromCheckpointEntity);
|
|
1072
|
+
}
|
|
1073
|
+
async putSignalWaiter(waiter) {
|
|
1074
|
+
const em = this.fork();
|
|
1075
|
+
await em.upsert(SignalWaiterEntity, {
|
|
1076
|
+
token: waiter.token,
|
|
1077
|
+
runId: waiter.runId,
|
|
1078
|
+
seq: waiter.seq,
|
|
1079
|
+
parallelGroup: waiter.parallelGroup ?? null
|
|
1080
|
+
});
|
|
1081
|
+
await em.flush();
|
|
1082
|
+
}
|
|
1083
|
+
async takeSignalWaiter(token) {
|
|
1084
|
+
const em = this.fork();
|
|
1085
|
+
const entity = await em.findOne(SignalWaiterEntity, {
|
|
1086
|
+
token
|
|
1087
|
+
});
|
|
1088
|
+
if (!entity) return null;
|
|
1089
|
+
const waiter = {
|
|
1090
|
+
token: entity.token,
|
|
1091
|
+
runId: entity.runId,
|
|
1092
|
+
seq: entity.seq,
|
|
1093
|
+
parallelGroup: entity.parallelGroup ?? void 0
|
|
1094
|
+
};
|
|
1095
|
+
await em.remove(entity).flush();
|
|
1096
|
+
return waiter;
|
|
1097
|
+
}
|
|
1098
|
+
async listSignalWaiters(prefix) {
|
|
1099
|
+
const em = this.fork();
|
|
1100
|
+
const rows = await em.find(SignalWaiterEntity, {
|
|
1101
|
+
token: {
|
|
1102
|
+
$like: `${prefix}%`
|
|
1103
|
+
}
|
|
1104
|
+
});
|
|
1105
|
+
return rows.map((e) => ({
|
|
1106
|
+
token: e.token,
|
|
1107
|
+
runId: e.runId,
|
|
1108
|
+
seq: e.seq,
|
|
1109
|
+
parallelGroup: e.parallelGroup ?? void 0
|
|
1110
|
+
}));
|
|
1111
|
+
}
|
|
1112
|
+
async bufferSignal(token, payload) {
|
|
1113
|
+
const em = this.fork();
|
|
1114
|
+
const e = new BufferedSignalEntity();
|
|
1115
|
+
e.token = token;
|
|
1116
|
+
e.payload = payload ?? null;
|
|
1117
|
+
em.persist(e);
|
|
1118
|
+
await em.flush();
|
|
1119
|
+
}
|
|
1120
|
+
async takeBufferedSignal(token) {
|
|
1121
|
+
const em = this.fork();
|
|
1122
|
+
const entity = await em.findOne(BufferedSignalEntity, {
|
|
1123
|
+
token
|
|
1124
|
+
}, {
|
|
1125
|
+
orderBy: {
|
|
1126
|
+
id: "asc"
|
|
1127
|
+
}
|
|
1128
|
+
});
|
|
1129
|
+
if (!entity) return null;
|
|
1130
|
+
const payload = entity.payload ?? void 0;
|
|
1131
|
+
await em.remove(entity).flush();
|
|
1132
|
+
return {
|
|
1133
|
+
payload
|
|
1134
|
+
};
|
|
1135
|
+
}
|
|
1136
|
+
};
|
|
1137
|
+
function toRunEntity(run) {
|
|
1138
|
+
const e = new WorkflowRunEntity();
|
|
1139
|
+
e.id = run.id;
|
|
1140
|
+
e.workflow = run.workflow;
|
|
1141
|
+
e.workflowVersion = run.workflowVersion;
|
|
1142
|
+
e.status = run.status;
|
|
1143
|
+
e.input = run.input ?? null;
|
|
1144
|
+
e.output = run.output ?? null;
|
|
1145
|
+
e.error = run.error ?? null;
|
|
1146
|
+
if (run.wakeAt != null) e.wakeAt = new Date(run.wakeAt);
|
|
1147
|
+
if (run.lockedBy !== void 0) e.lockedBy = run.lockedBy;
|
|
1148
|
+
if (run.lockedUntil != null) e.lockedUntil = new Date(run.lockedUntil);
|
|
1149
|
+
if (run.awaitingDecisionTaskId !== void 0) e.awaitingDecisionTaskId = run.awaitingDecisionTaskId;
|
|
1150
|
+
if (run.recoveryAttempts !== void 0) e.recoveryAttempts = run.recoveryAttempts;
|
|
1151
|
+
e.tags = run.tags ?? null;
|
|
1152
|
+
e.searchAttributes = run.searchAttributes ?? null;
|
|
1153
|
+
e.priority = run.priority ?? null;
|
|
1154
|
+
e.namespace = run.namespace ?? "default";
|
|
1155
|
+
e.createdAt = run.createdAt;
|
|
1156
|
+
e.updatedAt = run.updatedAt;
|
|
1157
|
+
return e;
|
|
1158
|
+
}
|
|
1159
|
+
__name(toRunEntity, "toRunEntity");
|
|
1160
|
+
function fromRunEntity(e) {
|
|
1161
|
+
return {
|
|
1162
|
+
id: e.id,
|
|
1163
|
+
workflow: e.workflow,
|
|
1164
|
+
workflowVersion: e.workflowVersion,
|
|
1165
|
+
status: e.status,
|
|
1166
|
+
input: e.input ?? void 0,
|
|
1167
|
+
output: e.output ?? void 0,
|
|
1168
|
+
error: e.error ?? void 0,
|
|
1169
|
+
wakeAt: e.wakeAt?.getTime(),
|
|
1170
|
+
lockedBy: e.lockedBy ?? void 0,
|
|
1171
|
+
lockedUntil: e.lockedUntil?.getTime(),
|
|
1172
|
+
awaitingDecisionTaskId: e.awaitingDecisionTaskId ?? void 0,
|
|
1173
|
+
recoveryAttempts: e.recoveryAttempts ?? void 0,
|
|
1174
|
+
tags: e.tags ?? void 0,
|
|
1175
|
+
searchAttributes: e.searchAttributes ?? void 0,
|
|
1176
|
+
priority: e.priority ?? void 0,
|
|
1177
|
+
namespace: e.namespace,
|
|
1178
|
+
createdAt: e.createdAt,
|
|
1179
|
+
updatedAt: e.updatedAt
|
|
1180
|
+
};
|
|
1181
|
+
}
|
|
1182
|
+
__name(fromRunEntity, "fromRunEntity");
|
|
1183
|
+
function toCheckpointEntity(cp) {
|
|
1184
|
+
const e = new StepCheckpointEntity();
|
|
1185
|
+
e.runId = cp.runId;
|
|
1186
|
+
e.seq = cp.seq;
|
|
1187
|
+
e.name = cp.name;
|
|
1188
|
+
e.kind = cp.kind;
|
|
1189
|
+
e.stepId = cp.stepId;
|
|
1190
|
+
e.status = cp.status;
|
|
1191
|
+
e.input = cp.input ?? null;
|
|
1192
|
+
e.output = cp.output ?? null;
|
|
1193
|
+
e.error = cp.error ?? null;
|
|
1194
|
+
e.events = cp.events ?? null;
|
|
1195
|
+
e.attempts = cp.attempts;
|
|
1196
|
+
if (cp.workerGroup !== void 0) e.workerGroup = cp.workerGroup;
|
|
1197
|
+
if (cp.parallelGroup !== void 0) e.parallelGroup = cp.parallelGroup;
|
|
1198
|
+
if (cp.wakeAt != null) e.wakeAt = new Date(cp.wakeAt);
|
|
1199
|
+
e.enqueuedAt = cp.enqueuedAt;
|
|
1200
|
+
e.startedAt = cp.startedAt;
|
|
1201
|
+
e.finishedAt = cp.finishedAt;
|
|
1202
|
+
return e;
|
|
1203
|
+
}
|
|
1204
|
+
__name(toCheckpointEntity, "toCheckpointEntity");
|
|
1205
|
+
function fromCheckpointEntity(e) {
|
|
1206
|
+
return {
|
|
1207
|
+
runId: e.runId,
|
|
1208
|
+
seq: e.seq,
|
|
1209
|
+
name: e.name,
|
|
1210
|
+
kind: e.kind,
|
|
1211
|
+
stepId: e.stepId,
|
|
1212
|
+
status: e.status,
|
|
1213
|
+
input: e.input ?? void 0,
|
|
1214
|
+
output: e.output ?? void 0,
|
|
1215
|
+
error: e.error ?? void 0,
|
|
1216
|
+
events: e.events ?? void 0,
|
|
1217
|
+
attempts: e.attempts,
|
|
1218
|
+
workerGroup: e.workerGroup ?? void 0,
|
|
1219
|
+
parallelGroup: e.parallelGroup ?? void 0,
|
|
1220
|
+
wakeAt: e.wakeAt?.getTime(),
|
|
1221
|
+
enqueuedAt: e.enqueuedAt ?? e.startedAt,
|
|
1222
|
+
startedAt: e.startedAt,
|
|
1223
|
+
finishedAt: e.finishedAt
|
|
1224
|
+
};
|
|
1225
|
+
}
|
|
1226
|
+
__name(fromCheckpointEntity, "fromCheckpointEntity");
|
|
1227
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
1228
|
+
0 && (module.exports = {
|
|
1229
|
+
BufferedSignalEntity,
|
|
1230
|
+
ENTITIES,
|
|
1231
|
+
MikroOrmStateStore,
|
|
1232
|
+
RunAttributeEntity,
|
|
1233
|
+
SignalWaiterEntity,
|
|
1234
|
+
StepCheckpointEntity,
|
|
1235
|
+
WorkflowRunEntity,
|
|
1236
|
+
durableEntities,
|
|
1237
|
+
ensureMikroOrmDurableSchema
|
|
1238
|
+
});
|
|
1239
|
+
//# sourceMappingURL=index.cjs.map
|