This repository has been archived by the owner on Nov 4, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathkafka-queue.ts
227 lines (205 loc) · 8.92 KB
/
kafka-queue.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
import { PluginEvent } from '@posthog/plugin-scaffold'
import * as Sentry from '@sentry/node'
import { Consumer, EachBatchPayload, Kafka } from 'kafkajs'
import { PluginsServer, Queue } from 'types'
import { status } from '../status'
import { groupIntoBatches, killGracefully } from '../utils'
import { timeoutGuard } from './utils'
export class KafkaQueue implements Queue {
private pluginsServer: PluginsServer
private kafka: Kafka
private consumer: Consumer
private wasConsumerRan: boolean
private processEventBatch: (batch: PluginEvent[]) => Promise<PluginEvent[]>
private saveEvent: (event: PluginEvent) => Promise<void>
constructor(
pluginsServer: PluginsServer,
processEventBatch: (batch: PluginEvent[]) => Promise<any>,
saveEvent: (event: PluginEvent) => Promise<void>
) {
this.pluginsServer = pluginsServer
this.kafka = pluginsServer.kafka!
this.consumer = KafkaQueue.buildConsumer(this.kafka)
this.wasConsumerRan = false
this.processEventBatch = processEventBatch
this.saveEvent = saveEvent
}
private async eachBatch({
batch,
resolveOffset,
heartbeat,
commitOffsetsIfNecessary,
isRunning,
isStale,
}: EachBatchPayload): Promise<void> {
const batchStartTimer = new Date()
const uuidOrder = new Map<string, number>()
const uuidOffset = new Map<string, string>()
const pluginEvents: PluginEvent[] = batch.messages.map((message, index) => {
const { data: dataStr, ...rawEvent } = JSON.parse(message.value!.toString())
const event = { ...rawEvent, ...JSON.parse(dataStr) }
uuidOrder.set(event.uuid, index)
uuidOffset.set(event.uuid, message.offset)
return {
...event,
site_url: event.site_url || null,
ip: event.ip || null,
}
})
const maxBatchSize = Math.max(
15,
Math.min(
100,
Math.ceil(
pluginEvents.length / this.pluginsServer.WORKER_CONCURRENCY / this.pluginsServer.TASKS_PER_WORKER
)
)
)
const processingTimeout = timeoutGuard(
`Still running plugins on ${pluginEvents.length} events. Timeout warning after 30 sec!`
)
const processingBatches = groupIntoBatches(pluginEvents, maxBatchSize)
const processedEvents = (
await Promise.all(
processingBatches.map(async (batch) => {
const timer = new Date()
const processedBatch = this.processEventBatch(batch)
this.pluginsServer.statsd?.timing('kafka_queue.single_event_batch', timer)
return processedBatch
})
)
).flat()
clearTimeout(processingTimeout)
this.pluginsServer.statsd?.timing('kafka_queue.each_batch.process_events', batchStartTimer)
const batchIngestionTimer = new Date()
// Sort in the original order that the events came in, putting any randomly added events to the end.
// This is so we would resolve the correct kafka offsets in order.
processedEvents.sort(
(a, b) => (uuidOrder.get(a.uuid!) || pluginEvents.length) - (uuidOrder.get(b.uuid!) || pluginEvents.length)
)
const ingestionTimeout = timeoutGuard(
`Still ingesting ${processedEvents.length} events. Timeout warning after 30 sec!`
)
const ingestOneEvent = async (event: PluginEvent) => {
const singleIngestionTimeout = timeoutGuard(
`After 30 seconds still ingesting event: ${JSON.stringify(event)}`
)
const singleIngestionTimer = new Date()
try {
await this.saveEvent(event)
} catch (error) {
status.info('🔔', error)
Sentry.captureException(error)
throw error
} finally {
this.pluginsServer.statsd?.timing('kafka_queue.single_ingestion', singleIngestionTimer)
clearTimeout(singleIngestionTimeout)
}
}
const maxIngestionBatch = Math.max(
this.pluginsServer.WORKER_CONCURRENCY * this.pluginsServer.TASKS_PER_WORKER,
50
)
const ingestionBatches = groupIntoBatches(processedEvents, maxIngestionBatch)
for (const batch of ingestionBatches) {
await Promise.all(batch.map(ingestOneEvent))
const offset = uuidOffset.get(batch[batch.length - 1].uuid!)
if (offset) {
resolveOffset(offset)
}
await commitOffsetsIfNecessary()
}
clearTimeout(ingestionTimeout)
this.pluginsServer.statsd?.timing('kafka_queue.each_batch.ingest_events', batchIngestionTimer)
this.pluginsServer.statsd?.timing('kafka_queue.each_batch', batchStartTimer)
status.info(
'🧩',
`Kafka Batch of ${pluginEvents.length} events completed in ${
new Date().valueOf() - batchStartTimer.valueOf()
}ms (plugins: ${batchIngestionTimer.valueOf() - batchStartTimer.valueOf()}ms, ingestion: ${
new Date().valueOf() - batchIngestionTimer.valueOf()
}ms)`
)
resolveOffset(batch.lastOffset())
await commitOffsetsIfNecessary()
await heartbeat()
}
async start(): Promise<void> {
const startPromise = new Promise<void>(async (resolve, reject) => {
this.consumer.on(this.consumer.events.GROUP_JOIN, () => resolve())
this.consumer.on(this.consumer.events.CRASH, ({ payload: { error } }) => reject(error))
status.info('⏬', `Connecting Kafka consumer to ${this.pluginsServer.KAFKA_HOSTS}...`)
this.wasConsumerRan = true
await this.consumer.subscribe({ topic: this.pluginsServer.KAFKA_CONSUMPTION_TOPIC! })
// KafkaJS batching: https://kafka.js.org/docs/consuming#a-name-each-batch-a-eachbatch
await this.consumer.run({
eachBatchAutoResolve: false, // we are resolving the last offset of the batch more deliberately
autoCommitInterval: 500, // autocommit every 500 ms…
autoCommitThreshold: 1000, // …or every 1000 messages, whichever is sooner
eachBatch: async (payload) => {
try {
await this.eachBatch(payload)
} catch (error) {
status.info('💀', `Kafka Batch of ${payload.batch.messages.length} events failed!`)
Sentry.captureException(error)
throw error
}
},
})
})
return await startPromise
}
async pause(): Promise<void> {
if (this.wasConsumerRan && !this.isPaused()) {
status.info('⏳', 'Pausing Kafka consumer...')
this.consumer.pause([{ topic: this.pluginsServer.KAFKA_CONSUMPTION_TOPIC! }])
status.info('⏸', 'Kafka consumer paused!')
}
return Promise.resolve()
}
resume(): void {
if (this.wasConsumerRan && this.isPaused()) {
status.info('⏳', 'Resuming Kafka consumer...')
this.consumer.resume([{ topic: this.pluginsServer.KAFKA_CONSUMPTION_TOPIC! }])
status.info('▶️', 'Kafka consumer resumed!')
}
}
isPaused(): boolean {
return this.consumer.paused().some(({ topic }) => topic === this.pluginsServer.KAFKA_CONSUMPTION_TOPIC)
}
async stop(): Promise<void> {
status.info('⏳', 'Stopping Kafka queue...')
try {
await this.consumer.stop()
status.info('⏹', 'Kafka consumer stopped!')
} catch (error) {
status.error('⚠️', 'An error occurred while stopping Kafka queue:\n', error)
}
try {
await this.consumer.disconnect()
} catch {}
}
private static buildConsumer(kafka: Kafka): Consumer {
const consumer = kafka.consumer({
groupId: 'clickhouse-ingestion',
sessionTimeout: 60000,
readUncommitted: false,
})
const { GROUP_JOIN, CRASH, CONNECT, DISCONNECT } = consumer.events
consumer.on(GROUP_JOIN, ({ payload: { groupId } }) => {
status.info('✅', `Kafka consumer joined group ${groupId}!`)
})
consumer.on(CRASH, ({ payload: { error, groupId } }) => {
status.error('⚠️', `Kafka consumer group ${groupId} crashed:\n`, error)
Sentry.captureException(error)
killGracefully()
})
consumer.on(CONNECT, () => {
status.info('✅', 'Kafka consumer connected!')
})
consumer.on(DISCONNECT, () => {
status.info('🛑', 'Kafka consumer disconnected!')
})
return consumer
}
}