Add more debug statements to broker
Upgrade packages
This commit is contained in:
parent
d781458cee
commit
0dac59b426
1
.eslintignore
Normal file
1
.eslintignore
Normal file
@ -0,0 +1 @@
|
|||||||
|
tests
|
@ -12,11 +12,19 @@
|
|||||||
"plugins": [ "@typescript-eslint" ],
|
"plugins": [ "@typescript-eslint" ],
|
||||||
"parserOptions": {
|
"parserOptions": {
|
||||||
"ecmaVersion": 2022,
|
"ecmaVersion": 2022,
|
||||||
"sourceType": "module"
|
"sourceType": "module",
|
||||||
|
"project": "./tsconfig.json"
|
||||||
},
|
},
|
||||||
"rules": {
|
"rules": {
|
||||||
"@typescript-eslint/no-unused-vars": "off",
|
"@typescript-eslint/no-unused-vars": "off",
|
||||||
"@typescript-eslint/no-non-null-assertion":"off",
|
"@typescript-eslint/no-non-null-assertion": "off",
|
||||||
|
"@typescript-eslint/no-misused-promises": ["error", {
|
||||||
|
"checksVoidReturn": {
|
||||||
|
"arguments": false
|
||||||
|
}
|
||||||
|
}],
|
||||||
|
"@typescript-eslint/no-shadow": "error",
|
||||||
|
"@typescript-eslint/no-use-before-define": "error",
|
||||||
"accessor-pairs": "warn",
|
"accessor-pairs": "warn",
|
||||||
"array-callback-return": "warn",
|
"array-callback-return": "warn",
|
||||||
"array-bracket-newline": [
|
"array-bracket-newline": [
|
||||||
@ -74,7 +82,7 @@
|
|||||||
"warn",
|
"warn",
|
||||||
"never"
|
"never"
|
||||||
],
|
],
|
||||||
"eqeqeq": "warn",
|
"eqeqeq": "error",
|
||||||
"func-call-spacing": "warn",
|
"func-call-spacing": "warn",
|
||||||
"func-name-matching": "warn",
|
"func-name-matching": "warn",
|
||||||
"func-names": "warn",
|
"func-names": "warn",
|
||||||
@ -87,18 +95,38 @@
|
|||||||
"id-blacklist": "warn",
|
"id-blacklist": "warn",
|
||||||
"id-match": "warn",
|
"id-match": "warn",
|
||||||
"implicit-arrow-linebreak": "warn",
|
"implicit-arrow-linebreak": "warn",
|
||||||
"indent": "warn",
|
"indent": [
|
||||||
"init-declarations": "warn",
|
|
||||||
"quotes": ["error" , "single"],
|
|
||||||
"jsx-quotes": [
|
|
||||||
"warn",
|
"warn",
|
||||||
|
4,
|
||||||
|
{
|
||||||
|
"SwitchCase": 1,
|
||||||
|
"VariableDeclarator": "first",
|
||||||
|
"FunctionDeclaration": {
|
||||||
|
"parameters": "first"
|
||||||
|
},
|
||||||
|
"CallExpression": {
|
||||||
|
"arguments": "first"
|
||||||
|
},
|
||||||
|
"ArrayExpression": "first",
|
||||||
|
"ObjectExpression": "first",
|
||||||
|
"ImportDeclaration": "first"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"init-declarations": "warn",
|
||||||
|
"quotes": [
|
||||||
|
"error",
|
||||||
|
"single"
|
||||||
|
],
|
||||||
|
"jsx-quotes": [
|
||||||
|
"error",
|
||||||
"prefer-single"
|
"prefer-single"
|
||||||
],
|
],
|
||||||
"key-spacing": [
|
"key-spacing": [
|
||||||
"warn",
|
"warn",
|
||||||
{
|
{
|
||||||
"beforeColon": false,
|
"beforeColon": false,
|
||||||
"afterColon": true
|
"afterColon": true,
|
||||||
|
"align": "value"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"keyword-spacing": [
|
"keyword-spacing": [
|
||||||
@ -128,7 +156,7 @@
|
|||||||
],
|
],
|
||||||
"max-lines-per-function": [
|
"max-lines-per-function": [
|
||||||
"warn",
|
"warn",
|
||||||
100
|
140
|
||||||
],
|
],
|
||||||
"max-depth": [
|
"max-depth": [
|
||||||
"warn",
|
"warn",
|
||||||
@ -137,16 +165,16 @@
|
|||||||
"new-parens": "warn",
|
"new-parens": "warn",
|
||||||
"no-alert": "warn",
|
"no-alert": "warn",
|
||||||
"no-array-constructor": "warn",
|
"no-array-constructor": "warn",
|
||||||
// "no-bitwise": "warn",
|
|
||||||
"no-buffer-constructor": "warn",
|
"no-buffer-constructor": "warn",
|
||||||
"no-caller": "warn",
|
"no-caller": "warn",
|
||||||
"no-console": "warn",
|
"no-console": "warn",
|
||||||
|
"no-constant-binary-expression": "error",
|
||||||
"no-div-regex": "warn",
|
"no-div-regex": "warn",
|
||||||
"no-dupe-else-if": "warn",
|
"no-dupe-else-if": "warn",
|
||||||
"no-duplicate-imports": "warn",
|
"no-duplicate-imports": "warn",
|
||||||
"no-else-return": "warn",
|
"no-else-return": "warn",
|
||||||
"no-empty-function": "warn",
|
"no-empty-function": "warn",
|
||||||
"no-eq-null": "warn",
|
"no-eq-null": "off",
|
||||||
"no-eval": "warn",
|
"no-eval": "warn",
|
||||||
"no-extend-native": "warn",
|
"no-extend-native": "warn",
|
||||||
"no-extra-bind": "warn",
|
"no-extra-bind": "warn",
|
||||||
@ -164,7 +192,15 @@
|
|||||||
"no-loop-func": "warn",
|
"no-loop-func": "warn",
|
||||||
"no-mixed-requires": "warn",
|
"no-mixed-requires": "warn",
|
||||||
"no-multi-assign": "warn",
|
"no-multi-assign": "warn",
|
||||||
"no-multi-spaces": "warn",
|
"no-multi-spaces": [
|
||||||
|
"warn",
|
||||||
|
{
|
||||||
|
"ignoreEOLComments": true,
|
||||||
|
"exceptions": {
|
||||||
|
"ImportDeclaration": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
"no-multi-str": "warn",
|
"no-multi-str": "warn",
|
||||||
"no-multiple-empty-lines": "warn",
|
"no-multiple-empty-lines": "warn",
|
||||||
"no-native-reassign": "warn",
|
"no-native-reassign": "warn",
|
||||||
@ -185,23 +221,25 @@
|
|||||||
"no-restricted-modules": "warn",
|
"no-restricted-modules": "warn",
|
||||||
"no-restricted-properties": "warn",
|
"no-restricted-properties": "warn",
|
||||||
"no-restricted-syntax": "warn",
|
"no-restricted-syntax": "warn",
|
||||||
"no-return-assign": "warn",
|
"no-return-assign": [
|
||||||
|
"warn",
|
||||||
|
"except-parens"
|
||||||
|
],
|
||||||
"no-return-await": "warn",
|
"no-return-await": "warn",
|
||||||
"no-script-url": "warn",
|
"no-script-url": "warn",
|
||||||
"no-self-compare": "warn",
|
"no-self-compare": "warn",
|
||||||
"no-sequences": "warn",
|
"no-sequences": "warn",
|
||||||
"no-setter-return": "warn",
|
"no-setter-return": "warn",
|
||||||
"no-spaced-func": "warn",
|
"no-spaced-func": "warn",
|
||||||
"@typescript-eslint/no-shadow": "error",
|
"no-tabs": "error",
|
||||||
"no-tabs": "warn",
|
|
||||||
"no-template-curly-in-string": "error",
|
"no-template-curly-in-string": "error",
|
||||||
"no-throw-literal": "warn",
|
"no-throw-literal": "warn",
|
||||||
|
"no-trailing-spaces": "warn",
|
||||||
"no-undef-init": "error",
|
"no-undef-init": "error",
|
||||||
"no-undefined": "error",
|
"no-undefined": "error",
|
||||||
"no-unmodified-loop-condition": "warn",
|
"no-unmodified-loop-condition": "warn",
|
||||||
"no-unneeded-ternary": "error",
|
"no-unneeded-ternary": "error",
|
||||||
"no-unused-expressions": "warn",
|
"no-unused-expressions": "warn",
|
||||||
"@typescript-eslint/no-use-before-define": "error",
|
|
||||||
"no-useless-call": "warn",
|
"no-useless-call": "warn",
|
||||||
"no-useless-computed-key": "warn",
|
"no-useless-computed-key": "warn",
|
||||||
"no-useless-concat": "warn",
|
"no-useless-concat": "warn",
|
||||||
@ -209,7 +247,6 @@
|
|||||||
"no-useless-rename": "warn",
|
"no-useless-rename": "warn",
|
||||||
"no-useless-return": "warn",
|
"no-useless-return": "warn",
|
||||||
"no-var": "warn",
|
"no-var": "warn",
|
||||||
// "no-void": "warn",
|
|
||||||
"no-whitespace-before-property": "error",
|
"no-whitespace-before-property": "error",
|
||||||
"nonblock-statement-body-position": [
|
"nonblock-statement-body-position": [
|
||||||
"warn",
|
"warn",
|
||||||
@ -293,6 +330,16 @@
|
|||||||
"yoda": [
|
"yoda": [
|
||||||
"warn",
|
"warn",
|
||||||
"never"
|
"never"
|
||||||
|
],
|
||||||
|
"no-warning-comments": [
|
||||||
|
1,
|
||||||
|
{
|
||||||
|
"terms": [
|
||||||
|
"todo",
|
||||||
|
"fixme"
|
||||||
|
],
|
||||||
|
"location": "anywhere"
|
||||||
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
}
|
}
|
893
.yarn/releases/yarn-4.1.1.cjs
vendored
893
.yarn/releases/yarn-4.1.1.cjs
vendored
File diff suppressed because one or more lines are too long
925
.yarn/releases/yarn-4.5.0.cjs
vendored
Executable file
925
.yarn/releases/yarn-4.5.0.cjs
vendored
Executable file
File diff suppressed because one or more lines are too long
@ -1,5 +1,5 @@
|
|||||||
nodeLinker: node-modules
|
nodeLinker: node-modules
|
||||||
|
|
||||||
yarnPath: .yarn/releases/yarn-4.1.1.cjs
|
|
||||||
|
|
||||||
npmRegistryServer: "https://registry.corgi.wtf"
|
npmRegistryServer: "https://registry.corgi.wtf"
|
||||||
|
|
||||||
|
yarnPath: .yarn/releases/yarn-4.5.0.cjs
|
||||||
|
@ -54,5 +54,5 @@
|
|||||||
"optional": true
|
"optional": true
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"packageManager": "yarn@4.1.1"
|
"packageManager": "yarn@4.5.0"
|
||||||
}
|
}
|
||||||
|
@ -6,7 +6,7 @@ import { ILogger, IServer } from './interfaces/index.js';
|
|||||||
|
|
||||||
const SAFE_TO_RETRY = [ 'ER_LOCK_DEADLOCK', 'PROTOCOL_CONNECTION_LOST' ];
|
const SAFE_TO_RETRY = [ 'ER_LOCK_DEADLOCK', 'PROTOCOL_CONNECTION_LOST' ];
|
||||||
|
|
||||||
type Credentials = {
|
interface Credentials {
|
||||||
user: string,
|
user: string,
|
||||||
password: string,
|
password: string,
|
||||||
host: string,
|
host: string,
|
||||||
@ -18,7 +18,7 @@ type ExtendedCredentials = {
|
|||||||
node: string
|
node: string
|
||||||
} & Credentials
|
} & Credentials
|
||||||
|
|
||||||
export type MariaOptions = {
|
export interface MariaOptions {
|
||||||
load?: boolean,
|
load?: boolean,
|
||||||
cluster?: PoolClusterConfig,
|
cluster?: PoolClusterConfig,
|
||||||
client?: PoolConfig,
|
client?: PoolConfig,
|
||||||
@ -40,7 +40,7 @@ type MariaError = {
|
|||||||
|
|
||||||
type Value = (string | number | null | boolean | object)
|
type Value = (string | number | null | boolean | object)
|
||||||
type Values = (Value | Value[] | Value[][])[];
|
type Values = (Value | Value[] | Value[][])[];
|
||||||
type QueryOptions = {
|
interface QueryOptions {
|
||||||
node?: string,
|
node?: string,
|
||||||
timeout?: number,
|
timeout?: number,
|
||||||
errorIfNodeUnavailable?: boolean
|
errorIfNodeUnavailable?: boolean
|
||||||
@ -54,14 +54,14 @@ type StatusString =
|
|||||||
| 'donor'
|
| 'donor'
|
||||||
| 'joiner'
|
| 'joiner'
|
||||||
| 'joined'
|
| 'joined'
|
||||||
type Node = {
|
interface Node {
|
||||||
name: string,
|
name: string,
|
||||||
host: string,
|
host: string,
|
||||||
uuid?: string,
|
uuid?: string,
|
||||||
status?: StatusString
|
status?: StatusString
|
||||||
}
|
}
|
||||||
|
|
||||||
type StatusUpdate = {
|
interface StatusUpdate {
|
||||||
status: StatusString,
|
status: StatusString,
|
||||||
uuid: string,
|
uuid: string,
|
||||||
primary: string,
|
primary: string,
|
||||||
@ -145,7 +145,7 @@ class MariaDB
|
|||||||
return this.#_activeQueries;
|
return this.#_activeQueries;
|
||||||
}
|
}
|
||||||
|
|
||||||
// eslint-disable-next-line max-lines-per-function
|
|
||||||
async init ()
|
async init ()
|
||||||
{
|
{
|
||||||
if (!this.#load)
|
if (!this.#load)
|
||||||
@ -197,13 +197,17 @@ class MariaDB
|
|||||||
await new Promise<void>((resolve, reject) =>
|
await new Promise<void>((resolve, reject) =>
|
||||||
{
|
{
|
||||||
if (!this.#pool)
|
if (!this.#pool)
|
||||||
return reject(new Error('Missing connection pool'));
|
{
|
||||||
|
reject(new Error('Missing connection pool')); return;
|
||||||
|
}
|
||||||
this.#pool.getConnection((err, conn) =>
|
this.#pool.getConnection((err, conn) =>
|
||||||
{
|
{
|
||||||
if (err)
|
if (err)
|
||||||
return reject(err);
|
{
|
||||||
|
reject(err); return;
|
||||||
|
}
|
||||||
conn.release();
|
conn.release();
|
||||||
return resolve();
|
resolve();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -274,7 +278,9 @@ class MariaDB
|
|||||||
return new Promise<void>(resolve =>
|
return new Promise<void>(resolve =>
|
||||||
{
|
{
|
||||||
if (!this.#pool)
|
if (!this.#pool)
|
||||||
return resolve();
|
{
|
||||||
|
resolve(); return;
|
||||||
|
}
|
||||||
this.#pool.end(() =>
|
this.#pool.end(() =>
|
||||||
{
|
{
|
||||||
this.#pool?.removeAllListeners();
|
this.#pool?.removeAllListeners();
|
||||||
@ -359,7 +365,9 @@ class MariaDB
|
|||||||
return new Promise((resolve, reject) =>
|
return new Promise((resolve, reject) =>
|
||||||
{
|
{
|
||||||
if (!this.#pool)
|
if (!this.#pool)
|
||||||
return reject(new Error('Pool closed'));
|
{
|
||||||
|
reject(new Error('Pool closed')); return;
|
||||||
|
}
|
||||||
// Get node by name
|
// Get node by name
|
||||||
const pool = this.#pool;
|
const pool = this.#pool;
|
||||||
if (nodeName)
|
if (nodeName)
|
||||||
@ -386,11 +394,13 @@ class MariaDB
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
this.#logger?.debug(`Selected node ${nodeName} for query`);
|
this.#logger?.debug(`Selected node ${nodeName} for query`);
|
||||||
return pool.of(nodeName ?? '*').getConnection((err, conn) =>
|
pool.of(nodeName ?? '*').getConnection((err, conn) =>
|
||||||
{
|
{
|
||||||
if (err)
|
if (err)
|
||||||
return reject(err);
|
{
|
||||||
return resolve(conn);
|
reject(err); return;
|
||||||
|
}
|
||||||
|
resolve(conn);
|
||||||
});
|
});
|
||||||
|
|
||||||
});
|
});
|
||||||
|
@ -2,15 +2,15 @@ import { ILogger, IServer } from './interfaces/index.js';
|
|||||||
import amqp, { AmqpConnectionManager, ChannelWrapper } from 'amqp-connection-manager';
|
import amqp, { AmqpConnectionManager, ChannelWrapper } from 'amqp-connection-manager';
|
||||||
import { Channel, ConfirmChannel, ConsumeMessage, Options } from 'amqplib';
|
import { Channel, ConfirmChannel, ConsumeMessage, Options } from 'amqplib';
|
||||||
|
|
||||||
type ExchangeDef = {
|
interface ExchangeDef {
|
||||||
durable?: boolean,
|
durable?: boolean,
|
||||||
internal?: boolean,
|
internal?: boolean,
|
||||||
autoDelete?: boolean,
|
autoDelete?: boolean,
|
||||||
type?: 'direct' | 'topic' | 'headers' | 'fanout' | 'match' | string,
|
type?: 'direct' | 'topic' | 'headers' | 'fanout' | 'match',
|
||||||
arguments?: object
|
arguments?: object
|
||||||
}
|
}
|
||||||
|
|
||||||
type QueueDef = {
|
interface QueueDef {
|
||||||
durable?: boolean,
|
durable?: boolean,
|
||||||
messageTtl?: number,
|
messageTtl?: number,
|
||||||
exclusive?: boolean,
|
exclusive?: boolean,
|
||||||
@ -22,22 +22,18 @@ type QueueDef = {
|
|||||||
maxPriority?: number
|
maxPriority?: number
|
||||||
}
|
}
|
||||||
|
|
||||||
export type BrokerOptions = {
|
export interface BrokerOptions {
|
||||||
load?: boolean,
|
load?: boolean,
|
||||||
host: string,
|
host: string,
|
||||||
port: number
|
port: number
|
||||||
user: string,
|
user: string,
|
||||||
pass: string,
|
pass: string,
|
||||||
vhost: string,
|
vhost: string,
|
||||||
exchanges?: {
|
exchanges?: Record<string, ExchangeDef>,
|
||||||
[key: string]: ExchangeDef
|
queues?: Record<string, QueueDef>
|
||||||
},
|
|
||||||
queues?: {
|
|
||||||
[key: string]: QueueDef
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type InternalMessage = {
|
interface InternalMessage {
|
||||||
properties: object,
|
properties: object,
|
||||||
content: object
|
content: object
|
||||||
}
|
}
|
||||||
@ -54,23 +50,21 @@ type InternalQueueMsg = {
|
|||||||
type Consumer<T = unknown> = (content: T, msg: ConsumeMessage) => Promise<void> | void
|
type Consumer<T = unknown> = (content: T, msg: ConsumeMessage) => Promise<void> | void
|
||||||
type Subscriber<T = unknown> = (content: T, msg: ConsumeMessage) => Promise<void> | void
|
type Subscriber<T = unknown> = (content: T, msg: ConsumeMessage) => Promise<void> | void
|
||||||
|
|
||||||
export type SubscriptionOptions = {
|
export interface SubscriptionOptions {
|
||||||
exchangeType?: 'direct' | 'topic' | 'headers' | 'fanout' | 'match',
|
exchangeType?: 'direct' | 'topic' | 'headers' | 'fanout' | 'match',
|
||||||
routingKey?: string
|
routingKey?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
class MessageBroker
|
class MessageBroker
|
||||||
{
|
{
|
||||||
|
|
||||||
// Broker definitions
|
|
||||||
#load: boolean;
|
#load: boolean;
|
||||||
#hosts: string[];
|
#hosts: string[];
|
||||||
#port: number;
|
#port: number;
|
||||||
#username: string;
|
#username: string;
|
||||||
#password: string;
|
#password: string;
|
||||||
#vhost: string;
|
#vhost: string;
|
||||||
#exchanges: { [key: string]: ExchangeDef };
|
#exchanges: Record<string, ExchangeDef>;
|
||||||
#queues: {[key: string]: QueueDef};
|
#queues: Record<string, QueueDef>;
|
||||||
|
|
||||||
// Wrapper related
|
// Wrapper related
|
||||||
#connection: AmqpConnectionManager | null;
|
#connection: AmqpConnectionManager | null;
|
||||||
@ -88,7 +82,6 @@ class MessageBroker
|
|||||||
|
|
||||||
constructor (server: IServer, options: BrokerOptions)
|
constructor (server: IServer, options: BrokerOptions)
|
||||||
{
|
{
|
||||||
|
|
||||||
this.#load = options.load ?? true;
|
this.#load = options.load ?? true;
|
||||||
this.#hosts = options.host.split(',');
|
this.#hosts = options.host.split(',');
|
||||||
this.#username = options.user;
|
this.#username = options.user;
|
||||||
@ -119,7 +112,6 @@ class MessageBroker
|
|||||||
this.#_pQueue = [];
|
this.#_pQueue = [];
|
||||||
this.#_qQueue = [];
|
this.#_qQueue = [];
|
||||||
this.#_qTO = null;
|
this.#_qTO = null;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async init ()
|
async init ()
|
||||||
@ -130,7 +122,7 @@ class MessageBroker
|
|||||||
this.#logger?.info('Initialising message broker');
|
this.#logger?.info('Initialising message broker');
|
||||||
const credentials = this.#username ? `${this.#username}:${this.#password}@` : '';
|
const credentials = this.#username ? `${this.#username}:${this.#password}@` : '';
|
||||||
const connectionStrings = this.#hosts.map(host => `amqp://${credentials}${host}:${this.#port}/${this.#vhost}`);
|
const connectionStrings = this.#hosts.map(host => `amqp://${credentials}${host}:${this.#port}/${this.#vhost}`);
|
||||||
this.#connection = await amqp.connect(connectionStrings);
|
this.#connection = amqp.connect(connectionStrings);
|
||||||
|
|
||||||
this.#connection.on('disconnect', async ({ err }) =>
|
this.#connection.on('disconnect', async ({ err }) =>
|
||||||
{
|
{
|
||||||
@ -163,24 +155,27 @@ class MessageBroker
|
|||||||
|
|
||||||
await this.createChannel();
|
await this.createChannel();
|
||||||
this.#connection.on('connect', this.createChannel.bind(this));
|
this.#connection.on('connect', this.createChannel.bind(this));
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async close ()
|
async close ()
|
||||||
{
|
{
|
||||||
|
this.#logger?.status('Closing broker');
|
||||||
if (this.#channel)
|
if (this.#channel)
|
||||||
{
|
{
|
||||||
await this.#channel.close();
|
this.#logger?.info('Closing channel');
|
||||||
this.#channel.removeAllListeners();
|
this.#channel.removeAllListeners();
|
||||||
|
await this.#channel.close();
|
||||||
}
|
}
|
||||||
if (this.#connection)
|
if (this.#connection)
|
||||||
{
|
{
|
||||||
|
this.#logger?.info('Closing connection');
|
||||||
await this.#connection.close();
|
await this.#connection.close();
|
||||||
// No clue why the removeAllListeners function isn't exposed from the connection manager, but it exists since it's an EventEmitter
|
// No clue why the removeAllListeners function isn't exposed from the connection manager, but it exists since it's an EventEmitter
|
||||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
this.#connection.removeAllListeners();
|
this.#connection.removeAllListeners();
|
||||||
}
|
}
|
||||||
|
this.#logger?.status('Broker closed');
|
||||||
}
|
}
|
||||||
|
|
||||||
async createChannel ()
|
async createChannel ()
|
||||||
@ -188,14 +183,16 @@ class MessageBroker
|
|||||||
const exchanges = Object.entries(this.#exchanges);
|
const exchanges = Object.entries(this.#exchanges);
|
||||||
const queues = Object.entries(this.#queues);
|
const queues = Object.entries(this.#queues);
|
||||||
|
|
||||||
|
if (!this.#connection)
|
||||||
|
throw new Error('Broker not connected');
|
||||||
|
|
||||||
if (this.#channel)
|
if (this.#channel)
|
||||||
{
|
{
|
||||||
this.#logger?.debug('Closing old channel');
|
this.#logger?.debug('Closing old channel');
|
||||||
|
this.#channel.removeAllListeners();
|
||||||
await this.#channel.close().catch(err => this.#logger?.error(err.stack));
|
await this.#channel.close().catch(err => this.#logger?.error(err.stack));
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!this.#connection)
|
|
||||||
throw new Error();
|
|
||||||
this.#logger?.debug('Creating channel');
|
this.#logger?.debug('Creating channel');
|
||||||
this.#channel = this.#connection.createChannel({
|
this.#channel = this.#connection.createChannel({
|
||||||
setup: async (channel: Channel | ConfirmChannel) =>
|
setup: async (channel: Channel | ConfirmChannel) =>
|
||||||
@ -218,7 +215,9 @@ class MessageBroker
|
|||||||
await new Promise<void>((resolve, reject) =>
|
await new Promise<void>((resolve, reject) =>
|
||||||
{
|
{
|
||||||
if (!this.#channel)
|
if (!this.#channel)
|
||||||
return reject(new Error('Missing channel?'));
|
{
|
||||||
|
reject(new Error('Missing channel?')); return;
|
||||||
|
}
|
||||||
this.#channel.once('connect', () =>
|
this.#channel.once('connect', () =>
|
||||||
{
|
{
|
||||||
this.#channel?.removeListener('error', reject);
|
this.#channel?.removeListener('error', reject);
|
||||||
@ -255,6 +254,7 @@ class MessageBroker
|
|||||||
return Promise.reject(new Error('Channel doesn\'t exist'));
|
return Promise.reject(new Error('Channel doesn\'t exist'));
|
||||||
await this.#channel.consume(queue, async (msg: ConsumeMessage) =>
|
await this.#channel.consume(queue, async (msg: ConsumeMessage) =>
|
||||||
{
|
{
|
||||||
|
this.#logger?.debug(`Consumer for ${queue} (${consumer.name}) fired`);
|
||||||
if (msg.content)
|
if (msg.content)
|
||||||
await consumer(JSON.parse(msg.content.toString()), msg);
|
await consumer(JSON.parse(msg.content.toString()), msg);
|
||||||
this.#channel?.ack(msg);
|
this.#channel?.ack(msg);
|
||||||
@ -276,7 +276,6 @@ class MessageBroker
|
|||||||
const list = this.#subscribers.get(name) ?? [];
|
const list = this.#subscribers.get(name) ?? [];
|
||||||
list.push({ subscriber, options });
|
list.push({ subscriber, options });
|
||||||
this.#subscribers.set(name, list);
|
this.#subscribers.set(name, list);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private async _subscribe<T> (name: string, listener: Subscriber<T>, options: SubscriptionOptions): Promise<void>
|
private async _subscribe<T> (name: string, listener: Subscriber<T>, options: SubscriptionOptions): Promise<void>
|
||||||
@ -291,6 +290,7 @@ class MessageBroker
|
|||||||
await this.#channel.bindQueue(queue.queue, name, options.routingKey ?? '');
|
await this.#channel.bindQueue(queue.queue, name, options.routingKey ?? '');
|
||||||
await this.#channel.consume(queue.queue, async (msg) =>
|
await this.#channel.consume(queue.queue, async (msg) =>
|
||||||
{
|
{
|
||||||
|
this.#logger?.debug(`Subscriber for ${name} (${listener.name}) fired`);
|
||||||
if (msg.content && msg.content.toString().startsWith('{'))
|
if (msg.content && msg.content.toString().startsWith('{'))
|
||||||
await listener(JSON.parse(msg.content.toString()), msg);
|
await listener(JSON.parse(msg.content.toString()), msg);
|
||||||
else
|
else
|
||||||
@ -304,6 +304,7 @@ class MessageBroker
|
|||||||
// Add item to queue
|
// Add item to queue
|
||||||
async enqueue (queue: string, content: object, headers?: object): Promise<void | number>
|
async enqueue (queue: string, content: object, headers?: object): Promise<void | number>
|
||||||
{
|
{
|
||||||
|
this.#logger?.debug(`Adding to queue ${queue}`);
|
||||||
const properties = {
|
const properties = {
|
||||||
persistent: true,
|
persistent: true,
|
||||||
contentType: 'application/json',
|
contentType: 'application/json',
|
||||||
@ -312,7 +313,10 @@ class MessageBroker
|
|||||||
|
|
||||||
// The channel is null while the failover is occurring, so enqueue messages for publishing once the connection is restored
|
// The channel is null while the failover is occurring, so enqueue messages for publishing once the connection is restored
|
||||||
if (!this.#channel)
|
if (!this.#channel)
|
||||||
|
{
|
||||||
|
this.#logger?.debug('Channel is missing, adding to internal queue');
|
||||||
return this.#_qQueue.push({ queue, content, properties });
|
return this.#_qQueue.push({ queue, content, properties });
|
||||||
|
}
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
@ -329,6 +333,7 @@ class MessageBroker
|
|||||||
// Publish to exchange
|
// Publish to exchange
|
||||||
async publish (exchange: string, content: object, { headers, routingKey = '' }: {headers?: string, routingKey?: string} = {}): Promise<void|number>
|
async publish (exchange: string, content: object, { headers, routingKey = '' }: {headers?: string, routingKey?: string} = {}): Promise<void|number>
|
||||||
{
|
{
|
||||||
|
this.#logger?.debug(`Publishing to ${exchange}`);
|
||||||
const properties = {
|
const properties = {
|
||||||
contentType: 'application/json',
|
contentType: 'application/json',
|
||||||
headers
|
headers
|
||||||
@ -336,7 +341,10 @@ class MessageBroker
|
|||||||
|
|
||||||
// The channel is null while the failover is occurring, so enqueue messages for publishing once the connection is restored
|
// The channel is null while the failover is occurring, so enqueue messages for publishing once the connection is restored
|
||||||
if (!this.#channel)
|
if (!this.#channel)
|
||||||
|
{
|
||||||
|
this.#logger?.debug('Channel is missing, adding to internal queue');
|
||||||
return this.#_pQueue.push({ exchange, content, routingKey, properties });
|
return this.#_pQueue.push({ exchange, content, routingKey, properties });
|
||||||
|
}
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
|
@ -2,7 +2,7 @@ import { inspect } from 'node:util';
|
|||||||
import { MongoClient, MongoClientOptions, Db, Document, WithId, ObjectId, Filter, IndexSpecification, CreateIndexesOptions, FindOptions, ModifyResult, DistinctOptions } from 'mongodb';
|
import { MongoClient, MongoClientOptions, Db, Document, WithId, ObjectId, Filter, IndexSpecification, CreateIndexesOptions, FindOptions, ModifyResult, DistinctOptions } from 'mongodb';
|
||||||
import { IServer, ILogger } from './interfaces/index.js';
|
import { IServer, ILogger } from './interfaces/index.js';
|
||||||
|
|
||||||
type Credentials = {
|
interface Credentials {
|
||||||
URI?: string,
|
URI?: string,
|
||||||
user?: string,
|
user?: string,
|
||||||
password?: string,
|
password?: string,
|
||||||
@ -12,12 +12,12 @@ type Credentials = {
|
|||||||
authDb?: string
|
authDb?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
type MongoQuery = {
|
interface MongoQuery {
|
||||||
_id?: unknown,
|
_id?: unknown,
|
||||||
[key: string]: unknown
|
[key: string]: unknown
|
||||||
}
|
}
|
||||||
|
|
||||||
export type MongoOptions = {
|
export interface MongoOptions {
|
||||||
credentials: Credentials,
|
credentials: Credentials,
|
||||||
loggerOptions?: object,
|
loggerOptions?: object,
|
||||||
client?: MongoClientOptions,
|
client?: MongoClientOptions,
|
||||||
@ -26,7 +26,7 @@ export type MongoOptions = {
|
|||||||
metricsBuckets?: number[],
|
metricsBuckets?: number[],
|
||||||
}
|
}
|
||||||
|
|
||||||
type StringIndexable = {[key: string]: boolean | string | number | Document | object}
|
type StringIndexable = Record<string, boolean | string | number | Document | object>;
|
||||||
|
|
||||||
const objIsSubset = (superObj: StringIndexable, subObj: StringIndexable): boolean =>
|
const objIsSubset = (superObj: StringIndexable, subObj: StringIndexable): boolean =>
|
||||||
{
|
{
|
||||||
@ -67,7 +67,7 @@ class MongoDB
|
|||||||
throw new Error('No config options provided!');
|
throw new Error('No config options provided!');
|
||||||
|
|
||||||
const { user, password, host, port, database, URI, authDb } = config.credentials;
|
const { user, password, host, port, database, URI, authDb } = config.credentials;
|
||||||
if ((!host?.length || !port || !database?.length) && !URI)
|
if ((!host?.length || !port || !database.length) && !URI)
|
||||||
throw new Error('Must provide host, port, and database OR URI parameters!');
|
throw new Error('Must provide host, port, and database OR URI parameters!');
|
||||||
|
|
||||||
this.#config = config;
|
this.#config = config;
|
||||||
|
Loading…
Reference in New Issue
Block a user