/
consumer.ts
322 lines (306 loc) · 9.53 KB
/
consumer.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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
import { HttpClient } from "./http";
import { Message } from "./types";
export type TopicPartition = { topic: string; partition: number };
export type TopicPartitionOffset = TopicPartition & { offset: number };
export type FetchRequest = { timeout?: number; topicPartitionOffsets?: TopicPartitionOffset[] } & (
| { topic: string; partition: number; offset: number }
| { topic?: never; partition?: never; offset?: never }
);
type BaseConsumerRequest = {
/**
* The name of the consumer group which is used as Kafka consumer group id
* @see https://kafka.apache.org/documentation/#consumerconfigs_group.id
*/
consumerGroupId: string;
/**
* Used to identify kafka consumer instances in the same consumer group.
* Each consumer instance id is handled by a separate consumer client.
* @see https://kafka.apache.org/documentation/#consumerconfigs_group.instance.id
*/
instanceId: string;
};
export type ConsumeRequest = BaseConsumerRequest & {
topics: string[];
/**
* Defines the time to wait at most for the fetch request in milliseconds.
* It's optional and its default value 1000.
*/
timeout?: number;
/**
* If true, the consumer's offset will be periodically committed in the background.
*/
autoCommit?: boolean;
/**
* The frequency in milliseconds that the consumer offsets are auto-committed to Kafka
* if auto commit is enabled.
* Default is 5000.
*/
autoCommitInterval?: number;
/**
* What to do when there is no initial offset in Kafka or if the current
* offset does not exist any more on the server. Default value is `latest`.
*
* `earliest`: Automatically reset the offset to the earliest offset
*
* `latest`: Automatically reset the offset to the latest offset
*
* `none`: Throw exception to the consumer if no previous offset is found for the
* consumer's group.
*/
autoOffsetReset?: "earliest" | "latest" | "none";
};
export type FetchOptions = {
/**
* If true `fetch` will call upstash once for each topic in your request.
* This circumenvents the issue where upstash only returns from a single topic
* at a time when using fetch.
*
* All requests are executed in parallel.
*
* Default: true
*/
parallel?: boolean;
};
export type CommitRequest = BaseConsumerRequest & {
/**
* Commits the last consumed messages if left empty
*/
offset?: TopicPartitionOffset | TopicPartitionOffset[];
};
export type CommittedRequest = BaseConsumerRequest & { topicPartitions: TopicPartition[] };
/**
* Consumer APIs are used to fetch/consume messages from Kafka topics. Similar
* to Kafka clients there are two mechanisms to consume messages; one is
* seeking offsets manually and the other is to use consumer groups which
* manage offsets automatically inside a special Kafka topic.
*
* We call the first one as Fetch API and the second one as Consume API.
* Consume API has some additional methods if you wish to commit offsets manually.
*/
export class Consumer {
private readonly client: HttpClient;
constructor(client: HttpClient) {
this.client = client;
}
/**
* Fetches the message(s) starting with a given offset inside the partition.
* This API doesn't use consumer groups.
*
* When fetching from multiple topics it is important to understand that
* upstash only returns data for a single topic at a time, so you should
* call `fetch` multiple times.
*
* Fetch from a single <topic, partition, offset>:
* ```ts
* fetch({
* topic: "greeting",
* partition: 3,
* timeout: 1000
* })
* ```
*
* Fetch from multiple <topic, partition, offset> triples:
* ```ts
* fetch({
* topicPartitionOffsets": [
* {"topic": "greetings", "partition": 1, "offset": 1},
* {"topic": "greetings", "partition": 2, "offset": 1},
* {"topic": "greetings", "partition": 3, "offset": 1},
* {"topic": "cities", "partition": 1, "offset": 10},
* {"topic": "cities", "partition": 2, "offset": 20}
* ],
* timeout: 1000
* })
* ```
*
* You can even combine both:
* ```ts
* fetch({
* topic: "words",
* partition: 0,
* offset: 0,
* topicPartitionOffsets: [
* { topic: "cities", partition: 1, offset: 10},
* { topic: "cities", partition: 2, offset: 20}
* ],
* timeout: 5000
* })
* ```
*/
public async fetch(
req: FetchRequest,
opts: FetchOptions = { parallel: true },
): Promise<Message[]> {
let requests = [req];
if (opts?.parallel) {
requests = (req.topicPartitionOffsets ?? []).map((r) => ({ ...r, timeout: req.timeout }));
if (req.topic) {
requests.push({
topic: req.topic,
partition: req.partition,
offset: req.offset,
timeout: req.timeout,
});
}
}
const responses = await Promise.all(
requests.map(async (r) => await this.client.post<Message[]>({ path: ["fetch"], body: r })),
);
return responses.flat();
}
/**
* Fetches the message(s) using Kafka consumer group mechanism and may commit
* the offsets automatically.
*
* The first time a consumer is created, it needs to figure out the group
* coordinator by asking the Kafka brokers and joins the consumer group.
* This process takes some time to complete. That's why when a consumer
* instance is created first time, it may return empty messages until consumer
* group coordination is completed.
*
* Consume from a single topic with timeout:
* ```ts
* consume({
* consumerGroupId: "mygroup",
* instanceId: "myconsumer",
* topics: ["greetings"]
* })
* ```
*
* Consume from multiple topics:
* ```ts
* consume({
* consumerGroupId: "mygroup",
* instanceId: "myconsumer",
* topics: ["greetings", "cities", "world"],
* timeout: 1000
* })
* ```
*
* Consume from topics without auto commit:
* ```ts
* consume({
* consumerGroupId: "mygroup",
* instanceId: "myconsumer",
* topics: ["greetings", "cities", "world"],
* timeout: 1000,
* autoCommit: false
* })
* ```
*
* Consume from topics starting from the earliest message:
* ```ts
* consume({
* consumerGroupId: "mygroup",
* instanceId: "myconsumer",
* topics: ["greetings", "cities", "world"],
* timeout: 1000,
* autoOffsetReset: "earliest"
* })
* ```
*
* Consume from topics with custom auto commit interval:
* ```ts
* consume({
* consumerGroupId: "mygroup",
* instanceId: "myconsumer",
* topics: ["greetings", "cities", "world"],
* timeout: 1000,
* autoCommit: true,
* autoCommitInterval: 3000
* })
* ```
*/
public async consume(req: ConsumeRequest): Promise<Message[]> {
const body: Record<string, unknown> = {};
if (req.topics.length === 1) {
body.topic = req.topics[0];
} else {
body.topics = req.topics;
}
if (typeof req.timeout === "number") {
body.timeout = req.timeout;
}
const headers: Record<string, string> = {};
if (typeof req.autoCommit === "boolean") {
headers["Kafka-Enable-Auto-Commit"] = req.autoCommit.toString();
}
if (typeof req.autoCommitInterval === "number") {
headers["Kafka-Auto-Commit-Interval"] = req.autoCommitInterval.toString();
}
if (typeof req.autoOffsetReset === "string") {
headers["Kafka-Auto-Offset-Reset"] = req.autoOffsetReset;
}
return await this.client.post<Message[]>({
path: ["consume", req.consumerGroupId, req.instanceId],
headers,
body,
});
}
/**
* Commits the fetched message offsets. `commit` should be used alongside
* `consume`, especially when auto commit is disabled.
*
* Commit single topic partition offset:
* ```ts
* commit({
* consumerGroupId: "mygroup",
* instanceId: "myconsumer",
* offset: {
* topic: "cities",
* partition: 1,
* offset: 10,
* }
* })
* ```
*
* Commit multiple topic partition offsets:
* ```ts
* commit({
* consumerGroupId: "mygroup",
* instanceId: "myconsumer",
* offset: [
* { topic: "cities", partition: 0, offset: 13 },
* { topic: "cities", partition: 1, offset: 37 },
* { topic: "greetings", partition: 0, offset: 19 },
* ]
* })
* ```
*
* Commit all latest consumed message offsets:
* ```ts
* commit({
* consumerGroupId: "mygroup",
* instanceId: "myconsumer",
* })
* ```
*/
public async commit(req: CommitRequest): Promise<void> {
return await this.client.post({
path: ["commit", req.consumerGroupId, req.instanceId],
body: req.offset,
});
}
/**
* Returns the last committed offsets for the topic partitions inside the group.
*
* List committed offsets for multiple topic partitions:
* ```ts
* committed({
* consumerGroupId: "mygroup",
* instanceId: "myconsumer",
* topicPartitions: [
* { topic: "cities", partition: 0 },
* { topic: "cities", partition: 1 },
* { topic: "greetings", partition: 0},
* ]
* })
* ```
*/
public async committed(req: CommittedRequest): Promise<TopicPartitionOffset[]> {
return await this.client.post<TopicPartitionOffset[]>({
path: ["committed", req.consumerGroupId, req.instanceId],
body: req.topicPartitions,
});
}
}