-
Notifications
You must be signed in to change notification settings - Fork 0
/
StatefulWorkflow.test.ts
903 lines (765 loc) · 33.2 KB
/
StatefulWorkflow.test.ts
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
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
/* eslint-disable @typescript-eslint/no-floating-promises */
/* eslint-disable @typescript-eslint/ban-ts-comment */
// @ts-nocheck
import path from 'path';
import { WorkflowCoverage } from '@temporalio/nyc-test-coverage';
import { Workflow, ChronoFlow, StatefulWorkflowParams } from '../index';
import { Signal, Query } from '../decorators';
import { TestWorkflowEnvironment } from '@temporalio/testing';
import { Worker, Runtime, DefaultLogger, LogEntry } from '@temporalio/worker';
import { WorkflowClient } from '@temporalio/client';
import { v4 as uuid4 } from 'uuid';
import { SchemaManager } from '../store/SchemaManager';
import * as workflows from './testWorkflows';
import { logger } from '../utils/logger';
import {
OpenTelemetryActivityInboundInterceptor,
makeWorkflowExporter
} from '@temporalio/interceptors-opentelemetry/lib/worker';
import { normalizeEntities } from '../utils/entities';
import { getExternalWorkflowHandle } from '@temporalio/workflow';
import { cloneDeep } from 'lodash';
import dottie, { get, set } from 'dottie';
import { getExporter, getResource, getTracer } from '../utils/instrumentation';
import { Photo } from './testSchemas';
import { getCompositeKey, getMemo, limitRecursion, unflatten } from '../utils';
import { denormalize } from 'normalizr';
describe('StatefulWorkflow', () => {
let execute: (
workflowName: string,
params: StatefulWorkflowParams,
timeout: number
) => ReturnType<client.workflow.start>;
let client: ReturnType<typeof getClient>;
jest.setTimeout(120000);
beforeEach(() => {
client = getClient();
execute = (workflowName: string, params: StatefulWorkflowParams, workflowExecutionTimeout = 120000) => {
console.log(`Starting workflow: ${params.entityName}-${params.id}`);
return client.workflow.start(workflowName, {
taskQueue: 'test',
workflowExecutionTimeout,
workflowId: `${params.entityName}-${params.id}`,
args: [params]
});
};
});
describe('Workflow Initialization and State Validation', () => {
it('Should use state provided in params', async () => {
const userId = uuid4();
const data = {
id: userId,
listings: [{ id: uuid4(), name: 'Awesome test listing' }]
};
const normalizedData = normalizeEntities(data, SchemaManager.getInstance().getSchema('User'));
const handle = await execute(workflows.ShouldExecuteStateful, {
id: data.id,
entityName: 'User',
state: normalizedData
});
await sleep();
const state = await handle.query('state');
expect(state).toEqual(normalizedData);
});
it('Should initialise state from data params', async () => {
const data = { id: uuid4(), listings: [{ id: uuid4(), name: 'Awesome test listing' }] };
const handle = await execute(workflows.ShouldExecuteStateful, { id: data.id, entityName: 'User', data });
const expectedInitial = normalizeEntities(data, SchemaManager.getInstance().getSchema('User'));
await sleep();
const state = await handle.query('state');
expect(state).toEqual(expectedInitial);
});
it('Should initialize workflow without initial state', async () => {
const userId = uuid4();
const handle = await execute(workflows.ShouldExecuteStateful, { id: userId, entityName: 'User', state: {} });
await sleep();
const state = await handle.query('state');
expect(state).toEqual({});
});
it('Should initialize workflow with partial data and set missing properties to defaults', async () => {
const userId = uuid4();
const partialData = { id: userId };
const handle = await execute(workflows.ShouldExecuteStateful, {
id: userId,
entityName: 'User',
data: partialData
});
await sleep();
const state = await handle.query('state');
expect(state).toHaveProperty('User');
expect(state.User).toHaveProperty(userId);
});
it('Should initialize workflow with invalid data and handle gracefully', async () => {
const userId = uuid4();
const invalidData = { id: userId, invalidField: 'invalid' };
const handle = await execute(workflows.ShouldExecuteStateful, {
id: userId,
entityName: 'User',
data: invalidData
});
await sleep();
const state = await handle.query('state');
expect(state.User[userId]).toHaveProperty('invalidField');
});
});
describe('@Debounce() decorator', () => {
it('Should debounce properly', async () => {
const data = { id: uuid4(), listings: [{ id: uuid4(), name: 'Awesome test listing' }] };
const handle = await execute(workflows.ShouldExecuteStateful, { id: data.id, entityName: 'User', data });
const expectedInitial = normalizeEntities(data, SchemaManager.getInstance().getSchema('User'));
await sleep();
const state = await handle.query('state');
expect(state).toEqual(expectedInitial);
const counter = await handle.query('counter');
expect(counter).toBe(0);
await handle.signal('incrementNumberTest');
await sleep(15000);
expect(await handle.query('counter')).toBe(1);
});
});
describe('State Update Mechanisms', () => {
it('Should update state and child workflow and maintain state in parent and child correctly', async () => {
const data = { id: uuid4(), listings: [{ id: uuid4(), name: 'Awesome test listing' }] };
const handle = await execute(workflows.ShouldExecuteStateful, { id: data.id, entityName: 'User', data });
const expectedInitial = normalizeEntities(data, SchemaManager.getInstance().getSchema('User'));
await sleep();
// Initial state verification
const state = await handle.query('state');
expect(state).toEqual(expectedInitial);
// const { state: memoState } = await getMemo(client.workflow.getHandle(`User-${data.id}`));
// expect(memoState).toEqual(expectedInitial);
const initalExpectedMemo = state;
const { state: initialMemoValue } = await getMemo(handle);
expect(initialMemoValue).toEqual(initalExpectedMemo);
// Update state
const updatedData = { ...data, update: 'fromUpdate', listings: [{ ...data.listings[0], update: 'fromUpdate' }] };
const expectedUpdated = normalizeEntities(updatedData, SchemaManager.getInstance().getSchema('User'));
await handle.signal('update', { data: updatedData, entityName: 'User' });
await sleep(5000);
const updatedState = await handle.query('state');
expect(updatedState).toEqual(expectedUpdated);
const updatedExpectedMemo = expectedUpdated;
const { state: updatedMemoValue } = await getMemo(handle);
expect(updatedMemoValue).toEqual(updatedExpectedMemo);
// Verify child workflow state
const childHandle = await client.workflow.getHandle(`Listing-${data.listings[0].id}`);
const updatedListingState = await childHandle.query('state');
expect(updatedListingState).toEqual({ Listing: expectedUpdated.Listing });
await childHandle.signal('update', {
data: { id: data.listings[0].id, update: 'directly' },
entityName: 'Listing',
strategy: '$merge'
});
await sleep();
const parentData = await handle.query('state');
const childData = await childHandle.query('state');
expect(parentData).toEqual(
normalizeEntities(
{ ...data, update: 'fromUpdate', listings: [{ ...data.listings[0], update: 'directly' }] },
SchemaManager.getInstance().getSchema('User')
)
);
expect(childData).toEqual({
Listing: {
[data.listings[0]?.id]: {
...data.listings[0],
update: 'directly'
}
}
});
});
it('Should correctly handle deep nested updates in the state', async () => {
const id = uuid4();
const listingId = uuid4();
const photoId = uuid4();
const data = {
id,
listings: [{ id: listingId, photos: [{ id: photoId, name: 'Nested Item', listing: listingId }] }]
};
const expectedInitialState = normalizeEntities(data, SchemaManager.getInstance().getSchema('User'));
const handle = await execute(workflows.ShouldExecuteStateful, { id, entityName: 'User', data });
await sleep();
const state = await handle.query('state');
expect(state).toEqual(expectedInitialState);
data.listings[0].photos[0].name = 'Updated Nested';
const expectedUpdatedState = normalizeEntities(data, SchemaManager.getInstance().getSchema('User'));
await handle.signal('update', {
data,
entityName: 'User'
});
await sleep(5000);
const updatedState = await handle.query('state');
expect(updatedState).toEqual(expectedUpdatedState);
}, 45000);
it('Should correctly handle batch updates and state synchronization across workflows', async () => {
const data = {
id: uuid4(),
listings: [
{ id: uuid4(), name: 'Listing 1' },
{ id: uuid4(), name: 'Listing 2' }
]
};
const handle = await execute(workflows.ShouldExecuteStateful, { id: data.id, entityName: 'User', data });
await sleep();
const batchUpdate = { listings: data.listings.map((listing) => ({ ...listing, updated: 'batch' })) };
await handle.signal('update', { data: { ...data, ...batchUpdate }, entityName: 'User' });
await sleep();
const stateAfterBatchUpdate = await handle.query('state');
data.listings.forEach((listing) => {
expect(stateAfterBatchUpdate.Listing[listing.id].updated).toEqual('batch');
});
});
it('Should handle different merging strategies', async () => {
const userId = uuid4();
const initialData = { id: userId, name: 'Initial' };
const handle = await execute(workflows.ShouldExecuteStateful, {
id: userId,
entityName: 'User',
data: initialData
});
await sleep();
// Update using $merge strategy
const updatedDataMerge = { id: userId, age: 30 };
await handle.signal('update', { data: updatedDataMerge, entityName: 'User', strategy: '$merge' });
await sleep();
const mergedState = await handle.query('state');
expect(mergedState.User[userId]).toHaveProperty('name', 'Initial');
expect(mergedState.User[userId]).toHaveProperty('age', 30);
// Update using $set strategy
const updatedDataReplace = { id: userId, newField: 'Replaced' };
await handle.signal('update', { data: updatedDataReplace, entityName: 'User', strategy: '$set' });
await sleep();
const replacedState = await handle.query('state');
expect(replacedState.User[userId]).not.toHaveProperty('name');
expect(replacedState.User[userId]).toHaveProperty('newField', 'Replaced');
});
it('Should maintain consistency during concurrent updates', async () => {
const userId = uuid4();
const handle = await execute(workflows.ShouldExecuteStateful, {
id: userId,
entityName: 'User',
data: { id: userId, name: 'Initial' }
});
await sleep();
await handle.signal('update', { data: { id: userId, age: 25 }, entityName: 'User' }),
await handle.signal('update', { data: { id: userId, age: 30 }, entityName: 'User' }),
await handle.signal('update', { data: { id: userId, age: 35 }, entityName: 'User' });
await sleep();
const state = await handle.query('state');
expect(state.User[userId]).toHaveProperty('age', 35); // Last update should win
});
});
describe('@Action', () => {
it.skip('Should update state and child workflow and maintain state in parent and child correctly', async () => {
const data = { id: uuid4(), listings: [{ id: uuid4(), name: 'Awesome test listing' }] };
const handle = await execute(workflows.ShouldExecuteStateful, { id: data.id, entityName: 'User', data });
const expectedInitial = normalizeEntities(data, SchemaManager.getInstance().getSchema('User'));
await sleep();
// Initial state verification
const state = await handle.query('state');
expect(state).toEqual(expectedInitial);
// const { state: memoState } = await getMemo(client.workflow.getHandle(`User-${data.id}`));
// expect(memoState).toEqual(expectedInitial);
// Update state
const updatedData = { ...data, update: 'fromUpdate', listings: [{ ...data.listings[0], update: 'fromUpdate' }] };
const expectedUpdated = normalizeEntities(updatedData, SchemaManager.getInstance().getSchema('User'));
await handle.signal('update', { data: updatedData, entityName: 'User' });
await sleep(5000);
const updatedState = await handle.query('state');
expect(updatedState).toEqual(expectedUpdated);
// Verify child workflow state
const childHandle = await client.workflow.getHandle(`Listing-${data.listings[0].id}`);
const updatedListingState = await childHandle.query('state');
expect(updatedListingState).toEqual({ Listing: expectedUpdated.Listing });
await childHandle.signal('update', {
data: { id: data.listings[0].id, update: 'directly' },
entityName: 'Listing',
strategy: '$merge'
});
await sleep();
const parentData = await handle.query('state');
const childData = await childHandle.query('state');
expect(parentData).toEqual(
normalizeEntities(
{ ...data, update: 'fromUpdate', listings: [{ ...data.listings[0], update: 'directly' }] },
SchemaManager.getInstance().getSchema('User')
)
);
expect(childData).toEqual({
Listing: {
[data.listings[0]?.id]: {
...data.listings[0],
update: 'directly'
}
}
});
});
});
describe('Child Workflow Management', () => {
it('Should correctly manage one parent User and three child Listing workflows', async () => {
// Initialize data for one User and three Listings
const userId = uuid4();
const listingIds = [uuid4(), uuid4(), uuid4()];
const data = {
id: userId,
listings: listingIds.map((id) => ({ id, name: `Listing ${id}` }))
};
// Start the User workflow
const handle = await execute(workflows.ShouldExecuteStateful, {
id: data.id,
entityName: 'User',
data
});
// Ensure the parent User workflow is initialized with the correct normalized state
const expectedInitialState = normalizeEntities(data, SchemaManager.getInstance().getSchema('User'));
await sleep();
const state = await handle.query('state');
expect(state).toEqual(expectedInitialState);
// Start child Listing workflows for each listing
const client = getClient();
const childHandles = await Promise.all(listingIds.map((id) => client.workflow.getHandle(`Listing-${id}`)));
// Ensure each child Listing workflow is initialized with the correct normalized state
for (const [index, childHandle] of childHandles.entries()) {
await sleep();
const listingState = await childHandle.query('state');
expect(listingState.Listing).toEqual({
[listingIds[index]]: { id: listingIds[index], name: `Listing ${listingIds[index]}` }
});
}
// Update one of the listings in the User parent workflow
const updatedListingData = { id: listingIds[0], name: 'Updated Listing Name' };
const updatedData = {
...data,
listings: [{ ...updatedListingData }, ...data.listings.slice(1)]
};
await handle.signal('update', { data: updatedData, entityName: 'User' });
await sleep();
// Verify that the state in the User parent workflow is updated correctly
const updatedState = await handle.query('state');
expect(updatedState.Listing[listingIds[0]].name).toEqual('Updated Listing Name');
// Verify that the updated state is also reflected in the child Listing workflow
const updatedChildState = await childHandles[0].query('state');
expect(updatedChildState.Listing[listingIds[0]].name).toEqual('Updated Listing Name');
// Update another listing directly in the child workflow and check propagation back to the parent
await sleep();
const newDirectUpdate = { id: listingIds[1], name: 'Direct Child Update' };
await childHandles[1].signal('update', {
data: newDirectUpdate,
entityName: 'Listing',
strategy: '$merge'
});
await sleep();
// Verify the parent was updated!
const parentUpdatedState = await handle.query('state');
expect(parentUpdatedState.Listing[listingIds[1]].name).toEqual('Direct Child Update');
});
it('Should propagate updates correctly with multiple child workflows', async () => {
const data = {
id: uuid4(),
listings: [
{ id: uuid4(), name: 'Listing One' },
{ id: uuid4(), name: 'Listing Two' }
]
};
const handle = await execute(workflows.ShouldExecuteStateful, { id: data.id, entityName: 'User', data });
await sleep();
data.listings[1].name = 'Updated Listing Two';
await handle.signal('update', { data, entityName: 'User' });
await sleep();
const updatedState = await handle.query('state');
expect(updatedState).toEqual(normalizeEntities(data, SchemaManager.getInstance().getSchema('User')));
});
it('Should handle recursive relationships between User and Listings correctly', async () => {
const userId = uuid4();
const listingId = uuid4();
const listing2Id = uuid4();
const photoId = uuid4();
const photo2Id = uuid4();
const likeId = uuid4();
// Initial data for User with Listings, Photos, and Likes, forming a recursive structure
const data = {
id: userId,
listings: [
{
id: listingId,
user: userId,
photos: [
{
id: photoId,
user: userId,
listing: listingId,
likes: [{ id: likeId, user: userId, photo: photoId }]
}
]
},
{
id: listing2Id,
user: userId
}
]
};
// Start the User workflow
const handle = await execute(workflows.ShouldExecuteStateful, {
id: data.id,
entityName: 'User',
data
});
await sleep(5000); // Wait for workflows to initialize
// Ensure the User workflow is initialized with the correct normalized state
const expectedState = normalizeEntities(data, SchemaManager.getInstance().getSchema('User'));
const state = await handle.query('state');
expect(state).toEqual(expectedState);
const client = getClient();
// Verify Listing workflow state for listingId
const listingHandle = await client.workflow.getHandle(`Listing-${listingId}`);
const listingState = await listingHandle.query('state');
expect(listingState.Listing).toEqual(expectedState.Listing);
// Verify Listing2 workflow state**
const listing2Handle = await client.workflow.getHandle(`Listing-${listing2Id}`);
const listing2State = await listing2Handle.query('state');
expect(listing2State.Listing).toEqual(expectedState.Listing);
// Verify child Photo workflow state
const photoHandle = await client.workflow.getHandle(`Photo-${photoId}`);
const photoState = await photoHandle.query('state');
expect(photoState.Photo).toEqual({
[photoId]: {
id: photoId,
user: userId,
listing: listingId,
likes: [likeId]
}
});
// Verify child Like workflow state
const likeHandle = await client.workflow.getHandle(`Like-${likeId}`);
const likeState = await likeHandle.query('state');
expect(likeState.Like).toEqual({
[likeId]: { id: likeId, user: userId, photo: photoId }
});
// Update Listing data and propagate to children
expectedState.Listing[listingId].name = 'Updated Listing 1 Name';
expectedState.Listing[listing2Id].name = 'Updated Listing 2 Name';
let expectedData = limitRecursion(userId, 'User', expectedState);
const updatedListingData = {
id: listingId,
user: userId,
name: 'Updated Listing Name'
};
await handle.signal('update', {
data: expectedData,
entityName: 'User'
});
await sleep(5000); // Wait for state to propagate
// Verify state update propagation in User
const updatedState = await handle.query('state');
expect(updatedState.Listing[listingId].name).toEqual('Updated Listing 1 Name');
expect(updatedState.Listing[listing2Id].name).toEqual('Updated Listing 2 Name');
// Verify the state update is reflected in the Listing child workflow
let updatedListingState = await listingHandle.query('state');
expect(updatedListingState.Listing[listingId].name).toEqual('Updated Listing 1 Name');
let updatedListing2State = await listing2Handle.query('state');
expect(updatedListing2State.Listing[listing2Id].name).toEqual('Updated Listing 2 Name');
// Update one of the listings directly, and verify its state**
const updatedListing2Data = {
id: listing2Id,
user: userId,
name: 'Updated Listing2 Name',
photos: [
{
id: photo2Id,
user: userId,
listing: listing2Id
}
]
};
await listing2Handle.signal('update', {
data: updatedListing2Data,
entityName: 'Listing'
});
await sleep(5000); // Wait for state to propagate
// Verify the state update in Listing2 workflow
updatedListing2State = await listing2Handle.query('state');
console.log(updatedListing2State);
expect(updatedListing2State.Listing[listing2Id].name).toEqual('Updated Listing2 Name');
// Verify it propagates up to the parent by checking parent state**
const updatedUserState = await handle.query('state');
expect(updatedUserState.Listing[listing2Id].name).toEqual('Updated Listing2 Name');
// Verify both listings are still referenced in the state of the parent correctly**
expect(updatedUserState.Listing).toHaveProperty(listingId);
expect(updatedUserState.Listing).toHaveProperty(listing2Id);
// Optionally, verify the full listing objects
expect(updatedUserState.Listing[listingId]).toEqual(
expect.objectContaining({
id: listingId,
user: userId,
name: 'Updated Listing 1 Name'
})
);
expect(updatedUserState.Listing[listing2Id]).toEqual(
expect.objectContaining({
id: listing2Id,
user: userId,
name: 'Updated Listing2 Name'
})
);
});
it.skip('Shound have a working data proxy', async () => {
const userId = uuid4();
const listingId = uuid4();
const listing2Id = uuid4();
const photoId = uuid4();
const photo2Id = uuid4();
const likeId = uuid4();
// Initial data for User with Listings, Photos, and Likes, forming a recursive structure
const data = {
id: userId,
listings: [
{
id: listingId,
user: userId,
photos: [
{
id: photoId,
user: userId,
listing: listingId,
likes: [{ id: likeId, user: userId, photo: photoId }]
}
]
},
{
id: listing2Id,
user: userId
}
]
};
// const expectedState = normalizeEntities(data, SchemaManager.getInstance().getSchema('User'));
// console.dir(expectedState, { depth: 12 });
// process.exit(1);
// Start the User workflow
const handle = await execute(workflows.ShouldExecuteStateful, {
id: data.id,
entityName: 'User',
data
});
await sleep(30000); // Wait for workflows to initialize
// Ensure the User workflow is initialized with the correct normalized state
const expectedState = normalizeEntities(data, SchemaManager.getInstance().getSchema('User'));
const state = await handle.query('state');
expect(state).toEqual(expectedState);
await sleep(1000 * 30); // Wait for workflows to initialize
});
it('Should handle restarting child workflow after cancellation', async () => {
const data = { id: uuid4(), listings: [{ id: uuid4(), name: 'Test Listing' }] };
const handle = await execute(workflows.ShouldExecuteStateful, { id: data.id, entityName: 'User', data });
await sleep();
const client = getClient();
const childHandle = await client.workflow.getHandle(`Listing-${data.listings[0].id}`);
await childHandle.cancel();
await sleep();
const restartedChildHandle = await client.workflow.getHandle(`Listing-${data.listings[0].id}`);
await sleep();
const childState = await restartedChildHandle.query('state');
expect(childState.Listing).toHaveProperty(data.listings[0].id);
});
it.skip('Should cancel children upon parent cancellation', async () => {
const data = { id: uuid4(), listings: [{ id: uuid4(), name: 'Test Listing' }] };
const handle = await execute(workflows.ShouldExecuteStateful, { id: data.id, entityName: 'User', data });
await sleep();
expect(await handle.query('data')).toEqual(data);
await handle.cancel();
const client = getClient();
const childHandle = await client.workflow.getHandle(`Listing-${data.listings[0].id}`);
await handle.cancel();
await childHandle.result();
});
it.skip('Should handle completed child workflow and maintain state in the parent', async () => {
const listing = { id: uuid4(), name: 'Test Listing' };
const data = { id: uuid4(), listings: [listing] };
const handle = await execute(workflows.ShouldExecuteStateful, { id: data.id, entityName: 'User', data });
await sleep();
const client = getClient();
const childHandle = client.workflow.getHandle(`Listing-${data.listings[0].id}`);
await childHandle.signal('status', 'completed');
const childCompletedData = await childHandle.result();
expect(childCompletedData).toEqual(listing);
const parentData = await handle.query('data');
expect(parentData).toEqual(data);
});
});
describe('Error Handling and Recovery', () => {
it.skip('Should handle invalid state query by returning error', async () => {
const userId = uuid4();
const handle = await execute(workflows.ShouldExecuteStateful, { id: userId, entityName: 'User', state: {} });
await sleep();
try {
await handle.query('invalidState');
fail('Expected an error for invalid state query');
} catch (e) {
expect(e.message).toContain('did not register a handler');
}
});
it.skip('Should recover from signal errors and maintain state integrity', async () => {
const userId = uuid4();
const handle = await execute(workflows.ShouldExecuteStateful, {
id: userId,
entityName: 'User',
state: { User: { [userId]: { id: userId, name: 'Initial' } } }
});
await sleep();
try {
await handle.signal('update', { data: null, entityName: 'User' }); // Invalid data
} catch (e) {
expect(e.message).toContain('Invalid data');
}
await sleep();
const state = await handle.query('state');
expect(state.User[userId]).toHaveProperty('name', 'Initial');
});
});
describe('Performance and Scalability', () => {
it('Should handle rapid succession of updates correctly', async () => {
const data = { id: uuid4(), listings: [{ id: uuid4(), name: 'Listing' }] };
const handle = await execute(workflows.ShouldExecuteStateful, { id: data.id, entityName: 'User', data });
await sleep();
for (let i = 0; i < 5; i++) {
data.listings[0].name = `Update-${i}`;
await handle.signal('update', { data, entityName: 'User' });
}
await sleep(10000);
const finalState = await handle.query('state');
expect(finalState).toEqual(normalizeEntities(data, SchemaManager.getInstance().getSchema('User')));
});
it('Should handle a high volume of state changes without degradation', async () => {
const userId = uuid4();
const handle = await execute(workflows.ShouldExecuteStateful, {
id: userId,
entityName: 'User',
data: { id: userId, name: 'Initial' }
});
await sleep();
const updates = Array.from({ length: 50 }, (_, i) => ({
id: userId,
name: `Update-${i}`
}));
for (const update of updates) {
await handle.signal('update', { data: update, entityName: 'User' });
}
await sleep(2500);
const finalState = await handle.query('state');
expect(finalState.User[userId].name).toEqual('Update-49');
});
it('Should manage circular relationships without causing infinite loops', async () => {
const userId = uuid4();
const listingId = uuid4();
const data = {
id: userId,
listings: [{ id: listingId, content: 'Hello World', user: userId }]
};
const handle = await execute(workflows.ShouldExecuteStateful, { id: data.id, entityName: 'User', data });
await sleep(2500);
const initialState = await handle.query('state');
expect(initialState).toEqual(normalizeEntities(data, SchemaManager.getInstance().getSchema(`User`)));
data.listings[0].content = 'Updated Content';
const client = getClient();
const childHandle = await client.workflow.getHandle(`Listing-${listingId}`);
await childHandle.signal('update', { data: data.listings[0], entityName: 'Listing' });
await sleep(2500);
const parentData = await handle.query('state');
expect(parentData.Listing[data.listings[0].id].content).toEqual('Updated Content');
});
});
describe('Schema and Data Integrity', () => {
it('Should handle circular references correctly when updating nested entities', async () => {
const userId = uuid4();
const listingId = uuid4();
const photoId = uuid4();
const likeId = uuid4();
// Circular data structure where a user likes a photo that belongs to them via a listing
const data = {
id: userId,
listings: [
{
id: listingId,
user: userId,
photos: [
{ id: photoId, user: userId, listing: listingId, likes: [{ id: likeId, user: userId, photo: photoId }] }
]
}
]
};
// Start User workflow
const handle = await execute(workflows.ShouldExecuteStateful, {
id: data.id,
entityName: 'User',
data
});
await sleep(5000);
// Verify the User workflow is initialized correctly with normalized state
const expectedInitialState = normalizeEntities(data, SchemaManager.getInstance().getSchema('User'));
const state = await handle.query('state');
expect(state).toEqual(expectedInitialState);
// Start child Listing and Like workflows
const client = getClient();
const listingHandle = await client.workflow.getHandle(`Listing-${listingId}`);
const likeHandle = await client.workflow.getHandle(`Like-${likeId}`);
// Update the Like entity directly in the child workflow
await likeHandle.signal('update', {
data: { id: likeId, user: userId, newField: 'direct update' },
entityName: 'Like'
});
await sleep(5000);
// Verify that the state in the parent User workflow is updated correctly
const parentUpdatedState = await handle.query('state');
expect(parentUpdatedState.Like[likeId].newField).toEqual('direct update');
}, 45000);
});
describe('getCompositeKey', () => {
it('should generate a composite key from single-level attributes', () => {
const entity = {
id: '123',
type: 'abc'
};
const idAttributes = ['id', 'type'];
const compositeKey = getCompositeKey(entity, idAttributes);
expect(compositeKey).toBe('123-abc');
});
it('should generate a composite key from nested attributes', () => {
const entity = {
user: {
id: '123',
type: 'abc'
}
};
const idAttributes = ['user.id', 'user.type'];
const compositeKey = getCompositeKey(entity, idAttributes);
expect(compositeKey).toBe('123-abc');
});
it('should generate a composite key from mixed attributes', () => {
const entity = {
id: '123',
details: {
type: 'abc'
}
};
const idAttributes = ['id', 'details.type'];
const compositeKey = getCompositeKey(entity, idAttributes);
expect(compositeKey).toBe('123-abc');
});
it('should handle missing attributes gracefully', () => {
const entity = {
id: '123'
};
const idAttributes = ['id', 'type'];
const compositeKey = getCompositeKey(entity, idAttributes);
expect(compositeKey).toBe('123-');
});
it('should handle empty idAttributes array', () => {
const entity = {
id: '123',
type: 'abc'
};
const idAttributes: string[] = [];
const compositeKey = getCompositeKey(entity, idAttributes);
expect(compositeKey).toBe('');
});
});
});