-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
62 lines (47 loc) · 2.07 KB
/
index.js
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
const Pulsar = require("pulsar-client");
const Redis = require("redis");
const READ_TIMEOUT = parseInt(process.env.KNOWSTR_READ_TIMEOUT || 5000);
(async () => {
let exiting;
let msg;
let timeout;
const redisClient = Redis.createClient({
url: process.env.KNOWSTR_REDIS_URL || "redis://127.0.0.1:6379",
}).on("error", (err) => console.error("[RedisClientError]", err));
await redisClient.connect();
const [topic, token, url] = await Promise.all([redisClient.HGET("settings", "pulsar_topic"), redisClient.HGET("settings", "pulsar_token"), redisClient.HGET("settings", "pulsar_url")]);
const currentMessageId = await redisClient.GET(`pulsar_reader_example_message_id:${topic}`);
const clientParams = {
serviceUrl: url || process.env.KNOWSTR_PULSAR_URL || "pulsar://127.0.0.1:6650",
operationTimeoutSeconds: 30,
};
if (token || process.env.KNOWSTR_PULSAR_TOKEN) {
clientParams["authentication"] = new Pulsar.AuthenticationToken({
token: token || process.env.KNOWSTR_PULSAR_TOKEN,
});
}
// Create a client
const client = new Pulsar.Client(clientParams);
const mid = currentMessageId ? Pulsar.MessageId.deserialize(Buffer.from(currentMessageId, "hex")) : Pulsar.MessageId.earliest();
// Create a reader
const reader = await client.createReader({
topic: topic,
startMessageId: mid,
});
const onTimeout = async () => {
console.log("Exiting because of reader timeout");
await reader.close().catch(console.error);
await client.close().catch(console.error);
await redisClient.quit().catch(console.error);
process.exit();
};
timeout = setTimeout(onTimeout, READ_TIMEOUT);
while ((msg = await reader.readNext())) {
clearTimeout(timeout);
timeout = setTimeout(onTimeout, READ_TIMEOUT);
const payload = msg.getData().toString();
const event = JSON.parse(payload);
const messageId = msg.getMessageId().serialize().toString("hex");
await Promise.all([redisClient.SET(`pulsar_reader_example_message_id:${topic}`, messageId), redisClient.SET(`id:${event.id}`, parseInt(Date.now() / 1000))]);
}
})();