@friggframework/devtools 2.0.0--canary.474.86c5119.0 → 2.0.0--canary.474.6a0bba7.0

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.
Files changed (32) hide show
  1. package/infrastructure/domains/database/migration-builder.js +199 -1
  2. package/infrastructure/domains/database/migration-builder.test.js +73 -0
  3. package/infrastructure/domains/health/application/use-cases/__tests__/mismatch-analyzer-method-name.test.js +167 -0
  4. package/infrastructure/domains/health/application/use-cases/__tests__/repair-via-import-use-case.test.js +1130 -0
  5. package/infrastructure/domains/health/application/use-cases/reconcile-properties-use-case.js +6 -0
  6. package/infrastructure/domains/health/application/use-cases/repair-via-import-use-case.js +307 -1
  7. package/infrastructure/domains/health/application/use-cases/run-health-check-use-case.js +38 -5
  8. package/infrastructure/domains/health/application/use-cases/run-health-check-use-case.test.js +3 -3
  9. package/infrastructure/domains/health/docs/ACME-DEV-DRIFT-ANALYSIS.md +267 -0
  10. package/infrastructure/domains/health/docs/BUILD-VS-DEPLOYED-TEMPLATE-ANALYSIS.md +324 -0
  11. package/infrastructure/domains/health/docs/ORPHAN-DETECTION-ANALYSIS.md +386 -0
  12. package/infrastructure/domains/health/docs/SPEC-CLEANUP-COMMAND.md +1419 -0
  13. package/infrastructure/domains/health/docs/TDD-IMPLEMENTATION-SUMMARY.md +391 -0
  14. package/infrastructure/domains/health/docs/TEMPLATE-COMPARISON-IMPLEMENTATION.md +551 -0
  15. package/infrastructure/domains/health/domain/entities/issue.js +50 -1
  16. package/infrastructure/domains/health/domain/entities/issue.test.js +111 -0
  17. package/infrastructure/domains/health/domain/services/__tests__/health-score-percentage-based.test.js +380 -0
  18. package/infrastructure/domains/health/domain/services/__tests__/logical-id-mapper.test.js +672 -0
  19. package/infrastructure/domains/health/domain/services/__tests__/template-parser.test.js +496 -0
  20. package/infrastructure/domains/health/domain/services/health-score-calculator.js +174 -91
  21. package/infrastructure/domains/health/domain/services/health-score-calculator.test.js +332 -228
  22. package/infrastructure/domains/health/domain/services/logical-id-mapper.js +345 -0
  23. package/infrastructure/domains/health/domain/services/template-parser.js +245 -0
  24. package/infrastructure/domains/health/infrastructure/adapters/__tests__/orphan-detection-cfn-tagged.test.js +312 -0
  25. package/infrastructure/domains/health/infrastructure/adapters/__tests__/orphan-detection-multi-stack.test.js +367 -0
  26. package/infrastructure/domains/health/infrastructure/adapters/__tests__/orphan-detection-relationship-analysis.test.js +432 -0
  27. package/infrastructure/domains/health/infrastructure/adapters/aws-property-reconciler.js +407 -20
  28. package/infrastructure/domains/health/infrastructure/adapters/aws-property-reconciler.test.js +698 -26
  29. package/infrastructure/domains/health/infrastructure/adapters/aws-resource-detector.js +108 -14
  30. package/infrastructure/domains/health/infrastructure/adapters/aws-resource-detector.test.js +69 -12
  31. package/infrastructure/domains/health/infrastructure/adapters/aws-stack-repository.js +392 -1
  32. package/package.json +6 -6
@@ -21,6 +21,11 @@ jest.mock('@aws-sdk/client-ec2', () => ({
21
21
  ModifyVpcAttributeCommand: jest.fn(),
22
22
  }));
23
23
 
24
+ jest.mock('@aws-sdk/client-lambda', () => ({
25
+ LambdaClient: jest.fn(),
26
+ UpdateFunctionConfigurationCommand: jest.fn(),
27
+ }));
28
+
24
29
  describe('AWSPropertyReconciler', () => {
25
30
  let reconciler;
26
31
  let mockCFSend;
@@ -188,7 +193,7 @@ describe('AWSPropertyReconciler', () => {
188
193
  });
189
194
 
190
195
  describe('reconcileMultipleProperties', () => {
191
- it('should reconcile multiple properties in template mode', async () => {
196
+ it('should reconcile multiple properties in single UpdateStack call', async () => {
192
197
  const stackIdentifier = new StackIdentifier({
193
198
  stackName: 'my-app-prod',
194
199
  region: 'us-east-1',
@@ -209,7 +214,7 @@ describe('AWSPropertyReconciler', () => {
209
214
  }),
210
215
  ];
211
216
 
212
- // Mock GetTemplate for first property
217
+ // Mock GetTemplate - should be called ONCE
213
218
  mockCFSend.mockResolvedValueOnce({
214
219
  TemplateBody: JSON.stringify({
215
220
  Resources: {
@@ -225,28 +230,7 @@ describe('AWSPropertyReconciler', () => {
225
230
  }),
226
231
  });
227
232
 
228
- // Mock UpdateStack for first property
229
- mockCFSend.mockResolvedValueOnce({
230
- StackId: 'arn:aws:cloudformation:us-east-1:123456789012:stack/my-app-prod/guid',
231
- });
232
-
233
- // Mock GetTemplate for second property
234
- mockCFSend.mockResolvedValueOnce({
235
- TemplateBody: JSON.stringify({
236
- Resources: {
237
- MyVPC: {
238
- Type: 'AWS::EC2::VPC',
239
- Properties: {
240
- CidrBlock: '10.0.0.0/16',
241
- EnableDnsSupport: false,
242
- EnableDnsHostnames: true,
243
- },
244
- },
245
- },
246
- }),
247
- });
248
-
249
- // Mock UpdateStack for second property
233
+ // Mock UpdateStack - should be called ONCE with both property updates
250
234
  mockCFSend.mockResolvedValueOnce({
251
235
  StackId: 'arn:aws:cloudformation:us-east-1:123456789012:stack/my-app-prod/guid',
252
236
  });
@@ -258,9 +242,20 @@ describe('AWSPropertyReconciler', () => {
258
242
  mode: 'template',
259
243
  });
260
244
 
245
+ // Verify only 2 AWS SDK calls: 1 GetTemplate + 1 UpdateStack (not 3+ like before)
246
+ expect(mockCFSend).toHaveBeenCalledTimes(2);
247
+
248
+ // Verify result
261
249
  expect(result.reconciledCount).toBe(2);
262
250
  expect(result.failedCount).toBe(0);
263
251
  expect(result.results).toHaveLength(2);
252
+ expect(result.message).toContain('single UpdateStack call');
253
+
254
+ // Verify both properties were marked as successfully reconciled
255
+ expect(result.results[0].success).toBe(true);
256
+ expect(result.results[0].propertyPath).toBe('Properties.EnableDnsSupport');
257
+ expect(result.results[1].success).toBe(true);
258
+ expect(result.results[1].propertyPath).toBe('Properties.EnableDnsHostnames');
264
259
  });
265
260
  });
266
261
 
@@ -442,8 +437,685 @@ describe('AWSPropertyReconciler', () => {
442
437
 
443
438
  it('should throw error for unsupported type', async () => {
444
439
  await expect(
445
- reconciler.getReconciliationStrategy('AWS::Lambda::Function')
446
- ).rejects.toThrow('Resource type AWS::Lambda::Function not supported');
440
+ reconciler.getReconciliationStrategy('AWS::UnsupportedType::Resource')
441
+ ).rejects.toThrow('Resource type AWS::UnsupportedType::Resource not supported');
442
+ });
443
+
444
+ it('should get strategy for Lambda Function', async () => {
445
+ const strategy = await reconciler.getReconciliationStrategy(
446
+ 'AWS::Lambda::Function'
447
+ );
448
+
449
+ expect(strategy.supportsTemplateUpdate).toBe(true);
450
+ expect(strategy.supportsResourceUpdate).toBe(false);
451
+ expect(strategy.recommendedMode).toBe('template');
452
+ expect(strategy.limitations).toContain(
453
+ 'VpcConfig changes may take several minutes to propagate'
454
+ );
455
+ });
456
+ });
457
+
458
+ describe('Lambda Function VpcConfig Reconciliation (TDD)', () => {
459
+ let stackIdentifier;
460
+
461
+ beforeEach(() => {
462
+ stackIdentifier = new StackIdentifier({
463
+ stackName: 'test-stack',
464
+ region: 'us-east-1',
465
+ });
466
+ });
467
+
468
+ describe('reconcile Lambda VpcConfig.SubnetIds', () => {
469
+ it('should reconcile Lambda SubnetIds property mismatch', async () => {
470
+ const mismatch = new PropertyMismatch({
471
+ propertyPath: 'Properties.VpcConfig.SubnetIds',
472
+ expectedValue: ['subnet-111', 'subnet-222'],
473
+ actualValue: ['subnet-333', 'subnet-444'],
474
+ mutability: PropertyMutability.MUTABLE,
475
+ });
476
+
477
+ // Mock GetTemplate
478
+ mockCFSend.mockResolvedValueOnce({
479
+ TemplateBody: JSON.stringify({
480
+ Resources: {
481
+ AttioLambdaFunction: {
482
+ Type: 'AWS::Lambda::Function',
483
+ Properties: {
484
+ FunctionName: 'attio-lambda',
485
+ Runtime: 'nodejs20.x',
486
+ VpcConfig: {
487
+ SubnetIds: ['subnet-111', 'subnet-222'],
488
+ SecurityGroupIds: ['sg-111'],
489
+ },
490
+ },
491
+ },
492
+ },
493
+ }),
494
+ });
495
+
496
+ // Mock UpdateStack
497
+ mockCFSend.mockResolvedValueOnce({
498
+ StackId: 'arn:aws:cloudformation:us-east-1:123456789012:stack/test-stack/guid',
499
+ });
500
+
501
+ const result = await reconciler.reconcileProperty({
502
+ stackIdentifier,
503
+ logicalId: 'AttioLambdaFunction',
504
+ mismatch,
505
+ mode: 'template',
506
+ });
507
+
508
+ expect(result.success).toBe(true);
509
+ expect(result.mode).toBe('template');
510
+ expect(result.propertyPath).toBe('Properties.VpcConfig.SubnetIds');
511
+ expect(result.oldValue).toEqual(['subnet-111', 'subnet-222']);
512
+ expect(result.newValue).toEqual(['subnet-333', 'subnet-444']);
513
+ expect(result.message).toContain('Template updated to match actual resource state');
514
+ });
515
+
516
+ it('should recognize SubnetIds as mutable (no replacement required)', async () => {
517
+ const mismatch = new PropertyMismatch({
518
+ propertyPath: 'Properties.VpcConfig.SubnetIds',
519
+ expectedValue: ['subnet-111'],
520
+ actualValue: ['subnet-333'],
521
+ mutability: PropertyMutability.MUTABLE,
522
+ });
523
+
524
+ const canReconcile = await reconciler.canReconcile(mismatch);
525
+ expect(canReconcile).toBe(true);
526
+ });
527
+ });
528
+
529
+ describe('reconcile Lambda VpcConfig.SecurityGroupIds', () => {
530
+ it('should reconcile Lambda SecurityGroupIds property mismatch', async () => {
531
+ const mismatch = new PropertyMismatch({
532
+ propertyPath: 'Properties.VpcConfig.SecurityGroupIds',
533
+ expectedValue: ['sg-111'],
534
+ actualValue: ['sg-222', 'sg-333'],
535
+ mutability: PropertyMutability.MUTABLE,
536
+ });
537
+
538
+ // Mock GetTemplate
539
+ mockCFSend.mockResolvedValueOnce({
540
+ TemplateBody: JSON.stringify({
541
+ Resources: {
542
+ HealthLambdaFunction: {
543
+ Type: 'AWS::Lambda::Function',
544
+ Properties: {
545
+ FunctionName: 'health-lambda',
546
+ Runtime: 'nodejs20.x',
547
+ VpcConfig: {
548
+ SubnetIds: ['subnet-111', 'subnet-222'],
549
+ SecurityGroupIds: ['sg-111'],
550
+ },
551
+ },
552
+ },
553
+ },
554
+ }),
555
+ });
556
+
557
+ // Mock UpdateStack
558
+ mockCFSend.mockResolvedValueOnce({
559
+ StackId: 'arn:aws:cloudformation:us-east-1:123456789012:stack/test-stack/guid',
560
+ });
561
+
562
+ const result = await reconciler.reconcileProperty({
563
+ stackIdentifier,
564
+ logicalId: 'HealthLambdaFunction',
565
+ mismatch,
566
+ mode: 'template',
567
+ });
568
+
569
+ expect(result.success).toBe(true);
570
+ expect(result.mode).toBe('template');
571
+ expect(result.propertyPath).toBe('Properties.VpcConfig.SecurityGroupIds');
572
+ expect(result.newValue).toEqual(['sg-222', 'sg-333']);
573
+ });
574
+ });
575
+
576
+ describe('reconcile multiple Lambda VpcConfig properties', () => {
577
+ it('should reconcile both SubnetIds and SecurityGroupIds for same Lambda', async () => {
578
+ const mismatches = [
579
+ new PropertyMismatch({
580
+ propertyPath: 'Properties.VpcConfig.SubnetIds',
581
+ expectedValue: ['subnet-111', 'subnet-222'],
582
+ actualValue: ['subnet-333', 'subnet-444'],
583
+ mutability: PropertyMutability.MUTABLE,
584
+ }),
585
+ new PropertyMismatch({
586
+ propertyPath: 'Properties.VpcConfig.SecurityGroupIds',
587
+ expectedValue: ['sg-111'],
588
+ actualValue: ['sg-222'],
589
+ mutability: PropertyMutability.MUTABLE,
590
+ }),
591
+ ];
592
+
593
+ // Mock GetTemplate for first property (SubnetIds)
594
+ mockCFSend.mockResolvedValueOnce({
595
+ TemplateBody: JSON.stringify({
596
+ Resources: {
597
+ UserLambdaFunction: {
598
+ Type: 'AWS::Lambda::Function',
599
+ Properties: {
600
+ FunctionName: 'user-lambda',
601
+ Runtime: 'nodejs20.x',
602
+ VpcConfig: {
603
+ SubnetIds: ['subnet-111', 'subnet-222'],
604
+ SecurityGroupIds: ['sg-111'],
605
+ },
606
+ },
607
+ },
608
+ },
609
+ }),
610
+ });
611
+
612
+ // Mock UpdateStack for first property
613
+ mockCFSend.mockResolvedValueOnce({
614
+ StackId: 'arn:aws:cloudformation:us-east-1:123456789012:stack/test-stack/guid',
615
+ });
616
+
617
+ // Mock GetTemplate for second property (SecurityGroupIds)
618
+ mockCFSend.mockResolvedValueOnce({
619
+ TemplateBody: JSON.stringify({
620
+ Resources: {
621
+ UserLambdaFunction: {
622
+ Type: 'AWS::Lambda::Function',
623
+ Properties: {
624
+ FunctionName: 'user-lambda',
625
+ Runtime: 'nodejs20.x',
626
+ VpcConfig: {
627
+ SubnetIds: ['subnet-333', 'subnet-444'], // Updated from first reconciliation
628
+ SecurityGroupIds: ['sg-111'],
629
+ },
630
+ },
631
+ },
632
+ },
633
+ }),
634
+ });
635
+
636
+ // Mock UpdateStack for second property
637
+ mockCFSend.mockResolvedValueOnce({
638
+ StackId: 'arn:aws:cloudformation:us-east-1:123456789012:stack/test-stack/guid',
639
+ });
640
+
641
+ const result = await reconciler.reconcileMultipleProperties({
642
+ stackIdentifier,
643
+ logicalId: 'UserLambdaFunction',
644
+ mismatches,
645
+ mode: 'template',
646
+ });
647
+
648
+ expect(result.reconciledCount).toBe(2);
649
+ expect(result.failedCount).toBe(0);
650
+ expect(result.results).toHaveLength(2);
651
+ });
652
+ });
653
+
654
+ describe('Lambda reconciliation strategy', () => {
655
+ it('should provide reconciliation strategy for Lambda Function', async () => {
656
+ const strategy = await reconciler.getReconciliationStrategy(
657
+ 'AWS::Lambda::Function'
658
+ );
659
+
660
+ expect(strategy).toEqual({
661
+ supportsTemplateUpdate: true,
662
+ supportsResourceUpdate: false,
663
+ recommendedMode: 'template',
664
+ limitations: expect.arrayContaining([
665
+ 'VpcConfig changes may take several minutes to propagate',
666
+ ]),
667
+ });
668
+ });
669
+ });
670
+
671
+ describe('real-world drift scenario - 17 Lambda functions', () => {
672
+ it('should reconcile VpcConfig drift for multiple Lambda functions', async () => {
673
+ // Simulate real drift from user's test-stack stack
674
+ // 17 Lambda functions with 2 mismatches each (SubnetIds + SecurityGroupIds)
675
+ const lambdaFunctions = [
676
+ 'AttioLambdaFunction',
677
+ 'AttioQueueWorkerLambdaFunction',
678
+ 'HealthLambdaFunction',
679
+ ];
680
+
681
+ let totalReconciled = 0;
682
+
683
+ for (const logicalId of lambdaFunctions) {
684
+ const mismatches = [
685
+ new PropertyMismatch({
686
+ propertyPath: 'Properties.VpcConfig.SubnetIds',
687
+ expectedValue: ['subnet-old1', 'subnet-old2'],
688
+ actualValue: ['subnet-new1', 'subnet-new2'],
689
+ mutability: PropertyMutability.MUTABLE,
690
+ }),
691
+ new PropertyMismatch({
692
+ propertyPath: 'Properties.VpcConfig.SecurityGroupIds',
693
+ expectedValue: ['sg-old'],
694
+ actualValue: ['sg-new'],
695
+ mutability: PropertyMutability.MUTABLE,
696
+ }),
697
+ ];
698
+
699
+ // Mock GetTemplate + UpdateStack ONCE (batches both properties)
700
+ mockCFSend
701
+ .mockResolvedValueOnce({
702
+ TemplateBody: JSON.stringify({
703
+ Resources: {
704
+ [logicalId]: {
705
+ Type: 'AWS::Lambda::Function',
706
+ Properties: {
707
+ VpcConfig: {
708
+ SubnetIds: ['subnet-old1', 'subnet-old2'],
709
+ SecurityGroupIds: ['sg-old'],
710
+ },
711
+ },
712
+ },
713
+ },
714
+ }),
715
+ })
716
+ .mockResolvedValueOnce({ StackId: 'arn:...' });
717
+
718
+ const result = await reconciler.reconcileMultipleProperties({
719
+ stackIdentifier,
720
+ logicalId,
721
+ mismatches,
722
+ mode: 'template',
723
+ });
724
+
725
+ totalReconciled += result.reconciledCount;
726
+ }
727
+
728
+ // 3 functions × 2 properties each = 6 total reconciliations
729
+ expect(totalReconciled).toBe(6);
730
+ });
731
+ });
732
+ });
733
+
734
+ describe('large template handling (> 51KB limit)', () => {
735
+ it('should use S3 upload when template exceeds 51KB', async () => {
736
+ const stackIdentifier = new StackIdentifier({
737
+ stackName: 'test-stack',
738
+ region: 'us-east-1',
739
+ });
740
+
741
+ // Create large template that exceeds 51,200 bytes
742
+ const largeTemplate = {
743
+ Resources: {},
744
+ Outputs: {},
745
+ };
746
+
747
+ // Add many resources to exceed limit (need ~250 resources with outputs to reach 51KB+)
748
+ for (let i = 0; i < 250; i++) {
749
+ largeTemplate.Resources[`LambdaFunction${i}`] = {
750
+ Type: 'AWS::Lambda::Function',
751
+ Properties: {
752
+ FunctionName: `my-integration-function-${i}`,
753
+ Runtime: 'nodejs18.x',
754
+ Handler: 'index.handler',
755
+ Role: { 'Fn::GetAtt': ['LambdaExecutionRole', 'Arn'] },
756
+ Code: {
757
+ S3Bucket: 'my-deployment-bucket',
758
+ S3Key: `serverless/my-stack/dev/${Date.now()}/function-${i}.zip`,
759
+ },
760
+ VpcConfig: {
761
+ SubnetIds: ['subnet-33333333', 'subnet-44444444'],
762
+ SecurityGroupIds: ['sg-12345678'],
763
+ },
764
+ Environment: {
765
+ Variables: {
766
+ NODE_ENV: 'production',
767
+ DB_HOST: 'my-db-host',
768
+ DB_NAME: 'my-database',
769
+ },
770
+ },
771
+ },
772
+ };
773
+ largeTemplate.Outputs[`LambdaFunction${i}QualifiedArn`] = {
774
+ Description: `Current Lambda function version for function ${i}`,
775
+ Value: { 'Fn::GetAtt': [`LambdaFunction${i}`, 'Arn'] },
776
+ Export: { Name: { 'Fn::Sub': `\${AWS::StackName}-LambdaFunction${i}QualifiedArn` } },
777
+ };
778
+ }
779
+
780
+ const templateBody = JSON.stringify(largeTemplate);
781
+ expect(templateBody.length).toBeGreaterThan(51200);
782
+
783
+ // Mock CloudFormation repository with uploadTemplate and monitoring methods
784
+ const mockCFRepo = {
785
+ uploadTemplate: jest.fn().mockResolvedValue('https://bucket.s3.amazonaws.com/template.json'),
786
+ getStackEvents: jest.fn().mockResolvedValue([
787
+ {
788
+ LogicalResourceId: 'LambdaFunction0',
789
+ ResourceStatus: 'UPDATE_COMPLETE',
790
+ Timestamp: new Date(),
791
+ },
792
+ ]),
793
+ getStackStatus: jest.fn().mockResolvedValue('UPDATE_COMPLETE'),
794
+ };
795
+
796
+ const reconciler = new AWSPropertyReconciler({
797
+ region: 'us-east-1',
798
+ cloudFormationRepository: mockCFRepo,
799
+ });
800
+
801
+ const mismatch = new PropertyMismatch({
802
+ propertyPath: 'Properties.FunctionName',
803
+ expectedValue: 'old-function-name',
804
+ actualValue: 'my-integration-function-0',
805
+ mutability: PropertyMutability.MUTABLE,
806
+ });
807
+
808
+ // Mock GetTemplate
809
+ mockCFSend.mockResolvedValueOnce({
810
+ TemplateBody: templateBody,
811
+ });
812
+
813
+ // Mock UpdateStack (should use TemplateURL, not TemplateBody)
814
+ mockCFSend.mockResolvedValueOnce({ StackId: 'arn:...' });
815
+
816
+ const result = await reconciler.reconcileMultipleProperties({
817
+ stackIdentifier,
818
+ logicalId: 'LambdaFunction0', // Match resource in template
819
+ mismatches: [mismatch],
820
+ mode: 'template',
821
+ });
822
+
823
+ // Verify S3 upload was called with large template
824
+ expect(mockCFRepo.uploadTemplate).toHaveBeenCalledWith({
825
+ stackName: 'test-stack',
826
+ templateBody: expect.any(String),
827
+ });
828
+
829
+ // Verify template body passed to S3 is the large template
830
+ const uploadedTemplate = mockCFRepo.uploadTemplate.mock.calls[0][0].templateBody;
831
+ expect(uploadedTemplate.length).toBeGreaterThan(51200);
832
+
833
+ // Verify GetTemplate and UpdateStack were called
834
+ expect(mockCFSend).toHaveBeenCalledTimes(2);
835
+
836
+ // Success - reconciled the property
837
+ expect(result.reconciledCount).toBe(1);
838
+ expect(result.failedCount).toBe(0);
839
+ });
840
+
841
+ it('should use TemplateBody when template is under 51KB', async () => {
842
+ const stackIdentifier = new StackIdentifier({
843
+ stackName: 'small-stack',
844
+ region: 'us-east-1',
845
+ });
846
+
847
+ const smallTemplate = {
848
+ Resources: {
849
+ MyVPC: {
850
+ Type: 'AWS::EC2::VPC',
851
+ Properties: {
852
+ CidrBlock: '10.0.0.0/16',
853
+ },
854
+ },
855
+ },
856
+ };
857
+
858
+ const templateBody = JSON.stringify(smallTemplate);
859
+ expect(templateBody.length).toBeLessThan(51200);
860
+
861
+ const reconciler = new AWSPropertyReconciler({ region: 'us-east-1' });
862
+
863
+ const mismatch = new PropertyMismatch({
864
+ propertyPath: 'Properties.EnableDnsSupport',
865
+ expectedValue: true,
866
+ actualValue: false,
867
+ mutability: PropertyMutability.MUTABLE,
868
+ });
869
+
870
+ // Mock GetTemplate
871
+ mockCFSend.mockResolvedValueOnce({
872
+ TemplateBody: templateBody,
873
+ });
874
+
875
+ // Mock UpdateStack
876
+ mockCFSend.mockResolvedValueOnce({ StackId: 'arn:...' });
877
+
878
+ const result = await reconciler.reconcileMultipleProperties({
879
+ stackIdentifier,
880
+ logicalId: 'MyVPC',
881
+ mismatches: [mismatch],
882
+ mode: 'template',
883
+ });
884
+
885
+ // Verify 2 SDK calls: GetTemplate + UpdateStack
886
+ expect(mockCFSend).toHaveBeenCalledTimes(2);
887
+
888
+ // Success - small template doesn't require S3 upload
889
+ expect(result.reconciledCount).toBe(1);
890
+ expect(result.failedCount).toBe(0);
891
+ });
892
+ });
893
+
894
+ describe('resource mode batch reconciliation (TDD)', () => {
895
+ let stackIdentifier;
896
+ let mockLambdaSend;
897
+
898
+ beforeEach(() => {
899
+ stackIdentifier = new StackIdentifier({
900
+ stackName: 'test-stack',
901
+ region: 'us-east-1',
902
+ });
903
+
904
+ // Mock Lambda client
905
+ mockLambdaSend = jest.fn();
906
+ const { LambdaClient } = require('@aws-sdk/client-lambda');
907
+ LambdaClient.mockImplementation(() => ({ send: mockLambdaSend }));
908
+
909
+ // Re-create reconciler to get new Lambda client
910
+ reconciler = new AWSPropertyReconciler({ region: 'us-east-1' });
911
+ });
912
+
913
+ describe('reconcileMultipleProperties in resource mode', () => {
914
+ it('should batch Lambda VpcConfig updates via UpdateFunctionConfiguration', async () => {
915
+ const mismatches = [
916
+ new PropertyMismatch({
917
+ propertyPath: 'VpcConfig.SubnetIds',
918
+ expectedValue: ['subnet-11111111', 'subnet-22222222'],
919
+ actualValue: ['subnet-33333333', 'subnet-44444444'],
920
+ mutability: PropertyMutability.MUTABLE,
921
+ }),
922
+ new PropertyMismatch({
923
+ propertyPath: 'VpcConfig.SecurityGroupIds',
924
+ expectedValue: ['sg-expected'],
925
+ actualValue: ['sg-actual'],
926
+ mutability: PropertyMutability.MUTABLE,
927
+ }),
928
+ ];
929
+
930
+ // Mock Lambda UpdateFunctionConfiguration
931
+ mockLambdaSend.mockResolvedValueOnce({
932
+ FunctionName: 'test-stack-health',
933
+ VpcConfig: {
934
+ SubnetIds: ['subnet-11111111', 'subnet-22222222'],
935
+ SecurityGroupIds: ['sg-expected'],
936
+ },
937
+ });
938
+
939
+ const result = await reconciler.reconcileMultipleProperties({
940
+ stackIdentifier,
941
+ logicalId: 'HealthLambdaFunction',
942
+ physicalId: 'test-stack-health',
943
+ resourceType: 'AWS::Lambda::Function',
944
+ mismatches,
945
+ mode: 'resource',
946
+ });
947
+
948
+ expect(result.reconciledCount).toBe(2);
949
+ expect(result.failedCount).toBe(0);
950
+ expect(result.results).toHaveLength(2);
951
+ expect(result.results[0].success).toBe(true);
952
+ expect(result.results[0].mode).toBe('resource');
953
+ expect(result.message).toContain('Lambda VpcConfig updated');
954
+
955
+ // Verify UpdateFunctionConfiguration was called once with all changes
956
+ expect(mockLambdaSend).toHaveBeenCalledTimes(1);
957
+
958
+ // Verify the command was constructed correctly
959
+ // AWS SDK v3 UpdateFunctionConfigurationCommand wraps input in the command object
960
+ const { UpdateFunctionConfigurationCommand } = require('@aws-sdk/client-lambda');
961
+ expect(UpdateFunctionConfigurationCommand).toHaveBeenCalledWith({
962
+ FunctionName: 'test-stack-health',
963
+ VpcConfig: {
964
+ SubnetIds: ['subnet-11111111', 'subnet-22222222'],
965
+ SecurityGroupIds: ['sg-expected'],
966
+ },
967
+ });
968
+ });
969
+
970
+ it('should handle multiple Lambda functions in parallel', async () => {
971
+ // This test verifies that the reconciler can handle multiple Lambda functions
972
+ // Each Lambda should get its own UpdateFunctionConfiguration call
973
+ const lambdas = [
974
+ {
975
+ logicalId: 'HealthLambdaFunction',
976
+ physicalId: 'test-stack-health',
977
+ mismatches: [
978
+ new PropertyMismatch({
979
+ propertyPath: 'VpcConfig.SubnetIds',
980
+ expectedValue: ['subnet-111'],
981
+ actualValue: ['subnet-999'],
982
+ mutability: PropertyMutability.MUTABLE,
983
+ }),
984
+ ],
985
+ },
986
+ {
987
+ logicalId: 'UserLambdaFunction',
988
+ physicalId: 'test-stack-user',
989
+ mismatches: [
990
+ new PropertyMismatch({
991
+ propertyPath: 'VpcConfig.SubnetIds',
992
+ expectedValue: ['subnet-222'],
993
+ actualValue: ['subnet-888'],
994
+ mutability: PropertyMutability.MUTABLE,
995
+ }),
996
+ ],
997
+ },
998
+ ];
999
+
1000
+ // Mock successful responses for each Lambda
1001
+ mockLambdaSend.mockResolvedValue({
1002
+ VpcConfig: { SubnetIds: [], SecurityGroupIds: [] },
1003
+ });
1004
+
1005
+ // Reconcile first Lambda
1006
+ const result1 = await reconciler.reconcileMultipleProperties({
1007
+ stackIdentifier,
1008
+ logicalId: lambdas[0].logicalId,
1009
+ physicalId: lambdas[0].physicalId,
1010
+ resourceType: 'AWS::Lambda::Function',
1011
+ mismatches: lambdas[0].mismatches,
1012
+ mode: 'resource',
1013
+ });
1014
+
1015
+ // Reconcile second Lambda
1016
+ const result2 = await reconciler.reconcileMultipleProperties({
1017
+ stackIdentifier,
1018
+ logicalId: lambdas[1].logicalId,
1019
+ physicalId: lambdas[1].physicalId,
1020
+ resourceType: 'AWS::Lambda::Function',
1021
+ mismatches: lambdas[1].mismatches,
1022
+ mode: 'resource',
1023
+ });
1024
+
1025
+ expect(result1.reconciledCount).toBe(1);
1026
+ expect(result2.reconciledCount).toBe(1);
1027
+ expect(mockLambdaSend).toHaveBeenCalledTimes(2);
1028
+ });
1029
+
1030
+ it('should handle Lambda update failures gracefully', async () => {
1031
+ const mismatches = [
1032
+ new PropertyMismatch({
1033
+ propertyPath: 'VpcConfig.SubnetIds',
1034
+ expectedValue: ['subnet-111'],
1035
+ actualValue: ['subnet-999'],
1036
+ mutability: PropertyMutability.MUTABLE,
1037
+ }),
1038
+ ];
1039
+
1040
+ // Mock Lambda API error
1041
+ mockLambdaSend.mockRejectedValueOnce(
1042
+ new Error('InvalidParameterValueException: Subnets not in same VPC')
1043
+ );
1044
+
1045
+ const result = await reconciler.reconcileMultipleProperties({
1046
+ stackIdentifier,
1047
+ logicalId: 'HealthLambdaFunction',
1048
+ physicalId: 'test-stack-health',
1049
+ resourceType: 'AWS::Lambda::Function',
1050
+ mismatches,
1051
+ mode: 'resource',
1052
+ });
1053
+
1054
+ expect(result.reconciledCount).toBe(0);
1055
+ expect(result.failedCount).toBe(1);
1056
+ expect(result.message).toContain('Failed to update Lambda');
1057
+ expect(result.results[0].success).toBe(false);
1058
+ });
1059
+
1060
+ it('should skip immutable properties in resource mode', async () => {
1061
+ const mismatches = [
1062
+ new PropertyMismatch({
1063
+ propertyPath: 'VpcConfig.SubnetIds',
1064
+ expectedValue: ['subnet-111'],
1065
+ actualValue: ['subnet-999'],
1066
+ mutability: PropertyMutability.MUTABLE,
1067
+ }),
1068
+ new PropertyMismatch({
1069
+ propertyPath: 'FunctionName',
1070
+ expectedValue: 'old-name',
1071
+ actualValue: 'new-name',
1072
+ mutability: PropertyMutability.IMMUTABLE,
1073
+ }),
1074
+ ];
1075
+
1076
+ mockLambdaSend.mockResolvedValue({
1077
+ VpcConfig: { SubnetIds: ['subnet-111'], SecurityGroupIds: [] },
1078
+ });
1079
+
1080
+ const result = await reconciler.reconcileMultipleProperties({
1081
+ stackIdentifier,
1082
+ logicalId: 'HealthLambdaFunction',
1083
+ physicalId: 'test-stack-health',
1084
+ resourceType: 'AWS::Lambda::Function',
1085
+ mismatches,
1086
+ mode: 'resource',
1087
+ });
1088
+
1089
+ // Only mutable property should be reconciled
1090
+ expect(result.reconciledCount).toBe(1);
1091
+ expect(result.skippedCount).toBe(1);
1092
+ expect(result.results).toHaveLength(2);
1093
+ expect(result.results[0].success).toBe(true); // VpcConfig
1094
+ expect(result.results[1].success).toBe(false); // FunctionName
1095
+ expect(result.results[1].message).toContain('immutable');
1096
+ });
1097
+
1098
+ it('should throw error for unsupported resource types in resource mode', async () => {
1099
+ const mismatches = [
1100
+ new PropertyMismatch({
1101
+ propertyPath: 'SomeProperty',
1102
+ expectedValue: 'value1',
1103
+ actualValue: 'value2',
1104
+ mutability: PropertyMutability.MUTABLE,
1105
+ }),
1106
+ ];
1107
+
1108
+ await expect(
1109
+ reconciler.reconcileMultipleProperties({
1110
+ stackIdentifier,
1111
+ logicalId: 'MyUnsupportedResource',
1112
+ physicalId: 'resource-123',
1113
+ resourceType: 'AWS::Unsupported::Resource',
1114
+ mismatches,
1115
+ mode: 'resource',
1116
+ })
1117
+ ).rejects.toThrow('Resource mode reconciliation not supported for AWS::Unsupported::Resource');
1118
+ });
447
1119
  });
448
1120
  });
449
1121