@bobtail.software/b-durable 1.0.5 → 1.0.6

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.mjs CHANGED
@@ -1,551 +1 @@
1
- // src/runtime/persistence.ts
2
- var redis;
3
- var blockingRedis;
4
- function configurePersistence(clients) {
5
- if (redis || blockingRedis) {
6
- console.warn(
7
- "[Persistence] Los clientes de Redis ya han sido configurados. Omitiendo."
8
- );
9
- return;
10
- }
11
- redis = clients.commandClient;
12
- blockingRedis = clients.blockingClient;
13
- }
14
-
15
- // src/runtime/runtime.ts
16
- import { randomUUID } from "crypto";
17
- import ms from "ms";
18
- import { resolve } from "path";
19
-
20
- // src/runtime/constants.ts
21
- var TASK_QUEUE_KEY = "queue:tasks";
22
- var SLEEPERS_KEY = "durable:sleepers";
23
- var WorkflowStatus = {
24
- RUNNING: "RUNNING",
25
- SLEEPING: "SLEEPING",
26
- COMPLETED: "COMPLETED",
27
- FAILED: "FAILED",
28
- AWAITING_EVENT: "AWAITING_EVENT",
29
- AWAITING_SUBWORKFLOW: "AWAITING_SUBWORKFLOW"
30
- };
31
-
32
- // src/runtime/runtime.ts
33
- var WorkflowRepository = class {
34
- getKey(workflowId) {
35
- return `workflow:${workflowId}`;
36
- }
37
- getLockKey(workflowId) {
38
- return `workflow:${workflowId}:lock`;
39
- }
40
- async acquireLock(workflowId, lockTimeoutSeconds = 10) {
41
- const lockKey = this.getLockKey(workflowId);
42
- const result = await redis.set(lockKey, "locked", "EX", lockTimeoutSeconds, "NX");
43
- return result === "OK";
44
- }
45
- async releaseLock(workflowId) {
46
- await redis.del(this.getLockKey(workflowId));
47
- }
48
- async get(workflowId) {
49
- const data = await redis.hgetall(this.getKey(workflowId));
50
- if (!data || Object.keys(data).length === 0) {
51
- return null;
52
- }
53
- return {
54
- workflowId: data.workflowId,
55
- name: data.name,
56
- status: data.status,
57
- step: parseInt(data.step, 10),
58
- input: JSON.parse(data.input),
59
- state: JSON.parse(data.state),
60
- result: data.result ? JSON.parse(data.result) : void 0,
61
- error: data.error,
62
- parentId: data.parentId,
63
- subWorkflowId: data.subWorkflowId,
64
- awaitingEvent: data.awaitingEvent
65
- };
66
- }
67
- async create(instanceData) {
68
- const instance = {
69
- ...instanceData,
70
- step: 0,
71
- state: {}
72
- };
73
- const pipeline = redis.pipeline();
74
- pipeline.hset(this.getKey(instance.workflowId), {
75
- ...instance,
76
- input: JSON.stringify(instance.input),
77
- state: JSON.stringify(instance.state)
78
- });
79
- await pipeline.exec();
80
- }
81
- async updateState(workflowId, state) {
82
- await redis.hset(this.getKey(workflowId), "state", JSON.stringify(state));
83
- }
84
- async updateStatus(workflowId, status, extraFields = {}) {
85
- await redis.hset(this.getKey(workflowId), { status, ...extraFields });
86
- }
87
- async incrementStep(workflowId) {
88
- return redis.hincrby(this.getKey(workflowId), "step", 1);
89
- }
90
- async complete(workflowId, result) {
91
- await redis.hset(this.getKey(workflowId), {
92
- status: WorkflowStatus.COMPLETED,
93
- result: JSON.stringify(result ?? null)
94
- });
95
- }
96
- async fail(workflowId, error) {
97
- await redis.hset(this.getKey(workflowId), {
98
- status: WorkflowStatus.FAILED,
99
- error: error.message
100
- });
101
- }
102
- // --- Métodos para operaciones de Runtime ---
103
- async scheduleSleep(workflowId, wakeUpAt) {
104
- await this.updateStatus(workflowId, WorkflowStatus.SLEEPING);
105
- await redis.zadd(SLEEPERS_KEY, wakeUpAt, workflowId);
106
- }
107
- async getWorkflowsToWake() {
108
- const now = Date.now();
109
- const ids = await redis.zrangebyscore(SLEEPERS_KEY, 0, now);
110
- if (ids.length > 0) {
111
- await redis.zrem(SLEEPERS_KEY, ...ids);
112
- }
113
- return ids;
114
- }
115
- async enqueueTask(task) {
116
- await redis.lpush(TASK_QUEUE_KEY, JSON.stringify(task));
117
- }
118
- async resumeForCatch(workflowId, newState, catchStep) {
119
- const key = this.getKey(workflowId);
120
- await redis.hset(key, {
121
- state: JSON.stringify(newState),
122
- status: WorkflowStatus.RUNNING,
123
- step: catchStep.toString()
124
- });
125
- }
126
- };
127
- var DurableRuntime = class {
128
- durableFns = /* @__PURE__ */ new Map();
129
- repo = new WorkflowRepository();
130
- workerId = randomUUID();
131
- isRunning = false;
132
- schedulerInterval = null;
133
- sourceRoot;
134
- constructor(options) {
135
- this.sourceRoot = options.sourceRoot;
136
- }
137
- async start(durableFn, options, parentId) {
138
- if (options.workflowId) {
139
- const existing = await this.repo.get(options.workflowId);
140
- if (existing && existing.status !== WorkflowStatus.COMPLETED && existing.status !== WorkflowStatus.FAILED) {
141
- throw new Error(
142
- `Workflow with ID '${options.workflowId}' already exists and is in a running state (${existing.status}).`
143
- );
144
- }
145
- }
146
- const workflowId = options.workflowId ?? randomUUID();
147
- console.log(`[RUNTIME] Iniciando workflow '${durableFn.name}' con ID: ${workflowId}`);
148
- await this.repo.create({
149
- workflowId,
150
- name: durableFn.name,
151
- status: WorkflowStatus.RUNNING,
152
- input: options.input,
153
- parentId
154
- });
155
- this.scheduleExecution(workflowId, durableFn);
156
- return workflowId;
157
- }
158
- async scheduleExecution(workflowId, durableFn, lastResult, initialError) {
159
- setImmediate(() => {
160
- this._executeStep(workflowId, durableFn, lastResult, initialError).catch(
161
- (err) => {
162
- console.error(
163
- `[RUNTIME-FATAL] Error no manejado en la ejecuci\xF3n del workflow ${workflowId}`,
164
- err
165
- );
166
- }
167
- );
168
- });
169
- }
170
- async _executeStep(workflowId, durableFn, lastResult, initialError) {
171
- const hasLock = await this.repo.acquireLock(workflowId);
172
- if (!hasLock) {
173
- console.log(
174
- `[RUNTIME-LOCK] No se pudo adquirir el bloqueo para ${workflowId}, otro proceso est\xE1 trabajando. Se omitir\xE1 este ciclo.`
175
- );
176
- return;
177
- }
178
- let executionError = null;
179
- try {
180
- if (initialError) {
181
- throw initialError;
182
- }
183
- const instance = await this.repo.get(workflowId);
184
- if (!instance) return;
185
- if (instance.status !== WorkflowStatus.RUNNING) {
186
- console.log(
187
- `[RUNTIME] Se intent\xF3 ejecutar el workflow ${workflowId} pero su estado es ${instance.status}. Omitiendo.`
188
- );
189
- return;
190
- }
191
- const context = {
192
- workflowId,
193
- step: instance.step,
194
- input: instance.input,
195
- state: instance.state,
196
- result: lastResult,
197
- log: (message) => console.log(`[WF:${workflowId}] ${message}`)
198
- };
199
- const instruction = await durableFn.execute(context);
200
- await this.repo.updateState(workflowId, context.state);
201
- await this.handleInstruction(instruction, context, instance.name);
202
- } catch (error) {
203
- executionError = error instanceof Error ? error : new Error(String(error));
204
- console.error(`[RUNTIME] Error en workflow ${workflowId}:`, executionError);
205
- } finally {
206
- await this.repo.releaseLock(workflowId);
207
- }
208
- if (executionError) {
209
- await this.handleFailure(workflowId, executionError, durableFn);
210
- }
211
- }
212
- async handleInstruction(instruction, context, durableFunctionName) {
213
- const { workflowId } = context;
214
- switch (instruction.type) {
215
- case "SCHEDULE_TASK": {
216
- await this.repo.enqueueTask({
217
- workflowId,
218
- durableFunctionName,
219
- ...instruction
220
- });
221
- break;
222
- }
223
- case "SCHEDULE_SLEEP": {
224
- const durationMs = ms(instruction.duration);
225
- if (typeof durationMs !== "number") {
226
- throw new Error(
227
- `Invalid time value provided to bSleep: "${instruction.duration}"`
228
- );
229
- }
230
- const wakeUpAt = Date.now() + durationMs;
231
- await this.repo.scheduleSleep(workflowId, wakeUpAt);
232
- break;
233
- }
234
- case "WAIT_FOR_EVENT": {
235
- await this.repo.updateStatus(workflowId, WorkflowStatus.AWAITING_EVENT, {
236
- awaitingEvent: instruction.eventName
237
- });
238
- await redis.sadd(`events:awaiting:${instruction.eventName}`, workflowId);
239
- break;
240
- }
241
- case "EXECUTE_SUBWORKFLOW": {
242
- const subDurableFn = this.durableFns.get(instruction.workflowName);
243
- if (!subDurableFn)
244
- throw new Error(
245
- `Sub-workflow '${instruction.workflowName}' no encontrado.`
246
- );
247
- const subWorkflowId = await this.start(
248
- subDurableFn,
249
- { input: instruction.input },
250
- workflowId
251
- );
252
- await this.repo.updateStatus(
253
- workflowId,
254
- WorkflowStatus.AWAITING_SUBWORKFLOW,
255
- { subWorkflowId }
256
- );
257
- break;
258
- }
259
- case "COMPLETE": {
260
- await this.repo.complete(workflowId, instruction.result);
261
- await this.resumeParentWorkflow(workflowId);
262
- break;
263
- }
264
- }
265
- }
266
- async handleFailure(workflowId, error, durableFn) {
267
- const hasLock = await this.repo.acquireLock(workflowId, 20);
268
- if (!hasLock) {
269
- console.warn(
270
- `[RUNTIME-FAIL] No se pudo adquirir lock para manejar fallo en ${workflowId}. Reintentando m\xE1s tarde...`
271
- );
272
- return;
273
- }
274
- try {
275
- const instance = await this.repo.get(workflowId);
276
- if (!instance || instance.status === WorkflowStatus.FAILED) return;
277
- const stack = instance.state.tryCatchStack;
278
- if (stack && stack.length > 0) {
279
- const handler = stack.pop();
280
- const nextStep = handler?.catchStep;
281
- if (nextStep !== void 0) {
282
- console.log(
283
- `[RUNTIME-FAIL] Excepci\xF3n capturada en ${workflowId}. Saltando a la cl\xE1usula CATCH en el paso ${nextStep}.`
284
- );
285
- await this.repo.resumeForCatch(workflowId, instance.state, nextStep);
286
- this.scheduleExecution(workflowId, durableFn, {
287
- name: error.name,
288
- message: error.message,
289
- stack: error.stack
290
- });
291
- return;
292
- }
293
- }
294
- console.error(`[RUNTIME] Error no capturado en workflow ${workflowId}:`, error);
295
- await this.repo.fail(workflowId, error);
296
- await this.propagateFailureToParent(workflowId, error);
297
- } finally {
298
- await this.repo.releaseLock(workflowId);
299
- }
300
- }
301
- async resumeParentWorkflow(completedWorkflowId) {
302
- const completedInstance = await this.repo.get(completedWorkflowId);
303
- if (!completedInstance?.parentId) return;
304
- const parentId = completedInstance.parentId;
305
- const parentInstance = await this.repo.get(parentId);
306
- if (!parentInstance || parentInstance.status !== WorkflowStatus.AWAITING_SUBWORKFLOW || parentInstance.subWorkflowId !== completedWorkflowId) {
307
- return;
308
- }
309
- console.log(`[RUNTIME] Reanudando workflow padre ${parentId}.`);
310
- const durableFn = this.durableFns.get(parentInstance.name);
311
- if (!durableFn) {
312
- await this.repo.fail(
313
- parentId,
314
- new Error(`Definici\xF3n del workflow '${parentInstance.name}' no encontrada.`)
315
- );
316
- return;
317
- }
318
- await this.repo.updateStatus(parentId, WorkflowStatus.RUNNING, { subWorkflowId: "" });
319
- await this.repo.incrementStep(parentId);
320
- this.scheduleExecution(parentId, durableFn, completedInstance.result);
321
- }
322
- async propagateFailureToParent(failedWorkflowId, error) {
323
- const failedInstance = await this.repo.get(failedWorkflowId);
324
- if (!failedInstance?.parentId) return;
325
- const parentId = failedInstance.parentId;
326
- const parentInstance = await this.repo.get(parentId);
327
- if (!parentInstance || parentInstance.status !== WorkflowStatus.AWAITING_SUBWORKFLOW || parentInstance.subWorkflowId !== failedWorkflowId) {
328
- return;
329
- }
330
- console.log(
331
- `[RUNTIME] Propagando fallo del sub-workflow ${failedWorkflowId} al padre ${parentId}.`
332
- );
333
- const durableFn = this.durableFns.get(parentInstance.name);
334
- if (!durableFn) {
335
- await this.repo.fail(
336
- parentId,
337
- new Error(
338
- `Definici\xF3n del workflow '${parentInstance.name}' no encontrada al propagar fallo.`
339
- )
340
- );
341
- return;
342
- }
343
- await this.repo.updateStatus(parentId, WorkflowStatus.RUNNING, { subWorkflowId: "" });
344
- const propagationError = new Error(
345
- `Sub-workflow '${failedInstance.name}' (${failedWorkflowId}) fall\xF3: ${error.message}`
346
- );
347
- propagationError.stack = error.stack;
348
- this.scheduleExecution(parentId, durableFn, void 0, propagationError);
349
- }
350
- async sendEvent(workflowId, eventName, payload) {
351
- let hasLock = false;
352
- for (let i = 0; i < 3; i++) {
353
- hasLock = await this.repo.acquireLock(workflowId);
354
- if (hasLock) {
355
- break;
356
- }
357
- await new Promise((resolve2) => setTimeout(resolve2, 50));
358
- }
359
- if (!hasLock) {
360
- console.warn(
361
- `[RUNTIME-LOCK] No se pudo adquirir el bloqueo para sendEvent en ${workflowId}. El evento podr\xEDa ser descartado o retrasado.`
362
- );
363
- return;
364
- }
365
- try {
366
- const instance = await this.repo.get(workflowId);
367
- if (!instance) {
368
- console.warn(
369
- `[RUNTIME] Se intent\xF3 enviar un evento a un workflow no existente: ${workflowId}`
370
- );
371
- return;
372
- }
373
- if (instance.status !== WorkflowStatus.AWAITING_EVENT || instance.awaitingEvent !== eventName) {
374
- console.warn(
375
- `[RUNTIME] El workflow ${workflowId} no est\xE1 esperando el evento '${eventName}'. Estado actual: ${instance.status}, esperando: ${instance.awaitingEvent}.`
376
- );
377
- return;
378
- }
379
- console.log(
380
- `[RUNTIME] Evento '${eventName}' recibido para el workflow ${workflowId}. Reanudando...`
381
- );
382
- const durableFn = this.durableFns.get(instance.name);
383
- if (!durableFn) {
384
- console.error(
385
- `[RUNTIME] La definici\xF3n de la funci\xF3n durable '${instance.name}' no se encontr\xF3 para el workflow ${workflowId}.`
386
- );
387
- await this.repo.fail(
388
- workflowId,
389
- new Error(`Funci\xF3n durable '${instance.name}' no encontrada.`)
390
- );
391
- return;
392
- }
393
- await this.repo.updateStatus(workflowId, WorkflowStatus.RUNNING, {
394
- awaitingEvent: ""
395
- });
396
- await redis.srem(`events:awaiting:${eventName}`, workflowId);
397
- await this.repo.incrementStep(workflowId);
398
- this.scheduleExecution(workflowId, durableFn, payload);
399
- } catch (error) {
400
- console.error(
401
- `[RUNTIME] Error procesando el evento '${eventName}' para el workflow ${workflowId}:`,
402
- error
403
- );
404
- await this.repo.fail(
405
- workflowId,
406
- new Error(
407
- `Fallo al procesar el evento: ${error instanceof Error ? error.message : String(error)}`
408
- )
409
- );
410
- } finally {
411
- await this.repo.releaseLock(workflowId);
412
- }
413
- }
414
- startScheduler() {
415
- if (this.schedulerInterval) return;
416
- console.log("[SCHEDULER] Scheduler iniciado.");
417
- const checkSleepers = async () => {
418
- const workflowIds = await this.repo.getWorkflowsToWake();
419
- for (const workflowId of workflowIds) {
420
- const instance = await this.repo.get(workflowId);
421
- if (instance) {
422
- const durableFn = this.durableFns.get(instance.name);
423
- if (durableFn) {
424
- console.log(`[SCHEDULER] Reanudando workflow ${workflowId}`);
425
- await this.repo.updateStatus(
426
- workflowId,
427
- WorkflowStatus.RUNNING
428
- );
429
- await this.repo.incrementStep(workflowId);
430
- this.scheduleExecution(workflowId, durableFn, null);
431
- }
432
- }
433
- }
434
- };
435
- this.schedulerInterval = setInterval(checkSleepers, 2e3);
436
- }
437
- startWorker() {
438
- if (this.isRunning) return;
439
- this.isRunning = true;
440
- const processingQueueKey = `${TASK_QUEUE_KEY}:processing:${this.workerId}`;
441
- console.log(`[WORKER] Worker ${this.workerId} iniciado, esperando tareas...`);
442
- const listenForTasks = async () => {
443
- while (this.isRunning) {
444
- try {
445
- const taskString = await blockingRedis.brpoplpush(
446
- TASK_QUEUE_KEY,
447
- processingQueueKey,
448
- 0
449
- );
450
- if (!taskString) continue;
451
- const task = JSON.parse(taskString);
452
- console.log(`[WORKER] Tarea recibida: ${task.exportName}`);
453
- try {
454
- let module;
455
- if (task.modulePath.startsWith("virtual:")) {
456
- module = await import(task.modulePath);
457
- } else {
458
- const moduleFullPath = resolve(
459
- this.sourceRoot,
460
- task.modulePath
461
- );
462
- module = await import(moduleFullPath);
463
- }
464
- const serviceFn = module[task.exportName];
465
- if (typeof serviceFn !== "function")
466
- throw new Error(
467
- `'${task.exportName}' no es una funci\xF3n.`
468
- );
469
- const serviceResult = await serviceFn(...task.args);
470
- const durableFn = this.durableFns.get(task.durableFunctionName);
471
- if (durableFn) {
472
- await this.repo.incrementStep(task.workflowId);
473
- this.scheduleExecution(
474
- task.workflowId,
475
- durableFn,
476
- serviceResult
477
- );
478
- }
479
- await redis.lrem(processingQueueKey, 1, taskString);
480
- } catch (taskError) {
481
- const err = taskError instanceof Error ? taskError : new Error(String(taskError));
482
- console.error(
483
- `[WORKER] Falla en la tarea '${task.exportName}' para workflow ${task.workflowId}`,
484
- err
485
- );
486
- const durableFn = this.durableFns.get(task.durableFunctionName);
487
- if (durableFn) {
488
- await this.handleFailure(task.workflowId, err, durableFn);
489
- } else {
490
- await this.repo.fail(
491
- task.workflowId,
492
- new Error(
493
- `Definici\xF3n de workflow ${task.durableFunctionName} no encontrada durante el manejo de fallos.`
494
- )
495
- );
496
- }
497
- console.log(
498
- `[WORKER] Eliminando tarea procesada (con error manejado): ${task.exportName}`
499
- );
500
- await redis.lrem(processingQueueKey, 1, taskString);
501
- }
502
- } catch (error) {
503
- if (!this.isRunning) break;
504
- console.error("[WORKER] Error de infraestructura:", error);
505
- await new Promise((resolve2) => setTimeout(resolve2, 5e3));
506
- }
507
- }
508
- };
509
- listenForTasks();
510
- }
511
- run(durableFns) {
512
- this.durableFns = durableFns;
513
- this.startWorker();
514
- this.startScheduler();
515
- }
516
- stop() {
517
- this.isRunning = false;
518
- if (this.schedulerInterval) {
519
- clearInterval(this.schedulerInterval);
520
- }
521
- console.log("[RUNTIME] Solicitando detenci\xF3n...");
522
- }
523
- };
524
-
525
- // src/define.ts
526
- var bDurable = (def) => {
527
- return def;
528
- };
529
-
530
- // src/index.ts
531
- function bDurableInitialize(options) {
532
- console.log("--- Inicializando Sistema Durable ---");
533
- configurePersistence({
534
- commandClient: options.redisClient,
535
- blockingClient: options.blockingRedisClient
536
- });
537
- const runtime = new DurableRuntime({ sourceRoot: options.sourceRoot });
538
- runtime.run(options.durableFunctions);
539
- return {
540
- start: runtime.start.bind(runtime),
541
- sendEvent: (durableFn, workflowId, eventName, payload) => {
542
- return runtime.sendEvent(workflowId, eventName, payload);
543
- },
544
- stop: runtime.stop.bind(runtime),
545
- runtime
546
- };
547
- }
548
- export {
549
- bDurable,
550
- bDurableInitialize
551
- };
1
+ import P from"ioredis";var w="queue:tasks",m="durable:sleepers",v="worker:heartbeat:",W="queue:dead";function O(u){return`workflow:${u}`}var l={RUNNING:"RUNNING",SLEEPING:"SLEEPING",COMPLETED:"COMPLETED",FAILED:"FAILED",AWAITING_EVENT:"AWAITING_EVENT",AWAITING_SUBWORKFLOW:"AWAITING_SUBWORKFLOW",CANCELLING:"CANCELLING",CANCELLED:"CANCELLED",VERSION_MISMATCH:"VERSION_MISMATCH"};var o,E;function N(u){if(o||E){console.warn("[Persistence] Los clientes de Redis ya han sido configurados. Omitiendo.");return}o=u.commandClient,E=u.blockingClient}import{randomUUID as R}from"crypto";import L from"ms";import{resolve as D}from"path";var k=class extends Error{isCancellation=!0;constructor(t){super(t),this.name="WorkflowCancellationError"}};var x={info:(u,t)=>console.log(`[INFO] ${u}`,t||""),error:(u,t)=>console.error(`[ERROR] ${u}`,t||""),warn:(u,t)=>console.warn(`[WARN] ${u}`,t||""),debug:(u,t)=>console.debug(`[DEBUG] ${u}`,t||"")},I=class{constructor(t){this.retention=t}getKey(t){return`workflow:${t}`}getLockKey(t){return`workflow:${t}:lock`}async acquireLock(t,e=10){let s=this.getLockKey(t);return await o.set(s,"locked","EX",e,"NX")==="OK"}async releaseLock(t){await o.del(this.getLockKey(t))}async get(t){let e=await o.hgetall(this.getKey(t));return!e||Object.keys(e).length===0?null:{workflowId:e.workflowId,name:e.name,version:e.version,status:e.status,step:parseInt(e.step,10),input:JSON.parse(e.input),state:JSON.parse(e.state),result:e.result?JSON.parse(e.result):void 0,error:e.error,parentId:e.parentId,subWorkflowId:e.subWorkflowId,awaitingEvent:e.awaitingEvent,createdAt:e.createdAt?parseInt(e.createdAt,10):0,updatedAt:e.updatedAt?parseInt(e.updatedAt,10):0}}async create(t){let e=Date.now(),s={...t,step:0,state:{},createdAt:e,updatedAt:e},n={...s,input:JSON.stringify(s.input),state:JSON.stringify(s.state)};n.version===void 0&&delete n.version;let a=o.pipeline();a.hset(this.getKey(s.workflowId),n),await a.exec()}async updateState(t,e){await o.hset(this.getKey(t),{state:JSON.stringify(e),updatedAt:Date.now()})}async updateStatus(t,e,s={}){await o.hset(this.getKey(t),{status:e,...s,updatedAt:Date.now()})}async incrementStep(t){return o.hincrby(this.getKey(t),"step",1)}async applyRetention(t){if(this.retention){let e=L(this.retention)/1e3;e>0&&await o.expire(this.getKey(t),e)}}async complete(t,e){await o.hset(this.getKey(t),{status:l.COMPLETED,result:JSON.stringify(e??null)}),await this.applyRetention(t)}async fail(t,e,s=l.FAILED){await o.hset(this.getKey(t),{status:s,error:e.message}),await this.applyRetention(t)}async scheduleSleep(t,e){await this.updateStatus(t,l.SLEEPING),await o.zadd(m,e,t)}async getWorkflowsToWake(){let t=Date.now(),e=await o.zrangebyscore(m,0,t);return e.length>0&&await o.zrem(m,...e),e}async enqueueTask(t){await o.lpush(w,JSON.stringify(t))}async resumeForCatch(t,e,s){let n=this.getKey(t);await o.hset(n,{state:JSON.stringify(e),status:l.RUNNING,step:s.toString()})}async moveToDLQ(t,e){let s={...t,failedAt:Date.now(),error:e.message,stack:e.stack};await o.lpush(W,JSON.stringify(s))}},S=class{durableFns=new Map;repo;workerId=R();isRunning=!1;schedulerInterval=null;heartbeatInterval=null;sourceRoot;pollingInterval;logger;maxTaskRetries=3;constructor(t){this.sourceRoot=t.sourceRoot,this.repo=new I(t.retention),this.pollingInterval=t.pollingInterval||5e3,this.logger=t.logger||x}async getState(t){let e=await this.repo.get(t);return e?{workflowId:e.workflowId,name:e.name,version:e.version,status:e.status,step:e.step,input:e.input,output:e.result,state:e.state,error:e.error,createdAt:e.createdAt,updatedAt:e.updatedAt}:null}async start(t,e,s){if(e.workflowId){let r=await this.repo.get(e.workflowId);if(r&&r.status!==l.COMPLETED&&r.status!==l.FAILED)throw new Error(`Workflow with ID '${e.workflowId}' already exists and is in a running state (${r.status}).`)}let n=e.workflowId??R();this.logger.info(`[RUNTIME] Iniciando workflow '${t.name}' v${t.version} con ID: ${n}`),await this.repo.create({workflowId:n,name:t.name,version:t.version,status:l.RUNNING,input:e.input,parentId:s});let a=async()=>{};if(e.subscribe){let r=o.duplicate(),i=`signal:${n}`;r.on("message",(c,g)=>{if(c===i)try{let p=JSON.parse(g),f={name:p.signalName,payload:p.payload};e.subscribe?.(f)}catch(p){this.logger.error("Error al procesar se\xF1al",{error:p,workflowId:n})}}),await r.subscribe(i),a=async()=>{r.status==="ready"&&(r.unsubscribe(i).catch(()=>{}),r.quit().catch(()=>{}))}}return setImmediate(()=>{this._executeStep(n,t).catch(r=>{this.logger.error("Error fatal en ejecuci\xF3n inicial",{error:r,workflowId:n})})}),{workflowId:n,unsubscribe:a}}async scheduleExecution(t,e,s,n){setImmediate(()=>{this._executeStep(t,e,s,n).catch(a=>{this.logger.error("Error no manejado en scheduleExecution",{error:a,workflowId:t})})})}async _executeStep(t,e,s,n){if(await this.repo.acquireLock(t))try{if(n)throw n;let r=await this.repo.get(t);if(!r)return;if(r.status===l.CANCELLING)throw new k(r.error||"Workflow cancelled");if(r.status!==l.RUNNING)return;let i=r.version==="undefined"?void 0:r.version,c=e.version==="undefined"?void 0:e.version;if(String(i??"")!==String(c??"")){let d=new Error(`Version mismatch: DB=${i}, Code=${c}`);await this.repo.fail(t,d,l.VERSION_MISMATCH);return}let g={workflowId:t,step:r.step,input:r.input,state:r.state,result:s,log:(d,T)=>this.logger.info(d,{...T,workflowId:t,step:r.step})},p=await e.execute(g);await this.repo.updateState(t,g.state),await this.handleInstruction(p,g,r.name)&&(await this.repo.incrementStep(t),this.scheduleExecution(t,e,void 0))}catch(r){let i=r instanceof Error?r:new Error(String(r));this.logger.error("Error en workflow",{workflowId:t,error:i.message}),await this.handleFailure(t,i,e,!0)}finally{await this.repo.releaseLock(t)}}async handleInstruction(t,e,s){let{workflowId:n}=e;switch(t.type){case"SCHEDULE_TASK":return await this.repo.enqueueTask({workflowId:n,durableFunctionName:s,...t}),!1;case"SCHEDULE_SLEEP":{let a=L(t.duration);if(typeof a!="number")throw new Error(`Invalid time value provided to bSleep: "${t.duration}"`);let r=Date.now()+a;return await this.repo.scheduleSleep(n,r),!1}case"WAIT_FOR_EVENT":return await this.repo.updateStatus(n,l.AWAITING_EVENT,{awaitingEvent:t.eventName}),await o.sadd(`events:awaiting:${t.eventName}`,n),!1;case"EXECUTE_SUBWORKFLOW":{let a=this.durableFns.get(t.workflowName);if(!a)throw new Error(`Sub-workflow '${t.workflowName}' no encontrado.`);let{workflowId:r}=await this.start(a,{input:t.input},n);return await this.repo.updateStatus(n,l.AWAITING_SUBWORKFLOW,{subWorkflowId:r}),!1}case"SEND_SIGNAL":{let a=`signal:${n}`,r=JSON.stringify({signalName:t.signalName,payload:t.payload});return await o.publish(a,r),!0}case"COMPLETE":{let a=`signal:${n}`,r=JSON.stringify({signalName:"workflow:completed",payload:t.result});return await o.publish(a,r),await this.repo.complete(n,t.result),await this.resumeParentWorkflow(n),!1}}}async handleFailure(t,e,s,n=!1){if(!n&&!await this.repo.acquireLock(t,20)){this.logger.warn(`No se pudo adquirir lock para fallo en ${t}`);return}try{if(e instanceof k){await this.repo.fail(t,e,l.CANCELLED);let g=await this.repo.get(t);g?.subWorkflowId&&await this.cancel(g.subWorkflowId,`Parent workflow ${t} was cancelled`);return}let a=await this.repo.get(t);if(!a||a.status===l.FAILED||a.status===l.COMPLETED)return;let r=a.state.tryCatchStack;if(r&&r.length>0){let p=r.pop()?.catchStep;if(p!==void 0){this.logger.info(`Capturando error en step ${p}`,{workflowId:t}),await this.repo.resumeForCatch(t,a.state,p),this.scheduleExecution(t,s,{name:e.name,message:e.message,stack:e.stack});return}}let i=`signal:${t}`,c=JSON.stringify({signalName:"workflow:failed",payload:{message:e.message}});await o.publish(i,c),await this.repo.fail(t,e),await this.propagateFailureToParent(t,e)}finally{n||await this.repo.releaseLock(t)}}async resumeParentWorkflow(t){let e=await this.repo.get(t);if(!e?.parentId)return;let s=e.parentId,n=await this.repo.get(s);if(!n||n.status!==l.AWAITING_SUBWORKFLOW||n.subWorkflowId!==t)return;let a=this.durableFns.get(n.name);if(!a){await this.repo.fail(s,new Error(`Definici\xF3n del workflow '${n.name}' no encontrada.`));return}await this.repo.updateStatus(s,l.RUNNING,{subWorkflowId:""}),await this.repo.incrementStep(s),this.scheduleExecution(s,a,e.result)}async propagateFailureToParent(t,e){let s=await this.repo.get(t);if(!s?.parentId)return;let n=s.parentId,a=await this.repo.get(n);if(!a||a.status!==l.AWAITING_SUBWORKFLOW||a.subWorkflowId!==t)return;let r=this.durableFns.get(a.name);if(!r){await this.repo.fail(n,new Error(`Definici\xF3n del workflow '${a.name}' no encontrada al propagar fallo.`));return}await this.repo.updateStatus(n,l.RUNNING,{subWorkflowId:""});let i=new Error(`Sub-workflow '${s.name}' (${t}) fall\xF3: ${e.message}`);i.stack=e.stack,this.scheduleExecution(n,r,void 0,i)}async sendEvent(t,e,s){let n=!1;for(let a=0;a<3&&(n=await this.repo.acquireLock(t),!n);a++)await new Promise(r=>setTimeout(r,50));if(!n)return this.logger.warn("Lock timeout en sendEvent",{workflowId:t});try{let a=await this.repo.get(t);if(!a)return this.logger.warn("Evento para workflow inexistente",{workflowId:t});if(a.status!==l.AWAITING_EVENT||a.awaitingEvent!==e)return this.logger.warn("Workflow no esperaba este evento",{workflowId:t,expected:a.awaitingEvent,received:e});let r=this.durableFns.get(a.name);if(!r){await this.repo.fail(t,new Error(`Funci\xF3n durable '${a.name}' no encontrada.`));return}await this.repo.updateStatus(t,l.RUNNING,{awaitingEvent:""}),await o.srem(`events:awaiting:${e}`,t),await this.repo.incrementStep(t),this.scheduleExecution(t,r,s)}catch(a){let r=a instanceof Error?a:new Error(String(a)),i=(await this.repo.get(t))?.name||"",c=this.durableFns.get(i);await this.handleFailure(t,r,c,!0)}finally{await this.repo.releaseLock(t)}}async cancel(t,e){if(!await this.repo.acquireLock(t))return await new Promise(n=>setTimeout(n,100)),this.cancel(t,e);try{let n=await this.repo.get(t);if(!n||[l.COMPLETED,l.FAILED,l.CANCELLED].includes(n.status))return;if(await this.repo.updateStatus(t,l.CANCELLING,{error:e}),n.status===l.SLEEPING){await o.zrem(m,t);let a=this.durableFns.get(n.name);this.scheduleExecution(t,a)}if(n.status===l.AWAITING_EVENT){let a=this.durableFns.get(n.name);this.scheduleExecution(t,a)}}finally{await this.repo.releaseLock(t)}}startScheduler(){if(this.schedulerInterval)return;this.logger.info(`Scheduler iniciado (${this.pollingInterval}ms)`);let t=async()=>{await this.checkSleepers(),await this.reapDeadWorkers()};this.schedulerInterval=setInterval(t,this.pollingInterval)}async checkSleepers(){let t=await this.repo.getWorkflowsToWake();for(let e of t){let s=await this.repo.get(e);if(s){let n=this.durableFns.get(s.name);n&&(this.logger.info("Despertando workflow",{workflowId:e}),await this.repo.updateStatus(e,l.RUNNING),await this.repo.incrementStep(e),this.scheduleExecution(e,n,void 0))}}}async reapDeadWorkers(){let t=await o.keys(`${w}:processing:*`);for(let e of t){let s=e.split(":").pop();if(!s||await o.exists(`${v}${s}`))continue;this.logger.warn(`Worker muerto ${s}. Recuperando tareas.`);let n=await o.rpoplpush(e,w);for(;n;)n=await o.rpoplpush(e,w);await o.del(e)}}startHeartbeat(){let t=`${v}${this.workerId}`,e=Math.max(Math.ceil(this.pollingInterval*3/1e3),5),s=()=>{this.isRunning&&o.set(t,Date.now().toString(),"EX",e).catch(()=>{})};this.heartbeatInterval=setInterval(s,this.pollingInterval),s()}startWorker(){if(this.isRunning)return;this.isRunning=!0;let t=`${w}:processing:${this.workerId}`;this.logger.info(`Worker ${this.workerId} iniciado`),this.startHeartbeat(),(async()=>{for(;this.isRunning;)try{let s=await E.brpoplpush(w,t,0);if(!s)continue;let n=JSON.parse(s);this.logger.debug(`Ejecutando tarea: ${n.exportName}`,{workflowId:n.workflowId});try{let a;n.modulePath.startsWith("virtual:")?a=await import(n.modulePath):a=await import(D(this.sourceRoot,n.modulePath));let r=a[n.exportName];if(typeof r!="function")throw new Error(`'${n.exportName}' no es una funci\xF3n.`);let i=await r(...n.args),c=this.durableFns.get(n.durableFunctionName);c&&(await this.repo.incrementStep(n.workflowId),this.scheduleExecution(n.workflowId,c,i)),await o.lrem(t,1,s)}catch(a){let r=a instanceof Error?a:new Error(String(a));this.logger.error(`Fallo en tarea ${n.exportName}`,{workflowId:n.workflowId,error:r.message});let i=(n.attempts||0)+1;if(i<=this.maxTaskRetries)this.logger.warn(`Reintentando tarea (intento ${i}/${this.maxTaskRetries})`,{workflowId:n.workflowId}),n.attempts=i,await o.lpush(w,JSON.stringify(n)),await o.lrem(t,1,s);else{this.logger.error("Reintentos agotados. Moviendo a DLQ.",{workflowId:n.workflowId}),await this.repo.moveToDLQ(n,r);let c=this.durableFns.get(n.durableFunctionName);c?await this.handleFailure(n.workflowId,r,c):await this.repo.fail(n.workflowId,new Error(`Def missing for ${n.durableFunctionName}`)),await o.lrem(t,1,s)}}}catch(s){if(!this.isRunning)break;this.logger.error("Error infraestructura worker",{error:s}),await new Promise(n=>setTimeout(n,5e3))}})()}run(t){this.durableFns=t,this.startWorker(),this.startScheduler()}stop(){this.isRunning=!1,this.schedulerInterval&&clearInterval(this.schedulerInterval),this.heartbeatInterval&&clearInterval(this.heartbeatInterval),this.logger.info("Runtime detenido")}};var F=u=>({...u,__isDurable:!0});var A={info:(u,t)=>console.log(`[INFO] ${u}`,t||""),error:(u,t)=>console.error(`[ERROR] ${u}`,t||""),warn:(u,t)=>console.warn(`[WARN] ${u}`,t||""),debug:(u,t)=>console.debug(`[DEBUG] ${u}`,t||"")};function it(u){let t=u.logger||A;t.info("--- Inicializando Sistema Durable ---");let e=new P(u.redisClient.options),s=new Map;e.psubscribe("signal:*",r=>{r&&t.error("Error fatal al suscribirse a los canales de se\xF1ales:",{error:r})}),e.on("pmessage",(r,i,c)=>{let g=s.get(i);if(g&&g.length>0)try{let p=JSON.parse(c),f={name:p.signalName,payload:p.payload};[...g].forEach(d=>d(f))}catch(p){t.error(`Error al parsear mensaje de se\xF1al en ${i}`,{error:p})}});let n=(r,i)=>{let c=()=>{};return{workflowId:i,subscribe:async g=>{let p=`signal:${i}`,f=O(i),d=await u.redisClient.hgetall(f);if(d.status===l.COMPLETED)return g({name:"workflow:completed",payload:JSON.parse(d.result||"null")},c),{unsubscribe:c};if(d.status===l.FAILED)return g({name:"workflow:failed",payload:{message:d.error||"Unknown error"}},c),{unsubscribe:c};let T=null,b=()=>{if(!T)return;let h=s.get(p);if(h){let y=h.indexOf(T);y>-1&&h.splice(y,1),h.length===0&&s.delete(p)}};return T=h=>{g(h,b)},s.has(p)||s.set(p,[]),s.get(p)?.push(T),{unsubscribe:b}}}};N({commandClient:u.redisClient,blockingClient:u.blockingRedisClient});let a=new S({sourceRoot:u.sourceRoot,retention:u.retention,pollingInterval:u.pollingInterval,logger:t});return a.run(u.durableFunctions),{start:async(r,i)=>a.start(r,i),cancel:(r,i)=>a.cancel(r,i),getState:r=>a.getState(r),getWorkflowHandle:(r,i)=>n(r,i),sendEvent:(r,i,c,g)=>a.sendEvent(i,c,g),stop:()=>{a.stop(),e.quit().catch(()=>{})},runtime:a}}export{k as WorkflowCancellationError,F as bDurable,it as bDurableInitialize};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bobtail.software/b-durable",
3
- "version": "1.0.5",
3
+ "version": "1.0.6",
4
4
  "main": "dist/index.mjs",
5
5
  "types": "dist/index.d.mts",
6
6
  "description": "A system for creating durable, resilient, and type-safe workflows in JavaScript/TypeScript.",