-
Notifications
You must be signed in to change notification settings - Fork 59
/
Copy pathhelpers.ts
329 lines (282 loc) · 12 KB
/
helpers.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
import {DescribeStateMachineCommandOutput} from '@aws-sdk/client-sfn'
import {SFNClient} from '@aws-sdk/client-sfn/dist-types/SFNClient'
import {BaseContext} from 'clipanion'
import {diff} from 'deep-object-diff'
import {updateStateMachineDefinition} from './awsCommands'
import {DD_CI_IDENTIFYING_STRING} from './constants'
export const displayChanges = (
stepFunctionArn: string,
context: BaseContext,
commandName: string,
dryRun: boolean,
params: any,
previousParams?: any
): void => {
context.stdout.write(`\n${dryRun ? '\nPlanning for' : 'Will apply'} the following change:\n`)
if (previousParams !== undefined) {
context.stdout.write(
`\n${commandName}:\nFrom:\n${JSON.stringify(diff(params, previousParams), undefined, 2)}\nTo:\n${JSON.stringify(
diff(previousParams, params),
undefined,
2
)}\n`
)
} else {
context.stdout.write(`\n${commandName}:\n${JSON.stringify(params, undefined, 2)}\n`)
}
}
export const buildArn = (
partition: string,
service: string,
region: string,
accountId: string,
resourceType: string,
resourceId: string
): string => {
return `arn:${partition}:${service}:${region}:${accountId}:${resourceType}:${resourceId}`
}
export const buildLogGroupName = (stepFunctionName: string, env: string | undefined): string => {
return `/aws/vendedlogs/states/${stepFunctionName}-Logs${env !== undefined ? '-' + env : ''}`
}
export const buildSubscriptionFilterName = (stepFunctionName: string): string => {
return `${stepFunctionName}-${DD_CI_IDENTIFYING_STRING}`
}
export const isValidArn = (str: string): boolean => {
const arnFields = str.split(':')
return arnFields.length >= 7 && arnFields[0] === 'arn'
}
export const getStepFunctionLogGroupArn = (stepFunction: DescribeStateMachineCommandOutput): string | undefined => {
const [logDestinations] = stepFunction.loggingConfiguration?.destinations ?? [{cloudWatchLogsLogGroup: {}}]
return logDestinations.cloudWatchLogsLogGroup?.logGroupArn
}
export const parseArn = (
arn: string
): {
partition: string
region: string
accountId: string
resourceName: string
} => {
const [, partition, , region, accountId, , resourceName] = arn.split(':')
return {
partition,
region,
accountId,
resourceName,
}
}
export const buildLogAccessPolicyName = (stepFunction: DescribeStateMachineCommandOutput): string => {
return `LogsDeliveryAccessPolicy-${stepFunction.name}`
}
export const injectContextIntoTasks = async (
describeStateMachineCommandOutput: DescribeStateMachineCommandOutput,
stepFunctionsClient: SFNClient,
context: BaseContext,
dryRun: boolean
): Promise<void> => {
if (typeof describeStateMachineCommandOutput.definition !== 'string') {
return
}
let definitionHasBeenUpdated = false
const definitionObj = JSON.parse(describeStateMachineCommandOutput.definition) as StateMachineDefinitionType
for (const stepName in definitionObj.States) {
if (definitionObj.States.hasOwnProperty(stepName)) {
const step = definitionObj.States[stepName]
const lambdaUpdated = injectContextForLambdaFunctions(step, context, stepName)
const stepUpdated = injectContextForStepFunctions(step, context, stepName)
definitionHasBeenUpdated = definitionHasBeenUpdated || lambdaUpdated || stepUpdated
}
}
if (definitionHasBeenUpdated) {
await updateStateMachineDefinition(
stepFunctionsClient,
describeStateMachineCommandOutput,
definitionObj,
context,
dryRun
)
}
}
export type StateMachineDefinitionType = {
Comment?: string
StartAt?: string
States?: StatesType
}
export type StatesType = Record<string, StepType>
export type StepType = {
Type: string
Parameters?: ParametersType
Resource?: string
Next?: string
End?: boolean
}
export type PayloadObject = {
'Execution.$'?: any
Execution?: any
'State.$'?: any
State?: any
'StateMachine.$'?: any
StateMachine?: any
}
export type ParametersType = {
'Payload.$'?: string
Payload?: string | PayloadObject
FunctionName?: string
StateMachineArn?: string
TableName?: string
Input?: {
'CONTEXT.$'?: string
CONTEXT?: string
}
}
// Truth table
// Case | Input | Expected
// -----|----------------------------------------------------------|---------
// 1 | No "Payload" or "Payload.$" | true
// 2.1 | "Payload" is object, already injected | false
// 2.2 | "Payload" object has Execution, State or StateMachine | false
// 2.3 | "Payload" object has no Execution, State or StateMachine | true
// 3 | "Payload" is not object | false
// 4.1 | "Payload.$": "$" (default payload) | true
// 4.2 | "Payload.$": "States.JsonMerge($$, $, false)" or | false
// | "Payload.$": "$$['Execution', 'State', 'StateMachine']" |
// 4.3 | Custom "Payload.$" | false
export const injectContextForLambdaFunctions = (step: StepType, context: BaseContext, stepName: string): boolean => {
// not default lambda api or legacy lambda definition
// Using startsWith on the lambda invoke to allow for waitForTaskToken invocations
if (!step.Resource?.startsWith('arn:aws:states:::lambda:invoke') && !step.Resource?.startsWith('arn:aws:lambda')) {
return false
}
if (!step.Parameters) {
context.stdout
.write(`[Warn] Step ${stepName} does not have a Parameters field. Step Functions Context Object injection \
skipped. Your Step Functions trace will not be merged with downstream Lambda traces. To manually merge these traces, \
check out https://docs.datadoghq.com/serverless/step_functions/troubleshooting/\n`)
return false
}
// Case 1: payload field not set
if (!step.Parameters.hasOwnProperty('Payload.$') && !step.Parameters.hasOwnProperty('Payload')) {
step.Parameters[`Payload.$`] = `$$['Execution', 'State', 'StateMachine']`
return true
}
if (step.Parameters.hasOwnProperty('Payload')) {
if (typeof step.Parameters['Payload'] !== 'object') {
// Case 3: payload is not a JSON object
context.stdout
.write(`[Warn] Step ${stepName}'s Payload field is not a JSON object. Step Functions Context Object \
injection skipped. Your Step Functions trace will not be merged with downstream Lambda traces. To manually \
merge these traces, check out https://docs.datadoghq.com/serverless/step_functions/troubleshooting/\n`)
return false
} else {
// Case 2: payload is not a JSON object
const payload = step.Parameters.Payload
if (
payload['Execution.$'] === '$$.Execution' &&
payload['State.$'] === '$$.State' &&
payload['StateMachine.$'] === '$$.StateMachine'
) {
// Case 2.1: already injected into "Payload"
context.stdout.write(`Step ${stepName}: Context injection is already set up. Skipping context injection.\n`)
return false
} else if (
payload.hasOwnProperty('Execution.$') ||
payload.hasOwnProperty('Execution') ||
payload.hasOwnProperty('State.$') ||
payload.hasOwnProperty('State') ||
payload.hasOwnProperty('StateMachine.$') ||
payload.hasOwnProperty('StateMachine')
) {
// Case 2.2: "Payload" object has Execution, State or StateMachine
context.stdout
.write(`[Warn] Step ${stepName} may be using custom Execution, State or StateMachine field. Step Functions Context Object \
injection skipped. Your Step Functions trace will not be merged with downstream Lambda traces. To manually \
merge these traces, check out https://docs.datadoghq.com/serverless/step_functions/troubleshooting/\n`)
return false
} else {
// Case 2.3: "Payload" object has no Execution, State or StateMachine
payload['Execution.$'] = '$$.Execution'
payload['State.$'] = '$$.State'
payload['StateMachine.$'] = '$$.StateMachine'
return true
}
}
}
// Case 4.1: default payload
if (step.Parameters['Payload.$'] === '$') {
step.Parameters[`Payload.$`] = 'States.JsonMerge($$, $, false)'
return true
}
// Case 4.2: context injection is already set up using "Payload.$"
if (
step.Parameters['Payload.$'] === 'States.JsonMerge($$, $, false)' ||
step.Parameters['Payload.$'] === `$$['Execution', 'State', 'StateMachine']`
) {
context.stdout.write(` Step ${stepName}: Context injection is already set up. Skipping context injection.\n`)
return false
}
// Case 4.3: custom "Payload.$"
context.stdout
.write(`[Warn] Step ${stepName} has a custom Payload field. Step Functions Context Object injection skipped. \
Your Step Functions trace will not be merged with downstream Lambda traces. To manually merge these traces, \
check out https://docs.datadoghq.com/serverless/step_functions/troubleshooting/\n`)
return false
}
// Truth table
// Case | Input | Expected
// -----|----------------------------------------------------------|---------
// 1 | No "CONTEXT" or "CONTEXT.$" | true
// 2 | Has "CONTEXT" | false
// 3.1 | "CONTEXT.$": "States.JsonMerge($$, $, false)" or | false
// | "CONTEXT.$": "$$['Execution', 'State', 'StateMachine']" |
// 3.2 | Custom "CONTEXT.$" | false
export const injectContextForStepFunctions = (step: StepType, context: BaseContext, stepName: string): boolean => {
// not default lambda api
if (!step.Resource?.startsWith('arn:aws:states:::states:startExecution')) {
return false
}
if (!step.Parameters) {
context.stdout
.write(`[Warn] Step ${stepName} does not have a Parameters field. Step Functions Context Object injection \
skipped. Your Step Functions trace will not be merged with downstream Step Function traces. To manually merge these \
traces, check out https://docs.datadoghq.com/serverless/step_functions/troubleshooting/\n`)
return false
}
if (!step.Parameters.Input) {
step.Parameters.Input = {'CONTEXT.$': `$$['Execution', 'State', 'StateMachine']`}
return true
}
if (typeof step.Parameters.Input !== 'object') {
context.stdout
.write(`[Warn] Step ${stepName}'s Parameters.Input field is not a JSON object. Step Functions Context Object \
injection skipped. Your Step Functions trace will not be merged with downstream Step Function traces. To manually \
merge these traces, check out https://docs.datadoghq.com/serverless/step_functions/troubleshooting/\n`)
return false
}
// Case 1: 'CONTEXT.$' and 'CONTEXT' fields are not set
if (!step.Parameters.Input['CONTEXT.$'] && !step.Parameters.Input['CONTEXT']) {
step.Parameters.Input['CONTEXT.$'] = `$$['Execution', 'State', 'StateMachine']`
return true
}
// Case 2: Has 'CONTEXT' field.
// This case should be rare so we don't support context injection for this case for now
if (step.Parameters.Input.hasOwnProperty('CONTEXT')) {
context.stdout.write(`[Warn] Step ${stepName}'s has custom CONTEXT field. Step Functions Context Object \
injection skipped. Your Step Functions trace will not be merged with downstream Step Function traces. To manually \
merge these traces, check out https://docs.datadoghq.com/serverless/step_functions/troubleshooting/\n`)
return false
}
// Case 3.1 context injection is already set up
if (
step.Parameters.Input['CONTEXT.$'] === 'States.JsonMerge($$, $, false)' ||
step.Parameters.Input['CONTEXT.$'] === `$$['Execution', 'State', 'StateMachine']`
) {
context.stdout.write(` Step ${stepName}: Context injection is already set up. Skipping context injection.\n`)
return false
}
// Case 3.2 custom CONTEXT.$ field
context.stdout
.write(`[Warn] Step ${stepName}'s Parameters.Input field has a custom CONTEXT.$ field. Step Functions Context \
Object injection skipped. Your Step Functions trace will not be merged with downstream Step Function traces. To \
manually merge these traces, check out https://docs.datadoghq.com/serverless/step_functions/troubleshooting/\n`)
return false
}