@backendkit-labs/bulkhead 0.1.0 → 0.1.1

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/index.cjs CHANGED
@@ -1,229 +1,24 @@
1
1
  'use strict';
2
2
 
3
- // src/bulkhead/bulkhead.ts
4
- var BulkheadRejectedError = class extends Error {
5
- constructor(message) {
6
- super(message);
7
- this.name = "BulkheadRejectedError";
8
- }
9
- };
10
- var BulkheadTimeoutError = class extends Error {
11
- constructor(message) {
12
- super(message);
13
- this.name = "BulkheadTimeoutError";
14
- }
15
- };
16
- var Bulkhead = class {
17
- constructor(config) {
18
- this.config = config;
19
- }
20
- config;
21
- activeCalls = 0;
22
- nextId = 0;
23
- queue = [];
24
- totalCalls = 0;
25
- successfulCalls = 0;
26
- failedCalls = 0;
27
- rejectedCalls = 0;
28
- timedOutCalls = 0;
29
- totalDurationMs = 0;
30
- async execute(task) {
31
- const startTime = Date.now();
32
- this.totalCalls++;
33
- if (this.activeCalls < this.config.maxConcurrentCalls) {
34
- return this.runTask(task, startTime);
35
- }
36
- if (this.queue.length >= this.config.maxQueueSize) {
37
- if (this.config.rejectWhenFull) {
38
- this.rejectedCalls++;
39
- throw new BulkheadRejectedError(
40
- `Bulkhead '${this.config.name}' is full. Active: ${this.activeCalls}, Queue: ${this.queue.length}, Max: ${this.config.maxConcurrentCalls}`
41
- );
42
- }
43
- return this.waitAndRetry(task, startTime);
44
- }
45
- const entryId = this.nextId++;
46
- return new Promise((resolve, reject) => {
47
- const timeoutId = setTimeout(() => {
48
- const index = this.queue.findIndex((item) => item.id === entryId);
49
- if (index !== -1) this.queue.splice(index, 1);
50
- this.timedOutCalls++;
51
- reject(
52
- new BulkheadTimeoutError(
53
- `Bulkhead '${this.config.name}' timeout after ${this.config.queueTimeoutMs}ms`
54
- )
55
- );
56
- }, this.config.queueTimeoutMs);
57
- this.queue.push({
58
- id: entryId,
59
- task,
60
- resolve: (value) => {
61
- clearTimeout(timeoutId);
62
- resolve(value);
63
- },
64
- reject: (reason) => {
65
- clearTimeout(timeoutId);
66
- reject(reason);
67
- },
68
- queuedAt: startTime
69
- });
70
- this.processQueue();
71
- });
72
- }
73
- async runTask(task, startTime) {
74
- this.activeCalls++;
75
- try {
76
- const result = await task();
77
- this.successfulCalls++;
78
- this.totalDurationMs += Date.now() - startTime;
79
- return result;
80
- } catch (error) {
81
- this.failedCalls++;
82
- throw error;
83
- } finally {
84
- this.activeCalls--;
85
- this.processQueue();
86
- }
87
- }
88
- async waitAndRetry(task, startTime) {
89
- const maxRetries = 3;
90
- const baseDelay = 100;
91
- for (let attempt = 1; attempt <= maxRetries; attempt++) {
92
- if (this.activeCalls < this.config.maxConcurrentCalls) {
93
- return this.runTask(task, startTime);
94
- }
95
- await new Promise((resolve) => setTimeout(resolve, baseDelay * Math.pow(2, attempt - 1)));
96
- }
97
- this.rejectedCalls++;
98
- throw new BulkheadRejectedError(
99
- `Bulkhead '${this.config.name}' rejected after ${maxRetries} retries`
100
- );
101
- }
102
- processQueue() {
103
- while (this.activeCalls < this.config.maxConcurrentCalls && this.queue.length > 0) {
104
- const next = this.queue.shift();
105
- if (!next) break;
106
- const waitTime = Date.now() - next.queuedAt;
107
- if (waitTime > this.config.queueTimeoutMs) {
108
- next.reject(new BulkheadTimeoutError(`Task timed out after ${waitTime}ms in queue`));
109
- this.timedOutCalls++;
110
- continue;
111
- }
112
- this.activeCalls++;
113
- next.task().then((result) => {
114
- this.successfulCalls++;
115
- next.resolve(result);
116
- }).catch((error) => {
117
- this.failedCalls++;
118
- next.reject(error);
119
- }).finally(() => {
120
- this.activeCalls--;
121
- this.processQueue();
122
- });
123
- }
124
- }
125
- getMetrics() {
126
- return {
127
- name: this.config.name,
128
- activeCalls: this.activeCalls,
129
- queuedCalls: this.queue.length,
130
- maxConcurrentCalls: this.config.maxConcurrentCalls,
131
- maxQueueSize: this.config.maxQueueSize,
132
- totalCalls: this.totalCalls,
133
- successfulCalls: this.successfulCalls,
134
- failedCalls: this.failedCalls,
135
- rejectedCalls: this.rejectedCalls,
136
- timedOutCalls: this.timedOutCalls,
137
- averageDurationMs: this.successfulCalls > 0 ? Math.round(this.totalDurationMs / this.successfulCalls) : 0
138
- };
139
- }
140
- canAccept() {
141
- return this.activeCalls < this.config.maxConcurrentCalls || this.queue.length < this.config.maxQueueSize;
142
- }
143
- resetMetrics() {
144
- this.totalCalls = 0;
145
- this.successfulCalls = 0;
146
- this.failedCalls = 0;
147
- this.rejectedCalls = 0;
148
- this.timedOutCalls = 0;
149
- this.totalDurationMs = 0;
150
- }
151
- };
3
+ var chunkLXXCDKHB_cjs = require('./chunk-LXXCDKHB.cjs');
152
4
 
153
- // src/bulkhead/bulkhead.registry.ts
154
- var DEFAULT_CONFIG = {
155
- maxConcurrentCalls: 10,
156
- maxQueueSize: 100,
157
- queueTimeoutMs: 3e4,
158
- rejectWhenFull: true
159
- };
160
- var BulkheadRegistry = class {
161
- bulkheads = /* @__PURE__ */ new Map();
162
- getOrCreate(options) {
163
- if (!this.bulkheads.has(options.name)) {
164
- const config = { ...DEFAULT_CONFIG, ...options, name: options.name };
165
- this.bulkheads.set(options.name, new Bulkhead(config));
166
- }
167
- return this.bulkheads.get(options.name);
168
- }
169
- /** Per-client isolation — 5 concurrent, 20 queued */
170
- getForClient(clientId, endpoint) {
171
- const name = endpoint ? `client:${clientId}:${endpoint}` : `client:${clientId}`;
172
- return this.getOrCreate({ name, maxConcurrentCalls: 5, maxQueueSize: 20 });
173
- }
174
- /** Service-level limiting — 20 concurrent, 200 queued */
175
- getForService(serviceName) {
176
- return this.getOrCreate({
177
- name: `service:${serviceName}`,
178
- maxConcurrentCalls: 20,
179
- maxQueueSize: 200
180
- });
181
- }
182
- /** Database connection limiting — 15 concurrent, 150 queued */
183
- getForDatabase(schema) {
184
- return this.getOrCreate({
185
- name: `database:${schema}`,
186
- maxConcurrentCalls: 15,
187
- maxQueueSize: 150
188
- });
189
- }
190
- /** External HTTP calls — 8 concurrent, 50 queued, 10s timeout */
191
- getForHttpExternal(serviceName) {
192
- return this.getOrCreate({
193
- name: `http:${serviceName}`,
194
- maxConcurrentCalls: 8,
195
- maxQueueSize: 50,
196
- queueTimeoutMs: 1e4
197
- });
198
- }
199
- getAllMetrics() {
200
- const metrics = {};
201
- for (const [name, bulkhead] of this.bulkheads) {
202
- metrics[name] = bulkhead.getMetrics();
203
- }
204
- return metrics;
205
- }
206
- /** Returns bulkheads at or above 80% active capacity */
207
- getOverloadedBulkheads() {
208
- const overloaded = [];
209
- for (const bulkhead of this.bulkheads.values()) {
210
- const m = bulkhead.getMetrics();
211
- if (m.activeCalls >= m.maxConcurrentCalls * 0.8) {
212
- overloaded.push(m);
213
- }
214
- }
215
- return overloaded;
216
- }
217
- resetAllMetrics() {
218
- for (const bulkhead of this.bulkheads.values()) {
219
- bulkhead.resetMetrics();
220
- }
221
- }
222
- };
223
5
 
224
- exports.Bulkhead = Bulkhead;
225
- exports.BulkheadRegistry = BulkheadRegistry;
226
- exports.BulkheadRejectedError = BulkheadRejectedError;
227
- exports.BulkheadTimeoutError = BulkheadTimeoutError;
6
+
7
+ Object.defineProperty(exports, "Bulkhead", {
8
+ enumerable: true,
9
+ get: function () { return chunkLXXCDKHB_cjs.Bulkhead; }
10
+ });
11
+ Object.defineProperty(exports, "BulkheadRegistry", {
12
+ enumerable: true,
13
+ get: function () { return chunkLXXCDKHB_cjs.BulkheadRegistry; }
14
+ });
15
+ Object.defineProperty(exports, "BulkheadRejectedError", {
16
+ enumerable: true,
17
+ get: function () { return chunkLXXCDKHB_cjs.BulkheadRejectedError; }
18
+ });
19
+ Object.defineProperty(exports, "BulkheadTimeoutError", {
20
+ enumerable: true,
21
+ get: function () { return chunkLXXCDKHB_cjs.BulkheadTimeoutError; }
22
+ });
228
23
  //# sourceMappingURL=index.cjs.map
229
24
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/bulkhead/bulkhead.ts","../src/bulkhead/bulkhead.registry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WAAW,CAAA,CAAA;AAAA,MACzB,kBAAA,EAAoB,CAAA;AAAA,MACpB,YAAA,EAAc,EAAA;AAAA,MACd,cAAA,EAAgB;AAAA,KACjB,CAAA;AAAA,EACH;AAAA,EAEA,aAAA,GAAiD;AAC/C,IAAA,MAAM,UAA2C,EAAC;AAClD,IAAA,KAAA,MAAW,CAAC,IAAA,EAAM,QAAQ,CAAA,IAAK,KAAK,SAAA,EAAW;AAC7C,MAAA,OAAA,CAAQ,IAAI,CAAA,GAAI,QAAA,CAAS,UAAA,EAAW;AAAA,IACtC;AACA,IAAA,OAAO,OAAA;AAAA,EACT;AAAA;AAAA,EAGA,sBAAA,GAA4C;AAC1C,IAAA,MAAM,aAAgC,EAAC;AACvC,IAAA,KAAA,MAAW,QAAA,IAAY,IAAA,CAAK,SAAA,CAAU,MAAA,EAAO,EAAG;AAC9C,MAAA,MAAM,CAAA,GAAI,SAAS,UAAA,EAAW;AAC9B,MAAA,IAAI,CAAA,CAAE,WAAA,IAAe,CAAA,CAAE,kBAAA,GAAqB,GAAA,EAAK;AAC/C,QAAA,UAAA,CAAW,KAAK,CAAC,CAAA;AAAA,MACnB;AAAA,IACF;AACA,IAAA,OAAO,UAAA;AAAA,EACT;AAAA,EAEA,eAAA,GAAwB;AACtB,IAAA,KAAA,MAAW,QAAA,IAAY,IAAA,CAAK,SAAA,CAAU,MAAA,EAAO,EAAG;AAC9C,MAAA,QAAA,CAAS,YAAA,EAAa;AAAA,IACxB;AAAA,EACF;AACF","file":"index.cjs","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"]}
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"index.cjs"}
package/dist/index.js CHANGED
@@ -1,224 +1,3 @@
1
- // src/bulkhead/bulkhead.ts
2
- var BulkheadRejectedError = class extends Error {
3
- constructor(message) {
4
- super(message);
5
- this.name = "BulkheadRejectedError";
6
- }
7
- };
8
- var BulkheadTimeoutError = class extends Error {
9
- constructor(message) {
10
- super(message);
11
- this.name = "BulkheadTimeoutError";
12
- }
13
- };
14
- var Bulkhead = class {
15
- constructor(config) {
16
- this.config = config;
17
- }
18
- config;
19
- activeCalls = 0;
20
- nextId = 0;
21
- queue = [];
22
- totalCalls = 0;
23
- successfulCalls = 0;
24
- failedCalls = 0;
25
- rejectedCalls = 0;
26
- timedOutCalls = 0;
27
- totalDurationMs = 0;
28
- async execute(task) {
29
- const startTime = Date.now();
30
- this.totalCalls++;
31
- if (this.activeCalls < this.config.maxConcurrentCalls) {
32
- return this.runTask(task, startTime);
33
- }
34
- if (this.queue.length >= this.config.maxQueueSize) {
35
- if (this.config.rejectWhenFull) {
36
- this.rejectedCalls++;
37
- throw new BulkheadRejectedError(
38
- `Bulkhead '${this.config.name}' is full. Active: ${this.activeCalls}, Queue: ${this.queue.length}, Max: ${this.config.maxConcurrentCalls}`
39
- );
40
- }
41
- return this.waitAndRetry(task, startTime);
42
- }
43
- const entryId = this.nextId++;
44
- return new Promise((resolve, reject) => {
45
- const timeoutId = setTimeout(() => {
46
- const index = this.queue.findIndex((item) => item.id === entryId);
47
- if (index !== -1) this.queue.splice(index, 1);
48
- this.timedOutCalls++;
49
- reject(
50
- new BulkheadTimeoutError(
51
- `Bulkhead '${this.config.name}' timeout after ${this.config.queueTimeoutMs}ms`
52
- )
53
- );
54
- }, this.config.queueTimeoutMs);
55
- this.queue.push({
56
- id: entryId,
57
- task,
58
- resolve: (value) => {
59
- clearTimeout(timeoutId);
60
- resolve(value);
61
- },
62
- reject: (reason) => {
63
- clearTimeout(timeoutId);
64
- reject(reason);
65
- },
66
- queuedAt: startTime
67
- });
68
- this.processQueue();
69
- });
70
- }
71
- async runTask(task, startTime) {
72
- this.activeCalls++;
73
- try {
74
- const result = await task();
75
- this.successfulCalls++;
76
- this.totalDurationMs += Date.now() - startTime;
77
- return result;
78
- } catch (error) {
79
- this.failedCalls++;
80
- throw error;
81
- } finally {
82
- this.activeCalls--;
83
- this.processQueue();
84
- }
85
- }
86
- async waitAndRetry(task, startTime) {
87
- const maxRetries = 3;
88
- const baseDelay = 100;
89
- for (let attempt = 1; attempt <= maxRetries; attempt++) {
90
- if (this.activeCalls < this.config.maxConcurrentCalls) {
91
- return this.runTask(task, startTime);
92
- }
93
- await new Promise((resolve) => setTimeout(resolve, baseDelay * Math.pow(2, attempt - 1)));
94
- }
95
- this.rejectedCalls++;
96
- throw new BulkheadRejectedError(
97
- `Bulkhead '${this.config.name}' rejected after ${maxRetries} retries`
98
- );
99
- }
100
- processQueue() {
101
- while (this.activeCalls < this.config.maxConcurrentCalls && this.queue.length > 0) {
102
- const next = this.queue.shift();
103
- if (!next) break;
104
- const waitTime = Date.now() - next.queuedAt;
105
- if (waitTime > this.config.queueTimeoutMs) {
106
- next.reject(new BulkheadTimeoutError(`Task timed out after ${waitTime}ms in queue`));
107
- this.timedOutCalls++;
108
- continue;
109
- }
110
- this.activeCalls++;
111
- next.task().then((result) => {
112
- this.successfulCalls++;
113
- next.resolve(result);
114
- }).catch((error) => {
115
- this.failedCalls++;
116
- next.reject(error);
117
- }).finally(() => {
118
- this.activeCalls--;
119
- this.processQueue();
120
- });
121
- }
122
- }
123
- getMetrics() {
124
- return {
125
- name: this.config.name,
126
- activeCalls: this.activeCalls,
127
- queuedCalls: this.queue.length,
128
- maxConcurrentCalls: this.config.maxConcurrentCalls,
129
- maxQueueSize: this.config.maxQueueSize,
130
- totalCalls: this.totalCalls,
131
- successfulCalls: this.successfulCalls,
132
- failedCalls: this.failedCalls,
133
- rejectedCalls: this.rejectedCalls,
134
- timedOutCalls: this.timedOutCalls,
135
- averageDurationMs: this.successfulCalls > 0 ? Math.round(this.totalDurationMs / this.successfulCalls) : 0
136
- };
137
- }
138
- canAccept() {
139
- return this.activeCalls < this.config.maxConcurrentCalls || this.queue.length < this.config.maxQueueSize;
140
- }
141
- resetMetrics() {
142
- this.totalCalls = 0;
143
- this.successfulCalls = 0;
144
- this.failedCalls = 0;
145
- this.rejectedCalls = 0;
146
- this.timedOutCalls = 0;
147
- this.totalDurationMs = 0;
148
- }
149
- };
150
-
151
- // src/bulkhead/bulkhead.registry.ts
152
- var DEFAULT_CONFIG = {
153
- maxConcurrentCalls: 10,
154
- maxQueueSize: 100,
155
- queueTimeoutMs: 3e4,
156
- rejectWhenFull: true
157
- };
158
- var BulkheadRegistry = class {
159
- bulkheads = /* @__PURE__ */ new Map();
160
- getOrCreate(options) {
161
- if (!this.bulkheads.has(options.name)) {
162
- const config = { ...DEFAULT_CONFIG, ...options, name: options.name };
163
- this.bulkheads.set(options.name, new Bulkhead(config));
164
- }
165
- return this.bulkheads.get(options.name);
166
- }
167
- /** Per-client isolation — 5 concurrent, 20 queued */
168
- getForClient(clientId, endpoint) {
169
- const name = endpoint ? `client:${clientId}:${endpoint}` : `client:${clientId}`;
170
- return this.getOrCreate({ name, maxConcurrentCalls: 5, maxQueueSize: 20 });
171
- }
172
- /** Service-level limiting — 20 concurrent, 200 queued */
173
- getForService(serviceName) {
174
- return this.getOrCreate({
175
- name: `service:${serviceName}`,
176
- maxConcurrentCalls: 20,
177
- maxQueueSize: 200
178
- });
179
- }
180
- /** Database connection limiting — 15 concurrent, 150 queued */
181
- getForDatabase(schema) {
182
- return this.getOrCreate({
183
- name: `database:${schema}`,
184
- maxConcurrentCalls: 15,
185
- maxQueueSize: 150
186
- });
187
- }
188
- /** External HTTP calls — 8 concurrent, 50 queued, 10s timeout */
189
- getForHttpExternal(serviceName) {
190
- return this.getOrCreate({
191
- name: `http:${serviceName}`,
192
- maxConcurrentCalls: 8,
193
- maxQueueSize: 50,
194
- queueTimeoutMs: 1e4
195
- });
196
- }
197
- getAllMetrics() {
198
- const metrics = {};
199
- for (const [name, bulkhead] of this.bulkheads) {
200
- metrics[name] = bulkhead.getMetrics();
201
- }
202
- return metrics;
203
- }
204
- /** Returns bulkheads at or above 80% active capacity */
205
- getOverloadedBulkheads() {
206
- const overloaded = [];
207
- for (const bulkhead of this.bulkheads.values()) {
208
- const m = bulkhead.getMetrics();
209
- if (m.activeCalls >= m.maxConcurrentCalls * 0.8) {
210
- overloaded.push(m);
211
- }
212
- }
213
- return overloaded;
214
- }
215
- resetAllMetrics() {
216
- for (const bulkhead of this.bulkheads.values()) {
217
- bulkhead.resetMetrics();
218
- }
219
- }
220
- };
221
-
222
- export { Bulkhead, BulkheadRegistry, BulkheadRejectedError, BulkheadTimeoutError };
1
+ export { Bulkhead, BulkheadRegistry, BulkheadRejectedError, BulkheadTimeoutError } from './chunk-SRWDZPTJ.js';
223
2
  //# sourceMappingURL=index.js.map
224
3
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/bulkhead/bulkhead.ts","../src/bulkhead/bulkhead.registry.ts"],"names":[],"mappings":";AA2BO,IAAM,qBAAA,GAAN,cAAoC,KAAA,CAAM;AAAA,EAC/C,YAAY,OAAA,EAAiB;AAC3B,IAAA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ACjB,CAAA;AAAA,EACH;AAAA,EAEA,aAAA,GAAiD;AAC/C,IAAA,MAAM,UAA2C,EAAC;AAClD,IAAA,KAAA,MAAW,CAAC,IAAA,EAAM,QAAQ,CAAA,IAAK,KAAK,SAAA,EAAW;AAC7C,MAAA,OAAA,CAAQ,IAAI,CAAA,GAAI,QAAA,CAAS,UAAA,EAAW;AAAA,IACtC;AACA,IAAA,OAAO,OAAA;AAAA,EACT;AAAA;AAAA,EAGA,sBAAA,GAA4C;AAC1C,IAAA,MAAM,aAAgC,EAAC;AACvC,IAAA,KAAA,MAAW,QAAA,IAAY,IAAA,CAAK,SAAA,CAAU,MAAA,EAAO,EAAG;AAC9C,MAAA,MAAM,CAAA,GAAI,SAAS,UAAA,EAAW;AAC9B,MAAA,IAAI,CAAA,CAAE,WAAA,IAAe,CAAA,CAAE,kBAAA,GAAqB,GAAA,EAAK;AAC/C,QAAA,UAAA,CAAW,KAAK,CAAC,CAAA;AAAA,MACnB;AAAA,IACF;AACA,IAAA,OAAO,UAAA;AAAA,EACT;AAAA,EAEA,eAAA,GAAwB;AACtB,IAAA,KAAA,MAAW,QAAA,IAAY,IAAA,CAAK,SAAA,CAAU,MAAA,EAAO,EAAG;AAC9C,MAAA,QAAA,CAAS,YAAA,EAAa;AAAA,IACxB;AAAA,EACF;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"]}
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"index.js"}