@cumulus/message 10.0.1 → 10.1.1

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.
@@ -1,6 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  import { Message } from '@cumulus/types';
4
+ const collectionIdSeparator = '___';
4
5
 
5
6
  /**
6
7
  * Utility functions for generating collection information or parsing collection information
@@ -27,7 +28,7 @@ type CollectionInfo = {
27
28
  * @alias module:Collections
28
29
  */
29
30
  export const constructCollectionId = (name: string, version: string) =>
30
- `${name}___${version}`;
31
+ `${name}${collectionIdSeparator}${version}`;
31
32
 
32
33
  /**
33
34
  * Returns the name and version of a collection based on
@@ -40,17 +41,19 @@ export const deconstructCollectionId = (collectionId: string) => {
40
41
  let name;
41
42
  let version;
42
43
  try {
43
- [name, version] = collectionId.split('___');
44
+ const last = collectionId.lastIndexOf(collectionIdSeparator);
45
+ name = collectionId.substring(0, last);
46
+ version = collectionId.substring(last + collectionIdSeparator.length);
47
+ if (name && version) {
48
+ return {
49
+ name,
50
+ version,
51
+ };
52
+ }
44
53
  } catch (error) {
45
- throw new Error(`invalid collectionId: ${JSON.stringify(collectionId)}`);
54
+ // do nothing, error thrown below
46
55
  }
47
- if (name && version) {
48
- return {
49
- name,
50
- version,
51
- };
52
- }
53
- throw new Error(`invalid collectionId: ${collectionId}`);
56
+ throw new Error(`invalid collectionId: ${JSON.stringify(collectionId)}`);
54
57
  };
55
58
 
56
59
  /**
@@ -0,0 +1,54 @@
1
+ import { SQSRecord, EventBridgeEvent } from 'aws-lambda';
2
+
3
+ import { parseSQSMessageBody } from '@cumulus/aws-client/SQS';
4
+ import { CumulusMessage } from '@cumulus/types/message';
5
+ import Logger from '@cumulus/logger';
6
+
7
+ import { getCumulusMessageFromExecutionEvent } from './StepFunctions';
8
+
9
+ const log = new Logger({ sender: '@cumulus/DeadLetterMessage' });
10
+
11
+ type StepFunctionEventBridgeEvent = EventBridgeEvent<'Step Functions Execution Status Change', { [key: string]: string }>;
12
+ type UnwrapDeadLetterCumulusMessageReturnType = (
13
+ StepFunctionEventBridgeEvent
14
+ | AWS.SQS.Message
15
+ | SQSRecord
16
+ | CumulusMessage
17
+ );
18
+
19
+ /**
20
+ * Unwrap dead letter Cumulus message, which may be wrapped in a
21
+ * States cloudwatch event, which is wrapped in an SQS message.
22
+ *
23
+ * @param {Object} messageBody - received SQS message
24
+ * @returns {Object} the cumulus message or nearest available object
25
+ */
26
+ export const unwrapDeadLetterCumulusMessage = async (
27
+ messageBody: UnwrapDeadLetterCumulusMessageReturnType
28
+ ): Promise<UnwrapDeadLetterCumulusMessageReturnType> => {
29
+ try {
30
+ if ('cumulus_meta' in messageBody) {
31
+ return messageBody;
32
+ }
33
+ if ('Body' in messageBody || 'body' in messageBody) {
34
+ // AWS.SQS.Message/SQS.Record case
35
+ const unwrappedMessageBody = parseSQSMessageBody(
36
+ messageBody
37
+ ) as CumulusMessage;
38
+ return await unwrapDeadLetterCumulusMessage(unwrappedMessageBody);
39
+ }
40
+ if (!('detail' in messageBody)) {
41
+ // Non-typed catchall
42
+ return messageBody;
43
+ }
44
+ // StepFunctionEventBridgeEvent case
45
+ const unwrappedMessageBody = await getCumulusMessageFromExecutionEvent(messageBody);
46
+ return await unwrapDeadLetterCumulusMessage(unwrappedMessageBody);
47
+ } catch (error) {
48
+ log.error(
49
+ 'Falling back to storing wrapped message after encountering unwrap error',
50
+ error
51
+ );
52
+ return messageBody;
53
+ }
54
+ };
@@ -8,14 +8,41 @@
8
8
  * const StepFunctions = require('@cumulus/message/StepFunctions');
9
9
  */
10
10
 
11
+ import { EventBridgeEvent } from 'aws-lambda';
11
12
  import { JSONPath } from 'jsonpath-plus';
13
+ import get from 'lodash/get';
14
+ import set from 'lodash/set';
15
+
16
+ import { getExecutionHistory } from '@cumulus/aws-client/StepFunctions';
17
+ import { getStepExitedEvent, getTaskExitedEventOutput } from '@cumulus/common/execution-history';
18
+ import { Message } from '@cumulus/types';
12
19
  import * as s3Utils from '@cumulus/aws-client/S3';
13
20
  import Logger from '@cumulus/logger';
14
- import { Message } from '@cumulus/types';
21
+
22
+ import { getMessageExecutionArn } from './Executions';
15
23
 
16
24
  const log = new Logger({
17
25
  sender: '@cumulus/message/StepFunctions',
18
26
  });
27
+ type ExecutionStatus = ('ABORTED' | 'RUNNING' | 'TIMED_OUT' | 'SUCCEEDED' | 'FAILED');
28
+
29
+ type ExecutionStatusToWorkflowStatusMap = {
30
+ [K in ExecutionStatus]: Message.WorkflowStatus;
31
+ };
32
+
33
+ const executionStatusToWorkflowStatus = (
34
+ executionStatus: ExecutionStatus
35
+ ): Message.WorkflowStatus => {
36
+ const statusMap: ExecutionStatusToWorkflowStatusMap = {
37
+ ABORTED: 'failed',
38
+ FAILED: 'failed',
39
+ RUNNING: 'running',
40
+ SUCCEEDED: 'completed',
41
+ TIMED_OUT: 'failed',
42
+ };
43
+
44
+ return statusMap[executionStatus];
45
+ };
19
46
 
20
47
  /**
21
48
  * Given a Step Function event, replace specified key in event with contents
@@ -91,3 +118,133 @@ export const parseStepMessage = async (
91
118
  }
92
119
  return <Message.CumulusMessage>parsedMessage;
93
120
  };
121
+
122
+ /**
123
+ * Searches the Execution step History for the TaskStateEntered pertaining to
124
+ * the failed task Id. HistoryEvent ids are numbered sequentially, starting at
125
+ * one.
126
+ *
127
+ * @param {HistoryEvent[]} events - Step Function events array
128
+ * @param {HistoryEvent} failedStepEvent - Step Function's failed event.
129
+ * @returns {string} name of the current stepfunction task or 'UnknownFailedStepName'.
130
+ */
131
+ export const getFailedStepName = (
132
+ events: AWS.StepFunctions.HistoryEvent[],
133
+ failedStepEvent: { id: number }
134
+ ) => {
135
+ try {
136
+ const previousEvents = events.slice(0, failedStepEvent.id - 1);
137
+ const startEvents = previousEvents.filter(
138
+ (e) => e.type === 'TaskStateEntered'
139
+ );
140
+ const stateName = startEvents.pop()?.stateEnteredEventDetails?.name;
141
+ if (!stateName) throw new Error('TaskStateEntered Event Object did not have `stateEnteredEventDetails.name`');
142
+ return stateName;
143
+ } catch (error) {
144
+ log.info('Failed to determine a failed stepName from execution events.');
145
+ log.error(error);
146
+ }
147
+ return 'UnknownFailedStepName';
148
+ };
149
+
150
+ /**
151
+ * Finds all failed execution events and returns the last one in the list.
152
+ *
153
+ * @param {Array<HistoryEventList>} events - array of AWS Stepfunction execution HistoryEvents
154
+ * @returns {HistoryEventList | undefined} - the last lambda or activity that failed in the
155
+ * event array, or an empty array.
156
+ */
157
+ export const lastFailedEventStep = (
158
+ events: AWS.StepFunctions.HistoryEvent[]
159
+ ): AWS.StepFunctions.HistoryEvent | undefined => {
160
+ const failures = events.filter((event) =>
161
+ ['LambdaFunctionFailed', 'ActivityFailed'].includes(event.type));
162
+ return failures.pop();
163
+ };
164
+
165
+ /**
166
+ * Get message to use for publishing failed execution notifications.
167
+ *
168
+ * Try to get the input to the last failed step in the execution so we can
169
+ * update the status of any granules/PDRs that don't exist in the initial execution
170
+ * input.
171
+ *
172
+ * Falls back to overall execution input.
173
+ *
174
+ * @param {Object} inputCumulusMessage - Workflow execution input message
175
+ * @param {Function} getExecutionHistoryFunction - Testing override for mock/etc of
176
+ * StepFunctions.getExecutionHistory
177
+ * @returns {Object} - CumulusMessage Execution step message or execution input message
178
+ */
179
+ export const getFailedExecutionMessage = async (
180
+ inputCumulusMessage: Message.CumulusMessage,
181
+ getExecutionHistoryFunction: typeof getExecutionHistory = getExecutionHistory
182
+ ) => {
183
+ const amendedCumulusMessage = { ...inputCumulusMessage };
184
+
185
+ try {
186
+ const executionArn = getMessageExecutionArn(amendedCumulusMessage);
187
+ if (!executionArn) { throw new Error('No execution arn found'); }
188
+ const { events } = await getExecutionHistoryFunction({ executionArn });
189
+
190
+ const lastFailedEvent = lastFailedEventStep(events);
191
+ if (!lastFailedEvent) {
192
+ log.warn(`No failed step events found in execution ${executionArn}`);
193
+ return amendedCumulusMessage;
194
+ }
195
+ const failedExecutionStepName = getFailedStepName(events, lastFailedEvent);
196
+ const failedStepExitedEvent = getStepExitedEvent(events, lastFailedEvent);
197
+
198
+ if (!failedStepExitedEvent) {
199
+ log.info(`Could not retrieve output from last failed step in execution ${executionArn}, falling back to execution input`);
200
+ log.info(`Could not find TaskStateExited event after step ID ${lastFailedEvent.id} for execution ${executionArn}`);
201
+ return {
202
+ ...amendedCumulusMessage,
203
+ exception: {
204
+ ...lastFailedEvent.activityFailedEventDetails,
205
+ ...lastFailedEvent.lambdaFunctionFailedEventDetails,
206
+ failedExecutionStepName,
207
+
208
+ },
209
+ };
210
+ }
211
+ const taskExitedEventOutput = JSON.parse(getTaskExitedEventOutput(failedStepExitedEvent) || '{}');
212
+ taskExitedEventOutput.exception = {
213
+ ...taskExitedEventOutput.exception,
214
+ failedExecutionStepName,
215
+ };
216
+ return await parseStepMessage(taskExitedEventOutput, failedExecutionStepName);
217
+ } catch (error) {
218
+ log.error('getFailedExecution failed to retrieve failure:', error);
219
+ return amendedCumulusMessage;
220
+ }
221
+ };
222
+
223
+ export const getCumulusMessageFromExecutionEvent = async (executionEvent: EventBridgeEvent<'Step Functions Execution Status Change', { [key: string]: string }>) => {
224
+ let cumulusMessage;
225
+ if (executionEvent.detail.status === 'RUNNING') {
226
+ cumulusMessage = JSON.parse(executionEvent.detail.input);
227
+ } else if (executionEvent.detail.status === 'SUCCEEDED') {
228
+ cumulusMessage = JSON.parse(executionEvent.detail.output);
229
+ } else {
230
+ const inputMessage = JSON.parse(get(executionEvent, 'detail.input', '{}'));
231
+ cumulusMessage = await getFailedExecutionMessage(inputMessage);
232
+ }
233
+
234
+ const fullCumulusMessage = (await pullStepFunctionEvent(
235
+ cumulusMessage
236
+ )) as Message.CumulusMessage;
237
+
238
+ const workflowStatus = executionStatusToWorkflowStatus(
239
+ executionEvent.detail.status as ExecutionStatus
240
+ );
241
+ set(fullCumulusMessage, 'meta.status', workflowStatus);
242
+
243
+ set(
244
+ fullCumulusMessage,
245
+ 'cumulus_meta.workflow_stop_time',
246
+ executionEvent.detail.stopDate
247
+ );
248
+
249
+ return fullCumulusMessage;
250
+ };