@backendkit-labs/bulkhead 0.1.0

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.
@@ -0,0 +1,450 @@
1
+ import { Injectable, Inject, Module, Logger, ServiceUnavailableException, RequestTimeoutException } from '@nestjs/common';
2
+ import { Reflector } from '@nestjs/core';
3
+ import { firstValueFrom, Observable } from 'rxjs';
4
+
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __decorateClass = (decorators, target, key, kind) => {
7
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
8
+ for (var i = decorators.length - 1, decorator; i >= 0; i--)
9
+ if (decorator = decorators[i])
10
+ result = (decorator(result)) || result;
11
+ return result;
12
+ };
13
+ var __decorateParam = (index, decorator) => (target, key) => decorator(target, key, index);
14
+
15
+ // src/bulkhead/bulkhead.ts
16
+ var BulkheadRejectedError = class extends Error {
17
+ constructor(message) {
18
+ super(message);
19
+ this.name = "BulkheadRejectedError";
20
+ }
21
+ };
22
+ var BulkheadTimeoutError = class extends Error {
23
+ constructor(message) {
24
+ super(message);
25
+ this.name = "BulkheadTimeoutError";
26
+ }
27
+ };
28
+ var Bulkhead = class {
29
+ constructor(config) {
30
+ this.config = config;
31
+ }
32
+ config;
33
+ activeCalls = 0;
34
+ nextId = 0;
35
+ queue = [];
36
+ totalCalls = 0;
37
+ successfulCalls = 0;
38
+ failedCalls = 0;
39
+ rejectedCalls = 0;
40
+ timedOutCalls = 0;
41
+ totalDurationMs = 0;
42
+ async execute(task) {
43
+ const startTime = Date.now();
44
+ this.totalCalls++;
45
+ if (this.activeCalls < this.config.maxConcurrentCalls) {
46
+ return this.runTask(task, startTime);
47
+ }
48
+ if (this.queue.length >= this.config.maxQueueSize) {
49
+ if (this.config.rejectWhenFull) {
50
+ this.rejectedCalls++;
51
+ throw new BulkheadRejectedError(
52
+ `Bulkhead '${this.config.name}' is full. Active: ${this.activeCalls}, Queue: ${this.queue.length}, Max: ${this.config.maxConcurrentCalls}`
53
+ );
54
+ }
55
+ return this.waitAndRetry(task, startTime);
56
+ }
57
+ const entryId = this.nextId++;
58
+ return new Promise((resolve, reject) => {
59
+ const timeoutId = setTimeout(() => {
60
+ const index = this.queue.findIndex((item) => item.id === entryId);
61
+ if (index !== -1) this.queue.splice(index, 1);
62
+ this.timedOutCalls++;
63
+ reject(
64
+ new BulkheadTimeoutError(
65
+ `Bulkhead '${this.config.name}' timeout after ${this.config.queueTimeoutMs}ms`
66
+ )
67
+ );
68
+ }, this.config.queueTimeoutMs);
69
+ this.queue.push({
70
+ id: entryId,
71
+ task,
72
+ resolve: (value) => {
73
+ clearTimeout(timeoutId);
74
+ resolve(value);
75
+ },
76
+ reject: (reason) => {
77
+ clearTimeout(timeoutId);
78
+ reject(reason);
79
+ },
80
+ queuedAt: startTime
81
+ });
82
+ this.processQueue();
83
+ });
84
+ }
85
+ async runTask(task, startTime) {
86
+ this.activeCalls++;
87
+ try {
88
+ const result = await task();
89
+ this.successfulCalls++;
90
+ this.totalDurationMs += Date.now() - startTime;
91
+ return result;
92
+ } catch (error) {
93
+ this.failedCalls++;
94
+ throw error;
95
+ } finally {
96
+ this.activeCalls--;
97
+ this.processQueue();
98
+ }
99
+ }
100
+ async waitAndRetry(task, startTime) {
101
+ const maxRetries = 3;
102
+ const baseDelay = 100;
103
+ for (let attempt = 1; attempt <= maxRetries; attempt++) {
104
+ if (this.activeCalls < this.config.maxConcurrentCalls) {
105
+ return this.runTask(task, startTime);
106
+ }
107
+ await new Promise((resolve) => setTimeout(resolve, baseDelay * Math.pow(2, attempt - 1)));
108
+ }
109
+ this.rejectedCalls++;
110
+ throw new BulkheadRejectedError(
111
+ `Bulkhead '${this.config.name}' rejected after ${maxRetries} retries`
112
+ );
113
+ }
114
+ processQueue() {
115
+ while (this.activeCalls < this.config.maxConcurrentCalls && this.queue.length > 0) {
116
+ const next = this.queue.shift();
117
+ if (!next) break;
118
+ const waitTime = Date.now() - next.queuedAt;
119
+ if (waitTime > this.config.queueTimeoutMs) {
120
+ next.reject(new BulkheadTimeoutError(`Task timed out after ${waitTime}ms in queue`));
121
+ this.timedOutCalls++;
122
+ continue;
123
+ }
124
+ this.activeCalls++;
125
+ next.task().then((result) => {
126
+ this.successfulCalls++;
127
+ next.resolve(result);
128
+ }).catch((error) => {
129
+ this.failedCalls++;
130
+ next.reject(error);
131
+ }).finally(() => {
132
+ this.activeCalls--;
133
+ this.processQueue();
134
+ });
135
+ }
136
+ }
137
+ getMetrics() {
138
+ return {
139
+ name: this.config.name,
140
+ activeCalls: this.activeCalls,
141
+ queuedCalls: this.queue.length,
142
+ maxConcurrentCalls: this.config.maxConcurrentCalls,
143
+ maxQueueSize: this.config.maxQueueSize,
144
+ totalCalls: this.totalCalls,
145
+ successfulCalls: this.successfulCalls,
146
+ failedCalls: this.failedCalls,
147
+ rejectedCalls: this.rejectedCalls,
148
+ timedOutCalls: this.timedOutCalls,
149
+ averageDurationMs: this.successfulCalls > 0 ? Math.round(this.totalDurationMs / this.successfulCalls) : 0
150
+ };
151
+ }
152
+ canAccept() {
153
+ return this.activeCalls < this.config.maxConcurrentCalls || this.queue.length < this.config.maxQueueSize;
154
+ }
155
+ resetMetrics() {
156
+ this.totalCalls = 0;
157
+ this.successfulCalls = 0;
158
+ this.failedCalls = 0;
159
+ this.rejectedCalls = 0;
160
+ this.timedOutCalls = 0;
161
+ this.totalDurationMs = 0;
162
+ }
163
+ };
164
+
165
+ // src/bulkhead/bulkhead.registry.ts
166
+ var DEFAULT_CONFIG = {
167
+ maxConcurrentCalls: 10,
168
+ maxQueueSize: 100,
169
+ queueTimeoutMs: 3e4,
170
+ rejectWhenFull: true
171
+ };
172
+ var BulkheadRegistry = class {
173
+ bulkheads = /* @__PURE__ */ new Map();
174
+ getOrCreate(options) {
175
+ if (!this.bulkheads.has(options.name)) {
176
+ const config = { ...DEFAULT_CONFIG, ...options, name: options.name };
177
+ this.bulkheads.set(options.name, new Bulkhead(config));
178
+ }
179
+ return this.bulkheads.get(options.name);
180
+ }
181
+ /** Per-client isolation — 5 concurrent, 20 queued */
182
+ getForClient(clientId, endpoint) {
183
+ const name = endpoint ? `client:${clientId}:${endpoint}` : `client:${clientId}`;
184
+ return this.getOrCreate({ name, maxConcurrentCalls: 5, maxQueueSize: 20 });
185
+ }
186
+ /** Service-level limiting — 20 concurrent, 200 queued */
187
+ getForService(serviceName) {
188
+ return this.getOrCreate({
189
+ name: `service:${serviceName}`,
190
+ maxConcurrentCalls: 20,
191
+ maxQueueSize: 200
192
+ });
193
+ }
194
+ /** Database connection limiting — 15 concurrent, 150 queued */
195
+ getForDatabase(schema) {
196
+ return this.getOrCreate({
197
+ name: `database:${schema}`,
198
+ maxConcurrentCalls: 15,
199
+ maxQueueSize: 150
200
+ });
201
+ }
202
+ /** External HTTP calls — 8 concurrent, 50 queued, 10s timeout */
203
+ getForHttpExternal(serviceName) {
204
+ return this.getOrCreate({
205
+ name: `http:${serviceName}`,
206
+ maxConcurrentCalls: 8,
207
+ maxQueueSize: 50,
208
+ queueTimeoutMs: 1e4
209
+ });
210
+ }
211
+ getAllMetrics() {
212
+ const metrics = {};
213
+ for (const [name, bulkhead] of this.bulkheads) {
214
+ metrics[name] = bulkhead.getMetrics();
215
+ }
216
+ return metrics;
217
+ }
218
+ /** Returns bulkheads at or above 80% active capacity */
219
+ getOverloadedBulkheads() {
220
+ const overloaded = [];
221
+ for (const bulkhead of this.bulkheads.values()) {
222
+ const m = bulkhead.getMetrics();
223
+ if (m.activeCalls >= m.maxConcurrentCalls * 0.8) {
224
+ overloaded.push(m);
225
+ }
226
+ }
227
+ return overloaded;
228
+ }
229
+ resetAllMetrics() {
230
+ for (const bulkhead of this.bulkheads.values()) {
231
+ bulkhead.resetMetrics();
232
+ }
233
+ }
234
+ };
235
+ var BulkheadService = class {
236
+ constructor(registry) {
237
+ this.registry = registry;
238
+ this.startMonitoring();
239
+ }
240
+ registry;
241
+ logger = new Logger(BulkheadService.name);
242
+ monitorInterval = null;
243
+ onModuleDestroy() {
244
+ if (this.monitorInterval) {
245
+ clearInterval(this.monitorInterval);
246
+ this.monitorInterval = null;
247
+ }
248
+ }
249
+ getAllMetrics() {
250
+ return this.registry.getAllMetrics();
251
+ }
252
+ getCriticalBulkheads() {
253
+ return Object.values(this.registry.getAllMetrics()).filter(
254
+ (m) => m.activeCalls / m.maxConcurrentCalls > 0.9
255
+ );
256
+ }
257
+ resetMetrics(name) {
258
+ if (name) {
259
+ this.registry.getOrCreate({ name }).resetMetrics();
260
+ } else {
261
+ this.registry.resetAllMetrics();
262
+ }
263
+ }
264
+ startMonitoring() {
265
+ this.monitorInterval = setInterval(() => {
266
+ const critical = this.getCriticalBulkheads();
267
+ if (critical.length > 0) {
268
+ this.logger.warn(
269
+ `Critical bulkheads detected: ${critical.length}`,
270
+ critical.map((c) => ({
271
+ name: c.name,
272
+ utilization: `${Math.round(c.activeCalls / c.maxConcurrentCalls * 100)}%`,
273
+ queued: c.queuedCalls
274
+ }))
275
+ );
276
+ }
277
+ }, 6e4);
278
+ }
279
+ };
280
+ BulkheadService = __decorateClass([
281
+ Injectable(),
282
+ __decorateParam(0, Inject(BulkheadRegistry))
283
+ ], BulkheadService);
284
+ var UseBulkhead = (options = {}) => Reflector.createDecorator({ key: "bulkhead", transform: () => options });
285
+ var BulkheadGuard = class {
286
+ constructor(reflector, registry) {
287
+ this.reflector = reflector;
288
+ this.registry = registry;
289
+ }
290
+ reflector;
291
+ registry;
292
+ async canActivate(context) {
293
+ const options = this.reflector.get("bulkhead", context.getHandler());
294
+ if (!options) return true;
295
+ const request = context.switchToHttp().getRequest();
296
+ const clientId = request.headers["x-client-id"] ?? "anonymous";
297
+ const bulkhead = options.perClient ? this.registry.getForClient(clientId, options.name ?? request.route?.path) : this.registry.getForService(options.name ?? "default");
298
+ if (!bulkhead.canAccept()) {
299
+ throw new ServiceUnavailableException("Service temporarily unavailable due to high load");
300
+ }
301
+ request["bulkhead"] = bulkhead;
302
+ return true;
303
+ }
304
+ };
305
+ BulkheadGuard = __decorateClass([
306
+ Injectable(),
307
+ __decorateParam(0, Inject(Reflector)),
308
+ __decorateParam(1, Inject(BulkheadRegistry))
309
+ ], BulkheadGuard);
310
+ var BulkheadInterceptor = class {
311
+ constructor(registry) {
312
+ this.registry = registry;
313
+ }
314
+ registry;
315
+ async intercept(context, next) {
316
+ const request = context.switchToHttp().getRequest();
317
+ const clientId = request.headers["x-client-id"] ?? "anonymous";
318
+ const handlerName = context.getHandler().name;
319
+ const bulkhead = this.registry.getForClient(clientId, handlerName);
320
+ try {
321
+ const result = await bulkhead.execute(() => firstValueFrom(next.handle()));
322
+ return new Observable((subscriber) => {
323
+ subscriber.next(result);
324
+ subscriber.complete();
325
+ });
326
+ } catch (error) {
327
+ if (error instanceof BulkheadRejectedError) {
328
+ throw new ServiceUnavailableException(
329
+ "Service at capacity \u2014 please retry in a moment"
330
+ );
331
+ }
332
+ if (error instanceof BulkheadTimeoutError) {
333
+ throw new RequestTimeoutException(
334
+ "Request timed out waiting for processing \u2014 please retry"
335
+ );
336
+ }
337
+ throw error;
338
+ }
339
+ }
340
+ };
341
+ BulkheadInterceptor = __decorateClass([
342
+ Injectable(),
343
+ __decorateParam(0, Inject(BulkheadRegistry))
344
+ ], BulkheadInterceptor);
345
+ var DEFAULT_CONCURRENCY = 50;
346
+ var DEFAULT_MAX_QUEUE = 100;
347
+ var HttpBulkheadMiddleware = class {
348
+ logger = new Logger(HttpBulkheadMiddleware.name);
349
+ bulkhead;
350
+ constructor() {
351
+ const concurrency = parseInt(
352
+ process.env["HTTP_BULKHEAD_CONCURRENCY"] ?? String(DEFAULT_CONCURRENCY),
353
+ 10
354
+ );
355
+ const maxQueueSize = parseInt(
356
+ process.env["HTTP_BULKHEAD_MAX_QUEUE"] ?? String(DEFAULT_MAX_QUEUE),
357
+ 10
358
+ );
359
+ this.bulkhead = new Bulkhead({
360
+ name: "http:global",
361
+ maxConcurrentCalls: concurrency,
362
+ maxQueueSize,
363
+ queueTimeoutMs: 3e4,
364
+ rejectWhenFull: true
365
+ });
366
+ this.logger.log(
367
+ `HTTP Bulkhead ready \u2014 concurrency: ${concurrency}, maxQueue: ${maxQueueSize}`
368
+ );
369
+ }
370
+ use(req, res, next) {
371
+ this.bulkhead.execute(
372
+ () => new Promise((resolve) => {
373
+ res.once("finish", resolve);
374
+ res.once("close", resolve);
375
+ next();
376
+ })
377
+ ).catch((error) => {
378
+ if (res.headersSent) return;
379
+ if (error instanceof BulkheadRejectedError) {
380
+ const m = this.bulkhead.getMetrics();
381
+ this.logger.warn(
382
+ `HTTP Bulkhead saturated [active=${m.activeCalls} queued=${m.queuedCalls}] \u2014 rejecting ${req.method} ${req.path}`
383
+ );
384
+ res.status(429).json({
385
+ statusCode: 429,
386
+ error: "Too Many Requests",
387
+ message: "Service temporarily overloaded. Please retry in a few seconds."
388
+ });
389
+ } else if (error instanceof BulkheadTimeoutError) {
390
+ res.status(503).json({
391
+ statusCode: 503,
392
+ error: "Service Unavailable",
393
+ message: "Request timed out waiting for processing."
394
+ });
395
+ }
396
+ });
397
+ }
398
+ getStats() {
399
+ return this.bulkhead.getMetrics();
400
+ }
401
+ };
402
+ HttpBulkheadMiddleware = __decorateClass([
403
+ Injectable()
404
+ ], HttpBulkheadMiddleware);
405
+
406
+ // src/nestjs/bulkhead.module.ts
407
+ var BulkheadModule = class {
408
+ };
409
+ BulkheadModule = __decorateClass([
410
+ Module({
411
+ providers: [
412
+ BulkheadRegistry,
413
+ BulkheadService,
414
+ BulkheadGuard,
415
+ BulkheadInterceptor,
416
+ HttpBulkheadMiddleware
417
+ ],
418
+ exports: [
419
+ BulkheadRegistry,
420
+ BulkheadService,
421
+ BulkheadGuard,
422
+ BulkheadInterceptor,
423
+ HttpBulkheadMiddleware
424
+ ]
425
+ })
426
+ ], BulkheadModule);
427
+
428
+ // src/nestjs/bulkhead.decorator.ts
429
+ function WithBulkhead(options) {
430
+ return function(_target, _propertyKey, descriptor) {
431
+ const originalMethod = descriptor.value;
432
+ descriptor.value = async function(...args) {
433
+ const registry = this.bulkheadRegistry;
434
+ if (!registry) throw new Error("BulkheadRegistry not injected in class.");
435
+ const bulkhead = registry.getOrCreate({
436
+ name: options.name,
437
+ maxConcurrentCalls: options.maxConcurrent ?? 5,
438
+ queueTimeoutMs: options.timeoutMs ?? 3e4,
439
+ maxQueueSize: 50,
440
+ rejectWhenFull: true
441
+ });
442
+ return bulkhead.execute(() => originalMethod.apply(this, args));
443
+ };
444
+ return descriptor;
445
+ };
446
+ }
447
+
448
+ export { BulkheadGuard, BulkheadInterceptor, BulkheadModule, BulkheadService, HttpBulkheadMiddleware, UseBulkhead, WithBulkhead };
449
+ //# sourceMappingURL=index.js.map
450
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/bulkhead/bulkhead.ts","../../src/bulkhead/bulkhead.registry.ts","../../src/nestjs/bulkhead.service.ts","../../src/nestjs/bulkhead.guard.ts","../../src/nestjs/bulkhead.interceptor.ts","../../src/nestjs/http-bulkhead.middleware.ts","../../src/nestjs/bulkhead.module.ts","../../src/nestjs/bulkhead.decorator.ts"],"names":["Injectable","Inject","ServiceUnavailableException","Logger"],"mappings":";;;;;;;;;;;;;;;AA2BO,IAAM,qBAAA,GAAN,cAAoC,KAAA,CAAM;AAAA,EAC/C,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,uBAAA;AAAA,EACd;AACF,CAAA;AAEO,IAAM,oBAAA,GAAN,cAAmC,KAAA,CAAM;AAAA,EAC9C,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,sBAAA;AAAA,EACd;AACF,CAAA;AAEO,IAAM,WAAN,MAAe;AAAA,EAkBpB,YAA6B,MAAA,EAAwB;AAAxB,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AAAA,EAAyB;A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AAY,IAAA,CAAiD,gBAAA;AACnE,MAAA,IAAI,CAAC,QAAA,EAAU,MAAM,IAAI,MAAM,yCAAyC,CAAA;AAExE,MAAA,MAAM,QAAA,GAAW,SAAS,WAAA,CAAY;AAAA,QACpC,MAAM,OAAA,CAAQ,IAAA;AAAA,QACd,kBAAA,EAAoB,QAAQ,aAAA,IAAiB,CAAA;AAAA,QAC7C,cAAA,EAAgB,QAAQ,SAAA,IAAa,GAAA;AAAA,QACrC,YAAA,EAAc,EAAA;AAAA,QACd,cAAA,EAAgB;AAAA,OACjB,CAAA;AAED,MAAA,OAAO,SAAS,OAAA,CAAQ,MAAM,eAAe,KAAA,CAAM,IAAA,EAAM,IAAI,CAAC,CAAA;AAAA,IAChE,CAAA;AAEA,IAAA,OAAO,UAAA;AAAA,EACT,CAAA;AACF","file":"index.js","sourcesContent":["export interface BulkheadConfig {\n /** Max number of concurrent executions */\n maxConcurrentCalls: number;\n /** Max queue size for waiting tasks */\n maxQueueSize: number;\n /** Max time a task can wait in queue (ms) */\n queueTimeoutMs: number;\n /** Reject immediately when queue is full; if false, retries with backoff */\n rejectWhenFull: boolean;\n /** Identifier used in metrics and error messages */\n name: string;\n}\n\nexport interface BulkheadMetrics {\n name: string;\n activeCalls: number;\n queuedCalls: number;\n maxConcurrentCalls: number;\n maxQueueSize: number;\n totalCalls: number;\n successfulCalls: number;\n failedCalls: number;\n rejectedCalls: number;\n timedOutCalls: number;\n averageDurationMs: number;\n}\n\nexport class BulkheadRejectedError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'BulkheadRejectedError';\n }\n}\n\nexport class BulkheadTimeoutError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'BulkheadTimeoutError';\n }\n}\n\nexport class Bulkhead {\n private activeCalls = 0;\n private nextId = 0;\n private queue: Array<{\n id: number;\n task: () => Promise<unknown>;\n resolve: (value: unknown) => void;\n reject: (reason: unknown) => void;\n queuedAt: number;\n }> = [];\n\n private totalCalls = 0;\n private successfulCalls = 0;\n private failedCalls = 0;\n private rejectedCalls = 0;\n private timedOutCalls = 0;\n private totalDurationMs = 0;\n\n constructor(private readonly config: BulkheadConfig) {}\n\n async execute<T>(task: () => Promise<T>): Promise<T> {\n const startTime = Date.now();\n this.totalCalls++;\n\n if (this.activeCalls < this.config.maxConcurrentCalls) {\n return this.runTask(task, startTime);\n }\n\n if (this.queue.length >= this.config.maxQueueSize) {\n if (this.config.rejectWhenFull) {\n this.rejectedCalls++;\n throw new BulkheadRejectedError(\n `Bulkhead '${this.config.name}' is full. ` +\n `Active: ${this.activeCalls}, Queue: ${this.queue.length}, Max: ${this.config.maxConcurrentCalls}`,\n );\n }\n return this.waitAndRetry(task, startTime);\n }\n\n const entryId = this.nextId++;\n return new Promise<T>((resolve, reject) => {\n const timeoutId = setTimeout(() => {\n const index = this.queue.findIndex(item => item.id === entryId);\n if (index !== -1) this.queue.splice(index, 1);\n this.timedOutCalls++;\n reject(\n new BulkheadTimeoutError(\n `Bulkhead '${this.config.name}' timeout after ${this.config.queueTimeoutMs}ms`,\n ),\n );\n }, this.config.queueTimeoutMs);\n\n this.queue.push({\n id: entryId,\n task: task as () => Promise<unknown>,\n resolve: value => {\n clearTimeout(timeoutId);\n resolve(value as T);\n },\n reject: reason => {\n clearTimeout(timeoutId);\n reject(reason);\n },\n queuedAt: startTime,\n });\n\n this.processQueue();\n });\n }\n\n private async runTask<T>(task: () => Promise<T>, startTime: number): Promise<T> {\n this.activeCalls++;\n try {\n const result = await task();\n this.successfulCalls++;\n this.totalDurationMs += Date.now() - startTime;\n return result;\n } catch (error) {\n this.failedCalls++;\n throw error;\n } finally {\n this.activeCalls--;\n this.processQueue();\n }\n }\n\n private async waitAndRetry<T>(task: () => Promise<T>, startTime: number): Promise<T> {\n const maxRetries = 3;\n const baseDelay = 100;\n\n for (let attempt = 1; attempt <= maxRetries; attempt++) {\n if (this.activeCalls < this.config.maxConcurrentCalls) {\n return this.runTask(task, startTime);\n }\n await new Promise(resolve => setTimeout(resolve, baseDelay * Math.pow(2, attempt - 1)));\n }\n\n this.rejectedCalls++;\n throw new BulkheadRejectedError(\n `Bulkhead '${this.config.name}' rejected after ${maxRetries} retries`,\n );\n }\n\n private processQueue(): void {\n while (this.activeCalls < this.config.maxConcurrentCalls && this.queue.length > 0) {\n const next = this.queue.shift();\n if (!next) break;\n\n const waitTime = Date.now() - next.queuedAt;\n if (waitTime > this.config.queueTimeoutMs) {\n next.reject(new BulkheadTimeoutError(`Task timed out after ${waitTime}ms in queue`));\n this.timedOutCalls++;\n continue;\n }\n\n this.activeCalls++;\n next\n .task()\n .then(result => {\n this.successfulCalls++;\n next.resolve(result);\n })\n .catch(error => {\n this.failedCalls++;\n next.reject(error);\n })\n .finally(() => {\n this.activeCalls--;\n this.processQueue();\n });\n }\n }\n\n getMetrics(): BulkheadMetrics {\n return {\n name: this.config.name,\n activeCalls: this.activeCalls,\n queuedCalls: this.queue.length,\n maxConcurrentCalls: this.config.maxConcurrentCalls,\n maxQueueSize: this.config.maxQueueSize,\n totalCalls: this.totalCalls,\n successfulCalls: this.successfulCalls,\n failedCalls: this.failedCalls,\n rejectedCalls: this.rejectedCalls,\n timedOutCalls: this.timedOutCalls,\n averageDurationMs:\n this.successfulCalls > 0 ? Math.round(this.totalDurationMs / this.successfulCalls) : 0,\n };\n }\n\n canAccept(): boolean {\n return (\n this.activeCalls < this.config.maxConcurrentCalls ||\n this.queue.length < this.config.maxQueueSize\n );\n }\n\n resetMetrics(): void {\n this.totalCalls = 0;\n this.successfulCalls = 0;\n this.failedCalls = 0;\n this.rejectedCalls = 0;\n this.timedOutCalls = 0;\n this.totalDurationMs = 0;\n }\n}\n","import { Bulkhead, BulkheadConfig, BulkheadMetrics } from './bulkhead.js';\n\nexport interface BulkheadOptions extends Partial<BulkheadConfig> {\n name: string;\n}\n\nconst DEFAULT_CONFIG: Omit<BulkheadConfig, 'name'> = {\n maxConcurrentCalls: 10,\n maxQueueSize: 100,\n queueTimeoutMs: 30000,\n rejectWhenFull: true,\n};\n\nexport class BulkheadRegistry {\n private readonly bulkheads = new Map<string, Bulkhead>();\n\n getOrCreate(options: BulkheadOptions): Bulkhead {\n if (!this.bulkheads.has(options.name)) {\n const config: BulkheadConfig = { ...DEFAULT_CONFIG, ...options, name: options.name };\n this.bulkheads.set(options.name, new Bulkhead(config));\n }\n return this.bulkheads.get(options.name)!;\n }\n\n /** Per-client isolation — 5 concurrent, 20 queued */\n getForClient(clientId: string, endpoint?: string): Bulkhead {\n const name = endpoint ? `client:${clientId}:${endpoint}` : `client:${clientId}`;\n return this.getOrCreate({ name, maxConcurrentCalls: 5, maxQueueSize: 20 });\n }\n\n /** Service-level limiting — 20 concurrent, 200 queued */\n getForService(serviceName: string): Bulkhead {\n return this.getOrCreate({\n name: `service:${serviceName}`,\n maxConcurrentCalls: 20,\n maxQueueSize: 200,\n });\n }\n\n /** Database connection limiting — 15 concurrent, 150 queued */\n getForDatabase(schema: string): Bulkhead {\n return this.getOrCreate({\n name: `database:${schema}`,\n maxConcurrentCalls: 15,\n maxQueueSize: 150,\n });\n }\n\n /** External HTTP calls — 8 concurrent, 50 queued, 10s timeout */\n getForHttpExternal(serviceName: string): Bulkhead {\n return this.getOrCreate({\n name: `http:${serviceName}`,\n maxConcurrentCalls: 8,\n maxQueueSize: 50,\n queueTimeoutMs: 10000,\n });\n }\n\n getAllMetrics(): Record<string, BulkheadMetrics> {\n const metrics: Record<string, BulkheadMetrics> = {};\n for (const [name, bulkhead] of this.bulkheads) {\n metrics[name] = bulkhead.getMetrics();\n }\n return metrics;\n }\n\n /** Returns bulkheads at or above 80% active capacity */\n getOverloadedBulkheads(): BulkheadMetrics[] {\n const overloaded: BulkheadMetrics[] = [];\n for (const bulkhead of this.bulkheads.values()) {\n const m = bulkhead.getMetrics();\n if (m.activeCalls >= m.maxConcurrentCalls * 0.8) {\n overloaded.push(m);\n }\n }\n return overloaded;\n }\n\n resetAllMetrics(): void {\n for (const bulkhead of this.bulkheads.values()) {\n bulkhead.resetMetrics();\n }\n }\n}\n","import { Injectable, Inject, Logger, OnModuleDestroy } from '@nestjs/common';\nimport { BulkheadRegistry } from '../bulkhead/bulkhead.registry.js';\nimport type { BulkheadMetrics } from '../bulkhead/bulkhead.js';\n\n@Injectable()\nexport class BulkheadService implements OnModuleDestroy {\n private readonly logger = new Logger(BulkheadService.name);\n private monitorInterval: ReturnType<typeof setInterval> | null = null;\n\n constructor(@Inject(BulkheadRegistry) private readonly registry: BulkheadRegistry) {\n this.startMonitoring();\n }\n\n onModuleDestroy(): void {\n if (this.monitorInterval) {\n clearInterval(this.monitorInterval);\n this.monitorInterval = null;\n }\n }\n\n getAllMetrics(): Record<string, BulkheadMetrics> {\n return this.registry.getAllMetrics();\n }\n\n getCriticalBulkheads(): BulkheadMetrics[] {\n return Object.values(this.registry.getAllMetrics()).filter(\n m => m.activeCalls / m.maxConcurrentCalls > 0.9,\n );\n }\n\n resetMetrics(name?: string): void {\n if (name) {\n this.registry.getOrCreate({ name }).resetMetrics();\n } else {\n this.registry.resetAllMetrics();\n }\n }\n\n private startMonitoring(): void {\n this.monitorInterval = setInterval(() => {\n const critical = this.getCriticalBulkheads();\n if (critical.length > 0) {\n this.logger.warn(\n `Critical bulkheads detected: ${critical.length}`,\n critical.map(c => ({\n name: c.name,\n utilization: `${Math.round((c.activeCalls / c.maxConcurrentCalls) * 100)}%`,\n queued: c.queuedCalls,\n })),\n );\n }\n }, 60_000);\n }\n}\n","import {\n Injectable,\n Inject,\n CanActivate,\n ExecutionContext,\n ServiceUnavailableException,\n} from '@nestjs/common';\nimport { Reflector } from '@nestjs/core';\nimport { BulkheadRegistry } from '../bulkhead/bulkhead.registry.js';\n\nexport interface BulkheadGuardOptions {\n /** Named bulkhead to use; defaults to the route path */\n name?: string;\n /** Create a separate bulkhead per x-client-id header value */\n perClient?: boolean;\n maxConcurrent?: number;\n timeoutMs?: number;\n}\n\nexport const UseBulkhead = (options: BulkheadGuardOptions = {}) =>\n Reflector.createDecorator<BulkheadGuardOptions>({ key: 'bulkhead', transform: () => options });\n\n@Injectable()\nexport class BulkheadGuard implements CanActivate {\n constructor(\n @Inject(Reflector) private readonly reflector: Reflector,\n @Inject(BulkheadRegistry) private readonly registry: BulkheadRegistry,\n ) {}\n\n async canActivate(context: ExecutionContext): Promise<boolean> {\n const options = this.reflector.get<BulkheadGuardOptions>('bulkhead', context.getHandler());\n if (!options) return true;\n\n const request = context.switchToHttp().getRequest();\n const clientId: string = request.headers['x-client-id'] ?? 'anonymous';\n\n const bulkhead = options.perClient\n ? this.registry.getForClient(clientId, options.name ?? (request.route?.path as string))\n : this.registry.getForService(options.name ?? 'default');\n\n if (!bulkhead.canAccept()) {\n throw new ServiceUnavailableException('Service temporarily unavailable due to high load');\n }\n\n (request as Record<string, unknown>)['bulkhead'] = bulkhead;\n return true;\n }\n}\n","import {\n Injectable,\n Inject,\n NestInterceptor,\n ExecutionContext,\n CallHandler,\n ServiceUnavailableException,\n RequestTimeoutException,\n} from '@nestjs/common';\nimport { firstValueFrom, Observable } from 'rxjs';\nimport { BulkheadRegistry } from '../bulkhead/bulkhead.registry.js';\nimport { BulkheadRejectedError, BulkheadTimeoutError } from '../bulkhead/bulkhead.js';\n\n@Injectable()\nexport class BulkheadInterceptor implements NestInterceptor {\n constructor(@Inject(BulkheadRegistry) private readonly registry: BulkheadRegistry) {}\n\n async intercept(context: ExecutionContext, next: CallHandler): Promise<Observable<unknown>> {\n const request = context.switchToHttp().getRequest();\n const clientId: string = request.headers['x-client-id'] ?? 'anonymous';\n const handlerName: string = context.getHandler().name;\n\n const bulkhead = this.registry.getForClient(clientId, handlerName);\n\n try {\n const result = await bulkhead.execute(() => firstValueFrom(next.handle()));\n return new Observable(subscriber => {\n subscriber.next(result);\n subscriber.complete();\n });\n } catch (error) {\n if (error instanceof BulkheadRejectedError) {\n throw new ServiceUnavailableException(\n 'Service at capacity — please retry in a moment',\n );\n }\n if (error instanceof BulkheadTimeoutError) {\n throw new RequestTimeoutException(\n 'Request timed out waiting for processing — please retry',\n );\n }\n throw error;\n }\n }\n}\n","import { Injectable, NestMiddleware, Logger } from '@nestjs/common';\nimport type { Request, Response, NextFunction } from 'express';\nimport { Bulkhead, BulkheadRejectedError, BulkheadTimeoutError } from '../bulkhead/bulkhead.js';\nimport type { BulkheadMetrics } from '../bulkhead/bulkhead.js';\n\nconst DEFAULT_CONCURRENCY = 50;\nconst DEFAULT_MAX_QUEUE = 100;\n\n/**\n * Global HTTP middleware that limits simultaneous in-flight requests.\n *\n * Configure via environment variables:\n * HTTP_BULKHEAD_CONCURRENCY — max concurrent requests (default: 50)\n * HTTP_BULKHEAD_MAX_QUEUE — max queued requests (default: 100)\n */\n@Injectable()\nexport class HttpBulkheadMiddleware implements NestMiddleware {\n private readonly logger = new Logger(HttpBulkheadMiddleware.name);\n private readonly bulkhead: Bulkhead;\n\n constructor() {\n const concurrency = parseInt(\n process.env['HTTP_BULKHEAD_CONCURRENCY'] ?? String(DEFAULT_CONCURRENCY),\n 10,\n );\n const maxQueueSize = parseInt(\n process.env['HTTP_BULKHEAD_MAX_QUEUE'] ?? String(DEFAULT_MAX_QUEUE),\n 10,\n );\n\n this.bulkhead = new Bulkhead({\n name: 'http:global',\n maxConcurrentCalls: concurrency,\n maxQueueSize,\n queueTimeoutMs: 30_000,\n rejectWhenFull: true,\n });\n\n this.logger.log(\n `HTTP Bulkhead ready — concurrency: ${concurrency}, maxQueue: ${maxQueueSize}`,\n );\n }\n\n use(req: Request, res: Response, next: NextFunction): void {\n this.bulkhead\n .execute(\n () =>\n new Promise<void>(resolve => {\n res.once('finish', resolve);\n res.once('close', resolve);\n next();\n }),\n )\n .catch((error: unknown) => {\n if (res.headersSent) return;\n if (error instanceof BulkheadRejectedError) {\n const m = this.bulkhead.getMetrics();\n this.logger.warn(\n `HTTP Bulkhead saturated [active=${m.activeCalls} queued=${m.queuedCalls}]` +\n ` — rejecting ${req.method} ${req.path}`,\n );\n res.status(429).json({\n statusCode: 429,\n error: 'Too Many Requests',\n message: 'Service temporarily overloaded. Please retry in a few seconds.',\n });\n } else if (error instanceof BulkheadTimeoutError) {\n res.status(503).json({\n statusCode: 503,\n error: 'Service Unavailable',\n message: 'Request timed out waiting for processing.',\n });\n }\n });\n }\n\n getStats(): BulkheadMetrics {\n return this.bulkhead.getMetrics();\n }\n}\n","import { Module } from '@nestjs/common';\nimport { BulkheadRegistry } from '../bulkhead/bulkhead.registry.js';\nimport { BulkheadService } from './bulkhead.service.js';\nimport { BulkheadGuard } from './bulkhead.guard.js';\nimport { BulkheadInterceptor } from './bulkhead.interceptor.js';\nimport { HttpBulkheadMiddleware } from './http-bulkhead.middleware.js';\n\n@Module({\n providers: [\n BulkheadRegistry,\n BulkheadService,\n BulkheadGuard,\n BulkheadInterceptor,\n HttpBulkheadMiddleware,\n ],\n exports: [\n BulkheadRegistry,\n BulkheadService,\n BulkheadGuard,\n BulkheadInterceptor,\n HttpBulkheadMiddleware,\n ],\n})\nexport class BulkheadModule {}\n","import { BulkheadRegistry } from '../bulkhead/bulkhead.registry.js';\n\n/**\n * Method decorator that wraps execution inside a named bulkhead.\n * The class must have `bulkheadRegistry: BulkheadRegistry` injected.\n */\nexport function WithBulkhead(options: {\n name: string;\n maxConcurrent?: number;\n timeoutMs?: number;\n}) {\n return function (\n _target: unknown,\n _propertyKey: string,\n descriptor: PropertyDescriptor,\n ): PropertyDescriptor {\n const originalMethod = descriptor.value as (...args: unknown[]) => Promise<unknown>;\n\n descriptor.value = async function (...args: unknown[]) {\n const registry = (this as { bulkheadRegistry?: BulkheadRegistry }).bulkheadRegistry;\n if (!registry) throw new Error('BulkheadRegistry not injected in class.');\n\n const bulkhead = registry.getOrCreate({\n name: options.name,\n maxConcurrentCalls: options.maxConcurrent ?? 5,\n queueTimeoutMs: options.timeoutMs ?? 30_000,\n maxQueueSize: 50,\n rejectWhenFull: true,\n });\n\n return bulkhead.execute(() => originalMethod.apply(this, args));\n };\n\n return descriptor;\n };\n}\n"]}
package/package.json ADDED
@@ -0,0 +1,89 @@
1
+ {
2
+ "name": "@backendkit-labs/bulkhead",
3
+ "version": "0.1.0",
4
+ "description": "Bulkhead concurrency limiting for Node.js — inspired by Resilience4j, with optional NestJS integration",
5
+ "type": "module",
6
+ "main": "./dist/index.cjs",
7
+ "module": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js",
13
+ "require": "./dist/index.cjs"
14
+ },
15
+ "./nestjs": {
16
+ "types": "./dist/nestjs/index.d.ts",
17
+ "import": "./dist/nestjs/index.js",
18
+ "require": "./dist/nestjs/index.cjs"
19
+ }
20
+ },
21
+ "files": [
22
+ "dist",
23
+ "README.md",
24
+ "LICENSE"
25
+ ],
26
+ "scripts": {
27
+ "build": "tsup",
28
+ "dev": "tsup --watch",
29
+ "test": "vitest run",
30
+ "test:watch": "vitest",
31
+ "test:coverage": "vitest run --coverage",
32
+ "typecheck": "tsc --noEmit",
33
+ "lint": "eslint src/",
34
+ "format": "prettier --write src/",
35
+ "prepublishOnly": "npm run build && npm run test && npm run lint"
36
+ },
37
+ "keywords": [
38
+ "resilience",
39
+ "bulkhead",
40
+ "concurrency",
41
+ "rate-limiting",
42
+ "circuit-breaker",
43
+ "nestjs",
44
+ "node",
45
+ "backend"
46
+ ],
47
+ "author": "Mairon José Cuello Martínez <[backendkit.dev@gmail.com - mmairon@gmail.com]>",
48
+ "license": "MIT",
49
+ "homepage": "https://github.com/backendkit-dev/backendkit-monorepo/tree/master/packages/bulkhead#readme",
50
+ "repository": {
51
+ "type": "git",
52
+ "url": "git+https://github.com/backendkit-dev/backendkit-monorepo.git",
53
+ "directory": "packages/bulkhead"
54
+ },
55
+ "bugs": {
56
+ "url": "https://github.com/backendkit-dev/backendkit-monorepo/issues"
57
+ },
58
+ "sideEffects": false,
59
+ "engines": {
60
+ "node": ">=18"
61
+ },
62
+ "peerDependencies": {
63
+ "@nestjs/common": ">=10.0.0",
64
+ "@nestjs/core": ">=10.0.0",
65
+ "express": ">=4.0.0",
66
+ "rxjs": ">=7.0.0"
67
+ },
68
+ "peerDependenciesMeta": {
69
+ "@nestjs/common": { "optional": true },
70
+ "@nestjs/core": { "optional": true },
71
+ "express": { "optional": true },
72
+ "rxjs": { "optional": true }
73
+ },
74
+ "devDependencies": {
75
+ "@eslint/js": "^9.39.4",
76
+ "@nestjs/common": "^10.0.0",
77
+ "@nestjs/core": "^10.0.0",
78
+ "@types/express": "^4.17.21",
79
+ "@types/node": "^22.0.0",
80
+ "eslint": "^9.0.0",
81
+ "prettier": "^3.0.0",
82
+ "reflect-metadata": "^0.2.0",
83
+ "rxjs": "^7.8.0",
84
+ "tsup": "^8.0.0",
85
+ "typescript": "^5.5.0",
86
+ "typescript-eslint": "^8.59.3",
87
+ "vitest": "^2.0.0"
88
+ }
89
+ }