forked from aws-amplify/amplify-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
EventBuffer.ts
249 lines (201 loc) · 5.88 KB
/
EventBuffer.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
import { ConsoleLogger as Logger } from '@aws-amplify/core';
import {
PutEventsResponse,
EventBuffer,
EventObject,
EventMap,
} from '../types';
import {
PutEventsCommand,
PutEventsCommandOutput,
} from '@aws-sdk/client-pinpoint';
const logger = new Logger('EventsBuffer');
const RETRYABLE_CODES = [429, 500];
const ACCEPTED_CODES = [202];
type EventsBufferConfig = {
bufferSize: number;
flushSize: number;
flushInterval: number;
resendLimit: number;
};
export default class EventsBuffer {
private _config;
private _client;
private _interval;
private _buffer: EventBuffer;
private _pause = false;
private _flush = false;
constructor(client, config: EventsBufferConfig) {
logger.debug('Instantiating buffer with config:', config);
this._buffer = [];
this._client = client;
this._config = config;
this._sendBatch = this._sendBatch.bind(this);
this._startLoop();
}
public push(event: EventObject) {
if (this._buffer > this._config.bufferSize) {
logger.debug('Exceeded analytics events buffer size');
return event.handlers.reject(
new Error('Exceeded the size of analytics events buffer')
);
}
const { eventId } = event.params.event;
const bufferElement = { [eventId]: event };
this._buffer.push(bufferElement);
}
public pause() {
this._pause = true;
}
public resume() {
this._pause = false;
}
public updateClient(client) {
this._client = client;
}
public flush() {
this._flush = true;
}
private _startLoop() {
if (this._interval) {
clearInterval(this._interval);
}
const { flushInterval } = this._config;
this._interval = setInterval(this._sendBatch, flushInterval);
}
private _sendBatch() {
const bufferLength = this._buffer.length;
if (this._flush && !bufferLength) {
clearInterval(this._interval);
}
if (this._pause || !bufferLength) {
return;
}
const { flushSize } = this._config;
const batchSize = Math.min(flushSize, bufferLength);
const bufferSubset = this._buffer.splice(0, batchSize);
this._putEvents(bufferSubset);
}
private async _putEvents(buffer: EventBuffer) {
const eventMap: EventMap = this._bufferToMap(buffer);
const batchEventParams = this._generateBatchEventParams(eventMap);
try {
const command: PutEventsCommand = new PutEventsCommand(batchEventParams);
const data: PutEventsCommandOutput = await this._client.send(command);
this._processPutEventsSuccessResponse(data, eventMap);
} catch (err) {
return this._handlePutEventsFailure(err, eventMap);
}
}
private _generateBatchEventParams(eventMap: EventMap) {
const batchEventParams = {
ApplicationId: '',
EventsRequest: {
BatchItem: {},
},
};
Object.values(eventMap).forEach(item => {
const { params } = item;
const { event, timestamp, config } = params;
const { name, attributes, metrics, eventId, session } = event;
const { appId, endpointId } = config;
const batchItem = batchEventParams.EventsRequest.BatchItem;
batchEventParams.ApplicationId = batchEventParams.ApplicationId || appId;
if (!batchItem[endpointId]) {
batchItem[endpointId] = {
Endpoint: {},
Events: {},
};
}
batchItem[endpointId].Events[eventId] = {
EventType: name,
Timestamp: new Date(timestamp).toISOString(),
Attributes: attributes,
Metrics: metrics,
Session: session,
};
});
return batchEventParams;
}
private _handlePutEventsFailure(err, eventMap: EventMap) {
logger.debug('_putEvents Failed: ', err);
const statusCode = err.$metadata && err.$metadata.httpStatusCode;
if (RETRYABLE_CODES.includes(statusCode)) {
const retryableEvents = Object.values(eventMap);
this._retry(retryableEvents);
return;
}
}
private _processPutEventsSuccessResponse(
data: PutEventsResponse,
eventMap: EventMap
) {
const { Results } = data.EventsResponse;
const retryableEvents: EventObject[] = [];
Object.entries(Results).forEach(([endpointId, endpointValues]) => {
const responses = endpointValues.EventsItemResponse;
Object.entries(responses).forEach(
([eventId, { StatusCode, Message }]) => {
const eventObject = eventMap[eventId];
// manually crafting handlers response to keep API consistant
const response = {
EventsResponse: {
Results: {
[endpointId]: {
EventsItemResponse: {
[eventId]: { StatusCode, Message },
},
},
},
},
};
if (ACCEPTED_CODES.includes(StatusCode)) {
eventObject.handlers.resolve(response);
return;
}
if (RETRYABLE_CODES.includes(StatusCode)) {
retryableEvents.push(eventObject);
return;
}
const { name } = eventObject.params.event;
logger.error(
`event ${eventId} : ${name} failed with error: ${Message}`
);
return eventObject.handlers.reject(response);
}
);
});
if (retryableEvents.length) {
this._retry(retryableEvents);
}
}
private _retry(retryableEvents: EventObject[]) {
// retryable events that haven't reached the resendLimit
const eligibleEvents: EventBuffer = [];
retryableEvents.forEach((event: EventObject) => {
const { params } = event;
const { eventId, name } = params.event;
if (params.resendLimit-- > 0) {
logger.debug(
`resending event ${eventId} : ${name} with ${params.resendLimit} retry attempts remaining`
);
eligibleEvents.push({ [eventId]: event });
return;
}
logger.debug(
`no retry attempts remaining for event ${eventId} : ${name}`
);
});
// add the events to the front of the buffer
this._buffer.unshift(...eligibleEvents);
}
// convert buffer to map, i.e. { eventId1: { params, handler }, eventId2: { params, handlers } }
// this allows us to easily access the handlers after receiving a batch response
private _bufferToMap(buffer: EventBuffer) {
return buffer.reduce((acc, curVal) => {
const [[key, value]] = Object.entries(curVal);
acc[key] = value;
return acc;
}, {});
}
}