@mbc-cqrs-serverless/cli 1.3.4 → 1.4.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mbc-cqrs-serverless/cli",
3
- "version": "1.3.4",
3
+ "version": "1.4.0",
4
4
  "description": "a CLI to get started with MBC CQRS serverless framework",
5
5
  "keywords": [
6
6
  "mbc",
@@ -58,5 +58,5 @@
58
58
  "@faker-js/faker": "^8.3.1",
59
59
  "copyfiles": "^2.4.1"
60
60
  },
61
- "gitHead": "e5b2e10fe73ebd89bf26b23942752d4ebe79388e"
61
+ "gitHead": "972a2726e2696e94e988dfc3135086b13cf2345b"
62
62
  }
@@ -20,6 +20,8 @@ EVENT_SOURCE_DISABLED=false
20
20
  # Serverless Offline (API Gateway)
21
21
  LOCAL_HTTP_PORT=3000
22
22
  LOCAL_LAMBDA_PORT=3002
23
+ # serverless-offline-lambda (external Lambda invoke)
24
+ LOCAL_OFFLINE_LAMBDA_PORT=4000
23
25
  # DynamoDB Local
24
26
  LOCAL_DYNAMODB_PORT=8000
25
27
  # MySQL (RDS)
@@ -72,7 +74,9 @@ SNS_ALARM_TOPIC_ARN=arn:aws:sns:ap-northeast-1:101010101010:AlarmSnsTopic
72
74
  # Cognito endpoint, useful for local development
73
75
  COGNITO_URL=http://localhost:${LOCAL_COGNITO_PORT:-9229}
74
76
  COGNITO_USER_POOL_ID=local_2G7noHgW
75
- COGNITO_USER_POLL_CLIENT_ID=dnk8y7ii3wled35p3lw0l2cd7
77
+ COGNITO_USER_POOL_CLIENT_ID=dnk8y7ii3wled35p3lw0l2cd7
78
+ # DEPRECATED: Use COGNITO_USER_POOL_CLIENT_ID instead (typo: POLL -> POOL)
79
+ # COGNITO_USER_POLL_CLIENT_ID=dnk8y7ii3wled35p3lw0l2cd7
76
80
  COGNITO_REGION=ap-northeast-1
77
81
  # AppSync endpoint, useful for local development
78
82
  APPSYNC_ENDPOINT=http://localhost:${LOCAL_APPSYNC_PORT:-4001}/graphql
@@ -785,6 +785,10 @@ export class InfraStack extends cdk.Stack {
785
785
  stateName: string,
786
786
  nextState: cdk.aws_stepfunctions.IChainable | null,
787
787
  integrationPattern: cdk.aws_stepfunctions.IntegrationPattern,
788
+ taskTimeout?: cdk.aws_stepfunctions.Timeout,
789
+ configureTask?: (
790
+ task: cdk.aws_stepfunctions_tasks.LambdaInvoke,
791
+ ) => cdk.aws_stepfunctions.IChainable,
788
792
  ) => {
789
793
  const payloadObject: {
790
794
  [key: string]: any
@@ -796,7 +800,7 @@ export class InfraStack extends cdk.Stack {
796
800
  integrationPattern ===
797
801
  cdk.aws_stepfunctions.IntegrationPattern.WAIT_FOR_TASK_TOKEN
798
802
  ) {
799
- payloadObject['taskToken'] = cdk.aws_stepfunctions.JsonPath.taskToken // '$$.Task.Token'
803
+ payloadObject['taskToken'] = cdk.aws_stepfunctions.JsonPath.taskToken
800
804
  }
801
805
  const lambdaTask = new cdk.aws_stepfunctions_tasks.LambdaInvoke(
802
806
  this,
@@ -808,12 +812,19 @@ export class InfraStack extends cdk.Stack {
808
812
  stateName,
809
813
  outputPath: '$.Payload[0][0]',
810
814
  integrationPattern,
815
+ ...(taskTimeout ? { taskTimeout } : {}),
811
816
  },
812
817
  )
818
+ // addCatch must run on the State before .next() turns it into a Chain.
819
+ const configuredTask = configureTask
820
+ ? (configureTask(
821
+ lambdaTask,
822
+ ) as cdk.aws_stepfunctions_tasks.LambdaInvoke)
823
+ : lambdaTask
813
824
  if (nextState) {
814
- return lambdaTask.next(nextState)
825
+ return configuredTask.next(nextState)
815
826
  }
816
- return lambdaTask
827
+ return configuredTask
817
828
  }
818
829
 
819
830
  // Define states
@@ -859,10 +870,34 @@ export class InfraStack extends cdk.Stack {
859
870
  cdk.aws_stepfunctions.IntegrationPattern.REQUEST_RESPONSE,
860
871
  )
861
872
 
873
+ // States.Timeout never invokes the wait_prev_command Lambda, so the
874
+ // command row is not updated (status/taskToken stay post-waitConfirmToken,
875
+ // typically wait_prev_command:FINISHED + stale token). That is one case of
876
+ // the broader cascade: any predecessor exit before FINISH leaves a
877
+ // non-finish status, so later versions will not self-resume and may each
878
+ // wait another 24h. Execution still fails here (CW ExecutionsFailed may fire).
879
+ const waitPrevCommandTimeoutHandler = new cdk.aws_stepfunctions.Pass(
880
+ this,
881
+ 'wait_prev_command_timeout',
882
+ {
883
+ stateName: 'wait_prev_command_timeout',
884
+ parameters: {
885
+ error: 'States.Timeout',
886
+ cause: 'wait_prev_command exceeded taskTimeout (24h)',
887
+ },
888
+ },
889
+ ).next(fail)
890
+
862
891
  const waitPrevCommand = lambdaInvoke(
863
892
  'wait_prev_command',
864
893
  setTtlCommand,
865
894
  cdk.aws_stepfunctions.IntegrationPattern.WAIT_FOR_TASK_TOKEN,
895
+ cdk.aws_stepfunctions.Timeout.duration(cdk.Duration.hours(24)),
896
+ (task) =>
897
+ task.addCatch(waitPrevCommandTimeoutHandler, {
898
+ errors: ['States.Timeout'],
899
+ resultPath: '$.timeoutError',
900
+ }),
866
901
  )
867
902
 
868
903
  // Define Choice state
@@ -917,6 +952,32 @@ export class InfraStack extends cdk.Stack {
917
952
  },
918
953
  )
919
954
 
955
+ // Pages when any command-handler execution fails — including wait_prev_command
956
+ // States.Timeout, which never invokes Lambda so publishAlarm cannot run.
957
+ const commandSfnFailedAlarm = new cdk.aws_cloudwatch.Alarm(
958
+ this,
959
+ 'command-handler-sfn-failed-alarm',
960
+ {
961
+ alarmName: prefix + 'command-handler-sfn-failed',
962
+ alarmDescription:
963
+ 'Command handler Step Functions execution failed (includes wait_prev_command 24h timeout)',
964
+ metric: stateMachine.metricFailed({
965
+ period: cdk.Duration.minutes(1),
966
+ statistic: 'Sum',
967
+ }),
968
+ threshold: 1,
969
+ evaluationPeriods: 1,
970
+ datapointsToAlarm: 1,
971
+ treatMissingData: cdk.aws_cloudwatch.TreatMissingData.NOT_BREACHING,
972
+ comparisonOperator:
973
+ cdk.aws_cloudwatch.ComparisonOperator
974
+ .GREATER_THAN_OR_EQUAL_TO_THRESHOLD,
975
+ },
976
+ )
977
+ commandSfnFailedAlarm.addAlarmAction(
978
+ new cdk.aws_cloudwatch_actions.SnsAction(alarmSns),
979
+ )
980
+
920
981
  // Output the State Machine's ARN
921
982
  this.stateMachineArn = new cdk.CfnOutput(this, 'StateMachineArn', {
922
983
  value: stateMachine.stateMachineArn,
@@ -1050,7 +1111,7 @@ export class InfraStack extends cdk.Stack {
1050
1111
  },
1051
1112
  })
1052
1113
  .itemProcessor(csvRowsHandlerState, {
1053
- executionType: aws_stepfunctions.ProcessorType.STANDARD,
1114
+ executionType: cdk.aws_stepfunctions.ProcessorType.STANDARD,
1054
1115
  })
1055
1116
 
1056
1117
  // Catch ALL Map state errors and route them to finalizeParentJobState
@@ -1230,6 +1291,14 @@ export class InfraStack extends cdk.Stack {
1230
1291
  resources: [commandSfnArn],
1231
1292
  })
1232
1293
 
1294
+ // SendTaskSuccess is scoped to this command state machine (same pattern as
1295
+ // CDK stateMachine.grantTaskResponse). Task tokens are still required at
1296
+ // call time; Resource '*' is unnecessary and over-broad for the template.
1297
+ const sfnTaskTokenPolicy = new cdk.aws_iam.PolicyStatement({
1298
+ actions: ['states:SendTaskSuccess'],
1299
+ resources: [stateMachine.stateMachineArn],
1300
+ })
1301
+
1233
1302
  const taskSfnPolicy = new cdk.aws_iam.PolicyStatement({
1234
1303
  actions: ['states:*'],
1235
1304
  resources: [taskSfnArn], // Access to all resources
@@ -1243,7 +1312,7 @@ export class InfraStack extends cdk.Stack {
1243
1312
  // Attach the policy to the Lambda function's execution role
1244
1313
  lambdaApi.role?.attachInlinePolicy(
1245
1314
  new cdk.aws_iam.Policy(this, 'lambda-event-sfn-policy', {
1246
- statements: [sfnPolicy],
1315
+ statements: [sfnPolicy, sfnTaskTokenPolicy],
1247
1316
  }),
1248
1317
  )
1249
1318
 
@@ -90,7 +90,7 @@ exports[`snapshot test for InfraStack 1`] = `
90
90
  "Arn",
91
91
  ],
92
92
  },
93
- "Runtime": "nodejs22.x",
93
+ "Runtime": "nodejs24.x",
94
94
  "Tags": [
95
95
  {
96
96
  "Key": "env",
@@ -210,6 +210,45 @@ exports[`snapshot test for InfraStack 1`] = `
210
210
  },
211
211
  "Type": "AWS::Cognito::UserPoolClient",
212
212
  },
213
+ "commandhandlersfnfailedalarmB54C35EC": {
214
+ "Properties": {
215
+ "AlarmActions": [
216
+ {
217
+ "Ref": "alarmsnsFB7BBC3B",
218
+ },
219
+ ],
220
+ "AlarmDescription": "Command handler Step Functions execution failed (includes wait_prev_command 24h timeout)",
221
+ "AlarmName": "dev--command-handler-sfn-failed",
222
+ "ComparisonOperator": "GreaterThanOrEqualToThreshold",
223
+ "DatapointsToAlarm": 1,
224
+ "Dimensions": [
225
+ {
226
+ "Name": "StateMachineArn",
227
+ "Value": {
228
+ "Ref": "commandhandlerstatemachine937D91FB",
229
+ },
230
+ },
231
+ ],
232
+ "EvaluationPeriods": 1,
233
+ "MetricName": "ExecutionsFailed",
234
+ "Namespace": "AWS/States",
235
+ "Period": 60,
236
+ "Statistic": "Sum",
237
+ "Tags": [
238
+ {
239
+ "Key": "env",
240
+ "Value": "dev",
241
+ },
242
+ {
243
+ "Key": "name",
244
+ "Value": "",
245
+ },
246
+ ],
247
+ "Threshold": 1,
248
+ "TreatMissingData": "notBreaching",
249
+ },
250
+ "Type": "AWS::CloudWatch::Alarm",
251
+ },
213
252
  "commandhandlersfnlog9072E963": {
214
253
  "DeletionPolicy": "Delete",
215
254
  "Properties": {
@@ -251,7 +290,7 @@ exports[`snapshot test for InfraStack 1`] = `
251
290
  "Arn",
252
291
  ],
253
292
  },
254
- "","Payload":{"input.$":"$","context.$":"$$"}}},"check_version_result":{"Type":"Choice","Choices":[{"Variable":"$.result","NumericEquals":0,"Next":"set_ttl_command"},{"Variable":"$.result","NumericEquals":1,"Next":"wait_prev_command"},{"Variable":"$.result","NumericEquals":-1,"Next":"fail"}],"Default":"wait_prev_command"},"wait_prev_command":{"Next":"set_ttl_command","Retry":[{"ErrorEquals":["Lambda.ClientExecutionTimeoutException","Lambda.ServiceException","Lambda.AWSLambdaException","Lambda.SdkClientException"],"IntervalSeconds":2,"MaxAttempts":6,"BackoffRate":2}],"Type":"Task","OutputPath":"$.Payload[0][0]","Resource":"arn:",
293
+ "","Payload":{"input.$":"$","context.$":"$$"}}},"check_version_result":{"Type":"Choice","Choices":[{"Variable":"$.result","NumericEquals":0,"Next":"set_ttl_command"},{"Variable":"$.result","NumericEquals":1,"Next":"wait_prev_command"},{"Variable":"$.result","NumericEquals":-1,"Next":"fail"}],"Default":"wait_prev_command"},"wait_prev_command":{"Next":"set_ttl_command","Retry":[{"ErrorEquals":["Lambda.ClientExecutionTimeoutException","Lambda.ServiceException","Lambda.AWSLambdaException","Lambda.SdkClientException"],"IntervalSeconds":2,"MaxAttempts":6,"BackoffRate":2}],"Catch":[{"ErrorEquals":["States.Timeout"],"ResultPath":"$.timeoutError","Next":"wait_prev_command_timeout"}],"Type":"Task","TimeoutSeconds":86400,"OutputPath":"$.Payload[0][0]","Resource":"arn:",
255
294
  {
256
295
  "Ref": "AWS::Partition",
257
296
  },
@@ -317,7 +356,7 @@ exports[`snapshot test for InfraStack 1`] = `
317
356
  "Arn",
318
357
  ],
319
358
  },
320
- "","Payload":{"input.$":"$","context.$":"$$"}}},"success":{"Type":"Succeed"},"fail":{"Type":"Fail","ErrorPath":"$.error","CausePath":"$.cause"}},"Comment":"A state machine that run the command stream handler"}",
359
+ "","Payload":{"input.$":"$","context.$":"$$"}}},"success":{"Type":"Succeed"},"wait_prev_command_timeout":{"Type":"Pass","Parameters":{"error":"States.Timeout","cause":"wait_prev_command exceeded taskTimeout (24h)"},"Next":"fail"},"fail":{"Type":"Fail","ErrorPath":"$.error","CausePath":"$.cause"}},"Comment":"A state machine that run the command stream handler"}",
321
360
  ],
322
361
  ],
323
362
  },
@@ -821,7 +860,18 @@ exports[`snapshot test for InfraStack 1`] = `
821
860
  "Fn::Join": [
822
861
  "",
823
862
  [
824
- "{"StartAt":"import-csv","States":{"import-csv":{"Type":"Map","End":true,"ItemProcessor":{"ProcessorConfig":{"Mode":"DISTRIBUTED","ExecutionType":"EXPRESS"},"StartAt":"csv_rows_handler","States":{"csv_rows_handler":{"End":true,"Retry":[{"ErrorEquals":["Lambda.ClientExecutionTimeoutException","Lambda.ServiceException","Lambda.AWSLambdaException","Lambda.SdkClientException"],"IntervalSeconds":2,"MaxAttempts":6,"BackoffRate":2}],"Type":"Task","OutputPath":"$.Payload[0][0]","Resource":"arn:",
863
+ "{"StartAt":"import-csv","States":{"import-csv":{"Type":"Map","ResultPath":"$.mapOutput","Next":"finalize_parent_job","Catch":[{"ErrorEquals":["States.ALL"],"ResultPath":"$.errorOutput","Next":"finalize_parent_job"}],"ItemProcessor":{"ProcessorConfig":{"Mode":"DISTRIBUTED","ExecutionType":"STANDARD"},"StartAt":"csv_rows_handler","States":{"csv_rows_handler":{"End":true,"Retry":[{"ErrorEquals":["Lambda.ClientExecutionTimeoutException","Lambda.ServiceException","Lambda.AWSLambdaException","Lambda.SdkClientException"],"IntervalSeconds":2,"MaxAttempts":6,"BackoffRate":2}],"Type":"Task","OutputPath":"$.Payload[0][0]","Resource":"arn:",
864
+ {
865
+ "Ref": "AWS::Partition",
866
+ },
867
+ ":states:::lambda:invoke","Parameters":{"FunctionName":"",
868
+ {
869
+ "Fn::GetAtt": [
870
+ "lambdaapi893CD94E",
871
+ "Arn",
872
+ ],
873
+ },
874
+ "","Payload":{"input.$":"$","context.$":"$$"}}}}},"MaxConcurrency":50,"ItemReader":{"Resource":"arn:aws:states:::s3:getObject","ReaderConfig":{"InputType":"CSV","CSVHeaderLocation":"FIRST_ROW"},"Parameters":{"Bucket.$":"$.bucket","Key.$":"$.key"}},"ResultWriter":{"Resource":"arn:aws:states:::s3:putObject","Parameters":{"Bucket":"your-import-bucket-name","Prefix":"sfn-results/import-csv"}},"ItemBatcher":{"MaxItemsPerBatch":100,"BatchInput":{"Attributes.$":"$"}},"Label":"import-csv"},"finalize_parent_job":{"Next":"success","Retry":[{"ErrorEquals":["Lambda.ServiceException","Lambda.AWSLambdaException","Lambda.SdkClientException"],"IntervalSeconds":2,"MaxAttempts":5,"BackoffRate":2}],"Type":"Task","OutputPath":"$.Payload[0][0]","Resource":"arn:",
825
875
  {
826
876
  "Ref": "AWS::Partition",
827
877
  },
@@ -832,7 +882,7 @@ exports[`snapshot test for InfraStack 1`] = `
832
882
  "Arn",
833
883
  ],
834
884
  },
835
- "","Payload":{"input.$":"$","context.$":"$$"}}}}},"MaxConcurrency":50,"ItemReader":{"Resource":"arn:aws:states:::s3:getObject","ReaderConfig":{"InputType":"CSV","CSVHeaderLocation":"FIRST_ROW"},"Parameters":{"Bucket.$":"$.bucket","Key.$":"$.key"}},"ItemBatcher":{"MaxInputBytesPerBatch":10,"BatchInput":{"Attributes.$":"$"}},"Label":"import-csv"}},"Comment":"A state machine for import-csv module handler"}",
885
+ "","Payload":{"input.$":"$","context.$":"$$"}}},"success":{"Type":"Succeed"}},"Comment":"A state machine for import-csv module handler"}",
836
886
  ],
837
887
  ],
838
888
  },
@@ -1066,6 +1116,9 @@ exports[`snapshot test for InfraStack 1`] = `
1066
1116
  "DATABASE_URL": "postgresql://@/?schema=public",
1067
1117
  "EVENT_SOURCE_DISABLED": "false",
1068
1118
  "FRONT_BASE_URL": "",
1119
+ "IMPORT_QUEUE_URL": {
1120
+ "Ref": "importactionsqs5E43BE2E",
1121
+ },
1069
1122
  "LOG_LEVEL": "verbose",
1070
1123
  "NODE_ENV": "dev",
1071
1124
  "NODE_OPTIONS": "--enable-source-maps",
@@ -1118,7 +1171,7 @@ exports[`snapshot test for InfraStack 1`] = `
1118
1171
  "Value": "",
1119
1172
  },
1120
1173
  ],
1121
- "Timeout": 31536000,
1174
+ "Timeout": 30,
1122
1175
  "TracingConfig": {
1123
1176
  "Mode": "Active",
1124
1177
  },
@@ -1148,7 +1201,7 @@ exports[`snapshot test for InfraStack 1`] = `
1148
1201
  "FilterCriteria": {
1149
1202
  "Filters": [
1150
1203
  {
1151
- "Pattern": "{"eventName":["INSERT"]}",
1204
+ "Pattern": "{"eventName":["INSERT"],"dynamodb":{"NewImage":{"syncMode":[{"exists":false}]}}}",
1152
1205
  },
1153
1206
  ],
1154
1207
  },
@@ -1181,7 +1234,7 @@ exports[`snapshot test for InfraStack 1`] = `
1181
1234
  "FilterCriteria": {
1182
1235
  "Filters": [
1183
1236
  {
1184
- "Pattern": "{"eventName":["INSERT"]}",
1237
+ "Pattern": "{"eventName":["INSERT"],"dynamodb":{"NewImage":{"syncMode":[{"exists":false}]}}}",
1185
1238
  },
1186
1239
  ],
1187
1240
  },
@@ -1214,7 +1267,7 @@ exports[`snapshot test for InfraStack 1`] = `
1214
1267
  "FilterCriteria": {
1215
1268
  "Filters": [
1216
1269
  {
1217
- "Pattern": "{"eventName":["INSERT"]}",
1270
+ "Pattern": "{"eventName":["INSERT"],"dynamodb":{"NewImage":{"syncMode":[{"exists":false}]}}}",
1218
1271
  },
1219
1272
  ],
1220
1273
  },
@@ -1594,6 +1647,20 @@ exports[`snapshot test for InfraStack 1`] = `
1594
1647
  ],
1595
1648
  },
1596
1649
  },
1650
+ {
1651
+ "Action": [
1652
+ "sqs:SendMessage",
1653
+ "sqs:GetQueueAttributes",
1654
+ "sqs:GetQueueUrl",
1655
+ ],
1656
+ "Effect": "Allow",
1657
+ "Resource": {
1658
+ "Fn::GetAtt": [
1659
+ "importactionsqs5E43BE2E",
1660
+ "Arn",
1661
+ ],
1662
+ },
1663
+ },
1597
1664
  ],
1598
1665
  "Version": "2012-10-17",
1599
1666
  },
@@ -1769,6 +1836,13 @@ exports[`snapshot test for InfraStack 1`] = `
1769
1836
  "Effect": "Allow",
1770
1837
  "Resource": "arn:aws:states:ap-northeast-1:101010101010:stateMachine:dev--command-handler",
1771
1838
  },
1839
+ {
1840
+ "Action": "states:SendTaskSuccess",
1841
+ "Effect": "Allow",
1842
+ "Resource": {
1843
+ "Ref": "commandhandlerstatemachine937D91FB",
1844
+ },
1845
+ },
1772
1846
  ],
1773
1847
  "Version": "2012-10-17",
1774
1848
  },
@@ -1926,7 +2000,7 @@ exports[`snapshot test for InfraStack 1`] = `
1926
2000
  "AllowOrigins": [
1927
2001
  "*",
1928
2002
  ],
1929
- "MaxAge": 31536000,
2003
+ "MaxAge": 3600,
1930
2004
  },
1931
2005
  "Description": "HTTP API for Lambda integration",
1932
2006
  "Name": "dev--api",
@@ -3030,7 +3104,7 @@ schema {
3030
3104
  "Arn",
3031
3105
  ],
3032
3106
  },
3033
- "","Payload":{"input.$":"$","context.$":"$$"}}}}},"MaxConcurrency":2}},"TimeoutSeconds":525600,"Comment":"A state machine for task handler"}",
3107
+ "","Payload":{"input.$":"$","context.$":"$$"}}}}},"MaxConcurrency":2}},"TimeoutSeconds":900,"Comment":"A state machine for task handler"}",
3034
3108
  ],
3035
3109
  ],
3036
3110
  },
@@ -0,0 +1 @@
1
+ placeholder app asset for hermetic infra tests
@@ -0,0 +1 @@
1
+ placeholder layer asset for hermetic infra tests
@@ -3,7 +3,7 @@
3
3
  */
4
4
 
5
5
  import * as cdk from 'aws-cdk-lib'
6
- import { Template } from 'aws-cdk-lib/assertions'
6
+ import { Match, Template } from 'aws-cdk-lib/assertions'
7
7
  import { getConfig } from '../config'
8
8
  import { InfraStack } from '../libs/infra-stack'
9
9
 
@@ -29,18 +29,20 @@ jest.mock('crypto', () => ({
29
29
  jest.mock('aws-cdk-lib', () => ({
30
30
  ...jest.requireActual('aws-cdk-lib'),
31
31
  Duration: {
32
- days: jest.fn(() => ({
33
- toMilliseconds: jest.fn(() => 365 * 24 * 60 * 60 * 1000), // Mock milliseconds for 365 days
32
+ days: jest.fn((n: number) => ({
33
+ toMilliseconds: jest.fn(() => n * 24 * 60 * 60 * 1000),
34
+ toSeconds: jest.fn(() => n * 24 * 60 * 60),
34
35
  })),
35
- hours: jest.fn(() => ({
36
- minutes: jest.fn(() => 365 * 24 * 60),
37
- toSeconds: jest.fn(() => 365 * 24 * 60 * 60),
36
+ hours: jest.fn((n: number) => ({
37
+ minutes: jest.fn(() => n * 60),
38
+ toSeconds: jest.fn(() => n * 60 * 60),
39
+ toMilliseconds: jest.fn(() => n * 60 * 60 * 1000),
38
40
  })),
39
- minutes: jest.fn(() => ({
40
- toSeconds: jest.fn(() => 365 * 24 * 60),
41
+ minutes: jest.fn((n: number) => ({
42
+ toSeconds: jest.fn(() => n * 60),
41
43
  })),
42
- seconds: jest.fn(() => ({
43
- toSeconds: jest.fn(() => 365 * 24 * 60 * 60),
44
+ seconds: jest.fn((n: number) => ({
45
+ toSeconds: jest.fn(() => n),
44
46
  })),
45
47
  },
46
48
  Expiration: {
@@ -52,6 +54,17 @@ jest.mock('aws-cdk-lib', () => ({
52
54
  },
53
55
  }))
54
56
 
57
+ // buildApp() shells out to a real `npm ci && npm run build:prod` of the parent
58
+ // application (via execSync). That cannot run in the isolated template / CI
59
+ // context, so it is mocked to return placeholder asset directories, keeping the
60
+ // CDK synthesis hermetic and the snapshot deterministic.
61
+ jest.mock('../libs/build-app', () => ({
62
+ buildApp: jest.fn(() => ({
63
+ layerPath: require('path').resolve(__dirname, 'fixtures/layer'),
64
+ appPath: require('path').resolve(__dirname, 'fixtures/app'),
65
+ })),
66
+ }))
67
+
55
68
  function replaceKeyValue(obj: any, desKey: string, desVal: string): any {
56
69
  if (typeof obj !== 'object' || obj === null) {
57
70
  return obj
@@ -93,3 +106,29 @@ test('snapshot test for InfraStack', () => {
93
106
 
94
107
  expect(template).toMatchSnapshot()
95
108
  })
109
+
110
+ test('lambda-api SendTaskSuccess is scoped to command-handler state machine', () => {
111
+ const cdkEnv: cdk.Environment = {
112
+ account: '101010101010',
113
+ region: 'ap-northeast-1',
114
+ }
115
+ const config = getConfig('dev')
116
+ const app = new cdk.App()
117
+ const stack = new InfraStack(app, 'TestInfraStackIam', {
118
+ env: cdkEnv,
119
+ config,
120
+ })
121
+ const template = Template.fromStack(stack)
122
+
123
+ template.hasResourceProperties('AWS::IAM::Policy', {
124
+ PolicyDocument: {
125
+ Statement: Match.arrayWith([
126
+ Match.objectLike({
127
+ Action: 'states:SendTaskSuccess',
128
+ Effect: 'Allow',
129
+ Resource: { Ref: 'commandhandlerstatemachine937D91FB' },
130
+ }),
131
+ ]),
132
+ },
133
+ })
134
+ })
@@ -5,7 +5,7 @@
5
5
  "main": "index.js",
6
6
  "scripts": {
7
7
  "postinstall": "patch-package",
8
- "dev": "HOST=0.0.0.0 npx cognito-local",
8
+ "dev": "sh ./start.sh",
9
9
  "test": "echo \"Error: no test specified\" && exit 1"
10
10
  },
11
11
  "author": "",
@@ -0,0 +1,46 @@
1
+ #!/bin/sh
2
+ set -e
3
+
4
+ # cognito-local derives the JWT `iss` claim from TokenConfig.IssuerDomain
5
+ # (default http://localhost:9229) in .cognito/config.json, independent of the
6
+ # listen port. To let the port be configured via LOCAL_COGNITO_PORT, we listen
7
+ # on $PORT and write a matching IssuerDomain so the emitted `iss` and the
8
+ # serverless authorizer's issuerUrl stay consistent (both http://localhost:$PORT).
9
+ #
10
+ # The config is merged (not overwritten) so any other cognito-local defaults or
11
+ # user-provided settings in .cognito/config.json are preserved.
12
+
13
+ PORT="${PORT:-9229}"
14
+ CONFIG_DIR="/app/.cognito"
15
+ CONFIG_FILE="${CONFIG_DIR}/config.json"
16
+
17
+ mkdir -p "${CONFIG_DIR}"
18
+
19
+ PORT="${PORT}" CONFIG_FILE="${CONFIG_FILE}" node -e '
20
+ const fs = require("fs");
21
+ const file = process.env.CONFIG_FILE;
22
+ const port = process.env.PORT;
23
+ let config = {};
24
+ try {
25
+ config = JSON.parse(fs.readFileSync(file, "utf8"));
26
+ } catch (e) {
27
+ if (e.code !== "ENOENT") {
28
+ // The file exists but could not be read/parsed (corrupted, permissions,
29
+ // manual edit mistake). Do NOT silently reset it — that would drop any
30
+ // other cognito-local settings the developer added. Fail fast instead.
31
+ console.error(
32
+ `[cognito-local] Failed to read ${file}: ${e.message}. ` +
33
+ "Refusing to overwrite it — fix or delete the file and retry.",
34
+ );
35
+ process.exit(1);
36
+ }
37
+ // ENOENT: first run, no config yet — start from an empty object.
38
+ }
39
+ config.TokenConfig = Object.assign({}, config.TokenConfig, {
40
+ IssuerDomain: `http://localhost:${port}`,
41
+ });
42
+ fs.writeFileSync(file, JSON.stringify(config, null, 2));
43
+ console.log(`[cognito-local] IssuerDomain set to http://localhost:${port}`);
44
+ '
45
+
46
+ exec env HOST=0.0.0.0 PORT="${PORT}" npx cognito-local
@@ -60,7 +60,6 @@ services:
60
60
  image: localstack/localstack
61
61
  ports:
62
62
  - '${LOCAL_S3_PORT:-4566}:4566'
63
- - '4510-4559:4510-4559'
64
63
  environment:
65
64
  - SERVICES=s3
66
65
  - AWS_DEFAULT_REGION=ap-northeast-1
@@ -85,7 +84,12 @@ services:
85
84
  build:
86
85
  context: ./cognito-local
87
86
  dockerfile: Dockerfile
87
+ environment:
88
+ # cognito-local listens on $PORT and emits JWT `iss` as http://localhost:$PORT
89
+ # (see cognito-local/start.sh). Host and container use the same port so the
90
+ # `iss` claim stays reachable from the serverless-offline authorizer.
91
+ - PORT=${LOCAL_COGNITO_PORT:-9229}
88
92
  ports:
89
- - ${LOCAL_COGNITO_PORT:-9229}:9229
93
+ - ${LOCAL_COGNITO_PORT:-9229}:${LOCAL_COGNITO_PORT:-9229}
90
94
  volumes:
91
95
  - ./docker-data/.cognito:/app/.cognito
@@ -11,15 +11,18 @@ Get-Content .env | ForEach-Object {
11
11
  }
12
12
  }
13
13
 
14
+ # Get S3 port from environment variable with default
15
+ $s3Port = if ($env:LOCAL_S3_PORT) { $env:LOCAL_S3_PORT } else { "4566" }
16
+
14
17
  Write-Host "======= check if S3 bucket exists ======="
15
- $bucketExists = aws --endpoint-url=http://localhost:4566 s3 ls | Select-String $env:S3_BUCKET_NAME
18
+ $bucketExists = aws --endpoint-url=http://localhost:$s3Port s3 ls | Select-String $env:S3_BUCKET_NAME
16
19
 
17
20
  if (-not $bucketExists) {
18
21
  Write-Host "Bucket $env:S3_BUCKET_NAME does not exist. Creating it..."
19
- aws --endpoint-url=http://localhost:4566 s3 mb "s3://$env:S3_BUCKET_NAME"
22
+ aws --endpoint-url=http://localhost:$s3Port s3 mb "s3://$env:S3_BUCKET_NAME"
20
23
  } else {
21
24
  Write-Host "Bucket $env:S3_BUCKET_NAME already exists."
22
25
  }
23
26
 
24
27
  Write-Host "======= list S3 buckets ======="
25
- aws --endpoint-url=http://localhost:4566 s3 ls
28
+ aws --endpoint-url=http://localhost:$s3Port s3 ls
@@ -5,15 +5,19 @@ if [ -f .env ]; then
5
5
  export $(echo $(cat .env | sed 's/#.*//g' | xargs) | envsubst)
6
6
  fi
7
7
 
8
+ # Get S3 port from environment variable with default
9
+ S3_PORT="${LOCAL_S3_PORT:-4566}"
10
+ S3_ENDPOINT_URL="http://localhost:${S3_PORT}"
11
+
8
12
  echo "======= check if S3 bucket exists ======="
9
- bucket_exists=$(aws --endpoint-url=http://localhost:4566 s3 ls | grep "$S3_BUCKET_NAME" | wc -l)
13
+ bucket_exists=$(aws --endpoint-url=${S3_ENDPOINT_URL} s3 ls | grep "$S3_BUCKET_NAME" | wc -l)
10
14
 
11
15
  if [ "$bucket_exists" -eq 0 ]; then
12
16
  echo "Bucket $S3_BUCKET_NAME does not exist. Creating it..."
13
- aws --endpoint-url=http://localhost:4566 s3 mb s3://$S3_BUCKET_NAME
17
+ aws --endpoint-url=${S3_ENDPOINT_URL} s3 mb s3://$S3_BUCKET_NAME
14
18
  else
15
19
  echo "Bucket $S3_BUCKET_NAME already exists."
16
20
  fi
17
21
 
18
22
  echo "======= list S3 buckets ======="
19
- aws --endpoint-url=http://localhost:4566 s3 ls
23
+ aws --endpoint-url=${S3_ENDPOINT_URL} s3 ls
@@ -84,7 +84,8 @@ while ($true) {
84
84
  }
85
85
  }
86
86
 
87
- # Wait for serverless to start
87
+ # Wait for serverless to start (cold start compiles TS and initializes many
88
+ # plugins, so allow a generous timeout to avoid failing the local startup flow)
88
89
  $start = Get-Date
89
90
  while ($true) {
90
91
  $elapsed = (New-TimeSpan -Start $start).TotalSeconds
@@ -117,6 +118,98 @@ while ($true) {
117
118
  }
118
119
 
119
120
 
121
+ # Register Step Functions state machines before triggering streams
122
+ $sfnPort = if ($env:LOCAL_SFN_PORT) { $env:LOCAL_SFN_PORT } else { "8083" }
123
+ $sfnEndpoint = "http://localhost:$sfnPort"
124
+
125
+ # Wait for Step Functions Local to accept connections before registering, so a
126
+ # not-yet-ready endpoint (the exact race this block fixes) does not cause silent
127
+ # registration failures.
128
+ $sfnStart = Get-Date
129
+ while ($true) {
130
+ $sfnElapsed = ((Get-Date) - $sfnStart).TotalSeconds
131
+ if ($sfnElapsed -gt 30) {
132
+ Write-Host "Timeout waiting for Step Functions Local at $sfnEndpoint"
133
+ exit 1
134
+ }
135
+ Write-Host "Check health Step Functions Local"
136
+ aws stepfunctions list-state-machines --endpoint-url $sfnEndpoint --region ap-northeast-1 *> $null
137
+ if ($LASTEXITCODE -eq 0) {
138
+ Write-Host "Step Functions Local is ACTIVE"
139
+ break
140
+ }
141
+ Write-Host "Step Functions Local is not ACTIVE"
142
+ Start-Sleep -Seconds 1
143
+ }
144
+
145
+ Write-Host "Registering Step Functions state machines..."
146
+
147
+ # Extract state machine names and definitions from serverless.yml using Node.js
148
+ $nodeScript = @"
149
+ const fs = require('fs');
150
+ const yaml = require('js-yaml');
151
+ let content = fs.readFileSync('./infra-local/serverless.yml', 'utf8');
152
+ content = content.replace(/\`$\{[^}]+\}/g, 'PLACEHOLDER');
153
+ const data = yaml.load(content);
154
+ const sms = (data.stepFunctions || {}).stateMachines || {};
155
+ const result = [];
156
+ for (const [key, sm] of Object.entries(sms)) {
157
+ result.push({ name: sm.name || key, definition: JSON.stringify(sm.definition) });
158
+ }
159
+ console.log(JSON.stringify(result));
160
+ "@
161
+
162
+ # Fail fast if extraction fails (e.g. js-yaml missing) so registration is not
163
+ # silently skipped and later surfaced only as repeated runtime warnings.
164
+ $nodeOutput = node -e $nodeScript
165
+ if ($LASTEXITCODE -ne 0) {
166
+ Write-Host "Failed to extract state machines from serverless.yml (is js-yaml installed?)"
167
+ exit 1
168
+ }
169
+ $stateMachines = $nodeOutput | ConvertFrom-Json
170
+
171
+ foreach ($sm in $stateMachines) {
172
+ $smName = $sm.name
173
+ $smDefinition = $sm.definition
174
+ Write-Host "Checking state machine: $smName"
175
+ # stderr discarded and success decided by $LASTEXITCODE (not string-matching
176
+ # the output) so a CLI error is not mistaken for an existing state machine.
177
+ $existing = aws stepfunctions list-state-machines `
178
+ --endpoint-url $sfnEndpoint `
179
+ --region ap-northeast-1 `
180
+ --query "stateMachines[?name=='$smName'].name" `
181
+ --output text 2>$null
182
+
183
+ if ($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($existing)) {
184
+ Write-Host "Creating state machine: $smName"
185
+ # Escape embedded double quotes before passing the JSON definition to
186
+ # aws.exe (same pattern as the put-item call below); native-command
187
+ # failures are detected via $LASTEXITCODE, not try/catch, which does not
188
+ # trigger on non-zero exit of external executables.
189
+ $escapedDefinition = $smDefinition -replace '"', '\"'
190
+ # The serverless-step-functions-local plugin also auto-registers state
191
+ # machines on offline:start:init; this block is a fallback for the race
192
+ # where Step Functions Local starts after that hook runs. A benign
193
+ # "already exists" is treated as success; only a real failure aborts.
194
+ $createOut = aws stepfunctions create-state-machine `
195
+ --endpoint-url $sfnEndpoint `
196
+ --region ap-northeast-1 `
197
+ --name $smName `
198
+ --role-arn "arn:aws:iam::101010101010:role/DummyRole" `
199
+ --definition $escapedDefinition 2>&1 | Out-String
200
+ if ($LASTEXITCODE -eq 0) {
201
+ Write-Host "Created $smName"
202
+ } elseif ($createOut -match "already exists|StateMachineAlreadyExists") {
203
+ Write-Host "State machine $smName already exists"
204
+ } else {
205
+ Write-Host "Failed to create ${smName}: $createOut"
206
+ exit 1
207
+ }
208
+ } else {
209
+ Write-Host "State machine $smName already exists"
210
+ }
211
+ }
212
+
120
213
  # Trigger command stream
121
214
  $timestamp = [math]::Round((Get-Date).Subtract((Get-Date "01/01/1970")).TotalSeconds)
122
215
  foreach ($table in $tables) {
@@ -141,6 +234,6 @@ foreach ($table in $tables) {
141
234
  # Trigger tasks stream
142
235
  Write-Host "Send a command to trigger command stream tasks"
143
236
  $command = @"
144
- aws dynamodb put-item --endpoint $endpoint --table-name "$tablePrefix-tasks" --item '{\"input\":{\"M\":{}},\"sk\":{\"S\":\"$timestamp\"},\"pk\":{\"S\":\"test\"}}'
237
+ aws dynamodb put-item --endpoint $endpoint --table-name "$tablePrefix-tasks" --item '{\"input\":{\"M\":{\"action\":{\"S\":\"trigger\"}}},\"sk\":{\"S\":\"$timestamp\"},\"pk\":{\"S\":\"test\"}}'
145
238
  "@
146
239
  Invoke-Expression $command
@@ -73,12 +73,13 @@ while true; do
73
73
  fi
74
74
  done
75
75
 
76
- # Wait serverless start
76
+ # Wait serverless start (cold start compiles TS and initializes many plugins,
77
+ # so allow a generous timeout to avoid failing the local startup flow)
77
78
  start=$(date +%s)
78
79
  while true; do
79
80
 
80
81
  elapsed=$(($(date +%s) - ${start}))
81
- if [[ ${elapsed} -gt 10 ]]; then
82
+ if [[ ${elapsed} -gt 100 ]]; then
82
83
  echo "Timeout"
83
84
  exit 1
84
85
  fi
@@ -95,6 +96,91 @@ while true; do
95
96
  fi
96
97
  done
97
98
 
99
+ # Register Step Functions state machines before triggering streams
100
+ SFN_PORT="${LOCAL_SFN_PORT:-8083}"
101
+ SFN_ENDPOINT="http://localhost:${SFN_PORT}"
102
+
103
+ # Wait for Step Functions Local to accept connections before registering, so a
104
+ # not-yet-ready endpoint (the exact race this block fixes) does not cause silent
105
+ # registration failures.
106
+ start=$(date +%s)
107
+ while true; do
108
+ elapsed=$(($(date +%s) - ${start}))
109
+ if [[ ${elapsed} -gt 30 ]]; then
110
+ echo "Timeout waiting for Step Functions Local at ${SFN_ENDPOINT}"
111
+ exit 1
112
+ fi
113
+ echo "Check health Step Functions Local"
114
+ if aws stepfunctions list-state-machines \
115
+ --endpoint-url ${SFN_ENDPOINT} \
116
+ --region ap-northeast-1 >/dev/null 2>&1; then
117
+ echo "Step Functions Local is ACTIVE"
118
+ break
119
+ fi
120
+ echo "Step Functions Local is not ACTIVE"
121
+ sleep 1
122
+ done
123
+
124
+ echo "Registering Step Functions state machines..."
125
+
126
+ # Extract state machine names and definitions from serverless.yml using Node.js.
127
+ # Fail fast if extraction fails (e.g. js-yaml missing) so registration is not
128
+ # silently skipped and later surfaced only as repeated runtime warnings.
129
+ sm_data=$(node -e "
130
+ const fs = require('fs');
131
+ const yaml = require('js-yaml');
132
+ let content = fs.readFileSync('./infra-local/serverless.yml', 'utf8');
133
+ // Replace Serverless Framework variable syntax to avoid YAML parse errors
134
+ content = content.replace(/\\\$\{[^}]+\}/g, 'PLACEHOLDER');
135
+ const data = yaml.load(content);
136
+ const sms = (data.stepFunctions || {}).stateMachines || {};
137
+ for (const [key, sm] of Object.entries(sms)) {
138
+ const name = sm.name || key;
139
+ const definition = JSON.stringify(sm.definition);
140
+ console.log(name + '\t' + definition);
141
+ }
142
+ ")
143
+ if [ $? -ne 0 ]; then
144
+ echo "Failed to extract state machines from serverless.yml (is js-yaml installed?)"
145
+ exit 1
146
+ fi
147
+
148
+ # A here-string (not a pipe) keeps the loop in the current shell so an "exit"
149
+ # on a failed create actually aborts the script before triggering streams.
150
+ while IFS=$'\t' read -r sm_name sm_definition; do
151
+ [ -z "${sm_name}" ] && continue
152
+ echo "Checking state machine: ${sm_name}"
153
+ # stderr is discarded (not captured) so a connection error is not mistaken
154
+ # for an existing state machine; readiness is already ensured above.
155
+ existing=$(aws stepfunctions list-state-machines \
156
+ --endpoint-url ${SFN_ENDPOINT} \
157
+ --region ap-northeast-1 \
158
+ --query "stateMachines[?name=='${sm_name}'].name" \
159
+ --output text 2>/dev/null)
160
+ if [ -z "${existing}" ]; then
161
+ echo "Creating state machine: ${sm_name}"
162
+ # The serverless-step-functions-local plugin also auto-registers state
163
+ # machines on offline:start:init; this block is a fallback for the race
164
+ # where Step Functions Local starts after that hook runs. A benign
165
+ # "already exists" is treated as success; only a real failure aborts.
166
+ if create_out=$(aws stepfunctions create-state-machine \
167
+ --endpoint-url ${SFN_ENDPOINT} \
168
+ --region ap-northeast-1 \
169
+ --name "${sm_name}" \
170
+ --role-arn "arn:aws:iam::101010101010:role/DummyRole" \
171
+ --definition "${sm_definition}" 2>&1); then
172
+ echo "Created ${sm_name}"
173
+ elif echo "${create_out}" | grep -qi "already exists\|StateMachineAlreadyExists"; then
174
+ echo "State machine ${sm_name} already exists"
175
+ else
176
+ echo "Failed to create ${sm_name}: ${create_out}"
177
+ exit 1
178
+ fi
179
+ else
180
+ echo "State machine ${sm_name} already exists"
181
+ fi
182
+ done <<< "${sm_data}"
183
+
98
184
  # Trigger command stream
99
185
  timestamp=$(date +%s)
100
186
  for table in "${tables[@]}"; do
@@ -103,4 +189,4 @@ for table in "${tables[@]}"; do
103
189
  done
104
190
 
105
191
  echo "Send a command to trigger command stream tasks"
106
- aws --endpoint=${endpoint} dynamodb put-item --table-name ${TABLE_PREFIX}-tasks --item "{\"input\":{\"M\":{}},\"sk\":{\"S\":\"${timestamp}\"},\"pk\":{\"S\":\"test\"}}"
192
+ aws --endpoint=${endpoint} dynamodb put-item --table-name ${TABLE_PREFIX}-tasks --item "{\"input\":{\"M\":{\"action\":{\"S\":\"trigger\"}}},\"sk\":{\"S\":\"${timestamp}\"},\"pk\":{\"S\":\"test\"}}"
@@ -24,6 +24,11 @@ custom:
24
24
  sesPort: ${env:LOCAL_SES_PORT, 8005}
25
25
  cognitoPort: ${env:LOCAL_COGNITO_PORT, 9229}
26
26
 
27
+ # serverless-offline-lambda plugin (external Lambda invoke, separate from serverless-offline lambdaPort)
28
+ lambda:
29
+ port: ${env:LOCAL_OFFLINE_LAMBDA_PORT, 4000}
30
+ host: 0.0.0.0
31
+
27
32
  serverless-offline:
28
33
  corsAllowOrigin: '*'
29
34
  corsAllowHeaders: '*'
@@ -85,6 +90,9 @@ custom:
85
90
  region: ap-northeast-1
86
91
  # lambdaEndpoint: http://0.0.0.0:3002
87
92
  externalInstance: true
93
+ # Honor LOCAL_SFN_PORT so a non-default port reaches Step Functions Local
94
+ # (Docker mapping, the SDK and the registration script all use this port).
95
+ stepFunctionsEndpoint: http://localhost:${env:LOCAL_SFN_PORT, 8083}
88
96
  serverless-dynamodb:
89
97
  stages:
90
98
  # set for create tables on dev enviroment
@@ -125,6 +133,9 @@ provider:
125
133
  localAuthorizer:
126
134
  type: jwt
127
135
  identitySource: $request.header.Authorization
136
+ # cognito-local emits the JWT `iss` claim as http://localhost:${LOCAL_COGNITO_PORT}
137
+ # (its listen port; see infra-local/cognito-local/start.sh, which writes a matching
138
+ # TokenConfig.IssuerDomain). Keep issuerUrl in sync with that configurable port.
128
139
  issuerUrl: http://localhost:${self:custom.cognitoPort}/local_2G7noHgW
129
140
  audience:
130
141
  - dnk8y7ii3wled35p3lw0l2cd7
@@ -71,6 +71,7 @@
71
71
  "eslint-plugin-simple-import-sort": "^10.0.0",
72
72
  "jest": "^29.7.0",
73
73
  "jest-junit": "^16.0.0",
74
+ "js-yaml": "^4.1.0",
74
75
  "nestjs-spelunker": "^1.3.0",
75
76
  "prettier": "^3.1.1",
76
77
  "run-script-os": "^1.1.6",