@venizia/ignis-helpers 0.4.1 → 0.4.2
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.
- package/dist/cjs/common/constants/duration.d.ts +4 -1
- package/dist/cjs/common/constants/duration.d.ts.map +1 -1
- package/dist/cjs/common/constants/duration.js +13 -8
- package/dist/cjs/common/constants/duration.js.map +1 -1
- package/dist/cjs/modules/env/app-env.d.ts.map +1 -1
- package/dist/cjs/modules/env/app-env.js +1 -1
- package/dist/cjs/modules/env/app-env.js.map +1 -1
- package/dist/cjs/modules/logger/hf/logger.d.ts.map +1 -1
- package/dist/cjs/modules/logger/hf/logger.js +3 -1
- package/dist/cjs/modules/logger/hf/logger.js.map +1 -1
- package/dist/cjs/modules/network/tcp-socket/base-tcp-server.helper.d.ts.map +1 -1
- package/dist/cjs/modules/network/tcp-socket/base-tcp-server.helper.js +3 -2
- package/dist/cjs/modules/network/tcp-socket/base-tcp-server.helper.js.map +1 -1
- package/dist/cjs/modules/secrets/base/abstract.helper.d.ts.map +1 -1
- package/dist/cjs/modules/secrets/base/abstract.helper.js +5 -1
- package/dist/cjs/modules/secrets/base/abstract.helper.js.map +1 -1
- package/dist/cjs/modules/worker-thread/thread/base.js +2 -2
- package/dist/cjs/modules/worker-thread/thread/base.js.map +1 -1
- package/dist/esm/common/constants/duration.d.ts +4 -1
- package/dist/esm/common/constants/duration.d.ts.map +1 -1
- package/dist/esm/common/constants/duration.js +13 -8
- package/dist/esm/common/constants/duration.js.map +1 -1
- package/dist/esm/modules/env/app-env.d.ts.map +1 -1
- package/dist/esm/modules/env/app-env.js +1 -1
- package/dist/esm/modules/env/app-env.js.map +1 -1
- package/dist/esm/modules/logger/hf/logger.d.ts.map +1 -1
- package/dist/esm/modules/logger/hf/logger.js +3 -1
- package/dist/esm/modules/logger/hf/logger.js.map +1 -1
- package/dist/esm/modules/network/tcp-socket/base-tcp-server.helper.d.ts.map +1 -1
- package/dist/esm/modules/network/tcp-socket/base-tcp-server.helper.js +3 -2
- package/dist/esm/modules/network/tcp-socket/base-tcp-server.helper.js.map +1 -1
- package/dist/esm/modules/secrets/base/abstract.helper.d.ts.map +1 -1
- package/dist/esm/modules/secrets/base/abstract.helper.js +5 -1
- package/dist/esm/modules/secrets/base/abstract.helper.js.map +1 -1
- package/dist/esm/modules/worker-thread/thread/base.js +2 -2
- package/dist/esm/modules/worker-thread/thread/base.js.map +1 -1
- package/package.json +3 -3
|
@@ -74,11 +74,14 @@ export declare class DurationMultipliers {
|
|
|
74
74
|
static readonly MONTH: number;
|
|
75
75
|
static readonly YEAR: number;
|
|
76
76
|
static readonly BY_UNIT: Record<string, number>;
|
|
77
|
+
/** The multiplier of a known unit, `null` for anything else - inherited property names included. */
|
|
78
|
+
private static multiplierOf;
|
|
77
79
|
/**
|
|
78
80
|
* `null` rather than a throw, so a caller that wants an error raises its own with its own context.
|
|
79
81
|
* Every method here answers the same way.
|
|
80
82
|
*
|
|
81
|
-
*
|
|
83
|
+
* The unit is checked against {@link DurationUnits.SCHEME_SET} first: a plain-object read alone
|
|
84
|
+
* would answer `'constructor'` or `'toString'` with a member of `Object.prototype`, not `undefined`.
|
|
82
85
|
*/
|
|
83
86
|
static toMilliseconds(opts: IDuration | null): number | null;
|
|
84
87
|
/** The inverse of {@link toMilliseconds}. Fractional on purpose - rounding here would silently lose a 36-hour window asked for in days. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"duration.d.ts","sourceRoot":"","sources":["../../../../src/common/constants/duration.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,WAAW,EAAE,MAAM,UAAU,CAAC;AAE5C,qEAAqE;AACrE,qBAAa,aAAa;IACxB,MAAM,CAAC,QAAQ,CAAC,WAAW,iBAAiB;IAC5C,MAAM,CAAC,QAAQ,CAAC,MAAM,YAAY;IAClC,MAAM,CAAC,QAAQ,CAAC,MAAM,YAAY;IAClC,MAAM,CAAC,QAAQ,CAAC,IAAI,UAAU;IAC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,CAAC,MAAM,SAA2B;IACjD,MAAM,CAAC,QAAQ,CAAC,MAAM,SAAoB;IAC1C,MAAM,CAAC,QAAQ,CAAC,IAAI,SAAoB;IACxC,MAAM,CAAC,QAAQ,CAAC,GAAG,SAAkB;IACrC,MAAM,CAAC,QAAQ,CAAC,IAAI,SAAgB;IACpC,MAAM,CAAC,QAAQ,CAAC,KAAK,SAAiB;IACtC,MAAM,CAAC,QAAQ,CAAC,IAAI,SAAkB;IAEtC,MAAM,CAAC,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAS7C;IAEF,oGAAoG;IACpG,OAAO,CAAC,MAAM,CAAC,YAAY;IAI3B;;;;;;OAMG;IACH,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,SAAS,GAAG,IAAI,GAAG,MAAM,GAAG,IAAI;IAc5D,2IAA2I;IAC3I,MAAM,CAAC,gBAAgB,CAAC,IAAI,EAAE;QAAE,YAAY,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,aAAa,CAAA;KAAE,GAAG,MAAM,GAAG,IAAI;IAU3F,qGAAqG;IACrG,MAAM,CAAC,OAAO,CAAC,IAAI,EAAE;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,aAAa,CAAC;QAAC,EAAE,EAAE,aAAa,CAAA;KAAE,GAAG,MAAM,GAAG,IAAI;IAW9F,2JAA2J;IAC3J,MAAM,CAAC,KAAK,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,GAAG,IAAI;IAqB7C,qGAAqG;IACrG,MAAM,CAAC,mBAAmB,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI;CAGzD"}
|
|
@@ -114,35 +114,40 @@ export class DurationMultipliers {
|
|
|
114
114
|
[DurationUnits.MONTH]: this.MONTH,
|
|
115
115
|
[DurationUnits.YEAR]: this.YEAR,
|
|
116
116
|
}; }
|
|
117
|
+
/** The multiplier of a known unit, `null` for anything else - inherited property names included. */
|
|
118
|
+
static multiplierOf(unit) {
|
|
119
|
+
return typeof unit === 'string' && DurationUnits.isValid(unit) ? this.BY_UNIT[unit] : null;
|
|
120
|
+
}
|
|
117
121
|
/**
|
|
118
122
|
* `null` rather than a throw, so a caller that wants an error raises its own with its own context.
|
|
119
123
|
* Every method here answers the same way.
|
|
120
124
|
*
|
|
121
|
-
*
|
|
125
|
+
* The unit is checked against {@link DurationUnits.SCHEME_SET} first: a plain-object read alone
|
|
126
|
+
* would answer `'constructor'` or `'toString'` with a member of `Object.prototype`, not `undefined`.
|
|
122
127
|
*/
|
|
123
128
|
static toMilliseconds(opts) {
|
|
124
129
|
if (!opts) {
|
|
125
130
|
return null;
|
|
126
131
|
}
|
|
127
|
-
const multiplier = this.
|
|
128
|
-
if (multiplier ===
|
|
132
|
+
const multiplier = this.multiplierOf(opts.unit);
|
|
133
|
+
if (multiplier === null || !Number.isFinite(opts.value)) {
|
|
129
134
|
return null;
|
|
130
135
|
}
|
|
131
136
|
return Math.round(opts.value * multiplier);
|
|
132
137
|
}
|
|
133
138
|
/** The inverse of {@link toMilliseconds}. Fractional on purpose - rounding here would silently lose a 36-hour window asked for in days. */
|
|
134
139
|
static fromMilliseconds(opts) {
|
|
135
|
-
const multiplier = this.
|
|
136
|
-
if (multiplier ===
|
|
140
|
+
const multiplier = this.multiplierOf(opts?.unit);
|
|
141
|
+
if (multiplier === null || !Number.isFinite(opts.milliseconds)) {
|
|
137
142
|
return null;
|
|
138
143
|
}
|
|
139
144
|
return opts.milliseconds / multiplier;
|
|
140
145
|
}
|
|
141
146
|
/** Unit to unit, through milliseconds. Fractional, for the reason {@link fromMilliseconds} gives. */
|
|
142
147
|
static convert(opts) {
|
|
143
|
-
const source = this.
|
|
144
|
-
const target = this.
|
|
145
|
-
if (source ===
|
|
148
|
+
const source = this.multiplierOf(opts?.from);
|
|
149
|
+
const target = this.multiplierOf(opts?.to);
|
|
150
|
+
if (source === null || target === null || !Number.isFinite(opts.value)) {
|
|
146
151
|
return null;
|
|
147
152
|
}
|
|
148
153
|
return (opts.value * source) / target;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"duration.js","sourceRoot":"","sources":["../../../../src/common/constants/duration.ts"],"names":[],"mappings":"AAEA,qEAAqE;AACrE,MAAM,OAAO,aAAa;aACR,gBAAW,GAAG,aAAa,CAAC;aAC5B,WAAM,GAAG,QAAQ,CAAC;aAClB,WAAM,GAAG,QAAQ,CAAC;aAClB,SAAI,GAAG,MAAM,CAAC;aACd,QAAG,GAAG,KAAK,CAAC;aACZ,SAAI,GAAG,MAAM,CAAC;aACd,UAAK,GAAG,OAAO,CAAC;aAChB,SAAI,GAAG,MAAM,CAAC;aAEd,eAAU,GAAG,IAAI,GAAG,CAAC;QACnC,IAAI,CAAC,WAAW;QAChB,IAAI,CAAC,MAAM;QACX,IAAI,CAAC,MAAM;QACX,IAAI,CAAC,IAAI;QACT,IAAI,CAAC,GAAG;QACR,IAAI,CAAC,IAAI;QACT,IAAI,CAAC,KAAK;QACV,IAAI,CAAC,IAAI;KACV,CAAC,CAAC;IAEH,MAAM,CAAC,OAAO,CAAC,KAAa;QAC1B,OAAO,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IACpC,CAAC;;AAKH;;;;;;GAMG;AACH,MAAM,OAAO,eAAe;aACV,OAAE,GAAG,aAAa,CAAC,WAAW,CAAC;aAC/B,SAAI,GAAG,aAAa,CAAC,WAAW,CAAC;aACjC,gBAAW,GAAG,aAAa,CAAC,WAAW,CAAC;aACxC,iBAAY,GAAG,aAAa,CAAC,WAAW,CAAC;aAEzC,MAAC,GAAG,aAAa,CAAC,MAAM,CAAC;aACzB,QAAG,GAAG,aAAa,CAAC,MAAM,CAAC;aAC3B,WAAM,GAAG,aAAa,CAAC,MAAM,CAAC;aAC9B,YAAO,GAAG,aAAa,CAAC,MAAM,CAAC;aAE/B,MAAC,GAAG,aAAa,CAAC,MAAM,CAAC;aACzB,QAAG,GAAG,aA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AAC,IAAI,EAAE,EAAE,CAAC,CAAC;QAEtC,IAAI,MAAM,KAAK,SAAS,IAAI,MAAM,KAAK,SAAS,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC;YACjF,OAAO,IAAI,CAAC;QACd,CAAC;QAED,OAAO,CAAC,IAAI,CAAC,KAAK,GAAG,MAAM,CAAC,GAAG,MAAM,CAAC;IACxC,CAAC;IAED,2JAA2J;IAC3J,MAAM,CAAC,KAAK,CAAC,KAAa;QACxB,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;YAC9B,OAAO,IAAI,CAAC;QACd,CAAC;QAED,MAAM,OAAO,GAAG,gBAAgB,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC,CAAC;QAEpD,IAAI,CAAC,OAAO,EAAE,CAAC;YACb,OAAO,IAAI,CAAC;QACd,CAAC;QAED,MAAM,IAAI,GAAG,eAAe,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC;QACjD,MAAM,KAAK,GAAG,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC;QAEjC,IAAI,CAAC,IAAI,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC;YACrC,OAAO,IAAI,CAAC;QACd,CAAC;QAED,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC;IACzB,CAAC;IAED,qGAAqG;IACrG,MAAM,CAAC,mBAAmB,CAAC,KAAa;QACtC,OAAO,IAAI,CAAC,cAAc,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC;IAChD,CAAC","sourcesContent":["import { type TConstValue } from '../types';\n\n/** The time units a duration can be expressed in, smallest first. */\nexport class DurationUnits {\n static readonly MILLISECOND = 'millisecond';\n static readonly SECOND = 'second';\n static readonly MINUTE = 'minute';\n static readonly HOUR = 'hour';\n static readonly DAY = 'day';\n static readonly WEEK = 'week';\n static readonly MONTH = 'month';\n static readonly YEAR = 'year';\n\n static readonly SCHEME_SET = new Set([\n this.MILLISECOND,\n this.SECOND,\n this.MINUTE,\n this.HOUR,\n this.DAY,\n this.WEEK,\n this.MONTH,\n this.YEAR,\n ]);\n\n static isValid(input: string): input is TDurationUnit {\n return this.SCHEME_SET.has(input);\n }\n}\n\nexport type TDurationUnit = TConstValue<typeof DurationUnits>;\n\n/**\n * Written spellings that resolve to a unit. Member names are the spelling, upper-cased - so\n * {@link resolve} upper-cases its input and reads one property, with no second table to keep in step.\n *\n * `M` is MINUTE and `MO` is MONTH - the same choice every duration library makes, and the one\n * ambiguity a reader will trip on. There is no single-letter month.\n */\nexport class DurationAliases {\n static readonly MS = DurationUnits.MILLISECOND;\n static readonly MSEC = DurationUnits.MILLISECOND;\n static readonly MILLISECOND = DurationUnits.MILLISECOND;\n static readonly MILLISECONDS = DurationUnits.MILLISECOND;\n\n static readonly S = DurationUnits.SECOND;\n static readonly SEC = DurationUnits.SECOND;\n static readonly SECOND = DurationUnits.SECOND;\n static readonly SECONDS = DurationUnits.SECOND;\n\n static readonly M = DurationUnits.MINUTE;\n static readonly MIN = DurationUnits.MINUTE;\n static readonly MINUTE = DurationUnits.MINUTE;\n static readonly MINUTES = DurationUnits.MINUTE;\n\n static readonly H = DurationUnits.HOUR;\n static readonly HR = DurationUnits.HOUR;\n static readonly HOUR = DurationUnits.HOUR;\n static readonly HOURS = DurationUnits.HOUR;\n\n static readonly D = DurationUnits.DAY;\n static readonly DAY = DurationUnits.DAY;\n static readonly DAYS = DurationUnits.DAY;\n\n static readonly W = DurationUnits.WEEK;\n static readonly WK = DurationUnits.WEEK;\n static readonly WEEK = DurationUnits.WEEK;\n static readonly WEEKS = DurationUnits.WEEK;\n\n static readonly MO = DurationUnits.MONTH;\n static readonly MON = DurationUnits.MONTH;\n static readonly MONTH = DurationUnits.MONTH;\n static readonly MONTHS = DurationUnits.MONTH;\n\n static readonly Y = DurationUnits.YEAR;\n static readonly YR = DurationUnits.YEAR;\n static readonly YEAR = DurationUnits.YEAR;\n static readonly YEARS = DurationUnits.YEAR;\n\n /** Resolves a written unit - `'d'`, `'days'`, `'DAY'` - to its canonical name, or `null`. */\n static resolve(input: string): TDurationUnit | null {\n if (typeof input !== 'string') {\n return null;\n }\n\n // Try the input as given first. `trim().toUpperCase()` allocates two strings and costs ~55ns,\n // where the lookup itself is ~1ns - so the spellings callers actually pass (`'day'`, `'d'`,\n // `'DAYS'`) must not pay for it. Measured, both ways.\n //\n // The table is declared below because it is derived FROM this class; it is read at call time,\n // never at class-evaluation time.\n /* eslint-disable @typescript-eslint/no-use-before-define */\n return ALIAS_LOOKUP.get(input) ?? ALIAS_LOOKUP.get(input.trim().toUpperCase()) ?? null;\n /* eslint-enable @typescript-eslint/no-use-before-define */\n }\n}\n\n/**\n * Derived from the class once, never hand-listed, so the two cannot drift. Reading the class\n * directly is slower and would need `name`/`length`/`constructor` guarded out. Each spelling is\n * stored upper and lower so the common call allocates nothing.\n */\nconst ALIAS_LOOKUP: Map<string, TDurationUnit> = new Map(\n Object.entries(DurationAliases)\n .filter((entry): entry is [string, TDurationUnit] => DurationUnits.isValid(entry[1] as string))\n .flatMap(([spelling, unit]): Array<[string, TDurationUnit]> => [\n [spelling, unit],\n [spelling.toLowerCase(), unit],\n ]),\n);\n\nexport interface IDuration {\n unit: TDurationUnit;\n value: number;\n}\n\n/** `30d`, `1500 ms`, `-2 Hours`. One number, optional space, one unit. */\nconst DURATION_PATTERN = /^([+-]?\\d+(?:\\.\\d+)?)\\s*([a-z]+)$/i;\n\n/**\n * A month is 30 days and a year 365, nominal. These size a WINDOW - a grace period, a cache TTL, a\n * near-expiry horizon - and must never compute a calendar date: adding `MONTH` to 31 January lands\n * on 2 March in a leap year and 3 March otherwise. Use a date library for calendar arithmetic.\n */\nexport class DurationMultipliers {\n static readonly MILLISECOND = 1;\n static readonly SECOND = 1000 * this.MILLISECOND;\n static readonly MINUTE = 60 * this.SECOND;\n static readonly HOUR = 60 * this.MINUTE;\n static readonly DAY = 24 * this.HOUR;\n static readonly WEEK = 7 * this.DAY;\n static readonly MONTH = 30 * this.DAY;\n static readonly YEAR = 365 * this.DAY;\n\n static readonly BY_UNIT: Record<string, number> = {\n [DurationUnits.MILLISECOND]: this.MILLISECOND,\n [DurationUnits.SECOND]: this.SECOND,\n [DurationUnits.MINUTE]: this.MINUTE,\n [DurationUnits.HOUR]: this.HOUR,\n [DurationUnits.DAY]: this.DAY,\n [DurationUnits.WEEK]: this.WEEK,\n [DurationUnits.MONTH]: this.MONTH,\n [DurationUnits.YEAR]: this.YEAR,\n };\n\n /**\n * `null` rather than a throw, so a caller that wants an error raises its own with its own context.\n * Every method here answers the same way.\n *\n * One map read, not a validity check followed by a read: an unknown unit is already `undefined`.\n */\n static toMilliseconds(opts: IDuration | null): number | null {\n if (!opts) {\n return null;\n }\n\n const multiplier = this.BY_UNIT[opts.unit];\n\n if (multiplier === undefined || !Number.isFinite(opts.value)) {\n return null;\n }\n\n return Math.round(opts.value * multiplier);\n }\n\n /** The inverse of {@link toMilliseconds}. Fractional on purpose - rounding here would silently lose a 36-hour window asked for in days. */\n static fromMilliseconds(opts: { milliseconds: number; unit: TDurationUnit }): number | null {\n const multiplier = this.BY_UNIT[opts?.unit];\n\n if (multiplier === undefined || !Number.isFinite(opts.milliseconds)) {\n return null;\n }\n\n return opts.milliseconds / multiplier;\n }\n\n /** Unit to unit, through milliseconds. Fractional, for the reason {@link fromMilliseconds} gives. */\n static convert(opts: { value: number; from: TDurationUnit; to: TDurationUnit }): number | null {\n const source = this.BY_UNIT[opts?.from];\n const target = this.BY_UNIT[opts?.to];\n\n if (source === undefined || target === undefined || !Number.isFinite(opts.value)) {\n return null;\n }\n\n return (opts.value * source) / target;\n }\n\n /** Reads a written duration - `'30d'`, `'1500 ms'`, `'2 hours'` - into {@link IDuration}. Aliases and the `M`/`MO` rule are on {@link DurationAliases}. */\n static parse(input: string): IDuration | null {\n if (typeof input !== 'string') {\n return null;\n }\n\n const matched = DURATION_PATTERN.exec(input.trim());\n\n if (!matched) {\n return null;\n }\n\n const unit = DurationAliases.resolve(matched[2]);\n const value = Number(matched[1]);\n\n if (!unit || !Number.isFinite(value)) {\n return null;\n }\n\n return { unit, value };\n }\n\n /** `'30d'` straight to milliseconds - the shape a TTL or a grace period is usually configured in. */\n static parseToMilliseconds(input: string): number | null {\n return this.toMilliseconds(this.parse(input));\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"duration.js","sourceRoot":"","sources":["../../../../src/common/constants/duration.ts"],"names":[],"mappings":"AAEA,qEAAqE;AACrE,MAAM,OAAO,aAAa;aACR,gBAAW,GAAG,aAAa,CAAC;aAC5B,WAAM,GAAG,QAAQ,CAAC;aAClB,WAAM,GAAG,QAAQ,CAAC;aAClB,SAAI,GAAG,MAAM,CAAC;aACd,QAAG,GAAG,KAAK,CAAC;aACZ,SAAI,GAAG,MAAM,CAAC;aACd,UAAK,GAAG,OAAO,CAAC;aAChB,SAAI,GAAG,MAAM,CAAC;aAEd,eAAU,GAAG,IAAI,GAAG,CAAC;QACnC,IAAI,CAAC,WAAW;QAChB,IAAI,CAAC,MAAM;QACX,IAAI,CAAC,MAAM;QACX,IAAI,CAAC,IAAI;QACT,IAAI,CAAC,GAAG;QACR,IAAI,CAAC,IAAI;QACT,IAAI,CAAC,KAAK;QACV,IAAI,CAAC,IAAI;KACV,CAAC,CAAC;IAEH,MAAM,CAAC,OAAO,CAAC,KAAa;QAC1B,OAAO,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IACpC,CAAC;;AAKH;;;;;;GAMG;AACH,MAAM,OAAO,eAAe;aACV,OAAE,GAAG,aAAa,CAAC,WAAW,CAAC;aAC/B,SAAI,GAAG,aAAa,CAAC,WAAW,CAAC;aACjC,gBAAW,GAAG,aAAa,CAAC,WAAW,CAAC;aACxC,iBAAY,GAAG,aAAa,CAAC,WAAW,CAAC;aAEzC,MAAC,GAAG,a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AAC,KAAK,CAAC,EAAE,CAAC;YACrC,OAAO,IAAI,CAAC;QACd,CAAC;QAED,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC;IACzB,CAAC;IAED,qGAAqG;IACrG,MAAM,CAAC,mBAAmB,CAAC,KAAa;QACtC,OAAO,IAAI,CAAC,cAAc,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC;IAChD,CAAC","sourcesContent":["import { type TConstValue } from '../types';\n\n/** The time units a duration can be expressed in, smallest first. */\nexport class DurationUnits {\n static readonly MILLISECOND = 'millisecond';\n static readonly SECOND = 'second';\n static readonly MINUTE = 'minute';\n static readonly HOUR = 'hour';\n static readonly DAY = 'day';\n static readonly WEEK = 'week';\n static readonly MONTH = 'month';\n static readonly YEAR = 'year';\n\n static readonly SCHEME_SET = new Set([\n this.MILLISECOND,\n this.SECOND,\n this.MINUTE,\n this.HOUR,\n this.DAY,\n this.WEEK,\n this.MONTH,\n this.YEAR,\n ]);\n\n static isValid(input: string): input is TDurationUnit {\n return this.SCHEME_SET.has(input);\n }\n}\n\nexport type TDurationUnit = TConstValue<typeof DurationUnits>;\n\n/**\n * Written spellings that resolve to a unit. Member names are the spelling, upper-cased - so\n * {@link resolve} upper-cases its input and reads one property, with no second table to keep in step.\n *\n * `M` is MINUTE and `MO` is MONTH - the same choice every duration library makes, and the one\n * ambiguity a reader will trip on. There is no single-letter month.\n */\nexport class DurationAliases {\n static readonly MS = DurationUnits.MILLISECOND;\n static readonly MSEC = DurationUnits.MILLISECOND;\n static readonly MILLISECOND = DurationUnits.MILLISECOND;\n static readonly MILLISECONDS = DurationUnits.MILLISECOND;\n\n static readonly S = DurationUnits.SECOND;\n static readonly SEC = DurationUnits.SECOND;\n static readonly SECOND = DurationUnits.SECOND;\n static readonly SECONDS = DurationUnits.SECOND;\n\n static readonly M = DurationUnits.MINUTE;\n static readonly MIN = DurationUnits.MINUTE;\n static readonly MINUTE = DurationUnits.MINUTE;\n static readonly MINUTES = DurationUnits.MINUTE;\n\n static readonly H = DurationUnits.HOUR;\n static readonly HR = DurationUnits.HOUR;\n static readonly HOUR = DurationUnits.HOUR;\n static readonly HOURS = DurationUnits.HOUR;\n\n static readonly D = DurationUnits.DAY;\n static readonly DAY = DurationUnits.DAY;\n static readonly DAYS = DurationUnits.DAY;\n\n static readonly W = DurationUnits.WEEK;\n static readonly WK = DurationUnits.WEEK;\n static readonly WEEK = DurationUnits.WEEK;\n static readonly WEEKS = DurationUnits.WEEK;\n\n static readonly MO = DurationUnits.MONTH;\n static readonly MON = DurationUnits.MONTH;\n static readonly MONTH = DurationUnits.MONTH;\n static readonly MONTHS = DurationUnits.MONTH;\n\n static readonly Y = DurationUnits.YEAR;\n static readonly YR = DurationUnits.YEAR;\n static readonly YEAR = DurationUnits.YEAR;\n static readonly YEARS = DurationUnits.YEAR;\n\n /** Resolves a written unit - `'d'`, `'days'`, `'DAY'` - to its canonical name, or `null`. */\n static resolve(input: string): TDurationUnit | null {\n if (typeof input !== 'string') {\n return null;\n }\n\n // Try the input as given first. `trim().toUpperCase()` allocates two strings and costs ~55ns,\n // where the lookup itself is ~1ns - so the spellings callers actually pass (`'day'`, `'d'`,\n // `'DAYS'`) must not pay for it. Measured, both ways.\n //\n // The table is declared below because it is derived FROM this class; it is read at call time,\n // never at class-evaluation time.\n /* eslint-disable @typescript-eslint/no-use-before-define */\n return ALIAS_LOOKUP.get(input) ?? ALIAS_LOOKUP.get(input.trim().toUpperCase()) ?? null;\n /* eslint-enable @typescript-eslint/no-use-before-define */\n }\n}\n\n/**\n * Derived from the class once, never hand-listed, so the two cannot drift. Reading the class\n * directly is slower and would need `name`/`length`/`constructor` guarded out. Each spelling is\n * stored upper and lower so the common call allocates nothing.\n */\nconst ALIAS_LOOKUP: Map<string, TDurationUnit> = new Map(\n Object.entries(DurationAliases)\n .filter((entry): entry is [string, TDurationUnit] => DurationUnits.isValid(entry[1] as string))\n .flatMap(([spelling, unit]): Array<[string, TDurationUnit]> => [\n [spelling, unit],\n [spelling.toLowerCase(), unit],\n ]),\n);\n\nexport interface IDuration {\n unit: TDurationUnit;\n value: number;\n}\n\n/** `30d`, `1500 ms`, `-2 Hours`. One number, optional space, one unit. */\nconst DURATION_PATTERN = /^([+-]?\\d+(?:\\.\\d+)?)\\s*([a-z]+)$/i;\n\n/**\n * A month is 30 days and a year 365, nominal. These size a WINDOW - a grace period, a cache TTL, a\n * near-expiry horizon - and must never compute a calendar date: adding `MONTH` to 31 January lands\n * on 2 March in a leap year and 3 March otherwise. Use a date library for calendar arithmetic.\n */\nexport class DurationMultipliers {\n static readonly MILLISECOND = 1;\n static readonly SECOND = 1000 * this.MILLISECOND;\n static readonly MINUTE = 60 * this.SECOND;\n static readonly HOUR = 60 * this.MINUTE;\n static readonly DAY = 24 * this.HOUR;\n static readonly WEEK = 7 * this.DAY;\n static readonly MONTH = 30 * this.DAY;\n static readonly YEAR = 365 * this.DAY;\n\n static readonly BY_UNIT: Record<string, number> = {\n [DurationUnits.MILLISECOND]: this.MILLISECOND,\n [DurationUnits.SECOND]: this.SECOND,\n [DurationUnits.MINUTE]: this.MINUTE,\n [DurationUnits.HOUR]: this.HOUR,\n [DurationUnits.DAY]: this.DAY,\n [DurationUnits.WEEK]: this.WEEK,\n [DurationUnits.MONTH]: this.MONTH,\n [DurationUnits.YEAR]: this.YEAR,\n };\n\n /** The multiplier of a known unit, `null` for anything else - inherited property names included. */\n private static multiplierOf(unit: unknown): number | null {\n return typeof unit === 'string' && DurationUnits.isValid(unit) ? this.BY_UNIT[unit] : null;\n }\n\n /**\n * `null` rather than a throw, so a caller that wants an error raises its own with its own context.\n * Every method here answers the same way.\n *\n * The unit is checked against {@link DurationUnits.SCHEME_SET} first: a plain-object read alone\n * would answer `'constructor'` or `'toString'` with a member of `Object.prototype`, not `undefined`.\n */\n static toMilliseconds(opts: IDuration | null): number | null {\n if (!opts) {\n return null;\n }\n\n const multiplier = this.multiplierOf(opts.unit);\n\n if (multiplier === null || !Number.isFinite(opts.value)) {\n return null;\n }\n\n return Math.round(opts.value * multiplier);\n }\n\n /** The inverse of {@link toMilliseconds}. Fractional on purpose - rounding here would silently lose a 36-hour window asked for in days. */\n static fromMilliseconds(opts: { milliseconds: number; unit: TDurationUnit }): number | null {\n const multiplier = this.multiplierOf(opts?.unit);\n\n if (multiplier === null || !Number.isFinite(opts.milliseconds)) {\n return null;\n }\n\n return opts.milliseconds / multiplier;\n }\n\n /** Unit to unit, through milliseconds. Fractional, for the reason {@link fromMilliseconds} gives. */\n static convert(opts: { value: number; from: TDurationUnit; to: TDurationUnit }): number | null {\n const source = this.multiplierOf(opts?.from);\n const target = this.multiplierOf(opts?.to);\n\n if (source === null || target === null || !Number.isFinite(opts.value)) {\n return null;\n }\n\n return (opts.value * source) / target;\n }\n\n /** Reads a written duration - `'30d'`, `'1500 ms'`, `'2 hours'` - into {@link IDuration}. Aliases and the `M`/`MO` rule are on {@link DurationAliases}. */\n static parse(input: string): IDuration | null {\n if (typeof input !== 'string') {\n return null;\n }\n\n const matched = DURATION_PATTERN.exec(input.trim());\n\n if (!matched) {\n return null;\n }\n\n const unit = DurationAliases.resolve(matched[2]);\n const value = Number(matched[1]);\n\n if (!unit || !Number.isFinite(value)) {\n return null;\n }\n\n return { unit, value };\n }\n\n /** `'30d'` straight to milliseconds - the shape a TTL or a grace period is usually configured in. */\n static parseToMilliseconds(input: string): number | null {\n return this.toMilliseconds(this.parse(input));\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"app-env.d.ts","sourceRoot":"","sources":["../../../../src/modules/env/app-env.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAC5C,OAAO,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAC;AAC3C,OAAO,EAAE,KAAK,uBAAuB,EAAE,MAAM,UAAU,CAAC;AAExD,sPAAsP;AACtP,qBAAa,WAAY,SAAQ,gBAAgB;IAC/C,gNAAgN;IACh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KAAK,UAAU,CAAC;KACxD,GACA,UAAU;IAcb,GAAG,CAAC,SAAS,EAAE,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,SAAS;IAI5C,KAAK,CAAC,IAAI,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;KAAE;IAO5C,aAAa;IAIb,IAAI;CAGL;AAoBD,eAAO,MAAM,sBAAsB,wBAAkC,CAAC;AAEtE,eAAO,MAAM,OAAO,wBAAyB,CAAC;AAC9C,eAAO,MAAM,IAAI,wBAAyB,CAAC"}
|
|
@@ -18,7 +18,7 @@ export class Environment extends EnvironmentNames {
|
|
|
18
18
|
export class ApplicationEnvironment extends BaseHelper {
|
|
19
19
|
constructor(opts) {
|
|
20
20
|
super({ scope: ApplicationEnvironment.name });
|
|
21
|
-
this.arguments =
|
|
21
|
+
this.arguments = Object.create(null);
|
|
22
22
|
this.prefix = opts.prefix;
|
|
23
23
|
for (const key in opts.envs) {
|
|
24
24
|
if (!key.startsWith(this.prefix)) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"app-env.js","sourceRoot":"","sources":["../../../../src/modules/env/app-env.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAC7D,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAC5C,OAAO,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAC;AAG3C,sPAAsP;AACtP,MAAM,OAAO,WAAY,SAAQ,gBAAgB;IAC/C,gNAAgN;IAChN,MAAM,KAAK,OAAO;QAChB,MAAM,EAAE,QAAQ,EAAE,GAAG,OAAO,CAAC,GAAG,CAAC;QACjC,OAAO,QAAQ,CAAC;IAClB,CAAC;IAED,MAAM,KAAK,OAAO;QAChB,OAAO,WAAW,CAAC,OAAO,IAAI,WAAW,CAAC,WAAW,CAAC;IACxD,CAAC;IAED,MAAM,CAAC,EAAE,CAAC,IAAsB;Q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AO,KAAK,aAAa,CAAC;IAC/C,CAAC;IAED,IAAI;QACF,OAAO,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;IACrC,CAAC;CACF;AAED,iNAAiN;AACjN,MAAM,aAAa,GAAG,MAAM,CAAC,GAAG,CAAC,+BAA+B,CAAC,CAAC;AAElE,MAAM,6BAA6B,GAAG,GAA2B,EAAE;IACjE,MAAM,MAAM,GAAuC,OAAO,CAAC,GAAG,CAAC,UAAU,EAAE,aAAa,CAAC,CAAC;IAC1F,IAAI,MAAM,EAAE,CAAC;QACX,OAAO,MAAM,CAAC;IAChB,CAAC;IAED,MAAM,OAAO,GAAG,IAAI,sBAAsB,CAAC;QACzC,MAAM,EAAE,gBAAgB,CAAC,OAAO,CAAC,GAAG,CAAC,sBAAsB,CAAC,IAAI,SAAS;QACzE,IAAI,EAAE,OAAO,CAAC,GAAG;KAClB,CAAC,CAAC;IACH,OAAO,CAAC,GAAG,CAAC,UAAU,EAAE,aAAa,EAAE,OAAO,CAAC,CAAC;IAEhD,OAAO,OAAO,CAAC;AACjB,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,sBAAsB,GAAG,6BAA6B,EAAE,CAAC;AAEtE,MAAM,CAAC,MAAM,OAAO,GAAG,sBAAsB,CAAC;AAC9C,MAAM,CAAC,MAAM,IAAI,GAAG,sBAAsB,CAAC","sourcesContent":["import { blankToUndefined } from '@/utilities/parse.utility';\nimport { BaseHelper } from '@/modules/base';\nimport { EnvironmentNames } from './names';\nimport { type IApplicationEnvironment } from './common';\n\n/** Adds the `NODE_ENV` reads to {@link EnvironmentNames}. Every name and set is inherited, so `Environment.PRODUCTION`, `Environment.COMMON_ENVS` and `Environment.DEVELOPMENT_ENVS` keep resolving here; only these two members need a `process`. */\nexport class Environment extends EnvironmentNames {\n /** `NODE_ENV` exactly as the host has it, `undefined` when unset. Destructured on purpose: `bun build` rewrites `process.env.NODE_ENV` to a literal at build time, a destructured read stays a runtime read. */\n static get ambient(): string | undefined {\n const { NODE_ENV } = process.env;\n return NODE_ENV;\n }\n\n static get current(): string {\n return Environment.ambient ?? Environment.DEVELOPMENT;\n }\n\n static is(opts: { name: string }) {\n return this.current === opts.name;\n }\n}\n\nexport class ApplicationEnvironment extends BaseHelper implements IApplicationEnvironment {\n private prefix: string;\n private arguments: Record<string, any> = Object.create(null);\n\n constructor(opts: { prefix: string; envs: Record<string, string | number | undefined> }) {\n super({ scope: ApplicationEnvironment.name });\n\n this.prefix = opts.prefix;\n\n for (const key in opts.envs) {\n if (!key.startsWith(this.prefix)) {\n continue;\n }\n\n this.arguments[key] = opts.envs[key];\n }\n }\n\n /**\n * Reads one name. A line that is present but empty - `KEY=`, or padded to `KEY= ` by a hand\n * edit - is a pipeline that forgot to export the value, not a value: it is normalised to\n * `undefined` so `defaultValue` applies, and `transform` is handed that `undefined` rather than\n * the empty string.\n *\n * The normalisation runs ONLY when the caller supplied a `defaultValue`, because that call site\n * has already declared what it wants when the name carries nothing. A caller without one still\n * receives `''` unchanged, so no existing read changes shape. `'0'` and `'false'` are values and\n * are never normalised.\n */\n get<ReturnType, BeforeTransformType = unknown>(\n key: string,\n opts?: {\n defaultValue?: ReturnType;\n transform?: (value: BeforeTransformType) => ReturnType;\n },\n ): ReturnType {\n const raw = this.arguments[key];\n\n const isBlank = raw === undefined || raw === null || (typeof raw === 'string' && !raw.trim());\n const rs = opts?.defaultValue !== undefined && isBlank ? undefined : raw;\n\n if (!opts?.transform) {\n return (rs ?? opts?.defaultValue) as ReturnType;\n }\n\n const transformed = opts.transform(rs);\n return (transformed ?? opts?.defaultValue) as ReturnType;\n }\n\n set<ValueType>(key: string, value: ValueType) {\n this.arguments[key] = value;\n }\n\n merge(opts: { envs: Record<string, string> }) {\n const envsEntries = Object.entries(opts.envs);\n for (const [key, value] of envsEntries) {\n this.arguments[key] = value;\n }\n }\n\n isDevelopment() {\n return Environment.ambient === 'development';\n }\n\n keys() {\n return Object.keys(this.arguments);\n }\n}\n\n/** A process can carry two copies of this module - an application's ESM import beside a CommonJS require. The instance lives in this globalThis slot so a `set()` through one copy is read through the other. */\nconst INSTANCE_SLOT = Symbol.for('ignis:application-environment');\n\nconst resolveApplicationEnvironment = (): ApplicationEnvironment => {\n const shared: ApplicationEnvironment | undefined = Reflect.get(globalThis, INSTANCE_SLOT);\n if (shared) {\n return shared;\n }\n\n const created = new ApplicationEnvironment({\n prefix: blankToUndefined(process.env.APPLICATION_ENV_PREFIX) ?? 'APP_ENV',\n envs: process.env,\n });\n Reflect.set(globalThis, INSTANCE_SLOT, created);\n\n return created;\n};\n\nexport const applicationEnvironment = resolveApplicationEnvironment();\n\nexport const AppEnvs = applicationEnvironment;\nexport const Envs = applicationEnvironment;\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"logger.d.ts","sourceRoot":"","sources":["../../../../../src/modules/logger/hf/logger.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,OAAO,EAAE,MAAM,gBAAgB,CAAC;AAC9C,OAAO,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AACzC,OAAO,EAAE,KAAK,OAAO,EAA+B,KAAK,SAAS,EAAE,MAAM,WAAW,CAAC;AAkBtF,4KAA4K;AAC5K,qBAAa,QAAS,SAAQ,cAAc;IAC1C,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,WAAW,CAAqB;IACxD,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,UAAU,CAAiC;IACnE,OAAO,CAAC,MAAM,CAAC,KAAK,CAA+B;IACnD,OAAO,CAAC,MAAM,CAAC,YAAY,CAAiC;IAE5D,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAS;IAC/B,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAa;IACxC,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAS;IAErC,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAa;IAElC,OAAO;IAQP,OAAO,CAAC,MAAM,CAAC,WAAW;IAS1B,MAAM,C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|
|
@@ -97,7 +97,9 @@ export class HfLogger extends AbstractLogger {
|
|
|
97
97
|
if (level === LogLevels.DEBUG && !SHOULD_LOG_DEBUG) {
|
|
98
98
|
return;
|
|
99
99
|
}
|
|
100
|
-
const levelCode = HF_LEVEL_CODES
|
|
100
|
+
const levelCode = Object.hasOwn(HF_LEVEL_CODES, level)
|
|
101
|
+
? HF_LEVEL_CODES[level]
|
|
102
|
+
: HF_LEVEL_CODES.info;
|
|
101
103
|
if (typeof message === 'string') {
|
|
102
104
|
this.writeString(levelCode, message, args);
|
|
103
105
|
return;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"logger.js","sourceRoot":"","sources":["../../../../../src/modules/logger/hf/logger.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AACzC,OAAO,EAAgB,SAAS,EAAE,gBAAgB,EAAkB,MAAM,WAAW,CAAC;AACtF,OAAO,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AACjD,OAAO,EACL,WAAW,EACX,UAAU,EACV,cAAc,EACd,oBAAoB,EACpB,kBAAkB,EAClB,iBAAiB,EACjB,YAAY,EACZ,cAAc,EACd,qBAAqB,EACrB,YAAY,EACZ,mBAAmB,GAEpB,MAAM,UAAU,CAAC;AAClB,OAAO,EAAE,SAAS,EAAE,MAAM,QAAQ,CAAC;AAEnC,4KAA4K;AAC5K,MAAM,OAAO,QAAS,SAAQ,cAAc;aAClB,gBAAW,GAAG,IAAI,WAAW,EAAE,CAAC;aAChC,eAAU,GAAG,IAAI,GAAG,EAAsB,CAAC;aACpD,UAAK,GAAG,IAAI,GAAG,EAAoB,CAAC;aACpC,iBAAY,GAAG,IAAI,GAAG,EAAsB,CAAC;IAQ5D,YAAoB,KAAa;QAC/B,KAAK,EAAE,CAAC;QACR,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,UAAU,GAAG,QAAQ,CAAC,WAAW,CAAC,KAAK,CA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AC,KAAgB,EAAE,OAA4B,EAAE,GAAG,IAAe;QACpE,IAAI,KAAK,KAAK,SAAS,CAAC,KAAK,IAAI,CAAC,gBAAgB,EAAE,CAAC;YACnD,OAAO;QACT,CAAC;QACD,MAAM,SAAS,GAAG,MAAM,CAAC,MAAM,CAAC,cAAc,EAAE,KAAK,CAAC;YACpD,CAAC,CAAC,cAAc,CAAC,KAAK,CAAC;YACvB,CAAC,CAAC,cAAc,CAAC,IAAI,CAAC;QACxB,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE,CAAC;YAChC,IAAI,CAAC,WAAW,CAAC,SAAS,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC;YAC3C,OAAO;QACT,CAAC;QACD,IAAI,CAAC,UAAU,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;IACtC,CAAC;IAED,GAAG,CAAC,UAAkB;QACpB,OAAO,QAAQ,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC,KAAK,IAAI,UAAU,EAAE,CAAC,CAAC;IACrD,CAAC","sourcesContent":["import { type AnyType } from '@/common/types';\nimport { AbstractLogger } from '../base';\nimport { type ILogger, LogLevels, SHOULD_LOG_DEBUG, type TLogLevel } from '../common';\nimport { formatLogMessage } from '../formatting';\nimport {\n BUFFER_SIZE,\n ENTRY_SIZE,\n HF_LEVEL_CODES,\n HF_MESSAGE_MAX_BYTES,\n HF_SCOPE_MAX_BYTES,\n MESSAGE_CACHE_CAP,\n OFFSET_LEVEL,\n OFFSET_MESSAGE,\n OFFSET_MESSAGE_LENGTH,\n OFFSET_SCOPE,\n OFFSET_SCOPE_LENGTH,\n type TRingState,\n} from './common';\nimport { HfLogRing } from './ring';\n\n/** Ring-buffer logger for hot paths; extends AbstractLogger, NOT BaseLogger - BaseLogger's string-sink plumbing is exactly the cost this implementation exists to avoid. */\nexport class HfLogger extends AbstractLogger {\n private static readonly textEncoder = new TextEncoder();\n private static readonly scopeCache = new Map<string, Uint8Array>();\n private static cache = new Map<string, HfLogger>();\n private static messageCache = new Map<string, Uint8Array>();\n\n private readonly scope: string;\n private readonly scopeBytes: Uint8Array;\n private readonly scopeLength: number;\n // Resolved once at construction (get() has already allocated the ring): saves a call and a null-check per log on a path budgeted in nanoseconds.\n private readonly ring: TRingState;\n\n private constructor(scope: string) {\n super();\n this.scope = scope;\n this.scopeBytes = HfLogger.encodeScope(scope);\n this.scopeLength = this.scopeBytes.length;\n this.ring = HfLogRing.get();\n }\n\n private static encodeScope(scope: string): Uint8Array {\n let bytes = HfLogger.scopeCache.get(scope);\n if (!bytes) {\n bytes = HfLogger.textEncoder.encode(scope).subarray(0, HF_SCOPE_MAX_BYTES);\n HfLogger.scopeCache.set(scope, bytes);\n }\n return bytes;\n }\n\n static get(scope: string): HfLogger {\n let logger = this.cache.get(scope);\n if (!logger) {\n logger = new HfLogger(scope); // first logger allocates the ring - never at import\n this.cache.set(scope, logger);\n }\n return logger;\n }\n\n /** Pre-encode a message at initialization time; the cache is FIFO-bounded so dynamic strings can't grow it without limit. */\n static encodeMessage(message: string): Uint8Array {\n const cached = this.messageCache.get(message);\n if (cached) {\n return cached;\n }\n\n const bytes = HfLogger.textEncoder.encode(message);\n if (this.messageCache.size >= MESSAGE_CACHE_CAP) {\n this.evictOldestMessage();\n }\n this.messageCache.set(message, bytes);\n return bytes;\n }\n\n private static evictOldestMessage(): void {\n const oldest = this.messageCache.keys().next().value;\n if (oldest === undefined) {\n return;\n }\n this.messageCache.delete(oldest);\n }\n\n private writeEntry(levelCode: number, messageBytes: Uint8Array): void {\n const ring = this.ring;\n const slot = ring.writeIndex++ & (BUFFER_SIZE - 1);\n const offset = slot * ENTRY_SIZE;\n ring.f64[offset >> 3] = performance.timeOrigin + performance.now();\n const bytes = ring.bytes;\n bytes[offset + OFFSET_LEVEL] = levelCode;\n bytes[offset + OFFSET_SCOPE_LENGTH] = this.scopeLength;\n bytes.set(this.scopeBytes, offset + OFFSET_SCOPE);\n const messageLength =\n messageBytes.length < HF_MESSAGE_MAX_BYTES ? messageBytes.length : HF_MESSAGE_MAX_BYTES;\n bytes[offset + OFFSET_MESSAGE_LENGTH] = messageLength;\n bytes.set(\n messageLength === messageBytes.length\n ? messageBytes\n : messageBytes.subarray(0, messageLength),\n offset + OFFSET_MESSAGE,\n );\n }\n\n private writeString(levelCode: number, message: string, args: Array<AnyType>): void {\n if (args.length > 0) {\n // Slow path, documented: args are formatted (deep inspection + redaction) - never dropped.\n this.writeEntry(levelCode, HfLogger.textEncoder.encode(formatLogMessage({ message, args })));\n return;\n }\n this.writeEntry(levelCode, HfLogger.encodeMessage(message));\n }\n\n debug(message: string, ...args: AnyType[]): void {\n if (!SHOULD_LOG_DEBUG) {\n return;\n }\n this.writeString(HF_LEVEL_CODES.debug, message, args);\n }\n\n info(message: string, ...args: AnyType[]): void {\n this.writeString(HF_LEVEL_CODES.info, message, args);\n }\n\n warn(message: string, ...args: AnyType[]): void {\n this.writeString(HF_LEVEL_CODES.warn, message, args);\n }\n\n error(message: string, ...args: AnyType[]): void {\n this.writeString(HF_LEVEL_CODES.error, message, args);\n }\n\n emerg(message: string, ...args: AnyType[]): void {\n this.writeString(HF_LEVEL_CODES.emerg, message, args);\n }\n\n log(level: TLogLevel, message: string, ...args: AnyType[]): void;\n log(level: TLogLevel, messageBytes: Uint8Array): void;\n log(level: TLogLevel, message: string | Uint8Array, ...args: AnyType[]): void {\n if (level === LogLevels.DEBUG && !SHOULD_LOG_DEBUG) {\n return;\n }\n const levelCode = Object.hasOwn(HF_LEVEL_CODES, level)\n ? HF_LEVEL_CODES[level]\n : HF_LEVEL_CODES.info;\n if (typeof message === 'string') {\n this.writeString(levelCode, message, args);\n return;\n }\n this.writeEntry(levelCode, message);\n }\n\n for(methodName: string): ILogger {\n return HfLogger.get(`${this.scope}-${methodName}`);\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base-tcp-server.helper.d.ts","sourceRoot":"","sources":["../../../../../src/modules/network/tcp-socket/base-tcp-server.helper.ts"],"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AAE,MAAM,CAAC;QAAC,MAAM,EAAE,gBAAgB,CAAA;KAAE,KAAK,IAAI,CAAC;IACnF,SAAS,CAAC,aAAa,CAAC,EAAE,CAAC,IAAI,EAAE;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,gBAAgB,CAAC;QAAC,KAAK,EAAE,KAAK,CAAA;KAAE,KAAK,IAAI,CAAC;IACjG,SAAS,CAAC,aAAa,CAAC,EAAE,CAAC,IAAI,EAAE;QAAE,MAAM,EAAE,gBAAgB,CAAC;QAAC,KAAK,EAAE,KAAK,CAAA;KAAE,KAAK,IAAI,CAAC;gBAGnF,IAAI,EAAE,uBAAuB,CAAC,mBAAmB,EAAE,gBAAgB,EAAE,gBAAgB,CAAC;
|
|
1
|
+
{"version":3,"file":"base-tcp-server.helper.d.ts","sourceRoot":"","sources":["../../../../../src/modules/network/tcp-socket/base-tcp-server.helper.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,cAAc,EAAE,MAAM,gBAAgB,CAAC;AACrD,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAI5C,OAAO,EACL,KAAK,aAAa,EAClB,KAAK,UAAU,EACf,KAAK,MAAM,IAAI,YAAY,EAC3B,KAAK,MAAM,IAAI,YAAY,EAC5B,MAAM,UAAU,CAAC;AAElB,MAAM,WAAW,gBAAgB,CAAC,gBAAgB;IAChD,EAAE,EAAE,MAAM,CAAC;IACX,MAAM,EAAE,gBAAgB,CAAC;IACzB,KAAK,EAAE,cAAc,GAAG,gBAAgB,GAAG,eAAe,CAAC;IAC3D,aAAa,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;IAC3B,OAAO,EAAE;QACP,WAAW,EAAE,IAAI,CAAC;QAClB,eAAe,EAAE,IAAI,GAAG,IAAI,CAAC;QAC7B,mBAAmB,CAAC,EAAE,UAAU,CAAC,OAAO,UAAU,CAAC,GAAG,IAAI,CAAC;QAC3D,CAAC,aAAa,EAAE,MAAM,GAAG,MA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HlD,UAAU;IAIV,SAAS,CAAC,IAAI,EAAE;QAAE,EAAE,EAAE,MAAM,CAAA;KAAE;IAI9B,SAAS;IAIT,0LAA0L;IACpL,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC;IAkC/B,cAAc,CAAC,IAAI,EAAE;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,cAAc,GAAG,gBAAgB,GAAG,eAAe,CAAA;KAAE;IAgC/F,IAAI,CAAC,IAAI,EAAE;QAAE,QAAQ,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAAA;KAAE;CA4B1D"}
|
|
@@ -10,7 +10,8 @@ export class BaseNetworkTcpServer extends BaseHelper {
|
|
|
10
10
|
});
|
|
11
11
|
this.serverOptions = {};
|
|
12
12
|
this.listenOptions = {};
|
|
13
|
-
|
|
13
|
+
// No prototype: `getClient({ id: 'constructor' })` must find nothing, not `Object`.
|
|
14
|
+
this.clients = Object.create(null);
|
|
14
15
|
this.serverOptions = opts.serverOptions;
|
|
15
16
|
this.listenOptions = opts.listenOptions;
|
|
16
17
|
this.authenticateOptions = opts.authenticateOptions;
|
|
@@ -179,7 +180,7 @@ export class BaseNetworkTcpServer extends BaseHelper {
|
|
|
179
180
|
}
|
|
180
181
|
client.socket.destroy();
|
|
181
182
|
}
|
|
182
|
-
this.clients =
|
|
183
|
+
this.clients = Object.create(null);
|
|
183
184
|
const server = this.server;
|
|
184
185
|
if (!server) {
|
|
185
186
|
return;
|
|
@@ -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":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAC5C,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAAE,MAAM,EAAE,MAAM,2BAA2B,CAAC;AACnD,OAAO,EAAE,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/base';\nimport { getError } from '@/modules/error';\nimport { getUID } from '@/utilities/parse.utility';\nimport { voidExecution } 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\nexport interface ITcpSocketClient<SocketClientType> {\n id: string;\n socket: SocketClientType;\n state: 'unauthorized' | 'authenticating' | 'authenticated';\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\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\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 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 this.clients = Object.assign({});\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 = 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 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 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 ? 'unauthorized' : '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 if (!client) {\n return;\n }\n\n client.storage.authenticateTimeout = null;\n\n if (client.state === '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 if (!client) {\n clearTimeout(authenticateTimeout);\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 for (const client of clientsValues) {\n const { authenticateTimeout } = client.storage;\n if (authenticateTimeout) {\n clearTimeout(authenticateTimeout);\n client.storage.authenticateTimeout = null;\n }\n\n client.socket.destroy();\n }\n\n this.clients = {};\n\n const server = this.server;\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: 'unauthorized' | 'authenticating' | 'authenticated' }) {\n const { id, state } = opts;\n\n const client = this.getClient({ id });\n if (!client) {\n this.logger.for('authenticateClient').error('Client NOT FOUND | ID: %s', id);\n return;\n }\n\n client.state = state;\n\n switch (state) {\n case 'unauthorized':\n case 'authenticating': {\n client.storage.authenticatedAt = null;\n break;\n }\n case '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 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 return;\n }\n\n const { socket } = client;\n if (!socket.writable) {\n this.logger.for(this.emit.name).error('Client NOT WRITABLE | ID: %s', clientId);\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 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":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAC5C,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAAE,MAAM,EAAE,MAAM,2BAA2B,CAAC;AACnD,OAAO,EAAE,aAAa,EAAE,MAAM,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/common/types';\nimport { BaseHelper } from '@/modules/base';\nimport { getError } from '@/modules/error';\nimport { getUID } from '@/utilities/parse.utility';\nimport { voidExecution } 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\nexport interface ITcpSocketClient<SocketClientType> {\n id: string;\n socket: SocketClientType;\n state: 'unauthorized' | 'authenticating' | 'authenticated';\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\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\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 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 = 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 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 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 ? 'unauthorized' : '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 if (!client) {\n return;\n }\n\n client.storage.authenticateTimeout = null;\n\n if (client.state === '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 if (!client) {\n clearTimeout(authenticateTimeout);\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 for (const client of clientsValues) {\n const { authenticateTimeout } = client.storage;\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 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: 'unauthorized' | 'authenticating' | 'authenticated' }) {\n const { id, state } = opts;\n\n const client = this.getClient({ id });\n if (!client) {\n this.logger.for('authenticateClient').error('Client NOT FOUND | ID: %s', id);\n return;\n }\n\n client.state = state;\n\n switch (state) {\n case 'unauthorized':\n case 'authenticating': {\n client.storage.authenticatedAt = null;\n break;\n }\n case '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 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 return;\n }\n\n const { socket } = client;\n if (!socket.writable) {\n this.logger.for(this.emit.name).error('Client NOT WRITABLE | ID: %s', clientId);\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 return;\n }\n\n socket.write(payload);\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"abstract.helper.d.ts","sourceRoot":"","sources":["../../../../../src/modules/secrets/base/abstract.helper.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAE5C,OAAO,KAAK,EACV,MAAM,EACN,iBAAiB,EACjB,YA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C,MAAM,CAAC;IAW7D,KAAK,CAAC,IAAI,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,GAAG,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,YAAY,CAAC;IAoBvE,QAAQ,CAAC,OAAO,EAAE,sBAAsB,GAAG,IAAI;IAI/C,iBAAiB,CAAC,IAAI,EAAE;QAAE,GAAG,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,gBAAgB,CAAA;KAAE,GAAG,IAAI;IAMlE,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC;IA4B/B,OAAO,CAAC,UAAU;IAOlB,OAAO,CAAC,iBAAiB;IASzB,OAAO,CAAC,YAAY;IAOpB,OAAO,CAAC,QAAQ;IAehB,OAAO,CAAC,eAAe;IAYvB,OAAO,CAAC,oBAAoB;YAWd,aAAa;YA6Cb,MAAM;YAoBN,gBAAgB;CAkB/B"}
|
|
@@ -57,7 +57,11 @@ export class AbstractSecretsHelper extends BaseHelper {
|
|
|
57
57
|
}
|
|
58
58
|
async get(opts) {
|
|
59
59
|
const bundle = await this.getBundle({ path: opts.path });
|
|
60
|
-
const raw = opts.key
|
|
60
|
+
const raw = opts.key
|
|
61
|
+
? Object.hasOwn(bundle, opts.key)
|
|
62
|
+
? bundle[opts.key]
|
|
63
|
+
: undefined
|
|
64
|
+
: bundle;
|
|
61
65
|
return (raw ?? opts.defaultValue);
|
|
62
66
|
}
|
|
63
67
|
async lease(opts) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"abstract.helper.js","sourceRoot":"","sources":["../../../../../src/modules/secrets/base/abstract.helper.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAC5C,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAwB3C,MAAM,aAAa,GAAW,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,GAAG,EAAE,EAAE,CAAC;AACxD,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AAC;QACH,CAAC;IACH,CAAC;CACF","sourcesContent":["import type { AnyType } from '@/common/types';\nimport { BaseHelper } from '@/modules/base';\nimport { getError } from '@/modules/error';\nimport type {\n IClock,\n IGetSecretOptions,\n ISecretLease,\n ISecretRotatable,\n ISecretRotationEvent,\n ISecretsHelper,\n ISecretsHelperOptions,\n ITimerAdapter,\n TSecretRotationHandler,\n TTimerHandle,\n} from '../common';\n\ninterface ICacheEntry {\n value: Record<string, string>;\n expiresAt: number;\n}\n\ninterface IRawFetchResult {\n value: Record<string, string>;\n lease?: { leaseId: string; ttlSeconds: number; renewable: boolean };\n}\n\nconst DEFAULT_CLOCK: IClock = { now: () => Date.now() };\nconst DEFAULT_TIMERS: ITimerAdapter = {\n set: (handler, ms) => setTimeout(handler, ms),\n clear: (handle) => clearTimeout(handle as AnyType),\n};\n\nconst DEFAULT_CACHE_TTL_SECONDS = 300;\nconst DEFAULT_RENEW_BEFORE_RATIO = 0.66;\n\n// setTimeout coerces any delay above this to 1ms, triggering an immediate renewal storm.\nconst TIMEOUT_MAX_MS = 2_147_483_647;\n// Floor so an invalid/tiny ttl never becomes a 0ms busy-loop.\nconst MIN_RENEW_DELAY_MS = 1_000;\n// Bounded exponential backoff for the renewal retry loop when Vault is unreachable.\nconst BACKOFF_BASE_MS = 1_000;\n// Capped at 31 to keep 2 ** (attempt - 1) inside double range: past ~1024 it overflows to Infinity and clampDelayMs's non-finite branch returns the FLOOR, collapsing a long backoff into a 1/sec retry storm.\nconst MAX_BACKOFF_ATTEMPT_EXPONENT = 31;\n\nexport abstract class AbstractSecretsHelper extends BaseHelper implements ISecretsHelper {\n protected readonly clock: IClock;\n protected readonly timers: ITimerAdapter;\n protected readonly cacheTtlSeconds: number;\n protected readonly renewBeforeRatio: number;\n\n private readonly cache = new Map<string, ICacheEntry>();\n private readonly leases = new Map<string, ISecretLease>();\n private readonly leasePaths = new Map<string, string>();\n private readonly timerHandles = new Map<string, TTimerHandle>();\n private readonly rotatables = new Map<string, ISecretRotatable[]>();\n private readonly rotateHandlers: TSecretRotationHandler[] = [];\n private readonly backoffAttempts = new Map<string, number>();\n private closed = false;\n\n constructor(opts: ISecretsHelperOptions) {\n super({ scope: opts.scope, identifier: opts.identifier });\n this.clock = opts.clock ?? DEFAULT_CLOCK;\n this.timers = opts.timers ?? DEFAULT_TIMERS;\n this.cacheTtlSeconds = opts.cacheTtlSeconds ?? DEFAULT_CACHE_TTL_SECONDS;\n\n const ratio = opts.renewBeforeRatio ?? DEFAULT_RENEW_BEFORE_RATIO;\n if (!Number.isFinite(ratio) || ratio <= 0 || ratio > 1) {\n throw getError({\n message: `[constructor] renewBeforeRatio must be within (0, 1] | received: ${ratio}`,\n });\n }\n this.renewBeforeRatio = ratio;\n }\n\n protected abstract fetchRaw(opts: { path: string }): Promise<IRawFetchResult>;\n protected abstract renewRaw(opts: {\n leaseId: string;\n ttlSeconds: number;\n }): Promise<{ ttlSeconds: number } | null>;\n protected abstract revokeRaw(opts: { leaseId: string }): Promise<void>;\n\n // Concrete providers override to authenticate; default is a no-op.\n async configure(): Promise<void> {\n return;\n }\n\n async getBundle(opts: { path: string }): Promise<Record<string, string>> {\n this.evictExpiredCache();\n const cached = this.cache.get(opts.path);\n if (cached && cached.expiresAt > this.clock.now()) {\n return cached.value;\n }\n const fresh = await this.fetchRaw({ path: opts.path });\n // A shutdown that ran while fetchRaw was in flight already cleared `cache` - honor that and hand back the fetched value uncached rather than resurrecting a map shutdown just emptied.\n if (this.closed) {\n return fresh.value;\n }\n this.writeCache({ path: opts.path, value: fresh.value });\n return fresh.value;\n }\n\n async get(opts: IGetSecretOptions<string>): Promise<string>;\n async get<TValue>(opts: IGetSecretOptions<TValue>): Promise<TValue>;\n async get<TValue = string>(opts: IGetSecretOptions<TValue>): Promise<TValue> {\n const bundle = await this.getBundle({ path: opts.path });\n const raw = opts.key ? bundle[opts.key] : (bundle as AnyType);\n return (raw ?? opts.defaultValue) as TValue;\n }\n\n async lease(opts: { path: string; key: string }): Promise<ISecretLease> {\n const fresh = await this.fetchRaw({ path: opts.path });\n // A shutdown that ran while fetchRaw was in flight already revoked/cleared every lease - committing this one now would resurrect leases/leasePaths with a lease no live provider will ever renew or revoke, so surface the shutdown instead of silently leaking it back in.\n if (this.closed) {\n throw getError({\n message: `[lease] Provider is shut down | path: ${opts.path} | key: ${opts.key}`,\n });\n }\n if (!fresh.lease) {\n throw getError({\n message: `[lease] Path returned no lease | path: ${opts.path} | key: ${opts.key}`,\n });\n }\n const lease: ISecretLease = { value: fresh.value, ...fresh.lease };\n this.leases.set(opts.key, lease);\n this.leasePaths.set(opts.key, opts.path);\n this.scheduleRenewal({ key: opts.key, lease });\n return lease;\n }\n\n onRotate(handler: TSecretRotationHandler): void {\n this.rotateHandlers.push(handler);\n }\n\n registerRotatable(opts: { key: string; target: ISecretRotatable }): void {\n const list = this.rotatables.get(opts.key) ?? [];\n list.push(opts.target);\n this.rotatables.set(opts.key, list);\n }\n\n async shutdown(): Promise<void> {\n const logger = this.logger.for(this.shutdown.name);\n this.closed = true;\n\n const timerHandlesValues = this.timerHandles.values();\n for (const handle of timerHandlesValues) {\n this.timers.clear(handle);\n }\n this.timerHandles.clear();\n this.backoffAttempts.clear();\n\n for (const [key, lease] of this.leases) {\n try {\n await this.revokeRaw({ leaseId: lease.leaseId });\n } catch (error) {\n logger.error(\n 'Revoke failed | key: %s | leaseId: %s | error: %s',\n key,\n lease.leaseId,\n error,\n );\n }\n }\n this.leases.clear();\n this.leasePaths.clear();\n this.cache.clear();\n }\n\n private writeCache(opts: { path: string; value: Record<string, string> }): void {\n this.cache.set(opts.path, {\n value: opts.value,\n expiresAt: this.clock.now() + this.cacheTtlSeconds * 1000,\n });\n }\n\n private evictExpiredCache(): void {\n const now = this.clock.now();\n for (const [path, entry] of this.cache) {\n if (entry.expiresAt <= now) {\n this.cache.delete(path);\n }\n }\n }\n\n private clampDelayMs(opts: { delayMs: number }): number {\n if (!Number.isFinite(opts.delayMs) || opts.delayMs <= 0) {\n return MIN_RENEW_DELAY_MS;\n }\n return Math.min(Math.max(opts.delayMs, MIN_RENEW_DELAY_MS), TIMEOUT_MAX_MS);\n }\n\n private armTimer(opts: { key: string; delayMs: number }): void {\n const existing = this.timerHandles.get(opts.key);\n if (existing) {\n this.timers.clear(existing);\n }\n const handle = this.timers.set(() => {\n this.handleRenewal({ key: opts.key }).catch((error) => {\n this.logger\n .for(this.armTimer.name)\n .error('Renewal handler crashed | key: %s | error: %s', opts.key, error);\n });\n }, opts.delayMs);\n this.timerHandles.set(opts.key, handle);\n }\n\n private scheduleRenewal(opts: { key: string; lease: ISecretLease }): void {\n if (this.closed) {\n return;\n }\n this.backoffAttempts.delete(opts.key);\n const delayMs = this.clampDelayMs({\n delayMs: opts.lease.ttlSeconds * this.renewBeforeRatio * 1000,\n });\n this.armTimer({ key: opts.key, delayMs });\n }\n\n // A transient Vault failure must not kill the loop; retry with bounded exponential backoff.\n private scheduleBackoffRetry(opts: { key: string }): void {\n if (this.closed) {\n return;\n }\n const attempt = (this.backoffAttempts.get(opts.key) ?? 0) + 1;\n this.backoffAttempts.set(opts.key, attempt);\n const cappedAttempt = Math.min(attempt, MAX_BACKOFF_ATTEMPT_EXPONENT);\n const delayMs = this.clampDelayMs({ delayMs: BACKOFF_BASE_MS * 2 ** (cappedAttempt - 1) });\n this.armTimer({ key: opts.key, delayMs });\n }\n\n private async handleRenewal(opts: { key: string }): Promise<void> {\n if (this.closed) {\n return;\n }\n const logger = this.logger.for(this.handleRenewal.name);\n const lease = this.leases.get(opts.key);\n if (!lease) {\n logger.debug('No lease to renew | key: %s', opts.key);\n return;\n }\n try {\n if (!lease.renewable) {\n await this.rotate({ key: opts.key });\n return;\n }\n\n const renewed = await this.renewRaw({\n leaseId: lease.leaseId,\n ttlSeconds: lease.ttlSeconds,\n });\n if (this.closed) {\n return;\n }\n\n if (!renewed) {\n await this.rotate({ key: opts.key });\n return;\n }\n\n const next: ISecretLease = { ...lease, ttlSeconds: renewed.ttlSeconds };\n this.leases.set(opts.key, next);\n this.scheduleRenewal({ key: opts.key, lease: next });\n } catch (error) {\n if (this.closed) {\n return;\n }\n logger.error(\n 'Renewal cycle failed; scheduling backoff retry | key: %s | error: %s',\n opts.key,\n error,\n );\n this.scheduleBackoffRetry({ key: opts.key });\n }\n }\n\n private async rotate(opts: { key: string }): Promise<void> {\n const path = this.leasePaths.get(opts.key);\n if (!path) {\n throw getError({ message: `[rotate] No lease path registered | key: ${opts.key}` });\n }\n const fresh = await this.fetchRaw({ path });\n if (this.closed) {\n return;\n }\n if (!fresh.lease) {\n throw getError({ message: `[rotate] Path returned no lease on rotation | key: ${opts.key}` });\n }\n const lease: ISecretLease = { value: fresh.value, ...fresh.lease };\n this.leases.set(opts.key, lease);\n this.writeCache({ path, value: fresh.value });\n // Arm the next renewal BEFORE dispatching: a wedged consumer must not stall the loop.\n this.scheduleRenewal({ key: opts.key, lease });\n await this.dispatchRotation({ key: opts.key, lease });\n }\n\n private async dispatchRotation(event: ISecretRotationEvent): Promise<void> {\n const logger = this.logger.for(this.dispatchRotation.name);\n for (const handler of this.rotateHandlers) {\n try {\n await handler(event);\n } catch (error) {\n logger.error('onRotate handler failed | key: %s | error: %s', event.key, error);\n }\n }\n const targets = this.rotatables.get(event.key) ?? [];\n for (const target of targets) {\n try {\n await target.onSecretRotated({ key: event.key, secret: event.lease.value });\n } catch (error) {\n logger.error('Rotatable failed | key: %s | error: %s', event.key, error);\n }\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"abstract.helper.js","sourceRoot":"","sources":["../../../../../src/modules/secrets/base/abstract.helper.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAC5C,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAwB3C,MAAM,aAAa,GAAW,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,GAAG,EAAE,EAAE,CAAC;AACxD,MAAM,cAAc,GAAkB;IACpC,GAAG,E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CAAC,wCAAwC,EAAE,KAAK,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;YAC3E,CAAC;QACH,CAAC;IACH,CAAC;CACF","sourcesContent":["import type { AnyType } from '@/common/types';\nimport { BaseHelper } from '@/modules/base';\nimport { getError } from '@/modules/error';\nimport type {\n IClock,\n IGetSecretOptions,\n ISecretLease,\n ISecretRotatable,\n ISecretRotationEvent,\n ISecretsHelper,\n ISecretsHelperOptions,\n ITimerAdapter,\n TSecretRotationHandler,\n TTimerHandle,\n} from '../common';\n\ninterface ICacheEntry {\n value: Record<string, string>;\n expiresAt: number;\n}\n\ninterface IRawFetchResult {\n value: Record<string, string>;\n lease?: { leaseId: string; ttlSeconds: number; renewable: boolean };\n}\n\nconst DEFAULT_CLOCK: IClock = { now: () => Date.now() };\nconst DEFAULT_TIMERS: ITimerAdapter = {\n set: (handler, ms) => setTimeout(handler, ms),\n clear: (handle) => clearTimeout(handle as AnyType),\n};\n\nconst DEFAULT_CACHE_TTL_SECONDS = 300;\nconst DEFAULT_RENEW_BEFORE_RATIO = 0.66;\n\n// setTimeout coerces any delay above this to 1ms, triggering an immediate renewal storm.\nconst TIMEOUT_MAX_MS = 2_147_483_647;\n// Floor so an invalid/tiny ttl never becomes a 0ms busy-loop.\nconst MIN_RENEW_DELAY_MS = 1_000;\n// Bounded exponential backoff for the renewal retry loop when Vault is unreachable.\nconst BACKOFF_BASE_MS = 1_000;\n// Capped at 31 to keep 2 ** (attempt - 1) inside double range: past ~1024 it overflows to Infinity and clampDelayMs's non-finite branch returns the FLOOR, collapsing a long backoff into a 1/sec retry storm.\nconst MAX_BACKOFF_ATTEMPT_EXPONENT = 31;\n\nexport abstract class AbstractSecretsHelper extends BaseHelper implements ISecretsHelper {\n protected readonly clock: IClock;\n protected readonly timers: ITimerAdapter;\n protected readonly cacheTtlSeconds: number;\n protected readonly renewBeforeRatio: number;\n\n private readonly cache = new Map<string, ICacheEntry>();\n private readonly leases = new Map<string, ISecretLease>();\n private readonly leasePaths = new Map<string, string>();\n private readonly timerHandles = new Map<string, TTimerHandle>();\n private readonly rotatables = new Map<string, ISecretRotatable[]>();\n private readonly rotateHandlers: TSecretRotationHandler[] = [];\n private readonly backoffAttempts = new Map<string, number>();\n private closed = false;\n\n constructor(opts: ISecretsHelperOptions) {\n super({ scope: opts.scope, identifier: opts.identifier });\n this.clock = opts.clock ?? DEFAULT_CLOCK;\n this.timers = opts.timers ?? DEFAULT_TIMERS;\n this.cacheTtlSeconds = opts.cacheTtlSeconds ?? DEFAULT_CACHE_TTL_SECONDS;\n\n const ratio = opts.renewBeforeRatio ?? DEFAULT_RENEW_BEFORE_RATIO;\n if (!Number.isFinite(ratio) || ratio <= 0 || ratio > 1) {\n throw getError({\n message: `[constructor] renewBeforeRatio must be within (0, 1] | received: ${ratio}`,\n });\n }\n this.renewBeforeRatio = ratio;\n }\n\n protected abstract fetchRaw(opts: { path: string }): Promise<IRawFetchResult>;\n protected abstract renewRaw(opts: {\n leaseId: string;\n ttlSeconds: number;\n }): Promise<{ ttlSeconds: number } | null>;\n protected abstract revokeRaw(opts: { leaseId: string }): Promise<void>;\n\n // Concrete providers override to authenticate; default is a no-op.\n async configure(): Promise<void> {\n return;\n }\n\n async getBundle(opts: { path: string }): Promise<Record<string, string>> {\n this.evictExpiredCache();\n const cached = this.cache.get(opts.path);\n if (cached && cached.expiresAt > this.clock.now()) {\n return cached.value;\n }\n const fresh = await this.fetchRaw({ path: opts.path });\n // A shutdown that ran while fetchRaw was in flight already cleared `cache` - honor that and hand back the fetched value uncached rather than resurrecting a map shutdown just emptied.\n if (this.closed) {\n return fresh.value;\n }\n this.writeCache({ path: opts.path, value: fresh.value });\n return fresh.value;\n }\n\n async get(opts: IGetSecretOptions<string>): Promise<string>;\n async get<TValue>(opts: IGetSecretOptions<TValue>): Promise<TValue>;\n async get<TValue = string>(opts: IGetSecretOptions<TValue>): Promise<TValue> {\n const bundle = await this.getBundle({ path: opts.path });\n const raw = opts.key\n ? Object.hasOwn(bundle, opts.key)\n ? bundle[opts.key]\n : undefined\n : (bundle as AnyType);\n return (raw ?? opts.defaultValue) as TValue;\n }\n\n async lease(opts: { path: string; key: string }): Promise<ISecretLease> {\n const fresh = await this.fetchRaw({ path: opts.path });\n // A shutdown that ran while fetchRaw was in flight already revoked/cleared every lease - committing this one now would resurrect leases/leasePaths with a lease no live provider will ever renew or revoke, so surface the shutdown instead of silently leaking it back in.\n if (this.closed) {\n throw getError({\n message: `[lease] Provider is shut down | path: ${opts.path} | key: ${opts.key}`,\n });\n }\n if (!fresh.lease) {\n throw getError({\n message: `[lease] Path returned no lease | path: ${opts.path} | key: ${opts.key}`,\n });\n }\n const lease: ISecretLease = { value: fresh.value, ...fresh.lease };\n this.leases.set(opts.key, lease);\n this.leasePaths.set(opts.key, opts.path);\n this.scheduleRenewal({ key: opts.key, lease });\n return lease;\n }\n\n onRotate(handler: TSecretRotationHandler): void {\n this.rotateHandlers.push(handler);\n }\n\n registerRotatable(opts: { key: string; target: ISecretRotatable }): void {\n const list = this.rotatables.get(opts.key) ?? [];\n list.push(opts.target);\n this.rotatables.set(opts.key, list);\n }\n\n async shutdown(): Promise<void> {\n const logger = this.logger.for(this.shutdown.name);\n this.closed = true;\n\n const timerHandlesValues = this.timerHandles.values();\n for (const handle of timerHandlesValues) {\n this.timers.clear(handle);\n }\n this.timerHandles.clear();\n this.backoffAttempts.clear();\n\n for (const [key, lease] of this.leases) {\n try {\n await this.revokeRaw({ leaseId: lease.leaseId });\n } catch (error) {\n logger.error(\n 'Revoke failed | key: %s | leaseId: %s | error: %s',\n key,\n lease.leaseId,\n error,\n );\n }\n }\n this.leases.clear();\n this.leasePaths.clear();\n this.cache.clear();\n }\n\n private writeCache(opts: { path: string; value: Record<string, string> }): void {\n this.cache.set(opts.path, {\n value: opts.value,\n expiresAt: this.clock.now() + this.cacheTtlSeconds * 1000,\n });\n }\n\n private evictExpiredCache(): void {\n const now = this.clock.now();\n for (const [path, entry] of this.cache) {\n if (entry.expiresAt <= now) {\n this.cache.delete(path);\n }\n }\n }\n\n private clampDelayMs(opts: { delayMs: number }): number {\n if (!Number.isFinite(opts.delayMs) || opts.delayMs <= 0) {\n return MIN_RENEW_DELAY_MS;\n }\n return Math.min(Math.max(opts.delayMs, MIN_RENEW_DELAY_MS), TIMEOUT_MAX_MS);\n }\n\n private armTimer(opts: { key: string; delayMs: number }): void {\n const existing = this.timerHandles.get(opts.key);\n if (existing) {\n this.timers.clear(existing);\n }\n const handle = this.timers.set(() => {\n this.handleRenewal({ key: opts.key }).catch((error) => {\n this.logger\n .for(this.armTimer.name)\n .error('Renewal handler crashed | key: %s | error: %s', opts.key, error);\n });\n }, opts.delayMs);\n this.timerHandles.set(opts.key, handle);\n }\n\n private scheduleRenewal(opts: { key: string; lease: ISecretLease }): void {\n if (this.closed) {\n return;\n }\n this.backoffAttempts.delete(opts.key);\n const delayMs = this.clampDelayMs({\n delayMs: opts.lease.ttlSeconds * this.renewBeforeRatio * 1000,\n });\n this.armTimer({ key: opts.key, delayMs });\n }\n\n // A transient Vault failure must not kill the loop; retry with bounded exponential backoff.\n private scheduleBackoffRetry(opts: { key: string }): void {\n if (this.closed) {\n return;\n }\n const attempt = (this.backoffAttempts.get(opts.key) ?? 0) + 1;\n this.backoffAttempts.set(opts.key, attempt);\n const cappedAttempt = Math.min(attempt, MAX_BACKOFF_ATTEMPT_EXPONENT);\n const delayMs = this.clampDelayMs({ delayMs: BACKOFF_BASE_MS * 2 ** (cappedAttempt - 1) });\n this.armTimer({ key: opts.key, delayMs });\n }\n\n private async handleRenewal(opts: { key: string }): Promise<void> {\n if (this.closed) {\n return;\n }\n const logger = this.logger.for(this.handleRenewal.name);\n const lease = this.leases.get(opts.key);\n if (!lease) {\n logger.debug('No lease to renew | key: %s', opts.key);\n return;\n }\n try {\n if (!lease.renewable) {\n await this.rotate({ key: opts.key });\n return;\n }\n\n const renewed = await this.renewRaw({\n leaseId: lease.leaseId,\n ttlSeconds: lease.ttlSeconds,\n });\n if (this.closed) {\n return;\n }\n\n if (!renewed) {\n await this.rotate({ key: opts.key });\n return;\n }\n\n const next: ISecretLease = { ...lease, ttlSeconds: renewed.ttlSeconds };\n this.leases.set(opts.key, next);\n this.scheduleRenewal({ key: opts.key, lease: next });\n } catch (error) {\n if (this.closed) {\n return;\n }\n logger.error(\n 'Renewal cycle failed; scheduling backoff retry | key: %s | error: %s',\n opts.key,\n error,\n );\n this.scheduleBackoffRetry({ key: opts.key });\n }\n }\n\n private async rotate(opts: { key: string }): Promise<void> {\n const path = this.leasePaths.get(opts.key);\n if (!path) {\n throw getError({ message: `[rotate] No lease path registered | key: ${opts.key}` });\n }\n const fresh = await this.fetchRaw({ path });\n if (this.closed) {\n return;\n }\n if (!fresh.lease) {\n throw getError({ message: `[rotate] Path returned no lease on rotation | key: ${opts.key}` });\n }\n const lease: ISecretLease = { value: fresh.value, ...fresh.lease };\n this.leases.set(opts.key, lease);\n this.writeCache({ path, value: fresh.value });\n // Arm the next renewal BEFORE dispatching: a wedged consumer must not stall the loop.\n this.scheduleRenewal({ key: opts.key, lease });\n await this.dispatchRotation({ key: opts.key, lease });\n }\n\n private async dispatchRotation(event: ISecretRotationEvent): Promise<void> {\n const logger = this.logger.for(this.dispatchRotation.name);\n for (const handler of this.rotateHandlers) {\n try {\n await handler(event);\n } catch (error) {\n logger.error('onRotate handler failed | key: %s | error: %s', event.key, error);\n }\n }\n const targets = this.rotatables.get(event.key) ?? [];\n for (const target of targets) {\n try {\n await target.onSecretRotated({ key: event.key, secret: event.lease.value });\n } catch (error) {\n logger.error('Rotatable failed | key: %s | error: %s', event.key, error);\n }\n }\n }\n}\n"]}
|
|
@@ -10,11 +10,11 @@ export class BaseWorkerThreadHelper extends AbstractWorkerThreadHelper {
|
|
|
10
10
|
message: '[BaseWorker] Cannot start worker in MAIN_THREAD',
|
|
11
11
|
});
|
|
12
12
|
}
|
|
13
|
-
this.buses =
|
|
13
|
+
this.buses = Object.create(null);
|
|
14
14
|
}
|
|
15
15
|
bindWorkerBus(opts) {
|
|
16
16
|
if (!this.buses) {
|
|
17
|
-
this.buses =
|
|
17
|
+
this.buses = Object.create(null);
|
|
18
18
|
}
|
|
19
19
|
const { key, bus } = opts;
|
|
20
20
|
if (this.buses[key]) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base.js","sourceRoot":"","sources":["../../../../../src/modules/worker-thread/thread/base.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAEnD,OAAO,EAAE,0BAA0B,EAAE,MAAM,YAAY,CAAC;AAExD,MAAM,OAAO,sBAAuB,SAAQ,0BAA0B;IACpE,YAAY,IAAuB;QACjC,MAAM,EAAE,KAAK,EAAE,GAAG,IAAI,CAAC;QACvB,KAAK,CAAC,EAAE,KAAK,EAAE,UAAU,EAAE,KAAK,EAAE,CAAC,CAAC;QAEpC,IAAI,YAAY,EAAE,CAAC;YACjB,MAAM,QAAQ,CAAC;gBACb,OAAO,EAAE,iDAAiD;aAC3D,CAAC,CAAC;QACL,CAAC;QAED,IAAI,CAAC,KAAK,GAAG,
|
|
1
|
+
{"version":3,"file":"base.js","sourceRoot":"","sources":["../../../../../src/modules/worker-thread/thread/base.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAEnD,OAAO,EAAE,0BAA0B,EAAE,MAAM,YAAY,CAAC;AAExD,MAAM,OAAO,sBAAuB,SAAQ,0BAA0B;IACpE,YAAY,IAAuB;QACjC,MAAM,EAAE,KAAK,EAAE,GAAG,IAAI,CAAC;QACvB,KAAK,CAAC,EAAE,KAAK,EAAE,UAAU,EAAE,KAAK,EAAE,CAAC,CAAC;QAEpC,IAAI,YAAY,EAAE,CAAC;YACjB,MAAM,QAAQ,CAAC;gBACb,OAAO,EAA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CAAC;QAChC,IAAI,CAAC,EAAE,EAAE,CAAC;YACR,MAAM,QAAQ,CAAC;gBACb,OAAO,EAAE,8CAA8C,IAAI,CAAC,GAAG,EAAE;aAClE,CAAC,CAAC;QACL,CAAC;QAED,OAAO,EAAwB,CAAC;IAClC,CAAC;CACF","sourcesContent":["import { getError } from '@/modules/error';\nimport { isMainThread } from 'node:worker_threads';\nimport { type IWorkerBus } from '../common';\nimport { AbstractWorkerThreadHelper } from './abstract';\n\nexport class BaseWorkerThreadHelper extends AbstractWorkerThreadHelper {\n constructor(opts: { scope: string }) {\n const { scope } = opts;\n super({ scope, identifier: scope });\n\n if (isMainThread) {\n throw getError({\n message: '[BaseWorker] Cannot start worker in MAIN_THREAD',\n });\n }\n\n this.buses = Object.create(null);\n }\n\n bindWorkerBus<IC, IP>(opts: { key: string; bus: IWorkerBus<IC, IP> }) {\n if (!this.buses) {\n this.buses = Object.create(null);\n }\n\n const { key, bus } = opts;\n if (this.buses[key]) {\n this.logger.for(this.bindWorkerBus.name).warn('Worker Bus existed | key: %s', key);\n return;\n }\n\n this.buses[key] = bus;\n }\n\n unbindWorkerBus(opts: { key: string }) {\n if (!this.buses) {\n return;\n }\n\n const { key } = opts;\n if (!(key in this.buses)) {\n this.logger.for(this.unbindWorkerBus.name).warn('Worker Bus not existed | key: %s', key);\n return;\n }\n\n this.buses[key]?.port?.removeAllListeners();\n delete this.buses[key];\n }\n\n getWorkerBus<IC, IP>(opts: { key: string }) {\n const rs = this.buses[opts.key];\n if (!rs) {\n throw getError({\n message: `[getWorkerBus] Not found worker bus | key: ${opts.key}`,\n });\n }\n\n return rs as IWorkerBus<IC, IP>;\n }\n}\n"]}
|