|
1 | | -const { EventBridgeClient, PutEventsCommand } = require('@aws-sdk/client-eventbridge'); |
2 | | -const eventBridgeClient = new EventBridgeClient(); |
3 | | - |
4 | | -exports.handler = async (event) => { |
5 | | - try { |
6 | | - const controlEventBusArn = process.env.CONTROL_PLANE_EVENT_BUS_ARN; |
7 | | - const dataEventBusArn = process.env.DATA_PLANE_EVENT_BUS_ARN; |
8 | | - |
9 | | - if (!event.Records || !Array.isArray(event.Records)) { |
10 | | - throw new Error("Invalid event format. Expected an array of records."); |
11 | | - } |
12 | | - |
13 | | - const batchSize = 10; // AWS EventBridge allows up to 10 entries per PutEvents request |
14 | | - const entries = []; |
15 | | - |
16 | | - for (const record of event.Records) { |
17 | | - try { |
18 | | - const snsMessage = JSON.parse(record.Sns.Message); |
19 | | - if (!validateEvent(snsMessage)) { |
20 | | - throw new Error("Invalid event structure"); |
21 | | - } |
22 | | - entries.push({ |
23 | | - Source: snsMessage.Source, |
24 | | - DetailType: snsMessage.DetailType, |
25 | | - Detail: JSON.stringify({ message: snsMessage.Message }), |
26 | | - EventBusName: snsMessage.Type === 'control' ? controlEventBusArn : dataEventBusArn |
27 | | - }); |
28 | | - } catch (err) { |
29 | | - console.error("Event validation failed", err); |
| 1 | + const { EventBridgeClient, PutEventsCommand } = require('@aws-sdk/client-eventbridge'); |
| 2 | + const { SQSClient, SendMessageCommand } = require('@aws-sdk/client-sqs'); |
| 3 | + |
| 4 | + const eventBridge = new EventBridgeClient({}); |
| 5 | + const sqs = new SQSClient({}); |
| 6 | + |
| 7 | + const DATA_PLANE_EVENT_BUS_ARN = process.env.DATA_PLANE_EVENT_BUS_ARN; |
| 8 | + const CONTROL_PLANE_EVENT_BUS_ARN = process.env.CONTROL_PLANE_EVENT_BUS_ARN; |
| 9 | + const DLQ_URL = process.env.DLQ_URL; |
| 10 | + const THROTTLE_DELAY_MS = parseInt(process.env.THROTTLE_DELAY_MS || '0', 10); |
| 11 | + const MAX_RETRIES = 3; |
| 12 | + const EVENTBRIDGE_MAX_BATCH_SIZE = 10; |
| 13 | + |
| 14 | + function validateEvent(event) { |
| 15 | + // Test Event |
| 16 | + // { |
| 17 | + // "type":"data", |
| 18 | + // "version":"0.1", |
| 19 | + // "source":"manual", |
| 20 | + // "detailtype":"testEvent", |
| 21 | + // "message":"Hello World" |
| 22 | + // } |
| 23 | + const requiredFields = ['type', 'version', 'source', 'message']; |
| 24 | + return requiredFields.every(field => event.hasOwnProperty(field)); |
| 25 | + } |
| 26 | + |
| 27 | + async function sendToEventBridge(events, eventBusArn) { |
| 28 | + // console.info(`Sending ${events.length} events to EventBridge: ${eventBusArn}`); |
| 29 | + |
| 30 | + const failedEvents = []; |
| 31 | + for (let i = 0; i < events.length; i += EVENTBRIDGE_MAX_BATCH_SIZE) { |
| 32 | + const batch = events.slice(i, i + EVENTBRIDGE_MAX_BATCH_SIZE); |
| 33 | + const entries = batch.map(event => ({ |
| 34 | + Source: 'custom.event', |
| 35 | + DetailType: event.type, |
| 36 | + Detail: JSON.stringify(event), |
| 37 | + EventBusName: eventBusArn |
| 38 | + })); |
| 39 | + |
| 40 | + let attempts = 0; |
| 41 | + while (attempts < MAX_RETRIES) { |
| 42 | + try { |
| 43 | + // console.info(`Attempt ${attempts + 1}: Sending batch of ${entries.length} events.`); |
| 44 | + |
| 45 | + const response = await eventBridge.send(new PutEventsCommand({ Entries: entries })); |
| 46 | + response.FailedEntryCount && response.Entries.forEach((entry, idx) => { |
| 47 | + if (entry.ErrorCode) { |
| 48 | + console.warn(`Event failed with error: ${entry.ErrorCode}`); |
| 49 | + failedEvents.push(batch[idx]); |
| 50 | + } |
| 51 | + }); |
| 52 | + break; |
| 53 | + } catch (error) { |
| 54 | + console.error(`EventBridge send error: ${error}`); |
| 55 | + |
| 56 | + if (error.retryable) { |
| 57 | + console.warn(`Retrying after backoff: attempt ${attempts + 1}`); |
| 58 | + await new Promise(res => setTimeout(res, 2 ** attempts * 100)); |
| 59 | + attempts++; |
| 60 | + } else { |
| 61 | + failedEvents.push(...batch); |
| 62 | + break; |
| 63 | + } |
| 64 | + } |
| 65 | + } |
30 | 66 | } |
31 | | - } |
32 | | - |
33 | | - for (let i = 0; i < entries.length; i += batchSize) { |
34 | | - const batch = entries.slice(i, i + batchSize); |
35 | | - const command = new PutEventsCommand({ Entries: batch }); |
36 | | - try { |
37 | | - const response = await eventBridgeClient.send(command); |
38 | | - console.log(`Batch sent to EventBridge. Failed count: ${response.FailedEntryCount}`); |
39 | | - if (response.FailedEntryCount > 0) { |
40 | | - console.warn(`Some events failed:`, response.Entries); |
41 | | - } |
42 | | - } catch (err) { |
43 | | - console.error("Error sending batch to EventBridge", err); |
| 67 | + return failedEvents; |
| 68 | + } |
| 69 | + |
| 70 | + async function sendToDLQ(events) { |
| 71 | + console.warn(`Sending ${events.length} failed events to DLQ`); |
| 72 | + |
| 73 | + for (const event of events) { |
| 74 | + await sqs.send(new SendMessageCommand({ QueueUrl: DLQ_URL, MessageBody: JSON.stringify(event) })); |
44 | 75 | } |
45 | | - } |
46 | | - |
47 | | - return { |
48 | | - statusCode: 200, |
49 | | - body: JSON.stringify({ message: "Events processed with potential failures" }) |
50 | | - }; |
51 | | - } catch (error) { |
52 | | - console.error("Error processing events", error); |
53 | | - return { |
54 | | - statusCode: 500, |
55 | | - body: JSON.stringify({ error: error.message }) |
56 | | - }; |
57 | 76 | } |
58 | | -}; |
59 | 77 |
|
60 | | -function validateEvent(event) { |
61 | | - // My test event looks like |
62 | | - // { |
63 | | - // "Type":"data", |
64 | | - // "Version":"0.1", |
65 | | - // "Source":"manual", |
66 | | - // "DetailType":"testEvent", |
67 | | - // "Message":"Hello World" |
68 | | - // } |
69 | | - return event && event.Type && event.Source && event.DetailType && event.Message && event.Version; |
70 | | -} |
| 78 | + exports.handler = async (snsEvent) => { |
| 79 | + // console.info(`Received SNS event with ${snsEvent.Records.length} records.`); |
| 80 | + |
| 81 | + if (THROTTLE_DELAY_MS > 0) { |
| 82 | + console.info(`Throttling enabled. Delaying processing by ${THROTTLE_DELAY_MS}ms`); |
| 83 | + await new Promise(res => setTimeout(res, THROTTLE_DELAY_MS)); |
| 84 | + } |
| 85 | + |
| 86 | + const records = snsEvent.Records.map(record => JSON.parse(record.Sns.Message)); |
| 87 | + const validEvents = records.filter(validateEvent); |
| 88 | + const invalidEvents = records.filter(event => !validateEvent(event)); |
| 89 | + |
| 90 | + // console.info(`Valid events: ${validEvents.length}, Invalid events: ${invalidEvents.length}`); |
| 91 | + |
| 92 | + if (invalidEvents.length) await sendToDLQ(invalidEvents); |
| 93 | + |
| 94 | + const dataEvents = validEvents.filter(event => event.type === 'data'); |
| 95 | + const controlEvents = validEvents.filter(event => event.type === 'control'); |
| 96 | + |
| 97 | + // console.info(`Data events: ${dataEvents.length}, Control events: ${controlEvents.length}`); |
| 98 | + |
| 99 | + const failedDataEvents = await sendToEventBridge(dataEvents, DATA_PLANE_EVENT_BUS_ARN); |
| 100 | + const failedControlEvents = await sendToEventBridge(controlEvents, CONTROL_PLANE_EVENT_BUS_ARN); |
| 101 | + |
| 102 | + await sendToDLQ([...failedDataEvents, ...failedControlEvents]); |
| 103 | + }; |
0 commit comments