dataflow-rs 2.1.5

A lightweight rules engine for building IFTTT-style automation and data processing pipelines in Rust. Define rules with JSONLogic conditions, execute actions, and chain workflows.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
import { createContext, useContext, useReducer, useCallback, useEffect, useRef, useMemo, ReactNode } from 'react';
import type {
  DebuggerState,
  DebuggerAction,
  ExecutionTrace,
  ExecutionStep,
  Message,
  Workflow,
  DataflowEngine,
  EngineFactory,
} from '../../../types';
import { getMessageAtStep, getChangesAtStep } from '../../../types';
import type { Change } from '../../../types';
import { PLAYBACK } from '../constants';

/**
 * Initial debugger state
 */
const initialState: DebuggerState = {
  isActive: false,
  trace: null,
  currentStepIndex: -1,
  playbackState: 'stopped',
  playbackSpeed: PLAYBACK.DEFAULT_SPEED_MS,
  inputPayload: null,
  isExecuting: false,
  executionError: null,
  skipFailedConditions: false,
};

/**
 * Get filtered step indices based on skipFailedConditions setting.
 * Returns indices of steps that should be shown during debugging.
 */
function getFilteredStepIndices(trace: ExecutionTrace | null, skipFailedConditions: boolean): number[] {
  if (!trace || trace.steps.length === 0) {
    return [];
  }
  if (!skipFailedConditions) {
    return trace.steps.map((_, i) => i);
  }
  return trace.steps
    .map((step, i) => ({ step, index: i }))
    .filter(({ step }) => step.result !== 'skipped')
    .map(({ index }) => index);
}

/**
 * Debugger reducer
 */
function debuggerReducer(state: DebuggerState, action: DebuggerAction): DebuggerState {
  switch (action.type) {
    case 'ACTIVATE':
      return {
        ...state,
        isActive: true,
      };

    case 'DEACTIVATE':
      return {
        ...initialState,
        inputPayload: state.inputPayload, // Preserve input
      };

    case 'SET_INPUT_PAYLOAD':
      return {
        ...state,
        inputPayload: action.payload,
      };

    case 'START_EXECUTION':
      return {
        ...state,
        isExecuting: true,
        executionError: null,
        trace: null,
        currentStepIndex: -1,
        playbackState: 'stopped',
      };

    case 'EXECUTE_TRACE':
      return {
        ...state,
        isExecuting: false,
        trace: action.trace,
        currentStepIndex: -1, // Start at "ready" state, before step 0
        playbackState: 'paused',
      };

    case 'EXECUTION_ERROR':
      return {
        ...state,
        isExecuting: false,
        executionError: action.error,
      };

    case 'PLAY':
      if (!state.trace || state.trace.steps.length === 0) return state;
      return {
        ...state,
        playbackState: 'playing',
      };

    case 'PAUSE':
      return {
        ...state,
        playbackState: 'paused',
      };

    case 'STOP':
      return {
        ...state,
        playbackState: 'stopped',
        currentStepIndex: -1, // Reset to "ready" state
      };

    case 'RESET':
      return {
        ...state,
        trace: null,
        currentStepIndex: -1,
        playbackState: 'stopped',
        executionError: null,
      };

    case 'STEP_FORWARD': {
      if (!state.trace || state.trace.steps.length === 0) {
        return state;
      }

      const filteredIndices = getFilteredStepIndices(state.trace, state.skipFailedConditions);
      if (filteredIndices.length === 0) {
        return state;
      }

      // Find current position in filtered list
      const currentFilteredPos = filteredIndices.findIndex(i => i === state.currentStepIndex);

      let nextIndex: number;
      if (state.currentStepIndex === -1) {
        // At ready state, go to first filtered step
        nextIndex = filteredIndices[0];
      } else if (currentFilteredPos === -1) {
        // Current step is not in filtered list (shouldn't happen), go to first
        nextIndex = filteredIndices[0];
      } else if (currentFilteredPos >= filteredIndices.length - 1) {
        // At end of filtered steps, pause
        return {
          ...state,
          playbackState: 'paused',
        };
      } else {
        // Move to next filtered step
        nextIndex = filteredIndices[currentFilteredPos + 1];
      }

      return {
        ...state,
        currentStepIndex: nextIndex,
      };
    }

    case 'STEP_BACKWARD': {
      if (!state.trace || state.currentStepIndex <= -1) {
        return state;
      }

      const filteredIndices = getFilteredStepIndices(state.trace, state.skipFailedConditions);
      if (filteredIndices.length === 0) {
        return {
          ...state,
          currentStepIndex: -1,
          playbackState: 'paused',
        };
      }

      // Find current position in filtered list
      const currentFilteredPos = filteredIndices.findIndex(i => i === state.currentStepIndex);

      let prevIndex: number;
      if (currentFilteredPos <= 0) {
        // At or before first filtered step, go to ready state
        prevIndex = -1;
      } else {
        // Move to previous filtered step
        prevIndex = filteredIndices[currentFilteredPos - 1];
      }

      return {
        ...state,
        currentStepIndex: prevIndex,
        playbackState: 'paused',
      };
    }

    case 'GO_TO_STEP':
      if (!state.trace || action.index < 0 || action.index >= state.trace.steps.length) return state;
      return {
        ...state,
        currentStepIndex: action.index,
        playbackState: 'paused', // Pause on manual navigation
      };

    case 'SET_SPEED':
      return {
        ...state,
        playbackSpeed: Math.max(PLAYBACK.MIN_SPEED_MS, Math.min(PLAYBACK.MAX_SPEED_MS, action.speed)),
      };

    case 'SET_SKIP_FAILED_CONDITIONS': {
      // If enabling filter and current step would be filtered out, move to nearest valid step
      if (action.skip && state.trace && state.currentStepIndex >= 0) {
        const currentStep = state.trace.steps[state.currentStepIndex];
        if (currentStep && currentStep.result === 'skipped') {
          // Find the next non-skipped step, or go to ready state
          const filteredIndices = getFilteredStepIndices(state.trace, true);
          const nextValidIndex = filteredIndices.find(i => i > state.currentStepIndex);
          const prevValidIndex = [...filteredIndices].reverse().find(i => i < state.currentStepIndex);

          return {
            ...state,
            skipFailedConditions: action.skip,
            currentStepIndex: nextValidIndex ?? prevValidIndex ?? -1,
          };
        }
      }
      return {
        ...state,
        skipFailedConditions: action.skip,
      };
    }

    default:
      return state;
  }
}

/**
 * Context value interface
 */
interface DebuggerContextValue {
  state: DebuggerState;
  dispatch: React.Dispatch<DebuggerAction>;
  // Convenience methods
  activate: () => void;
  deactivate: () => void;
  setInputPayload: (payload: Record<string, unknown>) => void;
  executeTrace: (trace: ExecutionTrace) => void;
  startExecution: () => void;
  setExecutionError: (error: string) => void;
  play: () => void;
  pause: () => void;
  stop: () => void;
  reset: () => void;
  stepForward: () => void;
  stepBackward: () => void;
  goToStep: (index: number) => void;
  setSpeed: (speed: number) => void;
  setSkipFailedConditions: (skip: boolean) => void;
  // Engine execution method
  runExecution: (workflows: Workflow[], payload: Record<string, unknown>) => Promise<ExecutionTrace | null>;
  // Computed values
  currentStep: ExecutionStep | null;
  currentMessage: Message | null;
  currentChanges: Change[];
  isAtStart: boolean;
  isAtEnd: boolean;
  hasTrace: boolean;
  progress: number;
  totalSteps: number;
  /** Current position within filtered steps (0-indexed), -1 if at ready state */
  currentFilteredPosition: number;
  /** Array of actual step indices that are shown (for navigation) */
  filteredStepIndices: number[];
  isEngineReady: boolean;
  skipFailedConditions: boolean;
}

const DebuggerContext = createContext<DebuggerContextValue | null>(null);

interface DebuggerProviderProps {
  children: ReactNode;
  /** Initial payload to use for debugging */
  initialPayload?: Record<string, unknown>;
  /** Auto-start in debug mode */
  autoActivate?: boolean;
  /**
   * Factory function to create engine instances when workflows change.
   * Called whenever workflows are updated to create a fresh engine.
   * Use this for custom WASM engines with plugins.
   */
  engineFactory?: EngineFactory;
}

/**
 * Provider component for debugger state
 */
export function DebuggerProvider({
  children,
  initialPayload,
  autoActivate = false,
  engineFactory,
}: DebuggerProviderProps) {
  const [state, dispatch] = useReducer(debuggerReducer, {
    ...initialState,
    inputPayload: initialPayload || null,
    isActive: autoActivate,
  });

  const playbackTimerRef = useRef<number | null>(null);
  const engineRef = useRef<DataflowEngine | null>(null);
  const lastWorkflowsJsonRef = useRef<string | null>(null);

  // Determine if engine is ready for execution
  const isEngineReady = Boolean(engineFactory);

  // Convenience action dispatchers
  const activate = useCallback(() => dispatch({ type: 'ACTIVATE' }), []);
  const deactivate = useCallback(() => dispatch({ type: 'DEACTIVATE' }), []);
  const setInputPayload = useCallback(
    (payload: Record<string, unknown>) => dispatch({ type: 'SET_INPUT_PAYLOAD', payload }),
    []
  );
  const executeTrace = useCallback(
    (trace: ExecutionTrace) => dispatch({ type: 'EXECUTE_TRACE', trace }),
    []
  );
  const startExecution = useCallback(() => dispatch({ type: 'START_EXECUTION' }), []);
  const setExecutionError = useCallback(
    (error: string) => dispatch({ type: 'EXECUTION_ERROR', error }),
    []
  );
  const play = useCallback(() => dispatch({ type: 'PLAY' }), []);
  const pause = useCallback(() => dispatch({ type: 'PAUSE' }), []);
  const stop = useCallback(() => dispatch({ type: 'STOP' }), []);
  const reset = useCallback(() => dispatch({ type: 'RESET' }), []);
  const stepForward = useCallback(() => dispatch({ type: 'STEP_FORWARD' }), []);
  const stepBackward = useCallback(() => dispatch({ type: 'STEP_BACKWARD' }), []);
  const goToStep = useCallback((index: number) => dispatch({ type: 'GO_TO_STEP', index }), []);
  const setSpeed = useCallback((speed: number) => dispatch({ type: 'SET_SPEED', speed }), []);
  const setSkipFailedConditions = useCallback(
    (skip: boolean) => dispatch({ type: 'SET_SKIP_FAILED_CONDITIONS', skip }),
    []
  );

  /**
   * Execute workflows with the provided payload and return the execution trace.
   * Uses engineFactory to create a new engine when workflows change.
   */
  const runExecution = useCallback(
    async (workflows: Workflow[], payload: Record<string, unknown>): Promise<ExecutionTrace | null> => {
      if (workflows.length === 0 || !engineFactory) {
        return null;
      }

      try {
        const workflowsJson = JSON.stringify(workflows);

        // Create new engine if workflows changed or no engine exists
        if (lastWorkflowsJsonRef.current !== workflowsJson || !engineRef.current) {
          // Dispose previous engine
          if (engineRef.current?.dispose) {
            engineRef.current.dispose();
          }
          engineRef.current = engineFactory(workflows);
          lastWorkflowsJsonRef.current = workflowsJson;
        }
        return await engineRef.current.processWithTrace(payload);
      } catch (error) {
        console.error('Execution error:', error);
        throw error;
      }
    },
    [engineFactory]
  );

  // Cleanup engine on unmount
  useEffect(() => {
    return () => {
      if (engineRef.current?.dispose) {
        engineRef.current.dispose();
        engineRef.current = null;
      }
    };
  }, []);

  // Handle playback timer
  useEffect(() => {
    if (state.playbackState === 'playing') {
      playbackTimerRef.current = window.setInterval(() => {
        dispatch({ type: 'STEP_FORWARD' });
      }, state.playbackSpeed);
    } else {
      if (playbackTimerRef.current) {
        clearInterval(playbackTimerRef.current);
        playbackTimerRef.current = null;
      }
    }

    return () => {
      if (playbackTimerRef.current) {
        clearInterval(playbackTimerRef.current);
      }
    };
  }, [state.playbackState, state.playbackSpeed]);

  // Memoize computed values to avoid unnecessary re-renders of consumers
  const currentStep = useMemo(
    () => state.trace && state.currentStepIndex >= 0
      ? state.trace.steps[state.currentStepIndex]
      : null,
    [state.trace, state.currentStepIndex]
  );

  const currentMessage = useMemo(
    () => state.trace && state.currentStepIndex >= 0
      ? getMessageAtStep(state.trace, state.currentStepIndex)
      : null,
    [state.trace, state.currentStepIndex]
  );

  const currentChanges = useMemo(
    () => state.trace && state.currentStepIndex >= 0
      ? getChangesAtStep(state.trace, state.currentStepIndex)
      : [],
    [state.trace, state.currentStepIndex]
  );

  const filteredStepIndices = useMemo(
    () => getFilteredStepIndices(state.trace, state.skipFailedConditions),
    [state.trace, state.skipFailedConditions]
  );

  const totalSteps = filteredStepIndices.length;

  const currentFilteredPos = useMemo(
    () => state.currentStepIndex >= 0
      ? filteredStepIndices.findIndex(i => i === state.currentStepIndex)
      : -1,
    [state.currentStepIndex, filteredStepIndices]
  );

  const isAtStart = state.currentStepIndex <= -1;
  const isAtEnd = currentFilteredPos >= totalSteps - 1 && currentFilteredPos >= 0;
  const hasTrace = state.trace !== null && totalSteps > 0;
  const progress = totalSteps > 0 && currentFilteredPos >= 0
    ? (currentFilteredPos + 1) / totalSteps
    : 0;

  const value = useMemo<DebuggerContextValue>(
    () => ({
      state,
      dispatch,
      activate,
      deactivate,
      setInputPayload,
      executeTrace,
      startExecution,
      setExecutionError,
      play,
      pause,
      stop,
      reset,
      stepForward,
      stepBackward,
      goToStep,
      setSpeed,
      setSkipFailedConditions,
      runExecution,
      currentStep,
      currentMessage,
      currentChanges,
      isAtStart,
      isAtEnd,
      hasTrace,
      progress,
      totalSteps,
      currentFilteredPosition: currentFilteredPos,
      filteredStepIndices,
      isEngineReady,
      skipFailedConditions: state.skipFailedConditions,
    }),
    [
      state,
      dispatch,
      activate,
      deactivate,
      setInputPayload,
      executeTrace,
      startExecution,
      setExecutionError,
      play,
      pause,
      stop,
      reset,
      stepForward,
      stepBackward,
      goToStep,
      setSpeed,
      setSkipFailedConditions,
      runExecution,
      currentStep,
      currentMessage,
      currentChanges,
      isAtStart,
      isAtEnd,
      hasTrace,
      progress,
      totalSteps,
      currentFilteredPos,
      filteredStepIndices,
      isEngineReady,
    ]
  );

  return <DebuggerContext.Provider value={value}>{children}</DebuggerContext.Provider>;
}

/**
 * Hook to access debugger context
 */
export function useDebugger() {
  const context = useContext(DebuggerContext);
  if (!context) {
    throw new Error('useDebugger must be used within a DebuggerProvider');
  }
  return context;
}

/**
 * Hook to check if debugger is available (doesn't throw if not in provider)
 */
export function useDebuggerOptional() {
  return useContext(DebuggerContext);
}