Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions apps/app/src/app/api/copilotkit/limit-regression.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// @vitest-environment node
import { afterEach, it, expect, vi } from "vitest";
import { NextRequest } from "next/server";
vi.mock("@copilotkit/runtime",()=>({CopilotRuntime:class {}, ExperimentalEmptyAdapter:class {},copilotRuntimeNextJSAppRouterEndpoint:()=>({handleRequest:async()=>new Response(null)})}));
vi.mock("@/lib/copilotkit-runtime-options",()=>({buildRuntimeOptions:()=>({})}));
vi.mock("@/lib/launch-telemetry",()=>({getLaunchTelemetry:()=>({activated:true,runtimeProperties:()=>undefined,recordOpened:()=>Promise.resolve()}),runtimeMethod:()=>undefined,observeRunResult:()=>Promise.resolve(false)}));
vi.mock("next/server",async importOriginal=>({...await importOriginal<typeof import("next/server")>(),after:vi.fn()}));
afterEach(()=>{vi.useRealTimers();vi.unstubAllEnvs();vi.restoreAllMocks();vi.resetModules();});
it("retains only accepted request timestamps during a rejected burst", async () => {
vi.useFakeTimers(); vi.stubEnv("RATE_LIMIT_ENABLED","true"); vi.stubEnv("RATE_LIMIT_MAX","2");
const arrays: unknown[][]=[]; const realSet=Map.prototype.set;
vi.spyOn(Map.prototype,"set").mockImplementation(function(this:Map<unknown,unknown>,key:unknown,value:unknown){if(key==="198.51.100.1"&&Array.isArray(value)) arrays.push(value);return realSet.call(this,key,value);});
const { POST }=await import("./route");
const request=()=>new NextRequest("http://localhost/api/copilotkit",{method:"POST",headers:{"x-forwarded-for":"198.51.100.1"}});
expect((await POST(request())).status).toBe(200); expect((await POST(request())).status).toBe(200);
for(let i=0;i<50;i++)expect((await POST(request())).status).toBe(429);
expect(Math.max(...arrays.map(a=>a.length))).toBe(2);
vi.advanceTimersByTime(60001); expect((await POST(request())).status).toBe(200);
});
4 changes: 4 additions & 0 deletions apps/app/src/app/api/copilotkit/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@ function isRateLimited(ip: string): boolean {
if (!RATE_LIMIT_ENABLED) return false;
const now = Date.now();
const timestamps = hits.get(ip)?.filter(t => t > now - RATE_LIMIT_WINDOW_MS) ?? [];
if (timestamps.length >= RATE_LIMIT_MAX) {
hits.set(ip, timestamps);
return true;
}
timestamps.push(now);
hits.set(ip, timestamps);
return timestamps.length > RATE_LIMIT_MAX;
Expand Down