-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathnats.js
192 lines (174 loc) · 4.59 KB
/
nats.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
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
'use strict'
const Eventemitter2 = require('eventemitter2').EventEmitter2
/**
*
*
* @class Nats
* @extends {EventEmitter}
*/
class Nats extends Eventemitter2 {
/**
* Creates an instance of Nats.
* @memberof Nats
*/
constructor() {
super({ delimiter: '.', wildcard: true })
this.subId = 1
this.inboxId = 1
this.subscriptions = new Map()
this.timeoutsMap = new Map()
this.connected = false
setImmediate(() => {
this.connected = true
this.emit('connect')
})
}
/**
* Close the NATS connection
* We working in-memory no need to implement this.
*
* @param {any} handler
* @memberof Nats
*/
close(handler) {
if (typeof handler === 'function') {
setImmediate(() => handler())
}
}
/**
* Set a timeout on a subscription. The subscription is cancelled if the
* expected number of messages is reached or the timeout is reached.
*
* @param {Mixed} sid
* @param {Number} timeout
* @param {Number} expectedMsg
* @param {any} handler
* @memberof Nats
*/
timeout(sid, timeout, expectedMsg, handler) {
this.timeoutsMap.set(sid, {
timeout,
expectedMsg,
receivedMsg: 0,
handler,
timer: setTimeout(() => handler(), timeout).unref()
})
}
/**
* Publish a message to the given subject, with optional reply and callback.
*
* @param {String} topic
* @param {String} payload
* @param {Function} handler
* @memberof Nats
*/
publish(topic, payload, handler) {
this.emit(topic, { payload })
setImmediate(() => {
if (handler) {
handler()
}
})
}
/**
* Publish a message with an implicit inbox listener as the reply. Message is optional.
* This should be treated as a subscription. You can optionally indicate how many
* messages you only want to receive using opt_options = {max:N}. Otherwise you
* will need to unsubscribe to stop the message stream.
* The Subscriber Id is returned.
*
* @param {String} topic
* @param {String} payload
* @param {Object} opts
* @param {Function} handler
* @return {Mixed}
* @memberof Nats
*/
request(topic, payload, opts, handler) {
const subData = {
max: opts.max || 1,
inbox: this.inboxId++
}
// represent the sid
const replyTo = `topic_${subData.inbox}`
// workaround to express a unlimited amount messages
if (subData.max === -1) {
subData.max = Number.MAX_SAFE_INTEGER
}
if (this.listeners(topic).length === 0) {
handler({
code: 'REQ_TIMEOUT' // NATS ERR CODE
})
return
}
// auto unsubscribe after max messages
this.many(replyTo, subData.max, event => {
const timeout = this.timeoutsMap.get(replyTo)
if (timeout) {
timeout.receivedMsg++
if (timeout.receivedMsg === timeout.expectedMsg) {
clearTimeout(timeout.timer)
}
}
// fire handler
setImmediate(() => handler(event.payload))
})
// start the request with inbox channel
this.emit(topic, { payload, replyTo })
return replyTo
}
/**
*
*
* @param {any} topic
* @param {any} opts
* @param {any} handler
* @memberof Nats
*/
subscribe(topic, opts, handler) {
// The greater than symbol (>), also known as the full wildcard, matches one or more tokens at the tail of a subject, and must be the last token.
topic = topic.replace(/>/g, '**')
let listener = event => {
setImmediate(() => handler(event.payload, event.replyTo))
}
let sub = { id: this.subId++, options: opts, handler, topic, listener }
this.subscriptions.set(sub.id, sub)
this.many(sub.topic, sub.options.max || Number.MAX_SAFE_INTEGER, listener)
return sub.id
}
/**
* Unsubscribe to a given Subscriber Id, with optional max parameter.
* Unsubscribing to a subscription that already yielded the specified number of messages
* will clear any pending timeout callbacks.
*
* @param {Mixed} sid
* @param {Number} opt_max
* @memberof Nats
*/
unsubscribe(topic, max) {
if (typeof topic === 'string') {
this.removeAllListeners(topic)
} else {
for (const s of this.subscriptions.values()) {
if (s.id === topic) {
this.removeListener(s.topic, s.listener)
this.emit('unsubscribed', s.id, s.topic)
break
}
}
}
}
/**
* Flush all pending data to the server.
* We working in-memory no need to implement this.
*
* @param {any} cb
* @memberof Nats
*/
flush(cb) {
if (typeof cb === 'function') {
cb()
}
}
}
module.exports = Nats