@artemiskit/sdk 0.3.0 → 0.3.3
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/CHANGELOG.md +225 -0
- package/README.md +44 -1
- package/dist/artemiskit.d.ts +149 -0
- package/dist/artemiskit.d.ts.map +1 -0
- package/dist/builders/index.d.ts +350 -0
- package/dist/builders/index.d.ts.map +1 -0
- package/dist/builders/index.js +398 -0
- package/dist/contracts/index.d.ts +253 -0
- package/dist/contracts/index.d.ts.map +1 -0
- package/dist/contracts/index.js +99 -0
- package/dist/guardian/action-validator.d.ts +92 -0
- package/dist/guardian/action-validator.d.ts.map +1 -0
- package/dist/guardian/circuit-breaker.d.ts +211 -0
- package/dist/guardian/circuit-breaker.d.ts.map +1 -0
- package/dist/guardian/guardian.d.ts +213 -0
- package/dist/guardian/guardian.d.ts.map +1 -0
- package/dist/guardian/guardrails.d.ts +107 -0
- package/dist/guardian/guardrails.d.ts.map +1 -0
- package/dist/guardian/index.d.ts +35 -0
- package/dist/guardian/index.d.ts.map +1 -0
- package/dist/guardian/intent-classifier.d.ts +81 -0
- package/dist/guardian/intent-classifier.d.ts.map +1 -0
- package/dist/guardian/interceptor.d.ts +141 -0
- package/dist/guardian/interceptor.d.ts.map +1 -0
- package/dist/guardian/policy.d.ts +52 -0
- package/dist/guardian/policy.d.ts.map +1 -0
- package/dist/guardian/semantic-validator.d.ts +61 -0
- package/dist/guardian/semantic-validator.d.ts.map +1 -0
- package/dist/guardian/types.d.ts +653 -0
- package/dist/guardian/types.d.ts.map +1 -0
- package/dist/index.d.ts +23 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +24847 -13653
- package/dist/matchers/core.d.ts +81 -0
- package/dist/matchers/core.d.ts.map +1 -0
- package/dist/matchers/index.d.ts +6 -0
- package/dist/matchers/index.d.ts.map +1 -0
- package/dist/matchers/jest.d.ts +46 -0
- package/dist/matchers/jest.d.ts.map +1 -0
- package/dist/matchers/vitest.d.ts +24 -0
- package/dist/matchers/vitest.d.ts.map +1 -0
- package/dist/types-only.d.ts +31 -0
- package/dist/types-only.d.ts.map +1 -0
- package/dist/types-only.js +1 -0
- package/dist/types.d.ts +377 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/utils/index.d.ts +112 -0
- package/dist/utils/index.d.ts.map +1 -0
- package/dist/utils/index.js +104 -0
- package/package.json +19 -4
- package/src/__tests__/builders.test.ts +445 -0
- package/src/__tests__/circuit-breaker.test.ts +704 -0
- package/src/__tests__/compare.test.ts +469 -0
- package/src/__tests__/contracts.test.ts +354 -0
- package/src/__tests__/guardian-modes.test.ts +215 -0
- package/src/__tests__/guardrails.test.ts +404 -0
- package/src/__tests__/semantic-validator.test.ts +421 -0
- package/src/__tests__/utils.test.ts +324 -0
- package/src/__tests__/validate.test.ts +307 -0
- package/src/artemiskit.ts +478 -5
- package/src/builders/index.ts +698 -0
- package/src/contracts/index.ts +357 -0
- package/src/guardian/circuit-breaker.ts +74 -28
- package/src/guardian/guardian.ts +307 -20
- package/src/guardian/guardrails.ts +143 -1
- package/src/guardian/index.ts +35 -1
- package/src/guardian/interceptor.ts +87 -11
- package/src/guardian/semantic-validator.ts +399 -0
- package/src/guardian/types.ts +413 -2
- package/src/index.ts +258 -14
- package/src/types-only.ts +276 -0
- package/src/types.ts +183 -0
- package/src/utils/index.ts +225 -0
- package/tsconfig.json +2 -1
|
@@ -0,0 +1,704 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tests for Guardian circuit breaker, metrics, and rate limiting modules
|
|
3
|
+
* - CircuitBreaker state transitions
|
|
4
|
+
* - MetricsCollector aggregation
|
|
5
|
+
* - RateLimiter token bucket
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
|
|
9
|
+
import { CircuitBreaker, MetricsCollector, RateLimiter } from '../guardian/circuit-breaker';
|
|
10
|
+
import type { Violation } from '../guardian/types';
|
|
11
|
+
|
|
12
|
+
// Helper to create a test violation
|
|
13
|
+
function createViolation(overrides: Partial<Violation> = {}): Violation {
|
|
14
|
+
return {
|
|
15
|
+
id: 'test-id',
|
|
16
|
+
type: 'injection_detection',
|
|
17
|
+
severity: 'high',
|
|
18
|
+
message: 'Test violation',
|
|
19
|
+
timestamp: new Date(),
|
|
20
|
+
action: 'block',
|
|
21
|
+
blocked: true,
|
|
22
|
+
...overrides,
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
describe('CircuitBreaker', () => {
|
|
27
|
+
// ===========================================================================
|
|
28
|
+
// Constructor and Defaults
|
|
29
|
+
// ===========================================================================
|
|
30
|
+
describe('constructor', () => {
|
|
31
|
+
test('should use default values when not specified', () => {
|
|
32
|
+
const cb = new CircuitBreaker({ enabled: true });
|
|
33
|
+
expect(cb.getState()).toBe('closed');
|
|
34
|
+
expect(cb.getViolationCount()).toBe(0);
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
test('should start in closed state', () => {
|
|
38
|
+
const cb = new CircuitBreaker({
|
|
39
|
+
enabled: true,
|
|
40
|
+
threshold: 3,
|
|
41
|
+
windowMs: 60000,
|
|
42
|
+
cooldownMs: 30000,
|
|
43
|
+
});
|
|
44
|
+
expect(cb.getState()).toBe('closed');
|
|
45
|
+
});
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
// ===========================================================================
|
|
49
|
+
// isOpen and allowRequest
|
|
50
|
+
// ===========================================================================
|
|
51
|
+
describe('isOpen', () => {
|
|
52
|
+
test('should return false when circuit is closed', () => {
|
|
53
|
+
const cb = new CircuitBreaker({ enabled: true });
|
|
54
|
+
expect(cb.isOpen()).toBe(false);
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
test('should return true when circuit is open', () => {
|
|
58
|
+
const cb = new CircuitBreaker({ enabled: true, threshold: 1 });
|
|
59
|
+
cb.recordViolation(createViolation());
|
|
60
|
+
expect(cb.isOpen()).toBe(true);
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
test('should return false when disabled', () => {
|
|
64
|
+
const cb = new CircuitBreaker({ enabled: false, threshold: 1 });
|
|
65
|
+
cb.forceState('open');
|
|
66
|
+
expect(cb.isOpen()).toBe(false);
|
|
67
|
+
});
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
describe('allowRequest', () => {
|
|
71
|
+
test('should allow requests when circuit is closed', () => {
|
|
72
|
+
const cb = new CircuitBreaker({ enabled: true });
|
|
73
|
+
expect(cb.allowRequest()).toBe(true);
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
test('should deny requests when circuit is open', () => {
|
|
77
|
+
const cb = new CircuitBreaker({ enabled: true, threshold: 1 });
|
|
78
|
+
cb.recordViolation(createViolation());
|
|
79
|
+
expect(cb.allowRequest()).toBe(false);
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
test('should always allow when disabled', () => {
|
|
83
|
+
const cb = new CircuitBreaker({ enabled: false });
|
|
84
|
+
cb.forceState('open');
|
|
85
|
+
expect(cb.allowRequest()).toBe(true);
|
|
86
|
+
});
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
// ===========================================================================
|
|
90
|
+
// State Transitions
|
|
91
|
+
// ===========================================================================
|
|
92
|
+
describe('state transitions', () => {
|
|
93
|
+
test('should transition from closed to open when threshold reached', () => {
|
|
94
|
+
const cb = new CircuitBreaker({
|
|
95
|
+
enabled: true,
|
|
96
|
+
threshold: 3,
|
|
97
|
+
windowMs: 60000,
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
expect(cb.getState()).toBe('closed');
|
|
101
|
+
|
|
102
|
+
cb.recordViolation(createViolation());
|
|
103
|
+
cb.recordViolation(createViolation());
|
|
104
|
+
expect(cb.getState()).toBe('closed');
|
|
105
|
+
|
|
106
|
+
cb.recordViolation(createViolation());
|
|
107
|
+
expect(cb.getState()).toBe('open');
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
test('should transition to half-open after cooldown', () => {
|
|
111
|
+
const cb = new CircuitBreaker({
|
|
112
|
+
enabled: true,
|
|
113
|
+
threshold: 1,
|
|
114
|
+
cooldownMs: 100, // Short cooldown for testing
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
cb.recordViolation(createViolation());
|
|
118
|
+
expect(cb.getState()).toBe('open');
|
|
119
|
+
|
|
120
|
+
// Wait for cooldown
|
|
121
|
+
const waitStart = Date.now();
|
|
122
|
+
while (Date.now() - waitStart < 150) {
|
|
123
|
+
// Busy wait
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// isOpen() should trigger transition to half-open
|
|
127
|
+
expect(cb.isOpen()).toBe(false);
|
|
128
|
+
expect(cb.getState()).toBe('half-open');
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
test('should transition from half-open to closed after successful requests', () => {
|
|
132
|
+
const cb = new CircuitBreaker({
|
|
133
|
+
enabled: true,
|
|
134
|
+
threshold: 1,
|
|
135
|
+
cooldownMs: 10,
|
|
136
|
+
halfOpenRequests: 2,
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
// Trip the circuit
|
|
140
|
+
cb.recordViolation(createViolation());
|
|
141
|
+
expect(cb.getState()).toBe('open');
|
|
142
|
+
|
|
143
|
+
// Wait for cooldown
|
|
144
|
+
const waitStart = Date.now();
|
|
145
|
+
while (Date.now() - waitStart < 50) {
|
|
146
|
+
// Busy wait
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// Trigger transition to half-open
|
|
150
|
+
cb.isOpen();
|
|
151
|
+
expect(cb.getState()).toBe('half-open');
|
|
152
|
+
|
|
153
|
+
// Record successful requests
|
|
154
|
+
cb.recordSuccess();
|
|
155
|
+
expect(cb.getState()).toBe('half-open');
|
|
156
|
+
|
|
157
|
+
cb.recordSuccess();
|
|
158
|
+
expect(cb.getState()).toBe('closed');
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
test('should trip again from half-open on violation', () => {
|
|
162
|
+
const cb = new CircuitBreaker({
|
|
163
|
+
enabled: true,
|
|
164
|
+
threshold: 1,
|
|
165
|
+
cooldownMs: 10,
|
|
166
|
+
});
|
|
167
|
+
|
|
168
|
+
// Trip the circuit
|
|
169
|
+
cb.recordViolation(createViolation());
|
|
170
|
+
expect(cb.getState()).toBe('open');
|
|
171
|
+
|
|
172
|
+
// Wait for cooldown and transition to half-open
|
|
173
|
+
const waitStart = Date.now();
|
|
174
|
+
while (Date.now() - waitStart < 50) {
|
|
175
|
+
// Busy wait
|
|
176
|
+
}
|
|
177
|
+
cb.isOpen();
|
|
178
|
+
expect(cb.getState()).toBe('half-open');
|
|
179
|
+
|
|
180
|
+
// Violation in half-open should trip again
|
|
181
|
+
cb.recordViolation(createViolation({ blocked: true }));
|
|
182
|
+
expect(cb.getState()).toBe('open');
|
|
183
|
+
});
|
|
184
|
+
});
|
|
185
|
+
|
|
186
|
+
// ===========================================================================
|
|
187
|
+
// Violation Tracking
|
|
188
|
+
// ===========================================================================
|
|
189
|
+
describe('violation tracking', () => {
|
|
190
|
+
test('should count violations within window', () => {
|
|
191
|
+
const cb = new CircuitBreaker({
|
|
192
|
+
enabled: true,
|
|
193
|
+
threshold: 10,
|
|
194
|
+
windowMs: 60000,
|
|
195
|
+
});
|
|
196
|
+
|
|
197
|
+
cb.recordViolation(createViolation());
|
|
198
|
+
cb.recordViolation(createViolation());
|
|
199
|
+
cb.recordViolation(createViolation());
|
|
200
|
+
|
|
201
|
+
expect(cb.getViolationCount()).toBe(3);
|
|
202
|
+
});
|
|
203
|
+
|
|
204
|
+
test('should not count violations when disabled', () => {
|
|
205
|
+
const cb = new CircuitBreaker({
|
|
206
|
+
enabled: false,
|
|
207
|
+
threshold: 10,
|
|
208
|
+
});
|
|
209
|
+
|
|
210
|
+
cb.recordViolation(createViolation());
|
|
211
|
+
cb.recordViolation(createViolation());
|
|
212
|
+
|
|
213
|
+
expect(cb.getViolationCount()).toBe(0);
|
|
214
|
+
});
|
|
215
|
+
|
|
216
|
+
test('should expire old violations outside window', () => {
|
|
217
|
+
const cb = new CircuitBreaker({
|
|
218
|
+
enabled: true,
|
|
219
|
+
threshold: 10,
|
|
220
|
+
windowMs: 100, // Short window
|
|
221
|
+
});
|
|
222
|
+
|
|
223
|
+
cb.recordViolation(createViolation());
|
|
224
|
+
expect(cb.getViolationCount()).toBe(1);
|
|
225
|
+
|
|
226
|
+
// Wait for window to expire
|
|
227
|
+
const waitStart = Date.now();
|
|
228
|
+
while (Date.now() - waitStart < 150) {
|
|
229
|
+
// Busy wait
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
// Recording new violation should clean up old ones
|
|
233
|
+
cb.recordViolation(createViolation());
|
|
234
|
+
expect(cb.getViolationCount()).toBe(1);
|
|
235
|
+
});
|
|
236
|
+
});
|
|
237
|
+
|
|
238
|
+
// ===========================================================================
|
|
239
|
+
// Trip and Reset
|
|
240
|
+
// ===========================================================================
|
|
241
|
+
describe('trip and reset', () => {
|
|
242
|
+
test('should manually trip the circuit', () => {
|
|
243
|
+
const cb = new CircuitBreaker({ enabled: true, threshold: 10 });
|
|
244
|
+
expect(cb.getState()).toBe('closed');
|
|
245
|
+
|
|
246
|
+
cb.trip();
|
|
247
|
+
expect(cb.getState()).toBe('open');
|
|
248
|
+
});
|
|
249
|
+
|
|
250
|
+
test('should reset the circuit', () => {
|
|
251
|
+
const cb = new CircuitBreaker({ enabled: true, threshold: 1 });
|
|
252
|
+
|
|
253
|
+
cb.recordViolation(createViolation());
|
|
254
|
+
expect(cb.getState()).toBe('open');
|
|
255
|
+
|
|
256
|
+
cb.reset();
|
|
257
|
+
expect(cb.getState()).toBe('closed');
|
|
258
|
+
expect(cb.getViolationCount()).toBe(0);
|
|
259
|
+
});
|
|
260
|
+
|
|
261
|
+
test('forceState should set any state', () => {
|
|
262
|
+
const cb = new CircuitBreaker({ enabled: true });
|
|
263
|
+
|
|
264
|
+
cb.forceState('open');
|
|
265
|
+
expect(cb.getState()).toBe('open');
|
|
266
|
+
|
|
267
|
+
cb.forceState('half-open');
|
|
268
|
+
expect(cb.getState()).toBe('half-open');
|
|
269
|
+
|
|
270
|
+
cb.forceState('closed');
|
|
271
|
+
expect(cb.getState()).toBe('closed');
|
|
272
|
+
});
|
|
273
|
+
});
|
|
274
|
+
|
|
275
|
+
// ===========================================================================
|
|
276
|
+
// Time Until Reset
|
|
277
|
+
// ===========================================================================
|
|
278
|
+
describe('getTimeUntilReset', () => {
|
|
279
|
+
test('should return 0 when circuit is closed', () => {
|
|
280
|
+
const cb = new CircuitBreaker({ enabled: true });
|
|
281
|
+
expect(cb.getTimeUntilReset()).toBe(0);
|
|
282
|
+
});
|
|
283
|
+
|
|
284
|
+
test('should return remaining time when circuit is open', () => {
|
|
285
|
+
const cb = new CircuitBreaker({
|
|
286
|
+
enabled: true,
|
|
287
|
+
threshold: 1,
|
|
288
|
+
cooldownMs: 5000,
|
|
289
|
+
});
|
|
290
|
+
|
|
291
|
+
cb.recordViolation(createViolation());
|
|
292
|
+
const timeUntilReset = cb.getTimeUntilReset();
|
|
293
|
+
|
|
294
|
+
expect(timeUntilReset).toBeGreaterThan(0);
|
|
295
|
+
expect(timeUntilReset).toBeLessThanOrEqual(5000);
|
|
296
|
+
});
|
|
297
|
+
});
|
|
298
|
+
|
|
299
|
+
// ===========================================================================
|
|
300
|
+
// Event Handlers
|
|
301
|
+
// ===========================================================================
|
|
302
|
+
describe('event handlers', () => {
|
|
303
|
+
test('should emit events on state changes', () => {
|
|
304
|
+
const cb = new CircuitBreaker({ enabled: true, threshold: 1 });
|
|
305
|
+
const events: string[] = [];
|
|
306
|
+
|
|
307
|
+
cb.onEvent((event) => {
|
|
308
|
+
events.push(event);
|
|
309
|
+
});
|
|
310
|
+
|
|
311
|
+
cb.recordViolation(createViolation());
|
|
312
|
+
|
|
313
|
+
expect(events).toContain('violation');
|
|
314
|
+
expect(events).toContain('open');
|
|
315
|
+
});
|
|
316
|
+
|
|
317
|
+
test('should emit success events', () => {
|
|
318
|
+
const cb = new CircuitBreaker({ enabled: true });
|
|
319
|
+
const events: string[] = [];
|
|
320
|
+
|
|
321
|
+
cb.onEvent((event) => {
|
|
322
|
+
events.push(event);
|
|
323
|
+
});
|
|
324
|
+
|
|
325
|
+
cb.recordSuccess();
|
|
326
|
+
|
|
327
|
+
expect(events).toContain('success');
|
|
328
|
+
});
|
|
329
|
+
|
|
330
|
+
test('should remove event handler with offEvent', () => {
|
|
331
|
+
const cb = new CircuitBreaker({ enabled: true });
|
|
332
|
+
const events: string[] = [];
|
|
333
|
+
|
|
334
|
+
const handler = (event: string) => {
|
|
335
|
+
events.push(event);
|
|
336
|
+
};
|
|
337
|
+
|
|
338
|
+
cb.onEvent(handler);
|
|
339
|
+
cb.recordSuccess();
|
|
340
|
+
expect(events.length).toBe(1);
|
|
341
|
+
|
|
342
|
+
cb.offEvent(handler);
|
|
343
|
+
cb.recordSuccess();
|
|
344
|
+
expect(events.length).toBe(1); // No new events
|
|
345
|
+
});
|
|
346
|
+
|
|
347
|
+
test('should handle errors in event handlers gracefully', () => {
|
|
348
|
+
const cb = new CircuitBreaker({ enabled: true });
|
|
349
|
+
|
|
350
|
+
cb.onEvent(() => {
|
|
351
|
+
throw new Error('Handler error');
|
|
352
|
+
});
|
|
353
|
+
|
|
354
|
+
// Should not throw
|
|
355
|
+
expect(() => cb.recordSuccess()).not.toThrow();
|
|
356
|
+
});
|
|
357
|
+
});
|
|
358
|
+
});
|
|
359
|
+
|
|
360
|
+
describe('MetricsCollector', () => {
|
|
361
|
+
// ===========================================================================
|
|
362
|
+
// Record Request
|
|
363
|
+
// ===========================================================================
|
|
364
|
+
describe('recordRequest', () => {
|
|
365
|
+
test('should track total requests', () => {
|
|
366
|
+
const mc = new MetricsCollector();
|
|
367
|
+
|
|
368
|
+
mc.recordRequest({ blocked: false, warned: false, latencyMs: 100, violations: [] });
|
|
369
|
+
mc.recordRequest({ blocked: false, warned: false, latencyMs: 100, violations: [] });
|
|
370
|
+
|
|
371
|
+
const metrics = mc.getMetrics();
|
|
372
|
+
expect(metrics.totalRequests).toBe(2);
|
|
373
|
+
});
|
|
374
|
+
|
|
375
|
+
test('should track blocked requests', () => {
|
|
376
|
+
const mc = new MetricsCollector();
|
|
377
|
+
|
|
378
|
+
mc.recordRequest({ blocked: true, warned: false, latencyMs: 100, violations: [] });
|
|
379
|
+
mc.recordRequest({ blocked: false, warned: false, latencyMs: 100, violations: [] });
|
|
380
|
+
|
|
381
|
+
const metrics = mc.getMetrics();
|
|
382
|
+
expect(metrics.blockedRequests).toBe(1);
|
|
383
|
+
expect(metrics.allowedRequests).toBe(1);
|
|
384
|
+
});
|
|
385
|
+
|
|
386
|
+
test('should track warned requests', () => {
|
|
387
|
+
const mc = new MetricsCollector();
|
|
388
|
+
|
|
389
|
+
mc.recordRequest({ blocked: false, warned: true, latencyMs: 100, violations: [] });
|
|
390
|
+
|
|
391
|
+
const metrics = mc.getMetrics();
|
|
392
|
+
expect(metrics.warnedRequests).toBe(1);
|
|
393
|
+
});
|
|
394
|
+
|
|
395
|
+
test('should calculate average latency', () => {
|
|
396
|
+
const mc = new MetricsCollector();
|
|
397
|
+
|
|
398
|
+
mc.recordRequest({ blocked: false, warned: false, latencyMs: 100, violations: [] });
|
|
399
|
+
mc.recordRequest({ blocked: false, warned: false, latencyMs: 200, violations: [] });
|
|
400
|
+
mc.recordRequest({ blocked: false, warned: false, latencyMs: 300, violations: [] });
|
|
401
|
+
|
|
402
|
+
const metrics = mc.getMetrics();
|
|
403
|
+
expect(metrics.averageLatencyMs).toBe(200);
|
|
404
|
+
});
|
|
405
|
+
|
|
406
|
+
test('should track violations by type', () => {
|
|
407
|
+
const mc = new MetricsCollector();
|
|
408
|
+
|
|
409
|
+
mc.recordRequest({
|
|
410
|
+
blocked: true,
|
|
411
|
+
warned: false,
|
|
412
|
+
latencyMs: 100,
|
|
413
|
+
violations: [createViolation({ type: 'injection_detection' })],
|
|
414
|
+
});
|
|
415
|
+
mc.recordRequest({
|
|
416
|
+
blocked: true,
|
|
417
|
+
warned: false,
|
|
418
|
+
latencyMs: 100,
|
|
419
|
+
violations: [createViolation({ type: 'pii_detection' })],
|
|
420
|
+
});
|
|
421
|
+
|
|
422
|
+
const metrics = mc.getMetrics();
|
|
423
|
+
expect(metrics.violationsByType.injection_detection).toBe(1);
|
|
424
|
+
expect(metrics.violationsByType.pii_detection).toBe(1);
|
|
425
|
+
});
|
|
426
|
+
|
|
427
|
+
test('should track violations by severity', () => {
|
|
428
|
+
const mc = new MetricsCollector();
|
|
429
|
+
|
|
430
|
+
mc.recordRequest({
|
|
431
|
+
blocked: true,
|
|
432
|
+
warned: false,
|
|
433
|
+
latencyMs: 100,
|
|
434
|
+
violations: [createViolation({ severity: 'critical' })],
|
|
435
|
+
});
|
|
436
|
+
mc.recordRequest({
|
|
437
|
+
blocked: true,
|
|
438
|
+
warned: false,
|
|
439
|
+
latencyMs: 100,
|
|
440
|
+
violations: [createViolation({ severity: 'high' })],
|
|
441
|
+
});
|
|
442
|
+
|
|
443
|
+
const metrics = mc.getMetrics();
|
|
444
|
+
expect(metrics.violationsBySeverity.critical).toBe(1);
|
|
445
|
+
expect(metrics.violationsBySeverity.high).toBe(1);
|
|
446
|
+
});
|
|
447
|
+
|
|
448
|
+
test('should track cost when provided', () => {
|
|
449
|
+
const mc = new MetricsCollector();
|
|
450
|
+
|
|
451
|
+
mc.recordRequest({
|
|
452
|
+
blocked: false,
|
|
453
|
+
warned: false,
|
|
454
|
+
latencyMs: 100,
|
|
455
|
+
violations: [],
|
|
456
|
+
cost: 0.01,
|
|
457
|
+
});
|
|
458
|
+
mc.recordRequest({
|
|
459
|
+
blocked: false,
|
|
460
|
+
warned: false,
|
|
461
|
+
latencyMs: 100,
|
|
462
|
+
violations: [],
|
|
463
|
+
cost: 0.02,
|
|
464
|
+
});
|
|
465
|
+
|
|
466
|
+
const metrics = mc.getMetrics();
|
|
467
|
+
expect(metrics.costTracking).toBeDefined();
|
|
468
|
+
expect(metrics.costTracking?.totalCost).toBe(0.03);
|
|
469
|
+
expect(metrics.costTracking?.currency).toBe('USD');
|
|
470
|
+
});
|
|
471
|
+
});
|
|
472
|
+
|
|
473
|
+
// ===========================================================================
|
|
474
|
+
// Get Metrics
|
|
475
|
+
// ===========================================================================
|
|
476
|
+
describe('getMetrics', () => {
|
|
477
|
+
test('should return empty metrics when no requests recorded', () => {
|
|
478
|
+
const mc = new MetricsCollector();
|
|
479
|
+
|
|
480
|
+
const metrics = mc.getMetrics();
|
|
481
|
+
expect(metrics.totalRequests).toBe(0);
|
|
482
|
+
expect(metrics.blockedRequests).toBe(0);
|
|
483
|
+
expect(metrics.averageLatencyMs).toBe(0);
|
|
484
|
+
});
|
|
485
|
+
|
|
486
|
+
test('should accept circuit breaker state', () => {
|
|
487
|
+
const mc = new MetricsCollector();
|
|
488
|
+
|
|
489
|
+
const metrics = mc.getMetrics('open');
|
|
490
|
+
expect(metrics.circuitBreakerState).toBe('open');
|
|
491
|
+
});
|
|
492
|
+
|
|
493
|
+
test('should calculate requests per second', () => {
|
|
494
|
+
const mc = new MetricsCollector();
|
|
495
|
+
|
|
496
|
+
mc.recordRequest({ blocked: false, warned: false, latencyMs: 100, violations: [] });
|
|
497
|
+
|
|
498
|
+
const metrics = mc.getMetrics();
|
|
499
|
+
expect(metrics.requestsPerSecond).toBeGreaterThanOrEqual(0);
|
|
500
|
+
});
|
|
501
|
+
});
|
|
502
|
+
|
|
503
|
+
// ===========================================================================
|
|
504
|
+
// Get Current Window Metrics
|
|
505
|
+
// ===========================================================================
|
|
506
|
+
describe('getCurrentWindowMetrics', () => {
|
|
507
|
+
test('should return current window only', () => {
|
|
508
|
+
const mc = new MetricsCollector();
|
|
509
|
+
|
|
510
|
+
mc.recordRequest({ blocked: false, warned: false, latencyMs: 100, violations: [] });
|
|
511
|
+
mc.recordRequest({ blocked: true, warned: false, latencyMs: 200, violations: [] });
|
|
512
|
+
|
|
513
|
+
const windowMetrics = mc.getCurrentWindowMetrics();
|
|
514
|
+
expect(windowMetrics.totalRequests).toBe(2);
|
|
515
|
+
expect(windowMetrics.blockedRequests).toBe(1);
|
|
516
|
+
expect(windowMetrics.allowedRequests).toBe(1);
|
|
517
|
+
expect(windowMetrics.averageLatencyMs).toBe(150);
|
|
518
|
+
});
|
|
519
|
+
});
|
|
520
|
+
|
|
521
|
+
// ===========================================================================
|
|
522
|
+
// Reset
|
|
523
|
+
// ===========================================================================
|
|
524
|
+
describe('reset', () => {
|
|
525
|
+
test('should clear all metrics', () => {
|
|
526
|
+
const mc = new MetricsCollector();
|
|
527
|
+
|
|
528
|
+
mc.recordRequest({ blocked: true, warned: false, latencyMs: 100, violations: [] });
|
|
529
|
+
mc.recordRequest({ blocked: false, warned: true, latencyMs: 200, violations: [] });
|
|
530
|
+
|
|
531
|
+
mc.reset();
|
|
532
|
+
|
|
533
|
+
const metrics = mc.getMetrics();
|
|
534
|
+
expect(metrics.totalRequests).toBe(0);
|
|
535
|
+
expect(metrics.blockedRequests).toBe(0);
|
|
536
|
+
expect(metrics.warnedRequests).toBe(0);
|
|
537
|
+
});
|
|
538
|
+
});
|
|
539
|
+
});
|
|
540
|
+
|
|
541
|
+
describe('RateLimiter', () => {
|
|
542
|
+
// ===========================================================================
|
|
543
|
+
// Allow Request
|
|
544
|
+
// ===========================================================================
|
|
545
|
+
describe('allowRequest', () => {
|
|
546
|
+
test('should allow requests within minute limit', () => {
|
|
547
|
+
const rl = new RateLimiter({ requestsPerMinute: 5 });
|
|
548
|
+
|
|
549
|
+
expect(rl.allowRequest().allowed).toBe(true);
|
|
550
|
+
expect(rl.allowRequest().allowed).toBe(true);
|
|
551
|
+
expect(rl.allowRequest().allowed).toBe(true);
|
|
552
|
+
});
|
|
553
|
+
|
|
554
|
+
test('should deny requests exceeding minute limit', () => {
|
|
555
|
+
const rl = new RateLimiter({ requestsPerMinute: 2 });
|
|
556
|
+
|
|
557
|
+
expect(rl.allowRequest().allowed).toBe(true);
|
|
558
|
+
expect(rl.allowRequest().allowed).toBe(true);
|
|
559
|
+
|
|
560
|
+
const result = rl.allowRequest();
|
|
561
|
+
expect(result.allowed).toBe(false);
|
|
562
|
+
expect(result.reason).toContain('minute');
|
|
563
|
+
expect(result.retryAfterMs).toBeDefined();
|
|
564
|
+
});
|
|
565
|
+
|
|
566
|
+
test('should deny requests exceeding hour limit', () => {
|
|
567
|
+
const rl = new RateLimiter({ requestsPerHour: 2 });
|
|
568
|
+
|
|
569
|
+
expect(rl.allowRequest().allowed).toBe(true);
|
|
570
|
+
expect(rl.allowRequest().allowed).toBe(true);
|
|
571
|
+
|
|
572
|
+
const result = rl.allowRequest();
|
|
573
|
+
expect(result.allowed).toBe(false);
|
|
574
|
+
expect(result.reason).toContain('hour');
|
|
575
|
+
});
|
|
576
|
+
|
|
577
|
+
test('should deny requests exceeding day limit', () => {
|
|
578
|
+
const rl = new RateLimiter({ requestsPerDay: 2 });
|
|
579
|
+
|
|
580
|
+
expect(rl.allowRequest().allowed).toBe(true);
|
|
581
|
+
expect(rl.allowRequest().allowed).toBe(true);
|
|
582
|
+
|
|
583
|
+
const result = rl.allowRequest();
|
|
584
|
+
expect(result.allowed).toBe(false);
|
|
585
|
+
expect(result.reason).toContain('day');
|
|
586
|
+
});
|
|
587
|
+
|
|
588
|
+
test('should deny requests exceeding burst limit', () => {
|
|
589
|
+
const rl = new RateLimiter({ burstLimit: 2 });
|
|
590
|
+
|
|
591
|
+
expect(rl.allowRequest().allowed).toBe(true);
|
|
592
|
+
expect(rl.allowRequest().allowed).toBe(true);
|
|
593
|
+
|
|
594
|
+
const result = rl.allowRequest();
|
|
595
|
+
expect(result.allowed).toBe(false);
|
|
596
|
+
expect(result.reason).toContain('Burst');
|
|
597
|
+
});
|
|
598
|
+
|
|
599
|
+
test('should check all limits in order', () => {
|
|
600
|
+
const rl = new RateLimiter({
|
|
601
|
+
requestsPerMinute: 100,
|
|
602
|
+
requestsPerHour: 2,
|
|
603
|
+
});
|
|
604
|
+
|
|
605
|
+
expect(rl.allowRequest().allowed).toBe(true);
|
|
606
|
+
expect(rl.allowRequest().allowed).toBe(true);
|
|
607
|
+
|
|
608
|
+
const result = rl.allowRequest();
|
|
609
|
+
expect(result.allowed).toBe(false);
|
|
610
|
+
expect(result.reason).toContain('hour');
|
|
611
|
+
});
|
|
612
|
+
});
|
|
613
|
+
|
|
614
|
+
// ===========================================================================
|
|
615
|
+
// Get Status
|
|
616
|
+
// ===========================================================================
|
|
617
|
+
describe('getStatus', () => {
|
|
618
|
+
test('should return current usage and limits', () => {
|
|
619
|
+
const rl = new RateLimiter({
|
|
620
|
+
requestsPerMinute: 10,
|
|
621
|
+
requestsPerHour: 100,
|
|
622
|
+
requestsPerDay: 1000,
|
|
623
|
+
burstLimit: 5,
|
|
624
|
+
});
|
|
625
|
+
|
|
626
|
+
rl.allowRequest();
|
|
627
|
+
rl.allowRequest();
|
|
628
|
+
|
|
629
|
+
const status = rl.getStatus();
|
|
630
|
+
expect(status.minuteUsed).toBe(2);
|
|
631
|
+
expect(status.minuteLimit).toBe(10);
|
|
632
|
+
expect(status.hourUsed).toBe(2);
|
|
633
|
+
expect(status.hourLimit).toBe(100);
|
|
634
|
+
expect(status.dayUsed).toBe(2);
|
|
635
|
+
expect(status.dayLimit).toBe(1000);
|
|
636
|
+
expect(status.burstTokens).toBe(3); // 5 - 2
|
|
637
|
+
expect(status.burstLimit).toBe(5);
|
|
638
|
+
});
|
|
639
|
+
|
|
640
|
+
test('should return undefined for unset limits', () => {
|
|
641
|
+
const rl = new RateLimiter({});
|
|
642
|
+
|
|
643
|
+
const status = rl.getStatus();
|
|
644
|
+
expect(status.minuteLimit).toBeUndefined();
|
|
645
|
+
expect(status.hourLimit).toBeUndefined();
|
|
646
|
+
expect(status.dayLimit).toBeUndefined();
|
|
647
|
+
});
|
|
648
|
+
});
|
|
649
|
+
|
|
650
|
+
// ===========================================================================
|
|
651
|
+
// Reset
|
|
652
|
+
// ===========================================================================
|
|
653
|
+
describe('reset', () => {
|
|
654
|
+
test('should reset all counters', () => {
|
|
655
|
+
const rl = new RateLimiter({
|
|
656
|
+
requestsPerMinute: 10,
|
|
657
|
+
burstLimit: 5,
|
|
658
|
+
});
|
|
659
|
+
|
|
660
|
+
rl.allowRequest();
|
|
661
|
+
rl.allowRequest();
|
|
662
|
+
|
|
663
|
+
let status = rl.getStatus();
|
|
664
|
+
expect(status.minuteUsed).toBe(2);
|
|
665
|
+
expect(status.burstTokens).toBe(3);
|
|
666
|
+
|
|
667
|
+
rl.reset();
|
|
668
|
+
|
|
669
|
+
status = rl.getStatus();
|
|
670
|
+
expect(status.minuteUsed).toBe(0);
|
|
671
|
+
expect(status.burstTokens).toBe(5);
|
|
672
|
+
});
|
|
673
|
+
});
|
|
674
|
+
|
|
675
|
+
// ===========================================================================
|
|
676
|
+
// Burst Token Refill
|
|
677
|
+
// ===========================================================================
|
|
678
|
+
describe('burst token refill', () => {
|
|
679
|
+
test('should refill burst tokens over time', () => {
|
|
680
|
+
const rl = new RateLimiter({ burstLimit: 3 });
|
|
681
|
+
|
|
682
|
+
// Use all tokens
|
|
683
|
+
rl.allowRequest();
|
|
684
|
+
rl.allowRequest();
|
|
685
|
+
rl.allowRequest();
|
|
686
|
+
|
|
687
|
+
let status = rl.getStatus();
|
|
688
|
+
expect(status.burstTokens).toBe(0);
|
|
689
|
+
|
|
690
|
+
// Wait for refill (1 token per second)
|
|
691
|
+
const waitStart = Date.now();
|
|
692
|
+
while (Date.now() - waitStart < 1100) {
|
|
693
|
+
// Busy wait
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
// Trigger refill by checking
|
|
697
|
+
rl.allowRequest();
|
|
698
|
+
|
|
699
|
+
status = rl.getStatus();
|
|
700
|
+
// Should have refilled at least 1 token, then used 1
|
|
701
|
+
expect(status.burstTokens).toBeGreaterThanOrEqual(0);
|
|
702
|
+
});
|
|
703
|
+
});
|
|
704
|
+
});
|