-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlocal.js
59 lines (54 loc) · 1.41 KB
/
local.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
const EventEmitter = require('node:events');
const subscribers = {};
const streams = {};
const xreaders = {};
class Local extends EventEmitter {
constructor() {
super();
this.instanceId = Math.random().toString(36).slice(2);
}
publish(channel, data) {
for (const [subscriber, fn] of subscribers[channel] || []) {
subscriber.emit('message', channel, data);
fn(null, 1);
}
}
subscribe(channel, fn) {
subscribers[channel] ||= [];
subscribers[channel].push([this, fn]);
}
xread() {
const args = [...arguments].reverse();
let [minId, key, STREAMS, ms, block] = args;
if (minId == '$') minId = Date.now();
const messages = streams[key]?.filter(m => m[0] > minId);
if (messages?.length) {
return [[key, messages]];
}
if (block) {
return new Promise(resolve => {
xreaders[key] ||= [];
xreaders[key].push({
minId,
instanceId: this.instanceId,
fn: resolve,
});
});
} else {
return null;
}
}
xadd(key, messageId, field, value) {
if (messageId == '*') messageId = Date.now();
streams[key] ||= [];
streams[key].push([messageId, [field, value]]);
setTimeout(_ => {
for (const r of xreaders[key] || []) {
if (r.instanceId != this.instanceId) {
r.fn(['key', [messageId, [field, value]]]);
}
}
}, 10);
}
}
module.exports = Local;