File size: 1,640 Bytes
fc93158
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { createLoopRateLimiter } from "./loop-rate-limiter.js";

describe("createLoopRateLimiter", () => {
  beforeEach(() => {
    vi.useFakeTimers();
  });

  afterEach(() => {
    vi.useRealTimers();
  });

  it("allows messages below the threshold", () => {
    const limiter = createLoopRateLimiter({ windowMs: 10_000, maxHits: 3 });
    limiter.record("conv:1");
    limiter.record("conv:1");
    expect(limiter.isRateLimited("conv:1")).toBe(false);
  });

  it("rate limits at the threshold", () => {
    const limiter = createLoopRateLimiter({ windowMs: 10_000, maxHits: 3 });
    limiter.record("conv:1");
    limiter.record("conv:1");
    limiter.record("conv:1");
    expect(limiter.isRateLimited("conv:1")).toBe(true);
  });

  it("does not cross-contaminate conversations", () => {
    const limiter = createLoopRateLimiter({ windowMs: 10_000, maxHits: 2 });
    limiter.record("conv:1");
    limiter.record("conv:1");
    expect(limiter.isRateLimited("conv:1")).toBe(true);
    expect(limiter.isRateLimited("conv:2")).toBe(false);
  });

  it("resets after the time window expires", () => {
    const limiter = createLoopRateLimiter({ windowMs: 5_000, maxHits: 2 });
    limiter.record("conv:1");
    limiter.record("conv:1");
    expect(limiter.isRateLimited("conv:1")).toBe(true);

    vi.advanceTimersByTime(6_000);
    expect(limiter.isRateLimited("conv:1")).toBe(false);
  });

  it("returns false for unknown conversations", () => {
    const limiter = createLoopRateLimiter();
    expect(limiter.isRateLimited("unknown")).toBe(false);
  });
});