-
-
Notifications
You must be signed in to change notification settings - Fork 62
/
glee.ts
331 lines (297 loc) · 9.48 KB
/
glee.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
323
324
325
326
327
328
329
330
331
/* eslint-disable @typescript-eslint/no-unused-vars */
import EventEmitter from 'events'
import async from 'async'
import Debug from 'debug'
import { AsyncAPIDocumentInterface as AsyncAPIDocument, ServerInterface as Server } from '@asyncapi/parser'
import GleeAdapter, { GleeAdapterOptions } from './adapter.js'
import GleeClusterAdapter from './cluster.js'
import GleeRouter, {
ChannelErrorMiddlewareTuple,
ChannelMiddlewareTuple,
GenericMiddleware,
} from './router.js'
import GleeMessage from './message.js'
import { matchChannel, duplicateMessage, getParams } from './util.js'
import { GleeConfig } from './index.js'
import GleeConnection from './connection.js'
import { MiddlewareCallback } from '../middlewares/index.js'
const debug = Debug('glee')
type AdapterRecord = {
Adapter: typeof GleeAdapter
instance?: GleeAdapter
serverName: string
server: Server
parsedAsyncAPI: AsyncAPIDocument
}
type ClusterAdapterRecord = {
Adapter: typeof GleeClusterAdapter
instance?: GleeClusterAdapter
}
export default class Glee extends EventEmitter {
private _options: GleeConfig
private _router: GleeRouter
private _adapters: AdapterRecord[]
private _clusterAdapter: ClusterAdapterRecord
/**
* Instantiates Glee.
*
* @param {Object} [options={}]
*/
constructor(options: GleeConfig = {}) {
super({ captureRejections: true })
this.on('error', console.error)
this._options = options
this._router = new GleeRouter()
this._adapters = []
}
get options(): GleeConfig {
return this._options
}
get adapters(): AdapterRecord[] {
return this._adapters
}
get clusterAdapter(): ClusterAdapterRecord {
return this._clusterAdapter
}
/**
* Adds a connection adapter.
*
* @param {GleeAdapter} adapter The adapter.
* @param {String} serverName The name of the AsyncAPI Server to use with the adapter.
* @param {AsyncAPIServer} server AsyncAPI Server to use with the adapter.
* @param {AsyncAPIDocument} parsedAsyncAPI The AsyncAPI document.
*/
addAdapter(
Adapter: typeof GleeAdapter,
{
serverName,
server,
parsedAsyncAPI,
}: { serverName: string; server: Server | undefined; parsedAsyncAPI: AsyncAPIDocument }
) {
this._adapters.push({ Adapter, serverName, server, parsedAsyncAPI })
}
/**
* Sets the cluster adapter to use.
*
* @param {GleeClusterAdapter} adapter The adapter.
*/
setClusterAdapter(Adapter: typeof GleeClusterAdapter) {
this._clusterAdapter = {
Adapter,
}
}
/**
* Use a middleware for inbound messages.
* @param {String} [channel] The channel you want to scope the middleware to.
* @param {Function|GleeRouter} ...middlewares A function or GleeRouter to use as a middleware.
*/
use(...middlewares: GenericMiddleware[]): void
use(channel: string, ...middlewares: GenericMiddleware[]): void
use(
channel: string | GenericMiddleware,
...middlewares: GenericMiddleware[]
): void {
this._router.use(...arguments) // eslint-disable-line prefer-rest-params
}
/**
* Use a middleware for outbound messages.
* @param {String} [channel] The channel you want to scope the middleware to.
* @param {Function|GleeRouter} ...middlewares A function or GleeRouter to use as a middleware.
*/
useOutbound(...middlewares: GenericMiddleware[]): void
useOutbound(channel: string, ...middlewares: GenericMiddleware[]): void
useOutbound(
channel: string | GenericMiddleware,
...middlewares: GenericMiddleware[]
): void {
this._router.useOutbound(...arguments) // eslint-disable-line prefer-rest-params
}
/**
* Send a message to the adapters.
*
* @param {Object|GleeMessage} message The payload of the message you want to send.
*/
send(message: GleeMessage): void {
message.setOutbound()
this._processMessage(
this._router.getOutboundMiddlewares(),
this._router.getOutboundErrorMiddlewares(),
message
)
}
/**
* Tells the adapters to connect.
*/
async connect(): Promise<any[]> {
const promises = []
this._adapters.forEach((a) => {
const adapterOptions: GleeAdapterOptions = {
glee: this,
serverName: a.serverName,
server: a.server,
parsedAsyncAPI: a.parsedAsyncAPI
}
a.instance = new a.Adapter(adapterOptions)
promises.push(a.instance.connect())
})
try {
if (this._clusterAdapter) {
this._clusterAdapter.instance = new this._clusterAdapter.Adapter(this)
promises.push(this._clusterAdapter.instance.connect().catch((error) => {
console.error('Error connecting to cluster:', error)
}))
}
} catch (error) {
console.error('Error connecting:', error)
}
return Promise.all(promises)
}
/**
* Alias for `connect`.
*/
async listen(): Promise<any[]> {
return this.connect()
}
/**
* Injects a message into the Glee inbound middleware chain.
*
* @param {GleeMessage} message The message you want to send.
* @param {String} serverName The name of the server this message is coming from.
* @param {GleeConnection} [connection] The connection used when receiving the message. Its type is unknown and must be handled by the adapters.
*/
injectMessage(
message: GleeMessage,
serverName: string,
connection: GleeConnection
) {
message.serverName = serverName
message.connection = connection
message.setInbound()
this._processMessage(
this._router.getMiddlewares(),
this._router.getErrorMiddlewares(),
message
)
}
/**
* Injects an error into the Glee inbound error middleware chain.
*
* @param {Any} error The error.
* @param {String} [channel] The channel of the error.
*/
injectError(error: Error, channel?: string) {
this._processError(
this._router.getErrorMiddlewares(),
error,
new GleeMessage({ channel })
)
}
/**
* Synchronizes the other instances in the cluster with the message.
*
* @param {GleeMessage} message
*/
syncCluster(message: GleeMessage): void {
if (this._clusterAdapter && !message.cluster) {
this._clusterAdapter.instance.send(message).catch((e: Error) => {
this._processError(this._router.getErrorMiddlewares(), e, message)
})
}
}
/**
* Starts executing the middlewares for the given message.
*
* @param {ChannelMiddlewareTuple} middlewares The middleware chain to execute.
* @param {ChannelErrorMiddlewareTuple} errorMiddlewares The middlewares chain to execute in case of error.
* @param {GleeMessage} message The message to pass to the middlewares.
* @private
*/
private _processMessage(
middlewares: ChannelMiddlewareTuple[],
errorMiddlewares: ChannelErrorMiddlewareTuple[],
message: GleeMessage
): void {
const mws = middlewares
.filter((mw) => matchChannel(mw.channel, message.channel))
.map((mw) => (msg: GleeMessage, next: MiddlewareCallback) => {
const msgForMiddleware: GleeMessage = duplicateMessage(msg)
msgForMiddleware.params = getParams(
mw.channel,
msgForMiddleware.channel
)
msgForMiddleware.on('send', (m: GleeMessage) => {
m.setOutbound()
this._processMessage(
this._router.getOutboundMiddlewares(),
this._router.getOutboundErrorMiddlewares(),
m
)
})
mw.fn.call(
mw.fn,
msgForMiddleware,
(err: Error, newMessage: GleeMessage) => {
const nextMessage = newMessage || msgForMiddleware
nextMessage.channel = message.channel // This is to avoid the channel to be modified.
next(err, nextMessage)
}
)
})
async.seq(...mws)(message, (err: Error, msg: GleeMessage) => {
if (err) {
message.notifyFailedProcessing()
debug('Error encountered while processing middlewares.')
this._processError(errorMiddlewares, err, msg)
return
}
if (middlewares === this._router.getOutboundMiddlewares()) {
debug('Outbound pipeline finished. Sending message...')
this._adapters.forEach((a: AdapterRecord) => {
if (
a.instance &&
(!msg.serverName || msg.serverName === a.serverName)
) {
a.instance.send(msg).catch((e: Error) => {
this._processError(errorMiddlewares, e, msg)
})
}
})
} else {
message.notifySuccessfulProcessing()
debug('Inbound pipeline finished.')
}
})
}
/**
* Starts executing the middlewares for the given error and message.
*
* @param {Array} errorMiddlewares The error middlewares chain to execute.
* @param {Any} error The error to pass to the middleware.
* @param {GleeMessage} message The message to pass to the middlewares.
* @private
*/
private _processError(
errorMiddlewares: ChannelErrorMiddlewareTuple[],
error: Error,
message: GleeMessage
): void {
const emws = errorMiddlewares.filter((emw) =>
matchChannel(emw.channel, message.channel)
)
if (!emws.length) return
this._execErrorMiddleware(emws, 0, error, message)
}
private _execErrorMiddleware(
emws: ChannelErrorMiddlewareTuple[],
index: number,
error: Error,
message: GleeMessage
) {
const emwsLength = emws.length
emws[(index + emwsLength) % emwsLength].fn(error, message, (err: Error) => {
if (!emws[index + 1]) return
this._execErrorMiddleware.call(null, emws, index + 1, err, message)
})
}
}