@venizia/ignis-helpers 0.4.8-11 → 0.4.8-13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. package/dist/esm/common/types/field-mapping.d.ts +6 -6
  2. package/dist/esm/common/types/field-mapping.js.map +1 -1
  3. package/dist/esm/modules/network/http-request/fetcher/axios-fetcher.d.ts +1 -1
  4. package/dist/esm/modules/network/http-request/fetcher/axios-fetcher.js.map +1 -1
  5. package/dist/esm/modules/network/http-request/fetcher/base-fetcher.d.ts +1 -1
  6. package/dist/esm/modules/network/http-request/fetcher/base-fetcher.js.map +1 -1
  7. package/dist/esm/modules/network/tcp-socket/base-tcp-client.helper.d.ts +4 -4
  8. package/dist/esm/modules/network/tcp-socket/base-tcp-client.helper.js +1 -1
  9. package/dist/esm/modules/network/tcp-socket/base-tcp-client.helper.js.map +1 -1
  10. package/dist/esm/modules/network/tcp-socket/base-tcp-server.helper.d.ts +3 -3
  11. package/dist/esm/modules/network/tcp-socket/base-tcp-server.helper.js.map +1 -1
  12. package/dist/esm/modules/queue/bullmq/helper.d.ts +14 -1
  13. package/dist/esm/modules/queue/bullmq/helper.js +52 -3
  14. package/dist/esm/modules/queue/bullmq/helper.js.map +1 -1
  15. package/dist/esm/modules/redis/base/abstract.helper.js +7 -1
  16. package/dist/esm/modules/redis/base/abstract.helper.js.map +1 -1
  17. package/dist/esm/modules/redis/common/types.d.ts +2 -0
  18. package/dist/esm/modules/redis/common/types.js.map +1 -1
  19. package/dist/esm/modules/redis/single/single.helper.js +2 -1
  20. package/dist/esm/modules/redis/single/single.helper.js.map +1 -1
  21. package/dist/esm/modules/socket/socket-io/client/browser-helper.js.map +1 -1
  22. package/dist/esm/modules/socket/socket-io/common/types/client.d.ts +2 -2
  23. package/dist/esm/modules/socket/socket-io/common/types/client.js.map +1 -1
  24. package/dist/esm/modules/socket/socket-io/common/types/server.d.ts +3 -1
  25. package/dist/esm/modules/socket/socket-io/common/types/server.js.map +1 -1
  26. package/dist/esm/modules/socket/socket-io/server/helper.d.ts +2 -2
  27. package/dist/esm/modules/socket/socket-io/server/helper.js.map +1 -1
  28. package/dist/esm/utilities/request.utility.d.ts +9 -11
  29. package/dist/esm/utilities/request.utility.js.map +1 -1
  30. package/package.json +3 -3
@@ -23,28 +23,28 @@ export type TFieldMappingNames<T extends Array<IFieldMapping>> = Extract<T[numbe
23
23
  export type TObjectFromFieldMappings<T extends readonly {
24
24
  name: string;
25
25
  type: string;
26
- [extra: string | symbol]: any;
26
+ [extra: string | symbol]: unknown;
27
27
  }[]> = {
28
28
  [K in T[number]['name']]: T extends {
29
29
  name: K;
30
30
  type: 'string';
31
- [extra: string | symbol]: any;
31
+ [extra: string | symbol]: unknown;
32
32
  } ? string : T extends {
33
33
  name: K;
34
34
  type: 'number';
35
- [extra: string | symbol]: any;
35
+ [extra: string | symbol]: unknown;
36
36
  } ? number : T extends {
37
37
  name: K;
38
38
  type: 'boolean';
39
- [extra: string | symbol]: any;
39
+ [extra: string | symbol]: unknown;
40
40
  } ? boolean : T extends {
41
41
  name: K;
42
42
  type: 'strings';
43
- [extra: string | symbol]: any;
43
+ [extra: string | symbol]: unknown;
44
44
  } ? string[] : T extends {
45
45
  name: K;
46
46
  type: 'numbers';
47
- [extra: string | symbol]: any;
47
+ [extra: string | symbol]: unknown;
48
48
  } ? number[] : never;
49
49
  };
50
50
  //# sourceMappingURL=field-mapping.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"field-mapping.js","sourceRoot":"","sources":["../../../../src/common/types/field-mapping.ts"],"names":[],"mappings":"AAEA,6CAA6C;AAC7C,MAAM,OAAO,qBAAqB;aAChB,WAAM,GAAG,QAAQ,CAAC;aAClB,WAAM,GAAG,QAAQ,CAAC;aAClB,YAAO,GAAG,SAAS,CAAC;aACpB,YAAO,GAAG,SAAS,CAAC;aACpB,YAAO,GAAG,SAAS,CAAC","sourcesContent":["import type { TConstValue } from './const-value';\n\n/** The value kinds a field mapping reads. */\nexport class FieldMappingDataTypes {\n static readonly STRING = 'string';\n static readonly NUMBER = 'number';\n static readonly STRINGS = 'strings';\n static readonly NUMBERS = 'numbers';\n static readonly BOOLEAN = 'boolean';\n}\n\n/** Valid field mapping data type values. */\nexport type TFieldMappingDataType = TConstValue<typeof FieldMappingDataTypes>;\n\n/** Describes one field to read: its `name`, its value `type`, and an optional `default`. */\nexport interface IFieldMapping {\n name: string;\n type: TFieldMappingDataType;\n default?: string | number | Array<string> | Array<number> | boolean;\n}\n\n/** The union of `name` values in a list of field mappings. */\nexport type TFieldMappingNames<T extends Array<IFieldMapping>> = Extract<\n T[number],\n { type: Exclude<T[number]['type'], undefined> }\n>['name'];\n\n/** The object a list of field mappings yields: one key per `name`, typed from its `type` (`string`, `number`, `boolean`, `strings` or `numbers`). Needs the list typed as a literal (`as const`) to narrow. */\nexport type TObjectFromFieldMappings<\n T extends readonly {\n name: string;\n type: string;\n [extra: string | symbol]: any;\n }[],\n> = {\n [K in T[number]['name']]: T extends {\n name: K;\n type: 'string';\n [extra: string | symbol]: any;\n }\n ? string\n : T extends { name: K; type: 'number'; [extra: string | symbol]: any }\n ? number\n : T extends { name: K; type: 'boolean'; [extra: string | symbol]: any }\n ? boolean\n : T extends { name: K; type: 'strings'; [extra: string | symbol]: any }\n ? string[]\n : T extends {\n name: K;\n type: 'numbers';\n [extra: string | symbol]: any;\n }\n ? number[]\n : never;\n};\n"]}
1
+ {"version":3,"file":"field-mapping.js","sourceRoot":"","sources":["../../../../src/common/types/field-mapping.ts"],"names":[],"mappings":"AAEA,6CAA6C;AAC7C,MAAM,OAAO,qBAAqB;aAChB,WAAM,GAAG,QAAQ,CAAC;aAClB,WAAM,GAAG,QAAQ,CAAC;aAClB,YAAO,GAAG,SAAS,CAAC;aACpB,YAAO,GAAG,SAAS,CAAC;aACpB,YAAO,GAAG,SAAS,CAAC","sourcesContent":["import type { TConstValue } from './const-value';\n\n/** The value kinds a field mapping reads. */\nexport class FieldMappingDataTypes {\n static readonly STRING = 'string';\n static readonly NUMBER = 'number';\n static readonly STRINGS = 'strings';\n static readonly NUMBERS = 'numbers';\n static readonly BOOLEAN = 'boolean';\n}\n\n/** Valid field mapping data type values. */\nexport type TFieldMappingDataType = TConstValue<typeof FieldMappingDataTypes>;\n\n/** Describes one field to read: its `name`, its value `type`, and an optional `default`. */\nexport interface IFieldMapping {\n name: string;\n type: TFieldMappingDataType;\n default?: string | number | Array<string> | Array<number> | boolean;\n}\n\n/** The union of `name` values in a list of field mappings. */\nexport type TFieldMappingNames<T extends Array<IFieldMapping>> = Extract<\n T[number],\n { type: Exclude<T[number]['type'], undefined> }\n>['name'];\n\n/** The object a list of field mappings yields: one key per `name`, typed from its `type` (`string`, `number`, `boolean`, `strings` or `numbers`). Needs the list typed as a literal (`as const`) to narrow. */\nexport type TObjectFromFieldMappings<\n T extends readonly {\n name: string;\n type: string;\n [extra: string | symbol]: unknown;\n }[],\n> = {\n [K in T[number]['name']]: T extends {\n name: K;\n type: 'string';\n [extra: string | symbol]: unknown;\n }\n ? string\n : T extends { name: K; type: 'number'; [extra: string | symbol]: unknown }\n ? number\n : T extends { name: K; type: 'boolean'; [extra: string | symbol]: unknown }\n ? boolean\n : T extends { name: K; type: 'strings'; [extra: string | symbol]: unknown }\n ? string[]\n : T extends {\n name: K;\n type: 'numbers';\n [extra: string | symbol]: unknown;\n }\n ? number[]\n : never;\n};\n"]}
@@ -33,7 +33,7 @@ export declare class AxiosFetcher extends AbstractNetworkFetchableHelper<'axios'
33
33
  */
34
34
  rejectUnauthorized?: boolean;
35
35
  });
36
- send<T = any>(opts: IAxiosRequestOptions, logger?: ILogger): Promise<AxiosResponse<T, any, {}, any>>;
36
+ send<T = unknown>(opts: IAxiosRequestOptions, logger?: ILogger): Promise<AxiosResponse<T, any, {}, any>>;
37
37
  }
38
38
  /** Options of `AxiosNetworkRequest`: an axios config with `baseUrl` in place of `baseURL`. */
39
39
  export interface IAxiosNetworkRequestOptions {
@@ -1 +1 @@
1
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,iCAAiC;YACnD,GAAG,OAAO;SACX,CAAC;QAEF,MAAM,cAAc,GAAuB;YACzC,eAAe,EAAE,IAAI;YACrB,cAAc,EAAE,CAAC,MAAc,EAAE,EAAE,CAAC,MAAM,GAAG,GAAG;YAChD,OAAO,EAAE,OAAO,IAAI,EAAE,GAAG,IAAI;YAC7B,GAAG,IAAI;YACP,OAAO,EAAE,OAAO;YAChB,OAAO,EAAE,aAAa;SACvB,CAAC;QAEF,KAAK,CAAC;YACJ,IAAI;YACJ,OAAO;YACP,OAAO,EAAE,IAAI,YAAY,CAAC,EAAE,IAAI,EAAE,cAAc,EAAE,CAAC;SACpD,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["import { type AnyObject, HTTP, type THttpMethod } from '@/common';\nimport { RedactUtility } from '@/common/redact';\nimport axios, { type AxiosInstance, type AxiosRequestConfig, type AxiosResponse } from 'axios';\nimport https from 'node:https';\nimport { stringify } from 'node:querystring';\nimport { BaseNetworkRequest } from '../base-network-request.helper';\nimport type { ILogger } from '@/modules/logger/common/types';\nimport { AbstractNetworkFetchableHelper, type IRequestOptions } from './base-fetcher';\n\n/** Request accepted by `AxiosFetcher`: an axios config where `body` is sent as the axios `data`. `rejectUnauthorized` set here overrides the instance setting for this call. */\nexport interface IAxiosRequestOptions extends AxiosRequestConfig, IRequestOptions {\n url: string;\n method?: THttpMethod;\n params?: AnyObject;\n body?: AnyObject;\n headers?: AnyObject;\n /** Whether this call rejects an HTTPS server whose certificate fails verification; `false` turns verification off for this call. */\n rejectUnauthorized?: boolean;\n}\n\n/** Fetcher over an axios instance (`getWorker()`). HTTPS calls share one keep-alive agent that verifies certificates unless `rejectUnauthorized` is `false`; an `httpsAgent` passed in the request wins. */\nexport class AxiosFetcher extends AbstractNetworkFetchableHelper<\n 'axios',\n IAxiosRequestOptions,\n // The named type, not the `axios.` NAMESPACE: the namespace form resolves only under node16\n // module resolution, and this package also emits an ESM build under `bundler` resolution.\n AxiosResponse<any, any>['data'],\n AxiosInstance\n> {\n /**\n * One agent for the instance, not one per request. Built here so TLS verification is decided\n * ONCE, at construction, rather than per call - and so connections are actually reused: a fresh\n * agent per request forces a new TCP and TLS handshake every time (measured: 10 handshakes for 10\n * requests, versus 1).\n */\n private readonly httpsAgent: https.Agent;\n\n constructor(opts: {\n name: string;\n defaultConfigs: AxiosRequestConfig;\n logger?: ILogger;\n /**\n * Whether this instance rejects an HTTPS server whose certificate fails verification.\n * `false` turns verification off.\n * @default true\n */\n rejectUnauthorized?: boolean;\n }) {\n super({ name: opts.name, variant: 'axios' });\n const { defaultConfigs } = opts;\n opts?.logger?.info('Creating new network request worker instance! Name: %s', this.name);\n\n this.httpsAgent = new https.Agent({\n keepAlive: true,\n rejectUnauthorized: opts.rejectUnauthorized ?? true,\n });\n\n this.worker = axios.create({ ...defaultConfigs });\n }\n\n override send<T = any>(opts: IAxiosRequestOptions, logger?: ILogger) {\n const { url, method = HTTP.Methods.GET, params = {}, body: data, headers, ...rest } = opts;\n const props: AxiosRequestConfig = {\n url,\n method: method.toUpperCase(),\n params,\n data,\n headers,\n paramsSerializer: { serialize: (p) => stringify(p) },\n ...rest,\n };\n\n const protocol = this.getProtocol(url);\n\n if (protocol === HTTP.Protocols.HTTPS) {\n // A caller's own agent WINS. The previous code assigned after the `...rest` spread, so a\n // hardened agent - custom CA, pinning, mTLS - was overwritten and the secure path was\n // unreachable through the public seam.\n props.httpsAgent =\n rest.httpsAgent ??\n (opts.rejectUnauthorized === undefined\n ? this.httpsAgent\n : new https.Agent({ keepAlive: true, rejectUnauthorized: opts.rejectUnauthorized }));\n }\n\n logger\n ?.for(this.send.name)\n .info('URL: %s | Props: %s', url, RedactUtility.redactSecrets({ value: props }));\n\n return this.worker.request<T>(props);\n }\n}\n\n/** Options of `AxiosNetworkRequest`: an axios config with `baseUrl` in place of `baseURL`. */\nexport interface IAxiosNetworkRequestOptions {\n name: string;\n networkOptions: Omit<AxiosRequestConfig, 'baseURL'> & {\n baseUrl?: string;\n };\n}\n\n/** `BaseNetworkRequest` over an `AxiosFetcher`. Defaults: JSON content type, 60000 ms `timeout`, and no rejection for status below 500 (`validateStatus`). */\nexport class AxiosNetworkRequest extends BaseNetworkRequest<'axios'> {\n constructor(opts: IAxiosNetworkRequestOptions) {\n const { name, networkOptions } = opts;\n const { headers, baseUrl, timeout, ...rest } = networkOptions;\n\n const mergedHeaders: AnyObject = {\n ['content-type']: 'application/json; charset=utf-8',\n ...headers,\n };\n\n const defaultConfigs: AxiosRequestConfig = {\n withCredentials: true,\n validateStatus: (status: number) => status < 500,\n timeout: timeout ?? 60 * 1000,\n ...rest,\n baseURL: baseUrl,\n headers: mergedHeaders,\n };\n\n super({\n name,\n baseUrl,\n fetcher: new AxiosFetcher({ name, defaultConfigs }),\n });\n }\n}\n"]}
1
+ {"version":3,"file":"axios-fetcher.js","sourceRoot":"","sources":["../../../../../../src/modules/network/http-request/fetcher/axios-fetcher.ts"],"names":[],"mappings":"AAAA,OAAO,EAAkB,IAAI,EAAoB,MAAM,UAAU,CAAC;AAClE,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAChD,OAAO,KAA0E,MAAM,OAAO,CAAC;AAC/F,OAAO,KAAK,MAAM,YAAY,CAAC;AAC/B,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,kBAAkB,EAAE,MAAM,gCAAgC,CAAC;AAEpE,OAAO,EAAE,8BAA8B,EAAwB,MAAM,gBAAgB,CAAC;AAatF,4MAA4M;AAC5M,MAAM,OAAO,YAAa,SAAQ,8BAOjC;IASC,YAAY,IAUX;QACC,KAAK,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC,CAAC;QAC7C,MAAM,EAAE,cAAc,EAAE,GAAG,IAAI,CAAC;QAChC,IAAI,EAAE,MAAM,EAAE,IAAI,CAAC,wDAAwD,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC;QAExF,IAAI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;aACpB,IAAI,CAAC,qBAAqB,EAAE,GAAG,EAAE,aAAa,CAAC,aAAa,CAAC,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC;QAEnF,OAAO,IAAI,CAAC,MAAM,CAAC,OAAO,CAAI,KAAK,CAAC,CAAC;IACvC,CAAC;CACF;AAUD,8JAA8J;AAC9J,MAAM,OAAO,mBAAoB,SAAQ,kBAA2B;IAClE,YAAY,IAAiC;QAC3C,MAAM,EAAE,IAAI,EAAE,cAAc,EAAE,GAAG,IAAI,CAAC;QACtC,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,GAAG,IAAI,EAAE,GAAG,cAAc,CAAC;QAE9D,MAAM,aAAa,GAAc;YAC/B,CAAC,cAAc,CAAC,EAAE,iCAAiC;YACnD,GAAG,OAAO;SACX,CAAC;QAEF,MAAM,cAAc,GAAuB;YACzC,eAAe,EAAE,IAAI;YACrB,cAAc,EAAE,CAAC,MAAc,EAAE,EAAE,CAAC,MAAM,GAAG,GAAG;YAChD,OAAO,EAAE,OAAO,IAAI,EAAE,GAAG,IAAI;YAC7B,GAAG,IAAI;YACP,OAAO,EAAE,OAAO;YAChB,OAAO,EAAE,aAAa;SACvB,CAAC;QAEF,KAAK,CAAC;YACJ,IAAI;YACJ,OAAO;YACP,OAAO,EAAE,IAAI,YAAY,CAAC,EAAE,IAAI,EAAE,cAAc,EAAE,CAAC;SACpD,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["import { type AnyObject, HTTP, type THttpMethod } from '@/common';\nimport { RedactUtility } from '@/common/redact';\nimport axios, { type AxiosInstance, type AxiosRequestConfig, type AxiosResponse } from 'axios';\nimport https from 'node:https';\nimport { stringify } from 'node:querystring';\nimport { BaseNetworkRequest } from '../base-network-request.helper';\nimport type { ILogger } from '@/modules/logger/common/types';\nimport { AbstractNetworkFetchableHelper, type IRequestOptions } from './base-fetcher';\n\n/** Request accepted by `AxiosFetcher`: an axios config where `body` is sent as the axios `data`. `rejectUnauthorized` set here overrides the instance setting for this call. */\nexport interface IAxiosRequestOptions extends AxiosRequestConfig, IRequestOptions {\n url: string;\n method?: THttpMethod;\n params?: AnyObject;\n body?: AnyObject;\n headers?: AnyObject;\n /** Whether this call rejects an HTTPS server whose certificate fails verification; `false` turns verification off for this call. */\n rejectUnauthorized?: boolean;\n}\n\n/** Fetcher over an axios instance (`getWorker()`). HTTPS calls share one keep-alive agent that verifies certificates unless `rejectUnauthorized` is `false`; an `httpsAgent` passed in the request wins. */\nexport class AxiosFetcher extends AbstractNetworkFetchableHelper<\n 'axios',\n IAxiosRequestOptions,\n // The named type, not the `axios.` NAMESPACE: the namespace form resolves only under node16\n // module resolution, and this package also emits an ESM build under `bundler` resolution.\n AxiosResponse<any, any>['data'],\n AxiosInstance\n> {\n /**\n * One agent for the instance, not one per request. Built here so TLS verification is decided\n * ONCE, at construction, rather than per call - and so connections are actually reused: a fresh\n * agent per request forces a new TCP and TLS handshake every time (measured: 10 handshakes for 10\n * requests, versus 1).\n */\n private readonly httpsAgent: https.Agent;\n\n constructor(opts: {\n name: string;\n defaultConfigs: AxiosRequestConfig;\n logger?: ILogger;\n /**\n * Whether this instance rejects an HTTPS server whose certificate fails verification.\n * `false` turns verification off.\n * @default true\n */\n rejectUnauthorized?: boolean;\n }) {\n super({ name: opts.name, variant: 'axios' });\n const { defaultConfigs } = opts;\n opts?.logger?.info('Creating new network request worker instance! Name: %s', this.name);\n\n this.httpsAgent = new https.Agent({\n keepAlive: true,\n rejectUnauthorized: opts.rejectUnauthorized ?? true,\n });\n\n this.worker = axios.create({ ...defaultConfigs });\n }\n\n override send<T = unknown>(opts: IAxiosRequestOptions, logger?: ILogger) {\n const { url, method = HTTP.Methods.GET, params = {}, body: data, headers, ...rest } = opts;\n const props: AxiosRequestConfig = {\n url,\n method: method.toUpperCase(),\n params,\n data,\n headers,\n paramsSerializer: { serialize: (p) => stringify(p) },\n ...rest,\n };\n\n const protocol = this.getProtocol(url);\n\n if (protocol === HTTP.Protocols.HTTPS) {\n // A caller's own agent WINS. The previous code assigned after the `...rest` spread, so a\n // hardened agent - custom CA, pinning, mTLS - was overwritten and the secure path was\n // unreachable through the public seam.\n props.httpsAgent =\n rest.httpsAgent ??\n (opts.rejectUnauthorized === undefined\n ? this.httpsAgent\n : new https.Agent({ keepAlive: true, rejectUnauthorized: opts.rejectUnauthorized }));\n }\n\n logger\n ?.for(this.send.name)\n .info('URL: %s | Props: %s', url, RedactUtility.redactSecrets({ value: props }));\n\n return this.worker.request<T>(props);\n }\n}\n\n/** Options of `AxiosNetworkRequest`: an axios config with `baseUrl` in place of `baseURL`. */\nexport interface IAxiosNetworkRequestOptions {\n name: string;\n networkOptions: Omit<AxiosRequestConfig, 'baseURL'> & {\n baseUrl?: string;\n };\n}\n\n/** `BaseNetworkRequest` over an `AxiosFetcher`. Defaults: JSON content type, 60000 ms `timeout`, and no rejection for status below 500 (`validateStatus`). */\nexport class AxiosNetworkRequest extends BaseNetworkRequest<'axios'> {\n constructor(opts: IAxiosNetworkRequestOptions) {\n const { name, networkOptions } = opts;\n const { headers, baseUrl, timeout, ...rest } = networkOptions;\n\n const mergedHeaders: AnyObject = {\n ['content-type']: 'application/json; charset=utf-8',\n ...headers,\n };\n\n const defaultConfigs: AxiosRequestConfig = {\n withCredentials: true,\n validateStatus: (status: number) => status < 500,\n timeout: timeout ?? 60 * 1000,\n ...rest,\n baseURL: baseUrl,\n headers: mergedHeaders,\n };\n\n super({\n name,\n baseUrl,\n fetcher: new AxiosFetcher({ name, defaultConfigs }),\n });\n }\n}\n"]}
@@ -10,7 +10,7 @@ export interface IRequestOptions {
10
10
  method?: THttpMethod;
11
11
  params?: AnyObject;
12
12
  timeout?: number;
13
- [extra: symbol | string]: any;
13
+ [extra: symbol | string]: unknown;
14
14
  }
15
15
  /** Contract of an HTTP fetcher: `send` takes the method from the options, the verb methods fix it, and `getWorker` returns the underlying client (`W`). */
16
16
  export interface IFetchable<V extends TFetcherVariant, RQ extends IRequestOptions, RS, W = unknown> {
@@ -1 +1 @@
1
- {"version":3,"file":"base-fetcher.js","sourceRoot":"","sources":["../../../../../../src/modules/network/http-request/fetcher/base-fetcher.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAoB,MAAM,yBAAyB,CAAC;AAsCjE,yNAAyN;AACzN,MAAM,OAAgB,8BAA8B;IAUlD,YAAY,IAA8C;QACxD,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC;QACtB,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC;QAE5B,IAAI,IAAI,CAAC,MAAM,KAAK,SAAS,EAAE,CAAC;YAC9B,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC;QAC5B,CAAC;IACH,CAAC;IAID,WAAW,CAAC,GAAW;QACrB,OAAO,GAAG,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC;IAC9E,CAAC;IAED,UAAU;QACR,OAAO,IAAI,CAAC,OAAO,CAAC;IACtB,CAAC;IAED,SAAS;QACP,OAAO,IAAI,CAAC,MAAM,CAAC;IACrB,CAAC;IAED,GAAG,CAAC,IAAQ,EAAE,MAAuB;QACnC,MAAM,EAAE,GAAG,IAAI,EAAE,GAAG,IAAI,CAAC;QAEzB,OAAO,IAAI,CAAC,IAAI,CAAC,EAAE,GAAG,IAAI,EAAE,MAAM,EAAE,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,MAAM,CAAC,CAAC;IAClE,CAAC;IAED,IAAI,CAAC,IAAQ,EAAE,MAAuB;QACpC,MAAM,EAAE,GAAG,IAAI,EAAE,GAAG,IAAI,CAAC;QAEzB,OAAO,IAAI,CAAC,IAAI,CAAC,EAAE,GAAG,IAAI,EAAE,MAAM,EAAE,IAAI,CAAC,OAAO,CAAC,IAAI,EAAE,EAAE,MAAM,CAAC,CAAC;IACnE,CAAC;IAED,GAAG,CAAC,IAAQ,EAAE,MAAuB;QACnC,MAAM,EAAE,GAAG,IAAI,EAAE,GAAG,IAAI,CAAC;QAEzB,OAAO,IAAI,CAAC,IAAI,CAAC,EAAE,GAAG,IAAI,EAAE,MAAM,EAAE,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,MAAM,CAAC,CAAC;IAClE,CAAC;IAED,KAAK,CAAC,IAAQ,EAAE,MAAuB;QACrC,MAAM,EAAE,GAAG,IAAI,EAAE,GAAG,IAAI,CAAC;QAEzB,OAAO,IAAI,CAAC,IAAI,CAAC,EAAE,GAAG,IAAI,EAAE,MAAM,EAAE,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,MAAM,CAAC,CAAC;IACpE,CAAC;IAED,MAAM,CAAC,IAAQ,EAAE,MAAuB;QACtC,MAAM,EAAE,GAAG,IAAI,EAAE,GAAG,IAAI,CAAC;QAEzB,OAAO,IAAI,CAAC,IAAI,CAAC,EAAE,GAAG,IAAI,EAAE,MAAM,EAAE,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,MAAM,CAAC,CAAC;IACrE,CAAC;IAED,KAAK,CAAC,IAAQ,EAAE,MAAuB;QACrC,MAAM,EAAE,GAAG,IAAI,EAAE,GAAG,IAAI,CAAC;QAEzB,OAAO,IAAI,CAAC,IAAI,CAAC,EAAE,GAAG,IAAI,EAAE,MAAM,EAAE,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,MAAM,CAAC,CAAC;IACpE,CAAC;CACF","sourcesContent":["import { HTTP, type THttpMethod } from '@/common/constants/http';\nimport { type AnyObject } from '@/common/types';\n// The leaf file, never the logger BARREL: that barrel reaches `node:module` and would drag this\n// browser-pure fetcher contract with it.\nimport type { ILogger } from '@/modules/logger/common/types';\nimport { type TFetcherVariant } from '../common';\n\n/** What a fetcher calls on the logger it is handed, so a host logger with only these two (a browser app's) is accepted as is. */\nexport type TFetcherLogger = Pick<ILogger, 'debug' | 'info'>;\n\n/** Options every fetcher accepts. `timeout` is in milliseconds; other keys pass through to the underlying client. */\nexport interface IRequestOptions {\n url: string;\n method?: THttpMethod;\n params?: AnyObject;\n timeout?: number;\n [extra: symbol | string]: any;\n}\n\n/** Contract of an HTTP fetcher: `send` takes the method from the options, the verb methods fix it, and `getWorker` returns the underlying client (`W`). */\nexport interface IFetchable<\n V extends TFetcherVariant,\n RQ extends IRequestOptions,\n RS,\n W = unknown,\n> {\n send(opts: RQ, logger?: TFetcherLogger): Promise<RS>;\n get(opts: RQ, logger?: TFetcherLogger): Promise<RS>;\n post(opts: RQ, logger?: TFetcherLogger): Promise<RS>;\n put(opts: RQ, logger?: TFetcherLogger): Promise<RS>;\n patch(opts: RQ, logger?: TFetcherLogger): Promise<RS>;\n delete(opts: RQ, logger?: TFetcherLogger): Promise<RS>;\n query(opts: RQ, logger?: TFetcherLogger): Promise<RS>;\n\n getVariant(): V;\n getWorker(): W;\n}\n\n/** `W` defaults to `unknown` so this stays free of `axios` - a concrete fetcher binds it to its real worker type (`AxiosInstance`, `typeof fetch`), which is then inherited on `this.worker` with no override needed. */\nexport abstract class AbstractNetworkFetchableHelper<\n V extends TFetcherVariant,\n RQ extends IRequestOptions,\n RS,\n W = unknown,\n> implements IFetchable<V, RQ, RS, W> {\n protected name: string;\n protected variant: V;\n protected worker: W;\n\n constructor(opts: { name: string; variant: V; worker?: W }) {\n this.name = opts.name;\n this.variant = opts.variant;\n\n if (opts.worker !== undefined) {\n this.worker = opts.worker;\n }\n }\n\n abstract send(opts: RQ, logger?: TFetcherLogger): Promise<RS>;\n\n getProtocol(url: string) {\n return url.startsWith('http:') ? HTTP.Protocols.HTTP : HTTP.Protocols.HTTPS;\n }\n\n getVariant() {\n return this.variant;\n }\n\n getWorker(): W {\n return this.worker;\n }\n\n get(opts: RQ, logger?: TFetcherLogger) {\n const { ...rest } = opts;\n\n return this.send({ ...rest, method: HTTP.Methods.GET }, logger);\n }\n\n post(opts: RQ, logger?: TFetcherLogger) {\n const { ...rest } = opts;\n\n return this.send({ ...rest, method: HTTP.Methods.POST }, logger);\n }\n\n put(opts: RQ, logger?: TFetcherLogger) {\n const { ...rest } = opts;\n\n return this.send({ ...rest, method: HTTP.Methods.PUT }, logger);\n }\n\n patch(opts: RQ, logger?: TFetcherLogger) {\n const { ...rest } = opts;\n\n return this.send({ ...rest, method: HTTP.Methods.PATCH }, logger);\n }\n\n delete(opts: RQ, logger?: TFetcherLogger) {\n const { ...rest } = opts;\n\n return this.send({ ...rest, method: HTTP.Methods.DELETE }, logger);\n }\n\n query(opts: RQ, logger?: TFetcherLogger) {\n const { ...rest } = opts;\n\n return this.send({ ...rest, method: HTTP.Methods.QUERY }, logger);\n }\n}\n"]}
1
+ {"version":3,"file":"base-fetcher.js","sourceRoot":"","sources":["../../../../../../src/modules/network/http-request/fetcher/base-fetcher.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAoB,MAAM,yBAAyB,CAAC;AAsCjE,yNAAyN;AACzN,MAAM,OAAgB,8BAA8B;IAUlD,YAAY,IAA8C;QACxD,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC;QACtB,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC;QAE5B,IAAI,IAAI,CAAC,MAAM,KAAK,SAAS,EAAE,CAAC;YAC9B,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC;QAC5B,CAAC;IACH,CAAC;IAID,WAAW,CAAC,GAAW;QACrB,OAAO,GAAG,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC;IAC9E,CAAC;IAED,UAAU;QACR,OAAO,IAAI,CAAC,OAAO,CAAC;IACtB,CAAC;IAED,SAAS;QACP,OAAO,IAAI,CAAC,MAAM,CAAC;IACrB,CAAC;IA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EAAE,GAAG,IAAI,EAAE,GAAG,IAAI,CAAC;QAEzB,OAAO,IAAI,CAAC,IAAI,CAAC,EAAE,GAAG,IAAI,EAAE,MAAM,EAAE,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,MAAM,CAAC,CAAC;IACpE,CAAC;CACF","sourcesContent":["import { HTTP, type THttpMethod } from '@/common/constants/http';\nimport { type AnyObject } from '@/common/types';\n// The leaf file, never the logger BARREL: that barrel reaches `node:module` and would drag this\n// browser-pure fetcher contract with it.\nimport type { ILogger } from '@/modules/logger/common/types';\nimport { type TFetcherVariant } from '../common';\n\n/** What a fetcher calls on the logger it is handed, so a host logger with only these two (a browser app's) is accepted as is. */\nexport type TFetcherLogger = Pick<ILogger, 'debug' | 'info'>;\n\n/** Options every fetcher accepts. `timeout` is in milliseconds; other keys pass through to the underlying client. */\nexport interface IRequestOptions {\n url: string;\n method?: THttpMethod;\n params?: AnyObject;\n timeout?: number;\n [extra: symbol | string]: unknown;\n}\n\n/** Contract of an HTTP fetcher: `send` takes the method from the options, the verb methods fix it, and `getWorker` returns the underlying client (`W`). */\nexport interface IFetchable<\n V extends TFetcherVariant,\n RQ extends IRequestOptions,\n RS,\n W = unknown,\n> {\n send(opts: RQ, logger?: TFetcherLogger): Promise<RS>;\n get(opts: RQ, logger?: TFetcherLogger): Promise<RS>;\n post(opts: RQ, logger?: TFetcherLogger): Promise<RS>;\n put(opts: RQ, logger?: TFetcherLogger): Promise<RS>;\n patch(opts: RQ, logger?: TFetcherLogger): Promise<RS>;\n delete(opts: RQ, logger?: TFetcherLogger): Promise<RS>;\n query(opts: RQ, logger?: TFetcherLogger): Promise<RS>;\n\n getVariant(): V;\n getWorker(): W;\n}\n\n/** `W` defaults to `unknown` so this stays free of `axios` - a concrete fetcher binds it to its real worker type (`AxiosInstance`, `typeof fetch`), which is then inherited on `this.worker` with no override needed. */\nexport abstract class AbstractNetworkFetchableHelper<\n V extends TFetcherVariant,\n RQ extends IRequestOptions,\n RS,\n W = unknown,\n> implements IFetchable<V, RQ, RS, W> {\n protected name: string;\n protected variant: V;\n protected worker: W;\n\n constructor(opts: { name: string; variant: V; worker?: W }) {\n this.name = opts.name;\n this.variant = opts.variant;\n\n if (opts.worker !== undefined) {\n this.worker = opts.worker;\n }\n }\n\n abstract send(opts: RQ, logger?: TFetcherLogger): Promise<RS>;\n\n getProtocol(url: string) {\n return url.startsWith('http:') ? HTTP.Protocols.HTTP : HTTP.Protocols.HTTPS;\n }\n\n getVariant() {\n return this.variant;\n }\n\n getWorker(): W {\n return this.worker;\n }\n\n get(opts: RQ, logger?: TFetcherLogger) {\n const { ...rest } = opts;\n\n return this.send({ ...rest, method: HTTP.Methods.GET }, logger);\n }\n\n post(opts: RQ, logger?: TFetcherLogger) {\n const { ...rest } = opts;\n\n return this.send({ ...rest, method: HTTP.Methods.POST }, logger);\n }\n\n put(opts: RQ, logger?: TFetcherLogger) {\n const { ...rest } = opts;\n\n return this.send({ ...rest, method: HTTP.Methods.PUT }, logger);\n }\n\n patch(opts: RQ, logger?: TFetcherLogger) {\n const { ...rest } = opts;\n\n return this.send({ ...rest, method: HTTP.Methods.PATCH }, logger);\n }\n\n delete(opts: RQ, logger?: TFetcherLogger) {\n const { ...rest } = opts;\n\n return this.send({ ...rest, method: HTTP.Methods.DELETE }, logger);\n }\n\n query(opts: RQ, logger?: TFetcherLogger) {\n const { ...rest } = opts;\n\n return this.send({ ...rest, method: HTTP.Methods.QUERY }, logger);\n }\n}\n"]}
@@ -30,7 +30,7 @@ export interface INetworkTcpClientProps<SocketClientOptions extends PlainConnect
30
30
  onClosed?: (opts: {
31
31
  client: SocketClientType;
32
32
  }) => void;
33
- onError?: (error: any) => void;
33
+ onError?: (error: unknown) => void;
34
34
  }
35
35
  /** TCP or TLS client that opens its socket through `createClientFn`, reports connect, data, close and error to the `on*` callbacks, and reconnects when enabled. */
36
36
  export declare class BaseNetworkTcpClient<SocketClientOptions extends PlainConnectionOptions | TlsConnectionOptions, SocketClientType extends PlainSocketClient | TlsSocketClient> extends BaseHelper {
@@ -41,7 +41,7 @@ export declare class BaseNetworkTcpClient<SocketClientOptions extends PlainConne
41
41
  maxReconnect: number;
42
42
  currentReconnect: number;
43
43
  };
44
- protected reconnectTimeout: any;
44
+ protected reconnectTimeout?: ReturnType<typeof setTimeout> | null;
45
45
  protected encoding?: BufferEncoding;
46
46
  protected createClientFn: (options: SocketClientOptions, connectionListener?: () => void) => SocketClientType;
47
47
  protected onConnected: (opts: {
@@ -54,7 +54,7 @@ export declare class BaseNetworkTcpClient<SocketClientOptions extends PlainConne
54
54
  protected onClosed?: (opts: {
55
55
  client: SocketClientType;
56
56
  }) => void;
57
- protected onError?: (error: any) => void;
57
+ protected onError?: (error: unknown) => void;
58
58
  constructor(opts: INetworkTcpClientProps<SocketClientOptions, SocketClientType>);
59
59
  getClient(): SocketClientType | null | undefined;
60
60
  /** Redacts before logging - a TLS client's options ARE its private key (`key`/`cert`/`passphrase`). */
@@ -65,7 +65,7 @@ export declare class BaseNetworkTcpClient<SocketClientOptions extends PlainConne
65
65
  message: string | Buffer;
66
66
  }): void;
67
67
  handleClosed(): void;
68
- handleError(error: any): void;
68
+ handleError(error: unknown): void;
69
69
  connect(opts: {
70
70
  resetReconnectCounter: boolean;
71
71
  }): void;
@@ -119,7 +119,7 @@ export class BaseNetworkTcpClient extends BaseHelper {
119
119
  }
120
120
  this.client?.destroy();
121
121
  this.client = null;
122
- clearTimeout(this.reconnectTimeout);
122
+ clearTimeout(this.reconnectTimeout ?? undefined);
123
123
  this.reconnectTimeout = null;
124
124
  this.logger
125
125
  .for(this.disconnect.name)
@@ -1 +1 @@
1
- {"version":3,"file":"base-tcp-client.helper.js","sourceRoot":"","sources":["../../../../../src/modules/network/tcp-socket/base-tcp-client.helper.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AACzD,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAChD,OAAO,EAAE,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import { RedactUtility } from '@/common/redact';\nimport { BaseHelper } from '@/modules/base';\nimport { type ValueOrPromise } from '@/common';\nimport {\n type TcpSocketConnectOpts as PlainConnectionOptions,\n type Socket as PlainSocketClient,\n} from 'node:net';\nimport {\n type ConnectionOptions as TlsConnectionOptions,\n type TLSSocket as TlsSocketClient,\n} from 'node:tls';\n\nconst DEFAULT_MAX_RETRY = 5;\n\n/** Options of a TCP client. `createClientFn` opens the socket, so one client type serves plain and TLS. */\nexport interface INetworkTcpClientProps<\n SocketClientOptions extends PlainConnectionOptions | TlsConnectionOptions,\n SocketClientType extends PlainSocketClient | TlsSocketClient,\n> {\n identifier: string;\n scope?: string;\n\n options: SocketClientOptions;\n /**\n * Retries after a close, up to `maxRetry` times.\n * @default false\n */\n reconnect?: boolean;\n /**\n * How many reconnects `reconnect` attempts.\n * @default 5\n */\n maxRetry?: number;\n /** When set, `onData` receives strings in this encoding instead of buffers. */\n encoding?: BufferEncoding;\n\n createClientFn: (\n options: SocketClientOptions,\n connectionListener?: () => void,\n ) => SocketClientType;\n\n onConnected?: (opts: { client: SocketClientType }) => ValueOrPromise<void>;\n onData?: (opts: { identifier: string; message: string | Buffer }) => ValueOrPromise<void>;\n onClosed?: (opts: { client: SocketClientType }) => void;\n onError?: (error: any) => void;\n}\n\n/** TCP or TLS client that opens its socket through `createClientFn`, reports connect, data, close and error to the `on*` callbacks, and reconnects when enabled. */\nexport class BaseNetworkTcpClient<\n SocketClientOptions extends PlainConnectionOptions | TlsConnectionOptions,\n SocketClientType extends PlainSocketClient | TlsSocketClient,\n> extends BaseHelper {\n protected client?: SocketClientType | null;\n\n protected options: SocketClientOptions;\n protected reconnect?: boolean;\n protected retry: { maxReconnect: number; currentReconnect: number } = {\n maxReconnect: DEFAULT_MAX_RETRY,\n currentReconnect: 0,\n };\n\n protected reconnectTimeout: any;\n protected encoding?: BufferEncoding;\n\n protected createClientFn: (\n options: SocketClientOptions,\n connectionListener?: () => void,\n ) => SocketClientType;\n\n protected onConnected: (opts: { client: SocketClientType }) => void;\n protected onData: (opts: { identifier: string; message: string | Buffer }) => void;\n protected onClosed?: (opts: { client: SocketClientType }) => void;\n protected onError?: (error: any) => void;\n\n constructor(opts: INetworkTcpClientProps<SocketClientOptions, SocketClientType>) {\n super({\n scope: opts.scope ?? opts.identifier ?? BaseNetworkTcpClient.name,\n identifier: opts.identifier,\n });\n this.options = opts.options;\n\n this.retry = {\n maxReconnect: opts.maxRetry ?? DEFAULT_MAX_RETRY,\n currentReconnect: 0,\n };\n\n this.createClientFn = opts.createClientFn;\n\n this.onConnected = opts?.onConnected ?? this.handleConnected;\n this.onData = opts?.onData ?? this.handleData;\n this.onClosed = opts?.onClosed ?? this.handleClosed;\n this.onError = opts?.onError ?? this.handleError;\n this.reconnect = opts?.reconnect ?? false;\n this.encoding = opts?.encoding;\n }\n\n getClient() {\n return this.client;\n }\n\n /** Redacts before logging - a TLS client's options ARE its private key (`key`/`cert`/`passphrase`). */\n protected getLoggableOptions(): unknown {\n return RedactUtility.redactSecrets({ value: this.options });\n }\n\n handleConnected() {\n this.logger\n .for(this.handleConnected.name)\n .info(\n '[%s] Connected to TCP Server | Options: %j',\n this.identifier,\n this.getLoggableOptions(),\n );\n this.retry.currentReconnect = 0;\n }\n\n handleData(_opts: { identifier: string; message: string | Buffer }) {}\n\n handleClosed() {\n this.logger\n .for(this.handleClosed.name)\n .info(\n '[%s] Closed connection TCP Server | Options: %j',\n this.identifier,\n this.getLoggableOptions(),\n );\n }\n\n handleError(error: any) {\n this.logger\n .for(this.handleError.name)\n .error(\n '[%s] Connection error | Options: %j | Error: %s',\n this.identifier,\n this.getLoggableOptions(),\n error,\n );\n\n if (!this.reconnect || this.retry.currentReconnect >= this.retry.maxReconnect) {\n return;\n }\n\n const { currentReconnect, maxReconnect } = this.retry;\n\n if (maxReconnect > -1 && currentReconnect >= maxReconnect) {\n this.logger\n .for(this.handleData.name)\n .info(\n 'Exceeded max retry to reconnect! Max: %d | Current: %d',\n maxReconnect,\n currentReconnect,\n );\n\n return;\n }\n\n this.reconnectTimeout = setTimeout(() => {\n this.client?.destroy();\n this.client = null;\n\n this.logger\n .for(this.handleClosed.name)\n .info(\n '[%s] Retrying to establish TCP Connection | Options: %j',\n this.identifier,\n this.getLoggableOptions(),\n );\n\n this.connect({ resetReconnectCounter: false });\n this.retry.currentReconnect++;\n }, 5000);\n }\n\n connect(opts: { resetReconnectCounter: boolean }) {\n if (this.isConnected()) {\n this.logger\n .for(this.connect.name)\n .info('[%s] NetworkTcpClient is already initialized!', this.identifier);\n\n return;\n }\n\n if (ObjectUtility.isEmpty({ value: this.options })) {\n this.logger\n .for(this.connect.name)\n .info('[%s] Cannot init TCP Client with null options', this.identifier);\n\n return;\n }\n\n this.logger\n .for(this.connect.name)\n .info(\n '[%s] New network tcp client | Options: %j',\n this.identifier,\n this.getLoggableOptions(),\n );\n\n if (opts?.resetReconnectCounter) {\n this.retry.currentReconnect = 0;\n }\n\n if (this.client !== null && this.client !== undefined) {\n this.client?.destroy();\n this.client = null;\n }\n\n // The listeners close over THIS socket: `this.client` is nulled by disconnect() and swapped by a reconnect, so reading it back would drop the close hook - or hand it the wrong socket.\n const client = this.createClientFn(this.options, () => {\n this.onConnected?.({ client });\n });\n\n this.client = client;\n\n if (this.encoding) {\n client.setEncoding(this.encoding);\n }\n\n client.on('data', (message: string | Buffer) => {\n this.onData({ identifier: this.identifier, message });\n });\n\n client.on('close', () => {\n this.onClosed?.({ client });\n });\n\n client.on('error', (error) => {\n this.onError?.(error);\n });\n }\n\n disconnect() {\n if (!this.client) {\n this.logger\n .for(this.disconnect.name)\n .info('[%s] NetworkTcpClient is not initialized yet!', this.identifier);\n\n return;\n }\n\n this.client?.destroy();\n this.client = null;\n\n clearTimeout(this.reconnectTimeout);\n this.reconnectTimeout = null;\n this.logger\n .for(this.disconnect.name)\n .info('[%s] NetworkTcpClient is destroyed!', this.identifier);\n }\n\n forceReconnect() {\n this.disconnect();\n this.connect({ resetReconnectCounter: true });\n }\n\n isConnected() {\n return this.client && this.client.readyState !== 'closed';\n }\n\n emit(opts: { payload: Buffer | string }) {\n if (!this.client) {\n this.logger\n .for(this.emit.name)\n .info('[%s] TPC Client is not configured yet!', this.identifier);\n\n return;\n }\n\n const { payload } = opts;\n\n if (!payload?.length) {\n this.logger\n .for(this.emit.name)\n .info('[%s] Invalid payload to write to TCP Socket!', this.identifier);\n\n return;\n }\n\n this.client.write(payload);\n }\n}\n"]}
1
+ {"version":3,"file":"base-tcp-client.helper.js","sourceRoot":"","sources":["../../../../../src/modules/network/tcp-socket/base-tcp-client.helper.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AACzD,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAChD,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAW5C,MAAM,iBAAiB,GAAG,CAAC,CAAC;AAmC5B,oKAAoK;AACpK,MAAM,OAAO,oBAGX,SAAQ,UAAU;IAuBlB,YAAY,IAAmE;QAC7E,KAAK,CAAC;YACJ,KAAK,EAAE,IAAI,CAAC,KAAK,IAAI,IAAI,CAAC,UAAU,IAAI,oBAAoB,CAAC,IAAI;YACjE,UAAU,EAAE,IAAI,CAAC,UAAU;SAC5B,CAAC,CAAC;QAtBK,UAAK,GAAuD;YACpE,YAAY,EAAE,iBAAiB;YAC/B,gBAAgB,EAAE,CAAC;SACpB,CAAC;QAoBA,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC;QAE5B,IAAI,CAAC,KAAK,GAAG;YACX,YAAY,EAAE,IAAI,CAAC,QAAQ,IAAI,iBAAiB;YAChD,gBAAgB,EAAE,CAAC;SACpB,CAAC;QAEF,IAAI,CAAC,cAAc,GAAG,IAAI,CAAC,cAAc,CAAC;QAE1C,IAAI,CAAC,WAAW,GAAG,IAAI,EAAE,WAAW,IAAI,IAAI,CAAC,eAAe,CAAC;QAC7D,IAAI,CAAC,MAAM,GAA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AC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC;iBACnB,IAAI,CAAC,wCAAwC,EAAE,IAAI,CAAC,UAAU,CAAC,CAAC;YAEnE,OAAO;QACT,CAAC;QAED,MAAM,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC;QAEzB,IAAI,CAAC,OAAO,EAAE,MAAM,EAAE,CAAC;YACrB,IAAI,CAAC,MAAM;iBACR,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC;iBACnB,IAAI,CAAC,8CAA8C,EAAE,IAAI,CAAC,UAAU,CAAC,CAAC;YAEzE,OAAO;QACT,CAAC;QAED,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;IAC7B,CAAC;CACF","sourcesContent":["import { ObjectUtility } from '@venizia/ignis-inversion';\nimport { RedactUtility } from '@/common/redact';\nimport { BaseHelper } from '@/modules/base';\nimport { type ValueOrPromise } from '@/common';\nimport {\n type TcpSocketConnectOpts as PlainConnectionOptions,\n type Socket as PlainSocketClient,\n} from 'node:net';\nimport {\n type ConnectionOptions as TlsConnectionOptions,\n type TLSSocket as TlsSocketClient,\n} from 'node:tls';\n\nconst DEFAULT_MAX_RETRY = 5;\n\n/** Options of a TCP client. `createClientFn` opens the socket, so one client type serves plain and TLS. */\nexport interface INetworkTcpClientProps<\n SocketClientOptions extends PlainConnectionOptions | TlsConnectionOptions,\n SocketClientType extends PlainSocketClient | TlsSocketClient,\n> {\n identifier: string;\n scope?: string;\n\n options: SocketClientOptions;\n /**\n * Retries after a close, up to `maxRetry` times.\n * @default false\n */\n reconnect?: boolean;\n /**\n * How many reconnects `reconnect` attempts.\n * @default 5\n */\n maxRetry?: number;\n /** When set, `onData` receives strings in this encoding instead of buffers. */\n encoding?: BufferEncoding;\n\n createClientFn: (\n options: SocketClientOptions,\n connectionListener?: () => void,\n ) => SocketClientType;\n\n onConnected?: (opts: { client: SocketClientType }) => ValueOrPromise<void>;\n onData?: (opts: { identifier: string; message: string | Buffer }) => ValueOrPromise<void>;\n onClosed?: (opts: { client: SocketClientType }) => void;\n onError?: (error: unknown) => void;\n}\n\n/** TCP or TLS client that opens its socket through `createClientFn`, reports connect, data, close and error to the `on*` callbacks, and reconnects when enabled. */\nexport class BaseNetworkTcpClient<\n SocketClientOptions extends PlainConnectionOptions | TlsConnectionOptions,\n SocketClientType extends PlainSocketClient | TlsSocketClient,\n> extends BaseHelper {\n protected client?: SocketClientType | null;\n\n protected options: SocketClientOptions;\n protected reconnect?: boolean;\n protected retry: { maxReconnect: number; currentReconnect: number } = {\n maxReconnect: DEFAULT_MAX_RETRY,\n currentReconnect: 0,\n };\n\n protected reconnectTimeout?: ReturnType<typeof setTimeout> | null;\n protected encoding?: BufferEncoding;\n\n protected createClientFn: (\n options: SocketClientOptions,\n connectionListener?: () => void,\n ) => SocketClientType;\n\n protected onConnected: (opts: { client: SocketClientType }) => void;\n protected onData: (opts: { identifier: string; message: string | Buffer }) => void;\n protected onClosed?: (opts: { client: SocketClientType }) => void;\n protected onError?: (error: unknown) => void;\n\n constructor(opts: INetworkTcpClientProps<SocketClientOptions, SocketClientType>) {\n super({\n scope: opts.scope ?? opts.identifier ?? BaseNetworkTcpClient.name,\n identifier: opts.identifier,\n });\n this.options = opts.options;\n\n this.retry = {\n maxReconnect: opts.maxRetry ?? DEFAULT_MAX_RETRY,\n currentReconnect: 0,\n };\n\n this.createClientFn = opts.createClientFn;\n\n this.onConnected = opts?.onConnected ?? this.handleConnected;\n this.onData = opts?.onData ?? this.handleData;\n this.onClosed = opts?.onClosed ?? this.handleClosed;\n this.onError = opts?.onError ?? this.handleError;\n this.reconnect = opts?.reconnect ?? false;\n this.encoding = opts?.encoding;\n }\n\n getClient() {\n return this.client;\n }\n\n /** Redacts before logging - a TLS client's options ARE its private key (`key`/`cert`/`passphrase`). */\n protected getLoggableOptions(): unknown {\n return RedactUtility.redactSecrets({ value: this.options });\n }\n\n handleConnected() {\n this.logger\n .for(this.handleConnected.name)\n .info(\n '[%s] Connected to TCP Server | Options: %j',\n this.identifier,\n this.getLoggableOptions(),\n );\n this.retry.currentReconnect = 0;\n }\n\n handleData(_opts: { identifier: string; message: string | Buffer }) {}\n\n handleClosed() {\n this.logger\n .for(this.handleClosed.name)\n .info(\n '[%s] Closed connection TCP Server | Options: %j',\n this.identifier,\n this.getLoggableOptions(),\n );\n }\n\n handleError(error: unknown) {\n this.logger\n .for(this.handleError.name)\n .error(\n '[%s] Connection error | Options: %j | Error: %s',\n this.identifier,\n this.getLoggableOptions(),\n error,\n );\n\n if (!this.reconnect || this.retry.currentReconnect >= this.retry.maxReconnect) {\n return;\n }\n\n const { currentReconnect, maxReconnect } = this.retry;\n\n if (maxReconnect > -1 && currentReconnect >= maxReconnect) {\n this.logger\n .for(this.handleData.name)\n .info(\n 'Exceeded max retry to reconnect! Max: %d | Current: %d',\n maxReconnect,\n currentReconnect,\n );\n\n return;\n }\n\n this.reconnectTimeout = setTimeout(() => {\n this.client?.destroy();\n this.client = null;\n\n this.logger\n .for(this.handleClosed.name)\n .info(\n '[%s] Retrying to establish TCP Connection | Options: %j',\n this.identifier,\n this.getLoggableOptions(),\n );\n\n this.connect({ resetReconnectCounter: false });\n this.retry.currentReconnect++;\n }, 5000);\n }\n\n connect(opts: { resetReconnectCounter: boolean }) {\n if (this.isConnected()) {\n this.logger\n .for(this.connect.name)\n .info('[%s] NetworkTcpClient is already initialized!', this.identifier);\n\n return;\n }\n\n if (ObjectUtility.isEmpty({ value: this.options })) {\n this.logger\n .for(this.connect.name)\n .info('[%s] Cannot init TCP Client with null options', this.identifier);\n\n return;\n }\n\n this.logger\n .for(this.connect.name)\n .info(\n '[%s] New network tcp client | Options: %j',\n this.identifier,\n this.getLoggableOptions(),\n );\n\n if (opts?.resetReconnectCounter) {\n this.retry.currentReconnect = 0;\n }\n\n if (this.client !== null && this.client !== undefined) {\n this.client?.destroy();\n this.client = null;\n }\n\n // The listeners close over THIS socket: `this.client` is nulled by disconnect() and swapped by a reconnect, so reading it back would drop the close hook - or hand it the wrong socket.\n const client = this.createClientFn(this.options, () => {\n this.onConnected?.({ client });\n });\n\n this.client = client;\n\n if (this.encoding) {\n client.setEncoding(this.encoding);\n }\n\n client.on('data', (message: string | Buffer) => {\n this.onData({ identifier: this.identifier, message });\n });\n\n client.on('close', () => {\n this.onClosed?.({ client });\n });\n\n client.on('error', (error) => {\n this.onError?.(error);\n });\n }\n\n disconnect() {\n if (!this.client) {\n this.logger\n .for(this.disconnect.name)\n .info('[%s] NetworkTcpClient is not initialized yet!', this.identifier);\n\n return;\n }\n\n this.client?.destroy();\n this.client = null;\n\n clearTimeout(this.reconnectTimeout ?? undefined);\n this.reconnectTimeout = null;\n this.logger\n .for(this.disconnect.name)\n .info('[%s] NetworkTcpClient is destroyed!', this.identifier);\n }\n\n forceReconnect() {\n this.disconnect();\n this.connect({ resetReconnectCounter: true });\n }\n\n isConnected() {\n return this.client && this.client.readyState !== 'closed';\n }\n\n emit(opts: { payload: Buffer | string }) {\n if (!this.client) {\n this.logger\n .for(this.emit.name)\n .info('[%s] TPC Client is not configured yet!', this.identifier);\n\n return;\n }\n\n const { payload } = opts;\n\n if (!payload?.length) {\n this.logger\n .for(this.emit.name)\n .info('[%s] Invalid payload to write to TCP Socket!', this.identifier);\n\n return;\n }\n\n this.client.write(payload);\n }\n}\n"]}
@@ -20,7 +20,7 @@ export interface ITcpSocketClient<SocketClientType> {
20
20
  connectedAt: Date;
21
21
  authenticatedAt: Date | null;
22
22
  authenticateTimeout?: ReturnType<typeof setTimeout> | null;
23
- [additionField: symbol | string]: any;
23
+ [additionField: symbol | string]: unknown;
24
24
  };
25
25
  }
26
26
  /** Options of `BaseNetworkTcpServer`. With `authenticateOptions.required`, `duration` (milliseconds, greater than 0) is how long a client has to authenticate before its socket is ended; the constructor throws without it. `createServerFn` builds the server, so one class serves plain and TLS. */
@@ -36,7 +36,7 @@ export interface ITcpSocketServerOptions<SocketServerOptions extends ServerOpts
36
36
  extraEvents?: Record<string, (opts: {
37
37
  id: string;
38
38
  socket: SocketClientType;
39
- args: any;
39
+ args: unknown;
40
40
  }) => ValueOrPromise<void>>;
41
41
  createServerFn: (options: Partial<SocketServerOptions>, connectionListener: (socket: SocketClientType) => void) => SocketServerType;
42
42
  onServerReady?: (opts: {
@@ -78,7 +78,7 @@ export declare class BaseNetworkTcpServer<SocketServerOptions extends ServerOpts
78
78
  protected extraEvents: Record<string, (opts: {
79
79
  id: string;
80
80
  socket: SocketClientType;
81
- args: any;
81
+ args: unknown;
82
82
  }) => ValueOrPromise<void>>;
83
83
  protected createServerFn: (options: Partial<SocketServerOptions>, connectionListener: (socket: SocketClientType) => void) => SocketServerType;
84
84
  protected onServerReady?: (opts: {
@@ -1 +1 @@
1
- {"version":3,"file":"base-tcp-server.helper.js","sourceRoot":"","sources":["../../../../../src/modules/network/tcp-socket/base-tcp-server.helper.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAC5C,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AACzD,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC;AAQ7D,6DAA6D;AAC7D,MAAM,OAAO,eAAe;aACV,iBAAY,GAAG,cAAc,CAAC;aAC9B,mBAAc,GAAG,gBAAgB,CAAC;aAClC,kBAAa,GAAG,eAAe,CAAC;;AAmDlD,iLAAiL;AACjL,MAAM,OAAO,oBAIX,SAAQ,UAAU;IA8BlB,YACE,IAAsF;QAEtF,KAAK,CAAC;YACJ,KAAK,EAAE,IAAI,CAAC,KAAK,IAAI,IAAI,CAAC,UAAU,IAAI,oBAAoB,CAAC,IAAI;YACjE,UAAU,EAAE,IAAI,CAAC,UAAU;SAC5B,CAAC,CAAC;QAnCK,kBAAa,GAAiC,EAAE,CAAC;QACjD,kBAAa,GAA2B,EAAE,CAAC;QAoCnD,oFAAoF;QACpF,IAAI,CAAC,O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AAC,CAAC,CAAC;gBACR,MAAM;YACR,CAAC;QACH,CAAC;IACH,CAAC;IAED,IAAI,CAAC,IAAoD;QACvD,MAAM,EAAE,QAAQ,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC;QACnC,MAAM,MAAM,GAAG,IAAI,CAAC,SAAS,CAAC,EAAE,EAAE,EAAE,QAAQ,EAAE,CAAC,CAAC;QAEhD,IAAI,CAAC,MAAM,EAAE,CAAC;YACZ,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,KAAK,CAAC,2BAA2B,EAAE,QAAQ,CAAC,CAAC;YAE7E,OAAO;QACT,CAAC;QAED,MAAM,EAAE,MAAM,EAAE,GAAG,MAAM,CAAC;QAE1B,IAAI,CAAC,MAAM,CAAC,QAAQ,EAAE,CAAC;YACrB,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,KAAK,CAAC,8BAA8B,EAAE,QAAQ,CAAC,CAAC;YAEhF,OAAO;QACT,CAAC;QAED,IAAI,CAAC,OAAO,EAAE,MAAM,EAAE,CAAC;YACrB,IAAI,CAAC,MAAM;iBACR,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC;iBACnB,IAAI,CACH,0DAA0D,EAC1D,IAAI,CAAC,UAAU,EACf,QAAQ,CACT,CAAC;YAEJ,OAAO;QACT,CAAC;QAED,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;IACxB,CAAC;CACF","sourcesContent":["import type { TConstValue } from '@/common/types';\nimport { type ValueOrPromise } from '@/common/types';\nimport { BaseHelper } from '@/modules/base';\nimport { getError } from '@/modules/error';\nimport { ParseUtility } from '@/utilities/parse.utility';\nimport { PromiseUtility } from '@/utilities/promise.utility';\nimport {\n type ListenOptions,\n type ServerOpts,\n type Socket as SocketClient,\n type Server as SocketServer,\n} from 'node:net';\n\n/** Where a TCP client is in the authentication handshake. */\nexport class TcpClientStates {\n static readonly UNAUTHORIZED = 'unauthorized';\n static readonly AUTHENTICATING = 'authenticating';\n static readonly AUTHENTICATED = 'authenticated';\n}\n\n/** Valid TCP client state values. */\nexport type TTcpClientState = TConstValue<typeof TcpClientStates>;\n\n/** A client connected to `BaseNetworkTcpServer`: its `id`, `socket`, authentication `state`, `subscriptions` and `storage` (connect and authenticate times, the pending authenticate timer). */\nexport interface ITcpSocketClient<SocketClientType> {\n id: string;\n socket: SocketClientType;\n state: TTcpClientState;\n subscriptions: Set<string>;\n storage: {\n connectedAt: Date;\n authenticatedAt: Date | null;\n authenticateTimeout?: ReturnType<typeof setTimeout> | null;\n [additionField: symbol | string]: any;\n };\n}\n\n/** Options of `BaseNetworkTcpServer`. With `authenticateOptions.required`, `duration` (milliseconds, greater than 0) is how long a client has to authenticate before its socket is ended; the constructor throws without it. `createServerFn` builds the server, so one class serves plain and TLS. */\nexport interface ITcpSocketServerOptions<\n SocketServerOptions extends ServerOpts = ServerOpts,\n SocketServerType extends SocketServer = SocketServer,\n SocketClientType extends SocketClient = SocketClient,\n> {\n scope?: string;\n identifier: string;\n\n serverOptions: Partial<SocketServerOptions>;\n listenOptions: Partial<ListenOptions>;\n authenticateOptions: { required: boolean; duration?: number };\n\n extraEvents?: Record<\n string,\n (opts: { id: string; socket: SocketClientType; args: any }) => ValueOrPromise<void>\n >;\n\n createServerFn: (\n options: Partial<SocketServerOptions>,\n connectionListener: (socket: SocketClientType) => void,\n ) => SocketServerType;\n\n onServerReady?: (opts: { server: SocketServerType }) => void;\n onClientConnected?: (opts: { id: string; socket: SocketClientType }) => void;\n onClientData?: (opts: { id: string; socket: SocketClientType; data: Buffer | string }) => void;\n onClientClose?: (opts: { id: string; socket: SocketClientType }) => void;\n onClientError?: (opts: { id: string; socket: SocketClientType; error: Error }) => void;\n onServerError?: (opts: { server: SocketServerType; error: Error }) => void;\n}\n\n/** TCP or TLS server that tracks connected clients by id, with an optional authentication window, and reports connection events to the `onClient*` and `onServer*` callbacks. */\nexport class BaseNetworkTcpServer<\n SocketServerOptions extends ServerOpts = ServerOpts,\n SocketServerType extends SocketServer = SocketServer,\n SocketClientType extends SocketClient = SocketClient,\n> extends BaseHelper {\n protected serverOptions: Partial<SocketServerOptions> = {};\n protected listenOptions: Partial<ListenOptions> = {};\n protected authenticateOptions: { required: boolean; duration?: number };\n\n protected clients: Record<string, ITcpSocketClient<SocketClientType>>;\n protected server: SocketServerType;\n\n protected extraEvents: Record<\n string,\n (opts: { id: string; socket: SocketClientType; args: any }) => ValueOrPromise<void>\n >;\n\n protected createServerFn: (\n options: Partial<SocketServerOptions>,\n connectionListener: (socket: SocketClientType) => void,\n ) => SocketServerType;\n\n protected onServerReady?: (opts: { server: SocketServerType }) => void;\n protected onClientConnected?: (opts: { id: string; socket: SocketClientType }) => void;\n protected onClientData?: (opts: {\n id: string;\n socket: SocketClientType;\n data: Buffer | string;\n }) => void;\n\n protected onClientClose?: (opts: { id: string; socket: SocketClientType }) => void;\n protected onClientError?: (opts: { id: string; socket: SocketClientType; error: Error }) => void;\n protected onServerError?: (opts: { server: SocketServerType; error: Error }) => void;\n\n constructor(\n opts: ITcpSocketServerOptions<SocketServerOptions, SocketServerType, SocketClientType>,\n ) {\n super({\n scope: opts.scope ?? opts.identifier ?? BaseNetworkTcpServer.name,\n identifier: opts.identifier,\n });\n\n // No prototype: `getClient({ id: 'constructor' })` must find nothing, not `Object`.\n this.clients = Object.create(null);\n\n this.serverOptions = opts.serverOptions;\n this.listenOptions = opts.listenOptions;\n this.authenticateOptions = opts.authenticateOptions;\n\n if (\n this.authenticateOptions.required &&\n (!this.authenticateOptions.duration || this.authenticateOptions.duration < 0)\n ) {\n throw getError({\n message:\n 'TCP Server | Invalid authenticate duration | Required duration for authenticateOptions',\n });\n }\n\n this.extraEvents = opts.extraEvents ?? {};\n\n this.createServerFn = opts.createServerFn;\n\n this.onServerReady = opts.onServerReady;\n this.onClientConnected = opts.onClientConnected;\n this.onClientData = opts.onClientData;\n this.onClientClose = opts.onClientClose;\n this.onClientError = opts.onClientError;\n this.onServerError = opts.onServerError;\n\n this.configure();\n }\n\n // Hooks run inside socket event listeners: a synchronous throw there is an uncaught exception that kills the process and skips the client-registry cleanup that follows it.\n protected invokeHook(opts: { scope: string; execution: () => void }) {\n const { scope, execution } = opts;\n\n try {\n execution();\n } catch (error) {\n this.logger.for(scope).error('Hook execution FAILED | Error: %s', error);\n }\n }\n\n configure() {\n this.server = this.createServerFn(this.serverOptions, (socket) => {\n this.onNewConnection({ socket });\n });\n\n // Without this listener a failed listen - a port already in use is the commonest boot failure there is - emits an unhandled 'error' event, which takes the whole process down with it.\n this.server.on('error', (error: Error) => {\n this.logger\n .for(this.configure.name)\n .error('TCP Socket Server error | Options: %j | Error: %s', this.listenOptions, error);\n\n this.invokeHook({\n scope: this.configure.name,\n execution: () => {\n this.onServerError?.({ server: this.server, error });\n },\n });\n });\n\n this.server.listen(this.listenOptions, () => {\n this.logger\n .for(this.configure.name)\n .info('TCP Socket Server is now listening | Options: %j', this.listenOptions);\n\n this.invokeHook({\n scope: this.configure.name,\n execution: () => {\n this.onServerReady?.({ server: this.server });\n },\n });\n });\n }\n\n onNewConnection(opts: { socket: SocketClientType }) {\n const { socket } = opts;\n\n const id = ParseUtility.getUID();\n\n socket.on('data', (data: Buffer | string) => {\n this.invokeHook({\n scope: 'onClientData',\n execution: () => {\n this.onClientData?.({ id, socket, data });\n },\n });\n });\n\n socket.on('error', (error: Error) => {\n this.logger.for('onClientConnect').error('Socket Error | ID: %s | Error: %s', id, error);\n\n this.invokeHook({\n scope: 'onClientError',\n execution: () => {\n this.onClientError?.({ id, socket, error });\n },\n });\n\n socket.end();\n });\n\n socket.on('close', (hasError: boolean) => {\n this.logger\n .for('onClientConnect')\n .info('Socket Closed | ID: %s | hasError: %s', id, hasError);\n\n this.invokeHook({\n scope: 'onClientClose',\n execution: () => {\n this.onClientClose?.({ id, socket });\n },\n });\n\n const authenticateTimeout = this.getClient({ id })?.storage?.authenticateTimeout;\n\n if (authenticateTimeout) {\n clearTimeout(authenticateTimeout);\n }\n\n // `delete`, not `omit`: omit rebuilds the WHOLE registry per disconnect, so a disconnect\n // storm is O(n^2) - measured at 5000 clients, 2.3s of drain with a 2.2s worst-case stall.\n delete this.clients[id];\n });\n\n for (const extraEvent in this.extraEvents) {\n socket.on(extraEvent, (args) => {\n PromiseUtility.voidExecution({\n logger: this.logger,\n scope: 'onClientConnect',\n // The async wrapper turns a SYNCHRONOUS throw from the handler into a rejection; calling it bare would throw out of this listener as an uncaught exception.\n execution: (async () => this.extraEvents[extraEvent]({ id, socket, args }))(),\n });\n });\n }\n\n this.clients[id] = {\n id,\n socket,\n state: this.authenticateOptions.required\n ? TcpClientStates.UNAUTHORIZED\n : TcpClientStates.AUTHENTICATED,\n subscriptions: new Set([]),\n storage: {\n connectedAt: new Date(),\n authenticatedAt: this.authenticateOptions.required ? null : new Date(),\n },\n };\n\n this.logger\n .for('onClientConnect')\n .info(\n 'New TCP SocketClient | Client: %s | authenticateOptions: %s %s',\n `${id} - ${socket.remoteAddress} - ${socket.remotePort} - ${socket.remoteFamily}`,\n this.authenticateOptions.required,\n this.authenticateOptions.duration,\n );\n\n this.invokeHook({\n scope: 'onClientConnected',\n execution: () => {\n this.onClientConnected?.({ id, socket });\n },\n });\n\n if (\n this.authenticateOptions.required &&\n this.authenticateOptions.duration &&\n this.authenticateOptions.duration > 0\n ) {\n const authenticateTimeout = setTimeout(() => {\n const client = this.getClient({ id });\n\n if (!client) {\n return;\n }\n\n client.storage.authenticateTimeout = null;\n\n if (client.state === TcpClientStates.AUTHENTICATED) {\n return;\n }\n\n this.emit({ clientId: id, payload: 'Unauthorized Client' });\n client.socket.end();\n }, this.authenticateOptions.duration);\n\n const client = this.getClient({ id });\n\n if (!client) {\n clearTimeout(authenticateTimeout);\n\n return;\n }\n\n client.storage.authenticateTimeout = authenticateTimeout;\n }\n }\n\n getClients() {\n return this.clients;\n }\n\n getClient(opts: { id: string }) {\n return this.clients?.[opts.id];\n }\n\n getServer() {\n return this.server;\n }\n\n /** Clears timers and destroys all client sockets before closing the listener - `server.close()` alone never settles while a socket stays attached. Idempotent; safe if never listened. */\n async shutdown(): Promise<void> {\n const clientsValues = Object.values(this.clients);\n\n for (const client of clientsValues) {\n const { authenticateTimeout } = client.storage;\n\n if (authenticateTimeout) {\n clearTimeout(authenticateTimeout);\n client.storage.authenticateTimeout = null;\n }\n\n client.socket.destroy();\n }\n\n this.clients = Object.create(null);\n\n const server = this.server;\n\n if (!server) {\n return;\n }\n\n // Not guarded on `listening`: listen() is async (DNS lookup), so a shutdown() racing startup could skip close() and leave the server bound forever; close() on a never-listened server just logs ERR_SERVER_NOT_RUNNING below.\n\n await new Promise<void>((resolve) => {\n server.close((error) => {\n if (error) {\n this.logger.for(this.shutdown.name).error('Failed to close server | Error: %s', error);\n }\n\n resolve();\n });\n });\n\n this.logger.for(this.shutdown.name).info('Server closed | Identifier: %s', this.identifier);\n }\n\n doAuthenticate(opts: { id: string; state: TTcpClientState }) {\n const { id, state } = opts;\n\n const client = this.getClient({ id });\n\n if (!client) {\n this.logger.for('authenticateClient').error('Client NOT FOUND | ID: %s', id);\n\n return;\n }\n\n client.state = state;\n\n switch (state) {\n case TcpClientStates.UNAUTHORIZED:\n case TcpClientStates.AUTHENTICATING: {\n client.storage.authenticatedAt = null;\n break;\n }\n case TcpClientStates.AUTHENTICATED: {\n client.storage.authenticatedAt = new Date();\n\n if (client.storage.authenticateTimeout) {\n clearTimeout(client.storage.authenticateTimeout);\n client.storage.authenticateTimeout = null;\n }\n\n break;\n }\n default: {\n break;\n }\n }\n }\n\n emit(opts: { clientId: string; payload: Buffer | string }) {\n const { clientId, payload } = opts;\n const client = this.getClient({ id: clientId });\n\n if (!client) {\n this.logger.for(this.emit.name).error('Client NOT FOUND | ID: %s', clientId);\n\n return;\n }\n\n const { socket } = client;\n\n if (!socket.writable) {\n this.logger.for(this.emit.name).error('Client NOT WRITABLE | ID: %s', clientId);\n\n return;\n }\n\n if (!payload?.length) {\n this.logger\n .for(this.emit.name)\n .info(\n '[%s] Client %s | Invalid payload to write to TCP Socket!',\n this.identifier,\n clientId,\n );\n\n return;\n }\n\n socket.write(payload);\n }\n}\n"]}
1
+ {"version":3,"file":"base-tcp-server.helper.js","sourceRoot":"","sources":["../../../../../src/modules/network/tcp-socket/base-tcp-server.helper.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAC5C,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AACzD,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC;AAQ7D,6DAA6D;AAC7D,MAAM,OAAO,eAAe;aACV,iBAAY,GAAG,cAAc,CAAC;aAC9B,mBAAc,GAAG,gBAAgB,CAAC;aAClC,kBAAa,GAAG,eAAe,CAAC;;AAmDlD,iLAAiL;AACjL,MAAM,OAAO,oBAIX,SAAQ,UAAU;IA8BlB,YACE,IAAsF;QAEtF,KAAK,CAAC;YACJ,KAAK,EAAE,IAAI,CAAC,KAAK,IAAI,IAAI,CAAC,UAAU,IAAI,oBAAoB,CAAC,IAAI;YACjE,UAAU,EAAE,IAAI,CAAC,UAAU;SAC5B,CAAC,CAAC;QAnCK,kBAAa,GAAiC,EAAE,CAAC;QACjD,kBAAa,GAA2B,EAAE,CAAC;QAoCnD,oFAAoF;QACpF,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;QAEnC,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC,aAAa,CAAC;QACxC,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC,aAAa,CAAC;QACxC,IAAI,CAAC,mBAAmB,GAAG,IAAI,CAAC,mBAAmB,CAAC;QAEpD,IACE,IAAI,CAAC,mBAAmB,CAAC,QAAQ;YACjC,CAAC,CAAC,IAAI,CAAC,m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,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,KAAK,CAAC,2BAA2B,EAAE,QAAQ,CAAC,CAAC;YAE7E,OAAO;QACT,CAAC;QAED,MAAM,EAAE,MAAM,EAAE,GAAG,MAAM,CAAC;QAE1B,IAAI,CAAC,MAAM,CAAC,QAAQ,EAAE,CAAC;YACrB,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,KAAK,CAAC,8BAA8B,EAAE,QAAQ,CAAC,CAAC;YAEhF,OAAO;QACT,CAAC;QAED,IAAI,CAAC,OAAO,EAAE,MAAM,EAAE,CAAC;YACrB,IAAI,CAAC,MAAM;iBACR,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC;iBACnB,IAAI,CACH,0DAA0D,EAC1D,IAAI,CAAC,UAAU,EACf,QAAQ,CACT,CAAC;YAEJ,OAAO;QACT,CAAC;QAED,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;IACxB,CAAC;CACF","sourcesContent":["import type { TConstValue } from '@/common/types';\nimport { type ValueOrPromise } from '@/common/types';\nimport { BaseHelper } from '@/modules/base';\nimport { getError } from '@/modules/error';\nimport { ParseUtility } from '@/utilities/parse.utility';\nimport { PromiseUtility } from '@/utilities/promise.utility';\nimport {\n type ListenOptions,\n type ServerOpts,\n type Socket as SocketClient,\n type Server as SocketServer,\n} from 'node:net';\n\n/** Where a TCP client is in the authentication handshake. */\nexport class TcpClientStates {\n static readonly UNAUTHORIZED = 'unauthorized';\n static readonly AUTHENTICATING = 'authenticating';\n static readonly AUTHENTICATED = 'authenticated';\n}\n\n/** Valid TCP client state values. */\nexport type TTcpClientState = TConstValue<typeof TcpClientStates>;\n\n/** A client connected to `BaseNetworkTcpServer`: its `id`, `socket`, authentication `state`, `subscriptions` and `storage` (connect and authenticate times, the pending authenticate timer). */\nexport interface ITcpSocketClient<SocketClientType> {\n id: string;\n socket: SocketClientType;\n state: TTcpClientState;\n subscriptions: Set<string>;\n storage: {\n connectedAt: Date;\n authenticatedAt: Date | null;\n authenticateTimeout?: ReturnType<typeof setTimeout> | null;\n [additionField: symbol | string]: unknown;\n };\n}\n\n/** Options of `BaseNetworkTcpServer`. With `authenticateOptions.required`, `duration` (milliseconds, greater than 0) is how long a client has to authenticate before its socket is ended; the constructor throws without it. `createServerFn` builds the server, so one class serves plain and TLS. */\nexport interface ITcpSocketServerOptions<\n SocketServerOptions extends ServerOpts = ServerOpts,\n SocketServerType extends SocketServer = SocketServer,\n SocketClientType extends SocketClient = SocketClient,\n> {\n scope?: string;\n identifier: string;\n\n serverOptions: Partial<SocketServerOptions>;\n listenOptions: Partial<ListenOptions>;\n authenticateOptions: { required: boolean; duration?: number };\n\n extraEvents?: Record<\n string,\n (opts: { id: string; socket: SocketClientType; args: unknown }) => ValueOrPromise<void>\n >;\n\n createServerFn: (\n options: Partial<SocketServerOptions>,\n connectionListener: (socket: SocketClientType) => void,\n ) => SocketServerType;\n\n onServerReady?: (opts: { server: SocketServerType }) => void;\n onClientConnected?: (opts: { id: string; socket: SocketClientType }) => void;\n onClientData?: (opts: { id: string; socket: SocketClientType; data: Buffer | string }) => void;\n onClientClose?: (opts: { id: string; socket: SocketClientType }) => void;\n onClientError?: (opts: { id: string; socket: SocketClientType; error: Error }) => void;\n onServerError?: (opts: { server: SocketServerType; error: Error }) => void;\n}\n\n/** TCP or TLS server that tracks connected clients by id, with an optional authentication window, and reports connection events to the `onClient*` and `onServer*` callbacks. */\nexport class BaseNetworkTcpServer<\n SocketServerOptions extends ServerOpts = ServerOpts,\n SocketServerType extends SocketServer = SocketServer,\n SocketClientType extends SocketClient = SocketClient,\n> extends BaseHelper {\n protected serverOptions: Partial<SocketServerOptions> = {};\n protected listenOptions: Partial<ListenOptions> = {};\n protected authenticateOptions: { required: boolean; duration?: number };\n\n protected clients: Record<string, ITcpSocketClient<SocketClientType>>;\n protected server: SocketServerType;\n\n protected extraEvents: Record<\n string,\n (opts: { id: string; socket: SocketClientType; args: unknown }) => ValueOrPromise<void>\n >;\n\n protected createServerFn: (\n options: Partial<SocketServerOptions>,\n connectionListener: (socket: SocketClientType) => void,\n ) => SocketServerType;\n\n protected onServerReady?: (opts: { server: SocketServerType }) => void;\n protected onClientConnected?: (opts: { id: string; socket: SocketClientType }) => void;\n protected onClientData?: (opts: {\n id: string;\n socket: SocketClientType;\n data: Buffer | string;\n }) => void;\n\n protected onClientClose?: (opts: { id: string; socket: SocketClientType }) => void;\n protected onClientError?: (opts: { id: string; socket: SocketClientType; error: Error }) => void;\n protected onServerError?: (opts: { server: SocketServerType; error: Error }) => void;\n\n constructor(\n opts: ITcpSocketServerOptions<SocketServerOptions, SocketServerType, SocketClientType>,\n ) {\n super({\n scope: opts.scope ?? opts.identifier ?? BaseNetworkTcpServer.name,\n identifier: opts.identifier,\n });\n\n // No prototype: `getClient({ id: 'constructor' })` must find nothing, not `Object`.\n this.clients = Object.create(null);\n\n this.serverOptions = opts.serverOptions;\n this.listenOptions = opts.listenOptions;\n this.authenticateOptions = opts.authenticateOptions;\n\n if (\n this.authenticateOptions.required &&\n (!this.authenticateOptions.duration || this.authenticateOptions.duration < 0)\n ) {\n throw getError({\n message:\n 'TCP Server | Invalid authenticate duration | Required duration for authenticateOptions',\n });\n }\n\n this.extraEvents = opts.extraEvents ?? {};\n\n this.createServerFn = opts.createServerFn;\n\n this.onServerReady = opts.onServerReady;\n this.onClientConnected = opts.onClientConnected;\n this.onClientData = opts.onClientData;\n this.onClientClose = opts.onClientClose;\n this.onClientError = opts.onClientError;\n this.onServerError = opts.onServerError;\n\n this.configure();\n }\n\n // Hooks run inside socket event listeners: a synchronous throw there is an uncaught exception that kills the process and skips the client-registry cleanup that follows it.\n protected invokeHook(opts: { scope: string; execution: () => void }) {\n const { scope, execution } = opts;\n\n try {\n execution();\n } catch (error) {\n this.logger.for(scope).error('Hook execution FAILED | Error: %s', error);\n }\n }\n\n configure() {\n this.server = this.createServerFn(this.serverOptions, (socket) => {\n this.onNewConnection({ socket });\n });\n\n // Without this listener a failed listen - a port already in use is the commonest boot failure there is - emits an unhandled 'error' event, which takes the whole process down with it.\n this.server.on('error', (error: Error) => {\n this.logger\n .for(this.configure.name)\n .error('TCP Socket Server error | Options: %j | Error: %s', this.listenOptions, error);\n\n this.invokeHook({\n scope: this.configure.name,\n execution: () => {\n this.onServerError?.({ server: this.server, error });\n },\n });\n });\n\n this.server.listen(this.listenOptions, () => {\n this.logger\n .for(this.configure.name)\n .info('TCP Socket Server is now listening | Options: %j', this.listenOptions);\n\n this.invokeHook({\n scope: this.configure.name,\n execution: () => {\n this.onServerReady?.({ server: this.server });\n },\n });\n });\n }\n\n onNewConnection(opts: { socket: SocketClientType }) {\n const { socket } = opts;\n\n const id = ParseUtility.getUID();\n\n socket.on('data', (data: Buffer | string) => {\n this.invokeHook({\n scope: 'onClientData',\n execution: () => {\n this.onClientData?.({ id, socket, data });\n },\n });\n });\n\n socket.on('error', (error: Error) => {\n this.logger.for('onClientConnect').error('Socket Error | ID: %s | Error: %s', id, error);\n\n this.invokeHook({\n scope: 'onClientError',\n execution: () => {\n this.onClientError?.({ id, socket, error });\n },\n });\n\n socket.end();\n });\n\n socket.on('close', (hasError: boolean) => {\n this.logger\n .for('onClientConnect')\n .info('Socket Closed | ID: %s | hasError: %s', id, hasError);\n\n this.invokeHook({\n scope: 'onClientClose',\n execution: () => {\n this.onClientClose?.({ id, socket });\n },\n });\n\n const authenticateTimeout = this.getClient({ id })?.storage?.authenticateTimeout;\n\n if (authenticateTimeout) {\n clearTimeout(authenticateTimeout);\n }\n\n // `delete`, not `omit`: omit rebuilds the WHOLE registry per disconnect, so a disconnect\n // storm is O(n^2) - measured at 5000 clients, 2.3s of drain with a 2.2s worst-case stall.\n delete this.clients[id];\n });\n\n for (const extraEvent in this.extraEvents) {\n socket.on(extraEvent, (args) => {\n PromiseUtility.voidExecution({\n logger: this.logger,\n scope: 'onClientConnect',\n // The async wrapper turns a SYNCHRONOUS throw from the handler into a rejection; calling it bare would throw out of this listener as an uncaught exception.\n execution: (async () => this.extraEvents[extraEvent]({ id, socket, args }))(),\n });\n });\n }\n\n this.clients[id] = {\n id,\n socket,\n state: this.authenticateOptions.required\n ? TcpClientStates.UNAUTHORIZED\n : TcpClientStates.AUTHENTICATED,\n subscriptions: new Set([]),\n storage: {\n connectedAt: new Date(),\n authenticatedAt: this.authenticateOptions.required ? null : new Date(),\n },\n };\n\n this.logger\n .for('onClientConnect')\n .info(\n 'New TCP SocketClient | Client: %s | authenticateOptions: %s %s',\n `${id} - ${socket.remoteAddress} - ${socket.remotePort} - ${socket.remoteFamily}`,\n this.authenticateOptions.required,\n this.authenticateOptions.duration,\n );\n\n this.invokeHook({\n scope: 'onClientConnected',\n execution: () => {\n this.onClientConnected?.({ id, socket });\n },\n });\n\n if (\n this.authenticateOptions.required &&\n this.authenticateOptions.duration &&\n this.authenticateOptions.duration > 0\n ) {\n const authenticateTimeout = setTimeout(() => {\n const client = this.getClient({ id });\n\n if (!client) {\n return;\n }\n\n client.storage.authenticateTimeout = null;\n\n if (client.state === TcpClientStates.AUTHENTICATED) {\n return;\n }\n\n this.emit({ clientId: id, payload: 'Unauthorized Client' });\n client.socket.end();\n }, this.authenticateOptions.duration);\n\n const client = this.getClient({ id });\n\n if (!client) {\n clearTimeout(authenticateTimeout);\n\n return;\n }\n\n client.storage.authenticateTimeout = authenticateTimeout;\n }\n }\n\n getClients() {\n return this.clients;\n }\n\n getClient(opts: { id: string }) {\n return this.clients?.[opts.id];\n }\n\n getServer() {\n return this.server;\n }\n\n /** Clears timers and destroys all client sockets before closing the listener - `server.close()` alone never settles while a socket stays attached. Idempotent; safe if never listened. */\n async shutdown(): Promise<void> {\n const clientsValues = Object.values(this.clients);\n\n for (const client of clientsValues) {\n const { authenticateTimeout } = client.storage;\n\n if (authenticateTimeout) {\n clearTimeout(authenticateTimeout);\n client.storage.authenticateTimeout = null;\n }\n\n client.socket.destroy();\n }\n\n this.clients = Object.create(null);\n\n const server = this.server;\n\n if (!server) {\n return;\n }\n\n // Not guarded on `listening`: listen() is async (DNS lookup), so a shutdown() racing startup could skip close() and leave the server bound forever; close() on a never-listened server just logs ERR_SERVER_NOT_RUNNING below.\n\n await new Promise<void>((resolve) => {\n server.close((error) => {\n if (error) {\n this.logger.for(this.shutdown.name).error('Failed to close server | Error: %s', error);\n }\n\n resolve();\n });\n });\n\n this.logger.for(this.shutdown.name).info('Server closed | Identifier: %s', this.identifier);\n }\n\n doAuthenticate(opts: { id: string; state: TTcpClientState }) {\n const { id, state } = opts;\n\n const client = this.getClient({ id });\n\n if (!client) {\n this.logger.for('authenticateClient').error('Client NOT FOUND | ID: %s', id);\n\n return;\n }\n\n client.state = state;\n\n switch (state) {\n case TcpClientStates.UNAUTHORIZED:\n case TcpClientStates.AUTHENTICATING: {\n client.storage.authenticatedAt = null;\n break;\n }\n case TcpClientStates.AUTHENTICATED: {\n client.storage.authenticatedAt = new Date();\n\n if (client.storage.authenticateTimeout) {\n clearTimeout(client.storage.authenticateTimeout);\n client.storage.authenticateTimeout = null;\n }\n\n break;\n }\n default: {\n break;\n }\n }\n }\n\n emit(opts: { clientId: string; payload: Buffer | string }) {\n const { clientId, payload } = opts;\n const client = this.getClient({ id: clientId });\n\n if (!client) {\n this.logger.for(this.emit.name).error('Client NOT FOUND | ID: %s', clientId);\n\n return;\n }\n\n const { socket } = client;\n\n if (!socket.writable) {\n this.logger.for(this.emit.name).error('Client NOT WRITABLE | ID: %s', clientId);\n\n return;\n }\n\n if (!payload?.length) {\n this.logger\n .for(this.emit.name)\n .info(\n '[%s] Client %s | Invalid payload to write to TCP Socket!',\n this.identifier,\n clientId,\n );\n\n return;\n }\n\n socket.write(payload);\n }\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import { BaseHelper } from '../../base.js';
2
- import { type IRedisHelper } from '../../redis/index.js';
2
+ import { type IRedisHelper, type TRedisClient } from '../../redis/index.js';
3
3
  import type { Job, Processor, Queue, QueueOptions, Worker, WorkerOptions } from 'bullmq';
4
4
  import { type TBullQueueRole } from '../common/index.js';
5
5
  /** Options for {@link BullMQHelper}. `role` decides whether a `Queue` or a `Worker` is built. */
@@ -46,7 +46,12 @@ export declare class BullMQHelper<TQueueElement = unknown, TQueueResult = unknow
46
46
  protected onWorkerDataCompleted?: (job: Job<TQueueElement, TQueueResult>, result: TQueueResult) => Promise<void>;
47
47
  protected onWorkerDataFail?: (job: Job<TQueueElement, TQueueResult> | undefined, error: Error) => Promise<void>;
48
48
  private readonly bullmqModule?;
49
+ private isClosing;
50
+ /** Every duplicate this helper handed to BullMQ: BullMQ never quits a client it is given, so `close()` does. */
51
+ private readonly duplicates;
49
52
  constructor(options: IBullMQOptions<TQueueElement, TQueueResult>);
53
+ /** BullMQ never reconnects a client: once ioredis stops reconnecting (`maxRetry` attempts used up) it is `end` for good, no job moves, and nothing else says so. */
54
+ protected reportClientEnded(): void;
50
55
  static newInstance<T = unknown, R = unknown>(opts: IBullMQOptions<T, R>): BullMQHelper<T, R>;
51
56
  /** Structural, never `instanceof`: ioredis is an optional peer, and a second copy fails `instanceof` anyway. */
52
57
  protected isClusterClient(): boolean;
@@ -56,6 +61,12 @@ export declare class BullMQHelper<TQueueElement = unknown, TQueueResult = unknow
56
61
  protected queueOptionsFor(opts: {
57
62
  queueName: string;
58
63
  }): QueueOptions;
64
+ /**
65
+ * The connection BullMQ owns: a duplicate of the helper's client, so the queue or worker connects it by itself
66
+ * whatever state the shared client is in. BullMQ treats a client it is handed as shared and never quits it, so the
67
+ * helper keeps the duplicate and quits it in `close()`.
68
+ */
69
+ protected createConnection(): TRedisClient;
59
70
  /** Full `Worker` options: `this.workerOptions`, then the connection/concurrency/lock fields the helper owns - in that precedence order. */
60
71
  protected workerOptionsFor(opts: {
61
72
  queueName: string;
@@ -74,6 +85,8 @@ export declare class BullMQHelper<TQueueElement = unknown, TQueueResult = unknow
74
85
  }): Worker<TQueueElement, TQueueResult>;
75
86
  configureWorker(): void;
76
87
  configure(): void;
88
+ /** `quit()` waits for the replies in flight; a client BullMQ already closed is left alone. */
89
+ private static release;
77
90
  close(): Promise<void>;
78
91
  }
79
92
  //# sourceMappingURL=helper.d.ts.map
@@ -1,5 +1,6 @@
1
1
  import { BaseHelper } from '../../base.js';
2
2
  import { getError } from '../../error/index.js';
3
+ import { RedisDefaults } from '../../redis/index.js';
3
4
  import { ErrorUtility } from '../../../utilities/error.utility.js';
4
5
  import { ModuleUtility } from '../../../utilities/module.utility.js';
5
6
  import { BullMQDefaults, BullQueueRoles, HookUtility } from '../common/index.js';
@@ -10,6 +11,9 @@ import { BullMQDefaults, BullQueueRoles, HookUtility } from '../common/index.js'
10
11
  export class BullMQHelper extends BaseHelper {
11
12
  constructor(options) {
12
13
  super({ scope: BullMQHelper.name, identifier: options.identifier });
14
+ this.isClosing = false;
15
+ /** Every duplicate this helper handed to BullMQ: BullMQ never quits a client it is given, so `close()` does. */
16
+ this.duplicates = [];
13
17
  const { queueName, redisConnection, role, numberOfWorker = BullMQDefaults.NUMBER_OF_WORKER, lockDuration = BullMQDefaults.LOCK_DURATION_MS, queueOptions, workerOptions, onWorkerData, onWorkerDataCompleted, onWorkerDataFail, module, } = options;
14
18
  this.bullmqModule = module;
15
19
  this.queueName = queueName;
@@ -24,6 +28,12 @@ export class BullMQHelper extends BaseHelper {
24
28
  this.onWorkerDataFail = onWorkerDataFail;
25
29
  this.configure();
26
30
  }
31
+ /** BullMQ never reconnects a client: once ioredis stops reconnecting (`maxRetry` attempts used up) it is `end` for good, no job moves, and nothing else says so. */
32
+ reportClientEnded() {
33
+ this.logger
34
+ .for(this.reportClientEnded.name)
35
+ .error('The Redis client ended, so BullMQ can no longer move jobs on queue %s | ioredis stopped reconnecting after maxRetry attempts | Back BullMQ with a helper whose maxRetry is %d (forever) | ID: %s', this.queueName, RedisDefaults.RETRY_FOREVER, this.identifier);
36
+ }
27
37
  static newInstance(opts) {
28
38
  return new BullMQHelper(opts);
29
39
  }
@@ -68,10 +78,24 @@ export class BullMQHelper extends BaseHelper {
68
78
  removeOnFail: true,
69
79
  },
70
80
  ...this.queueOptions,
71
- // The helper's own client, never a duplicate: BullMQ marks a client it is handed as shared and never quits it, so a duplicate would leak one connection per queue and worker. BullMQ opens (and closes) its own blocking connection.
72
- connection: this.redisConnection.getClient(),
81
+ connection: this.createConnection(),
73
82
  };
74
83
  }
84
+ /**
85
+ * The connection BullMQ owns: a duplicate of the helper's client, so the queue or worker connects it by itself
86
+ * whatever state the shared client is in. BullMQ treats a client it is handed as shared and never quits it, so the
87
+ * helper keeps the duplicate and quits it in `close()`.
88
+ */
89
+ createConnection() {
90
+ const connection = this.redisConnection.duplicateClient();
91
+ this.duplicates.push(connection);
92
+ connection.once('end', () => {
93
+ if (!this.isClosing) {
94
+ this.reportClientEnded();
95
+ }
96
+ });
97
+ return connection;
98
+ }
75
99
  /** Full `Worker` options: `this.workerOptions`, then the connection/concurrency/lock fields the helper owns - in that precedence order. */
76
100
  workerOptionsFor(opts) {
77
101
  this.logger
@@ -79,7 +103,7 @@ export class BullMQHelper extends BaseHelper {
79
103
  .debug('Building worker options | Queue: %s | ID: %s', opts.queueName, this.identifier);
80
104
  return {
81
105
  ...this.workerOptions,
82
- connection: this.redisConnection.getClient(),
106
+ connection: this.createConnection(),
83
107
  concurrency: this.numberOfWorker,
84
108
  lockDuration: this.lockDuration,
85
109
  };
@@ -158,7 +182,21 @@ export class BullMQHelper extends BaseHelper {
158
182
  }
159
183
  }
160
184
  }
185
+ /** `quit()` waits for the replies in flight; a client BullMQ already closed is left alone. */
186
+ static async release(opts) {
187
+ const { connection } = opts;
188
+ if (connection.status === 'end') {
189
+ return;
190
+ }
191
+ try {
192
+ await connection.quit();
193
+ }
194
+ catch {
195
+ connection.disconnect();
196
+ }
197
+ }
161
198
  async close() {
199
+ this.isClosing = true;
162
200
  const failures = [];
163
201
  // Both connections must be released even when the first close fails - otherwise a failing worker close silently leaks the queue's Redis connection forever.
164
202
  try {
@@ -179,6 +217,17 @@ export class BullMQHelper extends BaseHelper {
179
217
  .error('Error closing BullMQ queue: %s | ID: %s', error, this.identifier);
180
218
  failures.push(ErrorUtility.toError({ error }).message);
181
219
  }
220
+ for (const connection of this.duplicates.splice(0)) {
221
+ try {
222
+ await BullMQHelper.release({ connection });
223
+ }
224
+ catch (error) {
225
+ this.logger
226
+ .for(this.close.name)
227
+ .error('Error closing the BullMQ connection: %s | ID: %s', error, this.identifier);
228
+ failures.push(ErrorUtility.toError({ error }).message);
229
+ }
230
+ }
182
231
  if (failures.length) {
183
232
  throw getError({
184
233
  message: `[close][${this.identifier}] Failed to close BullMQ helper | Errors: ${failures.join(' | ')}`,