@bobtail.software/b-durable 1.0.3 → 1.0.5

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.mts CHANGED
@@ -1,11 +1,18 @@
1
1
  import Redis from 'ioredis';
2
2
  import ms from 'ms';
3
3
 
4
+ interface WorkflowState {
5
+ tryCatchStack?: {
6
+ catchStep?: number;
7
+ finallyStep?: number;
8
+ }[];
9
+ [key: string]: unknown;
10
+ }
4
11
  interface WorkflowContext<TInput = unknown> {
5
12
  workflowId: string;
6
13
  step: number;
7
14
  input: TInput;
8
- state: Record<string, unknown>;
15
+ state: WorkflowState;
9
16
  result?: unknown;
10
17
  log: (message: string) => void;
11
18
  }
@@ -28,26 +35,34 @@ type Instruction<TOutput = unknown> = {
28
35
  type: 'COMPLETE';
29
36
  result: TOutput;
30
37
  };
31
- interface DurableFunction<TInput = unknown, TOutput = unknown> {
38
+ interface DurableFunction<TInput = unknown, TOutput = unknown, TEvents = Record<string, never>> {
32
39
  __isDurable: true;
33
40
  name: string;
34
41
  execute: (context: WorkflowContext<TInput>) => Promise<Instruction<TOutput>>;
42
+ _TEvents?: TEvents;
35
43
  }
36
44
 
45
+ interface StartOptions<TInput> {
46
+ input: TInput;
47
+ workflowId?: string;
48
+ }
37
49
  declare class DurableRuntime {
38
50
  private durableFns;
39
- private isWorkerRunning;
40
- private isSchedulerRunning;
51
+ private repo;
52
+ private workerId;
53
+ private isRunning;
41
54
  private schedulerInterval;
42
55
  private readonly sourceRoot;
43
56
  constructor(options: {
44
57
  sourceRoot: string;
45
58
  });
46
- start<TInput, TOutput>(durableFn: DurableFunction<TInput, TOutput>, input: TInput, parentId?: string, predefinedWorkflowId?: string): Promise<string>;
47
- private executeStep;
59
+ start<TInput, TOutput>(durableFn: DurableFunction<TInput, TOutput>, options: StartOptions<TInput>, parentId?: string): Promise<string>;
60
+ private scheduleExecution;
61
+ private _executeStep;
48
62
  private handleInstruction;
63
+ private handleFailure;
49
64
  private resumeParentWorkflow;
50
- private failParentWorkflow;
65
+ private propagateFailureToParent;
51
66
  sendEvent<T>(workflowId: string, eventName: string, payload: T): Promise<void>;
52
67
  private startScheduler;
53
68
  private startWorker;
@@ -55,42 +70,56 @@ declare class DurableRuntime {
55
70
  stop(): void;
56
71
  }
57
72
 
58
- type DurableWorkflowFn<TInput, TOutput> = (input: TInput, context: Pick<WorkflowContext<TInput>, 'log' | 'workflowId'>) => Promise<TOutput>;
59
- /**
60
- * Marcador para que el compilador identifique y transforme una función en un workflow durable.
61
- * Esta función es un passthrough en tiempo de ejecución, su único propósito es para el análisis estático.
62
- * @param fn La función async que define la lógica del workflow.
63
- */
64
- declare const bDurable: <TInput, TOutput>(fn: DurableWorkflowFn<TInput, TOutput>) => DurableWorkflowFn<TInput, TOutput>;
65
-
66
73
  /**
67
- * Ejecuta un sub-workflow y espera de forma duradera su resultado.
68
- * @param workflow La función durable a ejecutar.
69
- * @param input La entrada para el sub-workflow.
70
- * @returns Una promesa que se resuelve con el resultado del sub-workflow.
74
+ * El contexto de ejecución proporcionado a cada workflow, con métodos de durabilidad tipados.
71
75
  */
72
- declare function bExecute<TInput, TOutput>(workflow: DurableWorkflowFn<TInput, TOutput>, input: TInput): Promise<TOutput>;
73
-
74
- /**
75
- * Pausa la ejecución del workflow de manera duradera.
76
- * Esta función es un marcador especial que el compilador `b-durable` transforma
77
- * en una instrucción para el runtime. No se ejecuta directamente.
78
- * @param duration Una cadena de tiempo como '2 days', '10h', '7s'.
79
- */
80
- declare function bSleep(duration: ms.StringValue): Promise<void>;
81
-
76
+ interface DurableContext<TEvents = Record<string, never>> extends Pick<WorkflowContext, 'log' | 'workflowId'> {
77
+ /**
78
+ * Pausa la ejecución del workflow de manera duradera.
79
+ * @param duration Una cadena de tiempo como '2 days', '10h', '7s'.
80
+ */
81
+ bSleep(duration: ms.StringValue): Promise<void>;
82
+ /**
83
+ * Pausa la ejecución del workflow hasta que se reciba un evento externo.
84
+ * El tipo del payload retornado se infiere automáticamente del contrato de eventos del workflow.
85
+ * @param eventName El nombre único del evento que se está esperando.
86
+ * @returns Una promesa que se resuelve con el payload del evento recibido.
87
+ */
88
+ bWaitForEvent<K extends keyof TEvents>(eventName: K): Promise<TEvents[K]>;
89
+ /**
90
+ * Ejecuta un sub-workflow y espera de forma duradera su resultado.
91
+ * @param workflow La función durable a ejecutar.
92
+ * @param input La entrada para el sub-workflow.
93
+ * @returns Una promesa que se resuelve con el resultado del sub-workflow.
94
+ */
95
+ bExecute<TInput, TOutput, TWorkflowEvents extends Record<string, any>>(workflow: DurableFunction<TInput, TOutput, TWorkflowEvents>, input: TInput): Promise<TOutput>;
96
+ }
97
+ type DurableWorkflowFn<TInput, TOutput, TEvents = Record<string, never>> = (input: TInput, context: DurableContext<TEvents>) => Promise<TOutput>;
98
+ interface DurableWorkflowDef<TInput, TOutput, TEvents = Record<string, never>> {
99
+ /**
100
+ * La función async que contiene la lógica del workflow.
101
+ */
102
+ workflow: DurableWorkflowFn<TInput, TOutput, TEvents>;
103
+ }
82
104
  /**
83
- * Pausa la ejecución del workflow hasta que se reciba un evento externo.
84
- * @param eventName El nombre único del evento que se está esperando.
85
- * @returns Una promesa que se resuelve con el payload del evento recibido.
105
+ * Marcador para que el compilador identifique y transforme una función en un workflow durable.
106
+ * Esta función es un passthrough en tiempo de ejecución, su único propósito es para el análisis estático.
86
107
  */
87
- declare function bWaitForEvent<T>(eventName: string): Promise<T>;
108
+ declare const bDurable: <TInput = any, TOutput = any, TEvents = Record<string, never>>(def: DurableWorkflowDef<TInput, TOutput, TEvents>) => DurableFunction<TInput, TOutput, TEvents>;
88
109
 
89
110
  interface BDurableAPI {
90
- start: <TInput, TOutput>(durableFn: DurableFunction<TInput, TOutput>, input: TInput) => Promise<string>;
111
+ start: <TInput, TOutput>(durableFn: DurableFunction<TInput, TOutput>, options: StartOptions<TInput>) => Promise<string>;
91
112
  stop: () => void;
92
113
  runtime: DurableRuntime;
93
- sendEvent: <T>(workflowId: string, eventName: string, payload: T) => Promise<void>;
114
+ /**
115
+ * Envía un evento a un workflow en ejecución que está en pausa esperando dicho evento.
116
+ * Esta función es estrictamente tipada basada en el tipo de eventos de la definición del workflow.
117
+ * @param durableFn La definición del workflow al que se le enviará el evento. Se usa para la inferencia de tipos.
118
+ * @param workflowId El ID del workflow al que se le enviará el evento.
119
+ * @param eventName El nombre del evento. Será autocompletado por el editor.
120
+ * @param payload La carga útil del evento. El tipo debe coincidir con el definido para `eventName`.
121
+ */
122
+ sendEvent: <TInput, TOutput, TWorkflowEvents, K extends keyof TWorkflowEvents>(durableFn: DurableFunction<TInput, TOutput, TWorkflowEvents>, workflowId: string, eventName: K, payload: TWorkflowEvents[K]) => Promise<void>;
94
123
  }
95
124
  interface InitializeOptions {
96
125
  durableFunctions: Map<string, DurableFunction<unknown, unknown>>;
@@ -100,4 +129,4 @@ interface InitializeOptions {
100
129
  }
101
130
  declare function bDurableInitialize(options: InitializeOptions): BDurableAPI;
102
131
 
103
- export { type BDurableAPI, type DurableFunction, type Instruction, type WorkflowContext, bDurable, bDurableInitialize, bExecute, bSleep, bWaitForEvent };
132
+ export { type BDurableAPI, type DurableFunction, type Instruction, type StartOptions, type WorkflowContext, type WorkflowState, bDurable, bDurableInitialize };