File size: 12,479 Bytes
f0743f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { Keyv } from 'keyv';
import { FlowStateManager } from './manager';
import { FlowState } from './types';

/** Mock class without extending Keyv */
class MockKeyv {
  private store: Map<string, FlowState<string>>;

  constructor() {
    this.store = new Map();
  }

  async get(key: string): Promise<FlowState<string> | undefined> {
    return this.store.get(key);
  }

  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  async set(key: string, value: FlowState<string>, _ttl?: number): Promise<true> {
    this.store.set(key, value);
    return true;
  }

  async delete(key: string): Promise<boolean> {
    return this.store.delete(key);
  }
}

describe('FlowStateManager', () => {
  let flowManager: FlowStateManager<string>;
  let store: MockKeyv;

  beforeEach(() => {
    store = new MockKeyv();
    // Type assertion here since we know our mock implements the necessary methods
    flowManager = new FlowStateManager(store as unknown as Keyv, { ttl: 30000, ci: true });
  });

  afterEach(() => {
    jest.clearAllMocks();
  });

  describe('Concurrency Tests', () => {
    it('should handle concurrent flow creation and return same result', async () => {
      const flowId = 'test-flow';
      const type = 'test-type';

      // Start two concurrent flow creations
      const flow1Promise = flowManager.createFlowWithHandler(flowId, type, async () => {
        await new Promise((resolve) => setTimeout(resolve, 100));
        return 'result';
      });

      const flow2Promise = flowManager.createFlowWithHandler(flowId, type, async () => {
        await new Promise((resolve) => setTimeout(resolve, 50));
        return 'different-result';
      });

      // Both should resolve to the same result from the first handler
      const [result1, result2] = await Promise.all([flow1Promise, flow2Promise]);

      expect(result1).toBe('result');
      expect(result2).toBe('result');
    });

    it('should handle flow timeout correctly', async () => {
      const flowId = 'timeout-flow';
      const type = 'test-type';

      // Create flow with very short TTL
      const shortTtlManager = new FlowStateManager(store as unknown as Keyv, {
        ttl: 100,
        ci: true,
      });

      const flowPromise = shortTtlManager.createFlow(flowId, type);

      await expect(flowPromise).rejects.toThrow('test-type flow timed out');
    });

    it('should maintain flow state consistency under high concurrency', async () => {
      const flowId = 'concurrent-flow';
      const type = 'test-type';

      // Create multiple concurrent operations
      const operations = [];
      for (let i = 0; i < 10; i++) {
        operations.push(
          flowManager.createFlowWithHandler(flowId, type, async () => {
            await new Promise((resolve) => setTimeout(resolve, Math.random() * 50));
            return `result-${i}`;
          }),
        );
      }

      // All operations should resolve to the same result
      const results = await Promise.all(operations);
      const firstResult = results[0];
      results.forEach((result: string) => {
        expect(result).toBe(firstResult);
      });
    });

    it('should handle race conditions in flow completion', async () => {
      const flowId = 'test-flow';
      const type = 'test-type';

      // Create initial flow
      const flowPromise = flowManager.createFlow(flowId, type);

      // Increase delay to ensure flow is properly created
      await new Promise((resolve) => setTimeout(resolve, 500));

      // Complete the flow
      await flowManager.completeFlow(flowId, type, 'result1');

      const result = await flowPromise;
      expect(result).toBe('result1');
    }, 15000);

    it('should handle concurrent flow monitoring', async () => {
      const flowId = 'test-flow';
      const type = 'test-type';

      // Create initial flow
      const flowPromise = flowManager.createFlow(flowId, type);

      // Increase delay
      await new Promise((resolve) => setTimeout(resolve, 500));

      // Complete the flow
      await flowManager.completeFlow(flowId, type, 'success');

      const result = await flowPromise;
      expect(result).toBe('success');
    }, 15000);

    it('should handle concurrent success and failure attempts', async () => {
      const flowId = 'race-flow';
      const type = 'test-type';

      const flowPromise = flowManager.createFlow(flowId, type);

      // Increase delay
      await new Promise((resolve) => setTimeout(resolve, 500));

      // Fail the flow
      await flowManager.failFlow(flowId, type, new Error('failure'));

      await expect(flowPromise).rejects.toThrow('failure');
    }, 15000);
  });

  describe('deleteFlow', () => {
    const flowId = 'test-flow-123';
    const type = 'test-type';
    const flowKey = `${type}:${flowId}`;

    it('deletes an existing flow', async () => {
      await store.set(flowKey, { type, status: 'PENDING', metadata: {}, createdAt: Date.now() });
      expect(await store.get(flowKey)).toBeDefined();

      const result = await flowManager.deleteFlow(flowId, type);

      expect(result).toBe(true);
      expect(await store.get(flowKey)).toBeUndefined();
    });

    it('returns false if the deletion errors', async () => {
      jest.spyOn(store, 'delete').mockRejectedValue(new Error('Deletion failed'));

      const result = await flowManager.deleteFlow(flowId, type);

      expect(result).toBe(false);
    });

    it('does nothing if the flow does not exist', async () => {
      expect(await store.get(flowKey)).toBeUndefined();

      const result = await flowManager.deleteFlow(flowId, type);

      expect(result).toBe(true);
    });
  });

  describe('isFlowStale', () => {
    const flowId = 'test-flow-stale';
    const type = 'test-type';
    const flowKey = `${type}:${flowId}`;

    it('returns not stale for non-existent flow', async () => {
      const result = await flowManager.isFlowStale(flowId, type);

      expect(result).toEqual({
        isStale: false,
        age: 0,
      });
    });

    it('returns not stale for PENDING flow regardless of age', async () => {
      const oldTimestamp = Date.now() - 10 * 60 * 1000; // 10 minutes ago
      await store.set(flowKey, {
        type,
        status: 'PENDING',
        metadata: {},
        createdAt: oldTimestamp,
      });

      const result = await flowManager.isFlowStale(flowId, type, 2 * 60 * 1000);

      expect(result).toEqual({
        isStale: false,
        age: 0,
        status: 'PENDING',
      });
    });

    it('returns not stale for recently COMPLETED flow', async () => {
      const recentTimestamp = Date.now() - 30 * 1000; // 30 seconds ago
      await store.set(flowKey, {
        type,
        status: 'COMPLETED',
        metadata: {},
        createdAt: Date.now() - 60 * 1000,
        completedAt: recentTimestamp,
      });

      const result = await flowManager.isFlowStale(flowId, type, 2 * 60 * 1000);

      expect(result.isStale).toBe(false);
      expect(result.status).toBe('COMPLETED');
      expect(result.age).toBeGreaterThan(0);
      expect(result.age).toBeLessThan(60 * 1000);
    });

    it('returns stale for old COMPLETED flow', async () => {
      const oldTimestamp = Date.now() - 5 * 60 * 1000; // 5 minutes ago
      await store.set(flowKey, {
        type,
        status: 'COMPLETED',
        metadata: {},
        createdAt: Date.now() - 10 * 60 * 1000,
        completedAt: oldTimestamp,
      });

      const result = await flowManager.isFlowStale(flowId, type, 2 * 60 * 1000);

      expect(result.isStale).toBe(true);
      expect(result.status).toBe('COMPLETED');
      expect(result.age).toBeGreaterThan(2 * 60 * 1000);
    });

    it('returns not stale for recently FAILED flow', async () => {
      const recentTimestamp = Date.now() - 30 * 1000; // 30 seconds ago
      await store.set(flowKey, {
        type,
        status: 'FAILED',
        metadata: {},
        createdAt: Date.now() - 60 * 1000,
        failedAt: recentTimestamp,
        error: 'Test error',
      });

      const result = await flowManager.isFlowStale(flowId, type, 2 * 60 * 1000);

      expect(result.isStale).toBe(false);
      expect(result.status).toBe('FAILED');
      expect(result.age).toBeGreaterThan(0);
      expect(result.age).toBeLessThan(60 * 1000);
    });

    it('returns stale for old FAILED flow', async () => {
      const oldTimestamp = Date.now() - 5 * 60 * 1000; // 5 minutes ago
      await store.set(flowKey, {
        type,
        status: 'FAILED',
        metadata: {},
        createdAt: Date.now() - 10 * 60 * 1000,
        failedAt: oldTimestamp,
        error: 'Test error',
      });

      const result = await flowManager.isFlowStale(flowId, type, 2 * 60 * 1000);

      expect(result.isStale).toBe(true);
      expect(result.status).toBe('FAILED');
      expect(result.age).toBeGreaterThan(2 * 60 * 1000);
    });

    it('uses custom stale threshold', async () => {
      const timestamp = Date.now() - 90 * 1000; // 90 seconds ago
      await store.set(flowKey, {
        type,
        status: 'COMPLETED',
        metadata: {},
        createdAt: Date.now() - 2 * 60 * 1000,
        completedAt: timestamp,
      });

      // 90 seconds old, threshold 60 seconds = stale
      const result1 = await flowManager.isFlowStale(flowId, type, 60 * 1000);
      expect(result1.isStale).toBe(true);

      // 90 seconds old, threshold 120 seconds = not stale
      const result2 = await flowManager.isFlowStale(flowId, type, 120 * 1000);
      expect(result2.isStale).toBe(false);
    });

    it('uses default threshold of 2 minutes when not specified', async () => {
      const timestamp = Date.now() - 3 * 60 * 1000; // 3 minutes ago
      await store.set(flowKey, {
        type,
        status: 'COMPLETED',
        metadata: {},
        createdAt: Date.now() - 5 * 60 * 1000,
        completedAt: timestamp,
      });

      // Should use default 2 minute threshold
      const result = await flowManager.isFlowStale(flowId, type);

      expect(result.isStale).toBe(true);
      expect(result.age).toBeGreaterThan(2 * 60 * 1000);
    });

    it('falls back to createdAt when completedAt/failedAt are not present', async () => {
      const createdTimestamp = Date.now() - 5 * 60 * 1000; // 5 minutes ago
      await store.set(flowKey, {
        type,
        status: 'COMPLETED',
        metadata: {},
        createdAt: createdTimestamp,
        // No completedAt or failedAt
      });

      const result = await flowManager.isFlowStale(flowId, type, 2 * 60 * 1000);

      expect(result.isStale).toBe(true);
      expect(result.status).toBe('COMPLETED');
      expect(result.age).toBeGreaterThan(2 * 60 * 1000);
    });

    it('handles flow with no timestamps', async () => {
      await store.set(flowKey, {
        type,
        status: 'COMPLETED',
        metadata: {},
        // No timestamps at all
      } as FlowState<string>);

      const result = await flowManager.isFlowStale(flowId, type, 2 * 60 * 1000);

      expect(result.isStale).toBe(false);
      expect(result.age).toBe(0);
      expect(result.status).toBe('COMPLETED');
    });

    it('prefers completedAt over createdAt for age calculation', async () => {
      const createdTimestamp = Date.now() - 10 * 60 * 1000; // 10 minutes ago
      const completedTimestamp = Date.now() - 30 * 1000; // 30 seconds ago
      await store.set(flowKey, {
        type,
        status: 'COMPLETED',
        metadata: {},
        createdAt: createdTimestamp,
        completedAt: completedTimestamp,
      });

      const result = await flowManager.isFlowStale(flowId, type, 2 * 60 * 1000);

      // Should use completedAt (30s) not createdAt (10m)
      expect(result.isStale).toBe(false);
      expect(result.age).toBeLessThan(60 * 1000);
    });

    it('prefers failedAt over createdAt for age calculation', async () => {
      const createdTimestamp = Date.now() - 10 * 60 * 1000; // 10 minutes ago
      const failedTimestamp = Date.now() - 30 * 1000; // 30 seconds ago
      await store.set(flowKey, {
        type,
        status: 'FAILED',
        metadata: {},
        createdAt: createdTimestamp,
        failedAt: failedTimestamp,
        error: 'Test error',
      });

      const result = await flowManager.isFlowStale(flowId, type, 2 * 60 * 1000);

      // Should use failedAt (30s) not createdAt (10m)
      expect(result.isStale).toBe(false);
      expect(result.age).toBeLessThan(60 * 1000);
    });
  });
});