Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 | 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 12x 10x | /* eslint-disable @typescript-eslint/no-unused-vars */
import EventEmitter from 'events'
import async from 'async'
import Debug from 'debug'
import GleeQuoreAdapter, { GleeQuoreAdapterOptions } from './lib/adapter.js'
import GleeQuoreClusterAdapter from './lib/cluster.js'
import GleeQuoreRouter, {
ChannelErrorMiddlewareTuple,
ChannelMiddlewareTuple,
GenericMiddleware,
} from './lib/router.js'
import GleeQuoreMessage, { IGleeQuoreMessageConstructor } from './lib/message.js'
import { matchChannel, duplicateMessage, getParams } from './lib/util.js'
import GleeQuoreConnection from './lib/connection.js'
import { MiddlewareCallback } from './middlewares/index.js'
import buffer2string from './middlewares/buffer2string.js'
import string2json from './middlewares/string2json.js'
import json2string from './middlewares/json2string.js'
import validate from './middlewares/validate.js'
import existsInAsyncAPI from './middlewares/existsInAsyncAPI.js'
import validateConnection from './middlewares/validateConnection.js'
import WebSocketServerAdapter from './adapters/ws/server.js'
import WebsocketClientAdapter from './adapters/ws/client.js'
import { EnrichedEvent, AuthEvent } from './lib/adapter.js'
import { getMessagesSchema } from './lib/util.js'
import { AsyncAPIDocumentInterface, ServerInterface } from '@asyncapi/parser'
import { AdapterRecord, AuthFunctionInfo, ClusterAdapterRecord, GleeQuoreFunction, GleeQuoreLifecycleFunction, GleeQuoreConfig, GleeQuoreLifecycleEvent, GleeQuoreFunctionEvent, GleeQuoreAuthFunction, GleeQuoreAuthFunctionEvent } from './index.d.js'
import MqttAdapter from './adapters/mqtt/index.js'
import KafkaAdapter from './adapters/kafka/index.js'
import HttpClientAdapter from './adapters/http/client.js'
import HttpServerAdapter from './adapters/http/server.js'
import RedisClusterAdapter from './adapters/cluster/redis/index.js'
import SocketIOAdapter from './adapters/socket.io/index.js'
const debug = Debug('gleequore')
export enum LifecycleEvent {
onConnect = 'onConnect',
onReconnect = 'onReconnect',
onDisconnect = 'onDisconnect',
onServerReady = 'onServerReady',
onServerConnectionOpen = 'onServerConnectionOpen',
onServerConnectionClose = 'onServerConnectionClose',
}
export interface LifecycleEventRecord {
func: GleeQuoreLifecycleFunction
servers: string[]
}
export interface FunctionInfoRecord {
run: GleeQuoreFunction
}
export default class GleeQuore {
private _asyncapi: AsyncAPIDocumentInterface
private _options: GleeQuoreConfig
private _router: GleeQuoreRouter
private _adapters: AdapterRecord[]
private _clusterAdapter: ClusterAdapterRecord
private _internalEvents: EventEmitter
private _lifecycleEvents: Map<string, LifecycleEventRecord[]>
private _functions: Map<string, FunctionInfoRecord>
private _authFunctions: Map<string, AuthFunctionInfo>
/**
* Instantiates the quore of Glee.
*
* @param {Object} [options={}]
*/
constructor(asyncapi: AsyncAPIDocumentInterface, options: GleeQuoreConfig = {}) {
this._asyncapi = asyncapi
this._options = options
this._router = new GleeQuoreRouter()
this._adapters = []
this._internalEvents = new EventEmitter({ captureRejections: true })
this._lifecycleEvents = new Map<string, LifecycleEventRecord[]>()
this._functions = new Map()
this._authFunctions = new Map<string, AuthFunctionInfo>()
this.use(existsInAsyncAPI(asyncapi))
this.useOutbound(existsInAsyncAPI(asyncapi))
this.useOutbound(validateConnection)
this.use((err, message, next) => {
this._internalEvents.emit('error', err)
next(err, message)
})
this.useOutbound((err, message, next) => {
this._internalEvents.emit('error', err)
next(err, message)
})
this.use(buffer2string)
this.use(string2json)
asyncapi.operations().filterByReceive().forEach(operation => {
const channel = operation.channels().all()[0] // operation can have only one channel.
Iif (operation.reply()) {
console.warn(`Operation ${operation.id()} has a reply defined. Glee does not support replies yet.`)
}
const schema = getMessagesSchema(operation)
const contextErrorMessage = `Your application is receiving a message on channel "${channel.id()}" but the payload of the message is not matching the definition(s) in your AsyncAPI document. If you believe your code is correct, have a look at your AsyncAPI document, especially the messages listed in the channels › ${channel.id()} section. Otherwise, check your code. Here's what failed:\n\n`
Iif (schema.oneOf.length > 1) {
this.use(channel.id(), validate(schema, contextErrorMessage))
} else if (schema.oneOf.length === 1) {
this.use(channel.id(), validate(schema.oneOf[0], contextErrorMessage))
}
this.use(channel.id(), (event, next) => {
this.runFunction(operation.id(), event).then(next).catch((err) => {
next(err, event, next)
})
})
})
asyncapi.operations().filterBySend().forEach(operation => {
const channel = operation.channels().all()[0] // operation can have only one channel.
Iif (operation.reply()) {
console.warn(`Operation ${operation.id()} has a reply defined. Glee does not support replies yet.`)
}
const schema = getMessagesSchema(operation)
const contextErrorMessage = `Your application is sending a message to channel "${channel.id()}" but the payload of the message is not matching the definition(s) in your AsyncAPI document. If you believe your code is correct, have a look at your AsyncAPI document, especially the messages listed in the channels › ${channel.id()} section. Otherwise, check your code. Here's what failed:\n\n`
Iif (schema.oneOf.length > 1) {
this.useOutbound(channel.id(), validate(schema, contextErrorMessage))
} else if (schema.oneOf.length === 1) {
this.useOutbound(channel.id(), validate(schema.oneOf[0], contextErrorMessage))
}
this.useOutbound(channel.id(), json2string)
})
this._internalEvents.on('adapter:auth', async (e: AuthEvent) => {
await this.runAuth({
app: this,
serverName: e.serverName,
authProps: e.authProps,
done: e.done,
doc: e.doc,
})
})
this._internalEvents.on('adapter:connect', async (e: EnrichedEvent) => {
await this.runLifecycleEvent(LifecycleEvent.onConnect, {
app: this,
serverName: e.serverName,
connection: e.connection,
})
})
this._internalEvents.on('adapter:reconnect', async (e: EnrichedEvent) => {
await this.runLifecycleEvent(LifecycleEvent.onReconnect, {
app: this,
serverName: e.serverName,
connection: e.connection,
})
})
this._internalEvents.on('adapter:close', async (e: EnrichedEvent) => {
await this.runLifecycleEvent(LifecycleEvent.onDisconnect, {
app: this,
serverName: e.serverName,
connection: e.connection,
})
})
this._internalEvents.on('adapter:server:ready', async (e: EnrichedEvent) => {
await this.runLifecycleEvent(LifecycleEvent.onServerReady, {
app: this,
serverName: e.serverName,
})
})
this._internalEvents.on('adapter:server:connection:open', async (e: EnrichedEvent) => {
await this.runLifecycleEvent(LifecycleEvent.onServerConnectionOpen, {
app: this,
serverName: e.serverName,
connection: e.connection,
})
})
this._internalEvents.on('adapter:server:connection:close', async (e: EnrichedEvent) => {
await this.runLifecycleEvent(LifecycleEvent.onServerConnectionClose, {
app: this,
serverName: e.serverName,
connection: e.connection,
})
})
}
get asyncapi(): AsyncAPIDocumentInterface {
return this._asyncapi
}
get options(): GleeQuoreConfig {
return this._options
}
get adapters(): AdapterRecord[] {
return this._adapters
}
get clusterAdapter(): ClusterAdapterRecord {
return this._clusterAdapter
}
/**
* Adds a connection adapter.
*
* @param {GleeQuoreAdapter} 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} asyncapi The AsyncAPI document.
*/
addAdapter(
Adapter: typeof GleeQuoreAdapter,
{
serverName,
server,
asyncapi,
}: { serverName: string; server: ServerInterface | undefined; asyncapi: AsyncAPIDocumentInterface }
) {
this._adapters.push({ Adapter, serverName, server, asyncapi })
}
/**
* Sets the cluster adapter to use.
*
* @param {GleeQuoreClusterAdapter} adapter The adapter.
*/
setClusterAdapter(Adapter: typeof GleeQuoreClusterAdapter) {
this._clusterAdapter = {
Adapter,
}
}
/**
* Use a middleware for inbound messages.
* @param {String} [channel] The channel you want to scope the middleware to.
* @param {Function|GleeQuoreRouter} ...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|GleeQuoreRouter} ...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 connected servers.
*
* @param {IGleeQuoreMessageConstructor|GleeQuoreMessage} message The message you want to send.
*/
send(message: IGleeQuoreMessageConstructor | GleeQuoreMessage): void {
console.log(message)
let msg: GleeQuoreMessage
if (message instanceof GleeQuoreMessage) {
msg = message
} else {
msg = new GleeQuoreMessage(message)
}
msg.setOutbound()
this._processMessage(
this._router.getOutboundMiddlewares(),
this._router.getOutboundErrorMiddlewares(),
msg
)
}
/**
* Starts the application.
*/
async start(): Promise<any[]> {
const promises = []
await this.registerAdapters()
this._adapters.forEach((a) => {
const adapterOptions: GleeQuoreAdapterOptions = {
glee: this,
serverName: a.serverName,
server: a.server,
parsedAsyncAPI: a.asyncapi
}
a.instance = new a.Adapter(adapterOptions)
promises.push(a.instance.connect())
})
try {
Iif (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)
}
/**
* Injects a message into the Glee inbound middleware chain.
*
* @param {GleeQuoreMessage} message The message you want to send.
* @param {String} serverName The name of the server this message is coming from.
* @param {GleeQuoreConnection} [connection] The connection used when receiving the message. Its type is unknown and must be handled by the adapters.
*/
injectMessage(
message: GleeQuoreMessage,
serverName: string,
connection: GleeQuoreConnection
) {
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 GleeQuoreMessage({ channel })
)
}
/**
* Synchronizes the other instances in the cluster with the message.
*
* @param {GleeQuoreMessage} message
*/
syncCluster(message: GleeQuoreMessage): void {
Iif (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 {GleeQuoreMessage} message The message to pass to the middlewares.
* @private
*/
private _processMessage(
middlewares: ChannelMiddlewareTuple[],
errorMiddlewares: ChannelErrorMiddlewareTuple[],
message: GleeQuoreMessage
): void {
const mws = middlewares
.filter((mw) => matchChannel(mw.channel, message.channel))
.map((mw) => (msg: GleeQuoreMessage, next: MiddlewareCallback) => {
const msgForMiddleware: GleeQuoreMessage = duplicateMessage(msg)
msgForMiddleware.params = getParams(
mw.channel,
msgForMiddleware.channel
)
msgForMiddleware.on('send', (m: GleeQuoreMessage) => {
m.setOutbound()
this._processMessage(
this._router.getOutboundMiddlewares(),
this._router.getOutboundErrorMiddlewares(),
m
)
})
mw.fn.call(
mw.fn,
msgForMiddleware,
(err: Error, newMessage: GleeQuoreMessage) => {
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: GleeQuoreMessage) => {
Iif (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) => {
Iif (
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 {GleeQuoreMessage} message The message to pass to the middlewares.
* @private
*/
private _processError(
errorMiddlewares: ChannelErrorMiddlewareTuple[],
error: Error,
message: GleeQuoreMessage
): void {
const emws = errorMiddlewares.filter((emw) =>
matchChannel(emw.channel, message.channel)
)
Iif (!emws.length) return
this._execErrorMiddleware(emws, 0, error, message)
}
private _execErrorMiddleware(
emws: ChannelErrorMiddlewareTuple[],
index: number,
error: Error,
message: GleeQuoreMessage
) {
const emwsLength = emws.length
emws[(index + emwsLength) % emwsLength].fn(error, message, (err: Error) => {
Iif (!emws[index + 1]) return
this._execErrorMiddleware.call(null, emws, index + 1, err, message)
})
}
emitInternalEvent(eventName: string | symbol, ...args: any[]): boolean {
return this._internalEvents.emit(eventName, ...args)
}
async registerAuth(serverName: string, authInfo: AuthFunctionInfo) {
this._authFunctions.set(serverName, authInfo)
}
async runAuth(params: GleeQuoreAuthFunctionEvent) {
const { serverName, done } = params
const auth = this._authFunctions.get(serverName)
Iif (!auth) {
console.error(`Missing Authentication function for server "${serverName}".`)
done(false, 422, 'Cannot find authentication function')
return
}
await auth.serverAuth(params)
}
async clientAuthConfig(serverName: string) {
return this._authFunctions.get(serverName)?.clientAuth
}
async on(operationId: string, func: GleeQuoreFunction) {
try {
const operation = this.asyncapi.operations().get(operationId)
if (!operation) {
throw new Error(`There's no operation with ID "${operationId}" in your AsyncAPI document.`)
} else Iif (operation.action() !== 'receive') {
throw new Error(`The operation with ID "${operationId}" has been defined as a "receive" operation in your AsyncAPI document. You can only call «.on()» over "receive" operations.`)
}
debug(`Registering operation: ${operationId}`)
this._functions.set(operationId, {
run: func,
})
} catch(err: unknown) {
this.emitInternalEvent('error', err)
}
}
async runFunction(operationId: string, message: GleeQuoreMessage) {
try {
debug(`Triggering function for operation ID: ${operationId}`)
const operation = this.asyncapi.operations().get(operationId)
Iif (!operation) {
throw new Error(`Error triggering operation with ID "${operationId}". There's no operation with such ID in your AsyncAPI document.`)
}
const operationFunction = this._functions.get(operationId)
Iif (!operationFunction) {
throw new Error(`Error triggering operation with ID "${operationId}". No operation has been registered with such ID. Please, register an operation with such ID as follows: «.on('${operationId}', (message) => { /* Your business logic here... */ })».`)
}
message.operation = operation
await operationFunction.run({
payload: message.payload,
query: message.query,
headers: message.headers,
request: message.request,
channel: message.channel,
connection: message.connection,
serverName: message.serverName,
app: this,
} as GleeQuoreFunctionEvent)
} catch (err: unknown) {
this.emitInternalEvent('error', err)
}
}
async registerLifecycleEvent(lifecycleEvent: LifecycleEvent, func: GleeQuoreLifecycleFunction, serverNames?: string[]) {
Iif (!this._lifecycleEvents.has(lifecycleEvent)) {
this._lifecycleEvents.set(lifecycleEvent, [])
}
this._lifecycleEvents.set(lifecycleEvent, [
...this._lifecycleEvents.get(lifecycleEvent),
{
func,
servers: serverNames,
},
])
}
async runLifecycleEvent(lifecycleEvent: LifecycleEvent, params: GleeQuoreLifecycleEvent) {
try {
Iif (!Array.isArray(this._lifecycleEvents.get(lifecycleEvent))) return
const connectionServer = params.connection.serverName
const handlers = this._lifecycleEvents.get(lifecycleEvent).filter((info) => {
Iif (info.servers) {
return info.servers.includes(connectionServer)
}
return true
})
Iif (!handlers.length) return
debug(`Running ${lifecycleEvent} lifecycle event...`)
await Promise.all(handlers.map((info) => info.func(params)))
} catch (err: unknown) {
this.emitInternalEvent('error', err)
}
}
async onConnect(func: GleeQuoreLifecycleFunction) {
this.registerLifecycleEvent(LifecycleEvent.onConnect, func)
}
async onConnectToServer(serverName: string, func: GleeQuoreLifecycleFunction) {
this.registerLifecycleEvent(LifecycleEvent.onConnect, func, [serverName])
}
async onConnectToServers(serverNames: string[], func: GleeQuoreLifecycleFunction) {
this.registerLifecycleEvent(LifecycleEvent.onConnect, func, serverNames)
}
async onReconnect(func: GleeQuoreLifecycleFunction) {
this.registerLifecycleEvent(LifecycleEvent.onReconnect, func)
}
async onReconnectToServer(serverName: string, func: GleeQuoreLifecycleFunction) {
this.registerLifecycleEvent(LifecycleEvent.onReconnect, func, [serverName])
}
async onReconnectToServers(serverNames: string[], func: GleeQuoreLifecycleFunction) {
this.registerLifecycleEvent(LifecycleEvent.onReconnect, func, serverNames)
}
async onDisconnect(func: GleeQuoreLifecycleFunction) {
this.registerLifecycleEvent(LifecycleEvent.onDisconnect, func)
}
async onDisconnectFromServer(serverName: string, func: GleeQuoreLifecycleFunction) {
this.registerLifecycleEvent(LifecycleEvent.onDisconnect, func, [serverName])
}
async onDisconnectFromServers(serverNames: string[], func: GleeQuoreLifecycleFunction) {
this.registerLifecycleEvent(LifecycleEvent.onDisconnect, func, serverNames)
}
async onAllServersConnectionClose(func: GleeQuoreLifecycleFunction) {
this.registerLifecycleEvent(LifecycleEvent.onServerConnectionClose, func)
}
async onServerConnectionCloses(serverName: string, func: GleeQuoreLifecycleFunction) {
this.registerLifecycleEvent(LifecycleEvent.onServerConnectionClose, func, [serverName])
}
async onServersConnectionClose(serverNames: string[], func: GleeQuoreLifecycleFunction) {
this.registerLifecycleEvent(LifecycleEvent.onServerConnectionClose, func, serverNames)
}
async onAllServersConnectionOpen(func: GleeQuoreLifecycleFunction) {
this.registerLifecycleEvent(LifecycleEvent.onServerConnectionOpen, func)
}
async onServerConnectionOpens(serverName: string, func: GleeQuoreLifecycleFunction) {
this.registerLifecycleEvent(LifecycleEvent.onServerConnectionOpen, func, [serverName])
}
async onServersConnectionOpen(serverNames: string[], func: GleeQuoreLifecycleFunction) {
this.registerLifecycleEvent(LifecycleEvent.onServerConnectionOpen, func, serverNames)
}
async onAllServersReady(func: GleeQuoreLifecycleFunction) {
this.registerLifecycleEvent(LifecycleEvent.onServerReady, func)
}
async onServerReady(serverName: string, func: GleeQuoreLifecycleFunction) {
this.registerLifecycleEvent(LifecycleEvent.onServerReady, func, [serverName])
}
async onServersReady(serverNames: string[], func: GleeQuoreLifecycleFunction) {
this.registerLifecycleEvent(LifecycleEvent.onServerReady, func, serverNames)
}
async onError(errorCallback: (err: Error) => void) {
this._internalEvents.on('error', errorCallback)
}
private async registerAdapters() {
const serverNames = await this.getSelectedServerNames()
serverNames.forEach((serverName) => {
const server: ServerInterface = this.asyncapi.servers().get(serverName)
Iif (!server) {
throw new Error(
`Server "${serverName}" is not defined in the AsyncAPI file.`
)
}
const protocol = server.protocol()
const remoteServers = this.asyncapi.extensions().get('x-remoteServers')?.value()
if (['mqtt', 'mqtts', 'secure-mqtt'].includes(protocol)) {
this.addAdapter(MqttAdapter, {
serverName,
server,
asyncapi: this.asyncapi,
})
} else if (['kafka', 'kafka-secure'].includes(protocol)) {
this.addAdapter(KafkaAdapter, {
serverName,
server,
asyncapi: this.asyncapi,
})
} else if (['amqp', 'amqps'].includes(protocol)) {
// TODO: Implement AMQP support
} else if (['ws', 'wss'].includes(protocol)) {
const configWsAdapter = this.options?.ws?.server?.adapter
if (remoteServers && remoteServers.includes(serverName)) {
this.addAdapter(WebsocketClientAdapter, {
serverName,
server,
asyncapi: this.asyncapi,
})
} else {
if (!configWsAdapter || configWsAdapter === 'native') {
this.addAdapter(WebSocketServerAdapter, {
serverName,
server,
asyncapi: this.asyncapi,
})
} else if (configWsAdapter === 'socket.io') {
this.addAdapter(SocketIOAdapter, {
serverName,
server,
asyncapi: this.asyncapi,
})
} else if (typeof configWsAdapter === 'object') {
this.addAdapter(configWsAdapter, {
serverName,
server,
asyncapi: this.asyncapi,
})
} else {
throw new Error(
`Unknown value for websocket.adapter found in glee.config.js: ${this.options?.ws?.server?.adapter}. Allowed values are 'native-websocket', 'socket.io', or a reference to a custom Glee adapter.`
)
}
}
} else if (['http', 'https'].includes(protocol)) {
if (remoteServers && remoteServers.includes(serverName)) {
this.addAdapter(HttpClientAdapter, {
serverName,
server,
asyncapi: this.asyncapi,
})
} else {
this.addAdapter(HttpServerAdapter, {
serverName,
server,
asyncapi: this.asyncapi,
})
}
} else {
// TODO: Improve error message with link to repo encouraging the developer to contribute.
throw new Error(`Protocol "${server.protocol()}" is not supported yet.`)
}
})
Iif (this.options.cluster) {
const { adapter } = this.options.cluster
if (!adapter || adapter === 'redis') {
this.setClusterAdapter(RedisClusterAdapter)
} else if (typeof adapter === 'function') {
this.setClusterAdapter(adapter)
} else {
throw new Error(`Unknown value for cluster.adapter in glee.config.js`)
}
}
}
async getSelectedServerNames(): Promise<string[]> {
const { includeServers: selectedServerNames } = this.options
Iif (!selectedServerNames || selectedServerNames.length === 0) {
return this.asyncapi.servers().all().map(e => e.id())
}
return this.asyncapi.servers().all().map(e => e.id()).filter((name) => {
return selectedServerNames.includes(name)
})
}
}
|