-
Notifications
You must be signed in to change notification settings - Fork 82
/
Copy pathbatch_event_processor.ts
303 lines (251 loc) · 9.14 KB
/
batch_event_processor.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
/**
* Copyright 2024, Optimizely
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { EventProcessor, ProcessableEvent } from "./event_processor";
import { Cache } from "../utils/cache/cache";
import { EventDispatcher, EventDispatcherResponse, LogEvent } from "./event_dispatcher/event_dispatcher";
import { buildLogEvent } from "./event_builder/log_event";
import { BackoffController, ExponentialBackoff, IntervalRepeater, Repeater } from "../utils/repeater/repeater";
import { LoggerFacade } from '../logging/logger';
import { BaseService, ServiceState, StartupLog } from "../service";
import { Consumer, Fn, Producer } from "../utils/type";
import { RunResult, runWithRetry } from "../utils/executor/backoff_retry_runner";
import { isSuccessStatusCode } from "../utils/http_request_handler/http_util";
import { EventEmitter } from "../utils/event_emitter/event_emitter";
import { IdGenerator } from "../utils/id_generator";
import { areEventContextsEqual } from "./event_builder/user_event";
import { EVENT_PROCESSOR_STOPPED, FAILED_TO_DISPATCH_EVENTS, FAILED_TO_DISPATCH_EVENTS_WITH_ARG } from "error_message";
import { OptimizelyError } from "../error/optimizly_error";
export const DEFAULT_MIN_BACKOFF = 1000;
export const DEFAULT_MAX_BACKOFF = 32000;
export type EventWithId = {
id: string;
event: ProcessableEvent;
};
export type RetryConfig = {
maxRetries?: number;
backoffProvider: Producer<BackoffController>;
}
export type BatchEventProcessorConfig = {
dispatchRepeater: Repeater,
failedEventRepeater?: Repeater,
batchSize: number,
eventStore?: Cache<EventWithId>,
eventDispatcher: EventDispatcher,
closingEventDispatcher?: EventDispatcher,
logger?: LoggerFacade,
retryConfig?: RetryConfig;
startupLogs?: StartupLog[];
};
type EventBatch = {
request: LogEvent,
ids: string[],
}
export const LOGGER_NAME = 'BatchEventProcessor';
export class BatchEventProcessor extends BaseService implements EventProcessor {
private eventDispatcher: EventDispatcher;
private closingEventDispatcher?: EventDispatcher;
private eventQueue: EventWithId[] = [];
private batchSize: number;
private eventStore?: Cache<EventWithId>;
private dispatchRepeater: Repeater;
private failedEventRepeater?: Repeater;
private idGenerator: IdGenerator = new IdGenerator();
private runningTask: Map<string, RunResult<EventDispatcherResponse>> = new Map();
private dispatchingEventIds: Set<string> = new Set();
private eventEmitter: EventEmitter<{ dispatch: LogEvent }> = new EventEmitter();
private retryConfig?: RetryConfig;
constructor(config: BatchEventProcessorConfig) {
super(config.startupLogs);
this.eventDispatcher = config.eventDispatcher;
this.closingEventDispatcher = config.closingEventDispatcher;
this.batchSize = config.batchSize;
this.eventStore = config.eventStore;
this.retryConfig = config.retryConfig;
this.dispatchRepeater = config.dispatchRepeater;
this.dispatchRepeater.setTask(() => this.flush());
this.failedEventRepeater = config.failedEventRepeater;
this.failedEventRepeater?.setTask(() => this.retryFailedEvents());
if (config.logger) {
this.setLogger(config.logger);
}
}
setLogger(logger: LoggerFacade): void {
this.logger = logger;
this.logger.setName(LOGGER_NAME);
}
onDispatch(handler: Consumer<LogEvent>): Fn {
return this.eventEmitter.on('dispatch', handler);
}
public async retryFailedEvents(): Promise<void> {
if (!this.eventStore) {
return;
}
const keys = (await this.eventStore.getKeys()).filter(
(k) => !this.dispatchingEventIds.has(k) && !this.eventQueue.find((e) => e.id === k)
);
const events = await this.eventStore.getBatched(keys);
const failedEvents: EventWithId[] = [];
events.forEach((e) => {
if(e) {
failedEvents.push(e);
}
});
if (failedEvents.length == 0) {
return;
}
failedEvents.sort((a, b) => a.id < b.id ? -1 : 1);
const batches: EventBatch[] = [];
let currentBatch: EventWithId[] = [];
failedEvents.forEach((event) => {
if (currentBatch.length === this.batchSize ||
(currentBatch.length > 0 && !areEventContextsEqual(currentBatch[0].event, event.event))) {
batches.push({
request: buildLogEvent(currentBatch.map((e) => e.event)),
ids: currentBatch.map((e) => e.id),
});
currentBatch = [];
}
currentBatch.push(event);
});
if (currentBatch.length > 0) {
batches.push({
request: buildLogEvent(currentBatch.map((e) => e.event)),
ids: currentBatch.map((e) => e.id),
});
}
batches.forEach((batch) => {
this.dispatchBatch(batch, false);
});
}
private createNewBatch(): EventBatch | undefined {
if (this.eventQueue.length == 0) {
return
}
const events: ProcessableEvent[] = [];
const ids: string[] = [];
this.eventQueue.forEach((event) => {
events.push(event.event);
ids.push(event.id);
});
this.eventQueue = [];
return { request: buildLogEvent(events), ids };
}
private async executeDispatch(request: LogEvent, closing = false): Promise<EventDispatcherResponse> {
const dispatcher = closing && this.closingEventDispatcher ? this.closingEventDispatcher : this.eventDispatcher;
return dispatcher.dispatchEvent(request).then((res) => {
if (res.statusCode && !isSuccessStatusCode(res.statusCode)) {
return Promise.reject(new OptimizelyError(FAILED_TO_DISPATCH_EVENTS_WITH_ARG, res.statusCode));
}
return Promise.resolve(res);
});
}
private dispatchBatch(batch: EventBatch, closing: boolean): void {
const { request, ids } = batch;
ids.forEach((id) => {
this.dispatchingEventIds.add(id);
});
const runResult: RunResult<EventDispatcherResponse> = this.retryConfig
? runWithRetry(
() => this.executeDispatch(request, closing), this.retryConfig.backoffProvider(), this.retryConfig.maxRetries
) : {
result: this.executeDispatch(request, closing),
cancelRetry: () => {},
};
this.eventEmitter.emit('dispatch', request);
const taskId = this.idGenerator.getId();
this.runningTask.set(taskId, runResult);
runResult.result.then((res) => {
ids.forEach((id) => {
this.dispatchingEventIds.delete(id);
this.eventStore?.remove(id);
});
return Promise.resolve();
}).catch((err) => {
// if the dispatch fails, the events will still be
// in the store for future processing
this.logger?.error(FAILED_TO_DISPATCH_EVENTS, err);
}).finally(() => {
this.runningTask.delete(taskId);
ids.forEach((id) => this.dispatchingEventIds.delete(id));
});
}
private async flush(closing = false): Promise<void> {
const batch = this.createNewBatch();
if (!batch) {
return;
}
this.dispatchRepeater.reset();
this.dispatchBatch(batch, closing);
}
async process(event: ProcessableEvent): Promise<void> {
if (!this.isRunning()) {
return Promise.reject('Event processor is not running');
}
const eventWithId = {
id: this.idGenerator.getId(),
event: event,
};
await this.eventStore?.set(eventWithId.id, eventWithId);
if (this.eventQueue.length > 0 && !areEventContextsEqual(this.eventQueue[0].event, event)) {
this.flush();
}
this.eventQueue.push(eventWithId);
if (this.eventQueue.length == this.batchSize) {
this.flush();
} else if (!this.dispatchRepeater.isRunning()) {
this.dispatchRepeater.start();
}
}
start(): void {
if (!this.isNew()) {
return;
}
super.start();
this.state = ServiceState.Running;
if(!this.disposable) {
this.failedEventRepeater?.start();
}
this.retryFailedEvents();
this.startPromise.resolve();
}
makeDisposable(): void {
super.makeDisposable();
this.batchSize = 1;
this.retryConfig = {
maxRetries: Math.min(this.retryConfig?.maxRetries ?? 5, 5),
backoffProvider:
this.retryConfig?.backoffProvider ||
(() => new ExponentialBackoff(DEFAULT_MIN_BACKOFF, DEFAULT_MAX_BACKOFF, 500)),
}
}
stop(): void {
if (this.isDone()) {
return;
}
if (this.isNew()) {
this.startPromise.reject(new OptimizelyError(EVENT_PROCESSOR_STOPPED));
}
this.state = ServiceState.Stopping;
this.dispatchRepeater.stop();
this.failedEventRepeater?.stop();
this.flush(true);
this.runningTask.forEach((task) => task.cancelRetry());
Promise.allSettled(Array.from(this.runningTask.values()).map((task) => task.result)).then(() => {
this.state = ServiceState.Terminated;
this.stopPromise.resolve();
});
}
}