A one-of-a-kind resume builder that keeps your privacy in mind. Completely secure, customizable, portable, open-source and free forever. Try it out today!
TypeScript agent-skillsaidsh-pluginhacktoberfestjavascriptmcp-serverreactresume-builderself-hostedtypescript
fix(api): multiplex resume update subscriptions and rate limit per user (#3661)
Hoàng Anh Tuấn21f0b9cca71d
diff --git a/docs/self-hosting/environment-variables.mdx b/docs/self-hosting/environment-variables.mdxindex 54a4a4172..a9de057c4 100644--- a/docs/self-hosting/environment-variables.mdx+++ b/docs/self-hosting/environment-variables.mdx@@ -204,8 +204,10 @@ Shared credentials stay in the environment and do not require `ENCRYPTION_SECRETRedis is optional on a single server. Without it, everything works, with these limits:- An Assistant reply that is interrupted by a page reload can't be picked up again.-- Rate limits, **Stop** on a running Assistant reply, live updates between open tabs and the check that counts each- public resume view once an hour are kept in the memory of one server process.+- Rate limits, **Stop** on a running Assistant reply and the check that counts each public resume view once an hour+ are kept in the memory of one server process.+- Live resume updates fall back to PostgreSQL `LISTEN`/`NOTIFY`, sharing a single connection per server process+ across all active subscriptions.Set `REDIS_URL` when you run more than one server process, or when you want replies to survive a reload. When Redis isconfigured, the [health endpoint](/self-hosting/docker#check-the-health-endpoint) also checks it.diff --git a/packages/api/src/features/resume/event-router.ts b/packages/api/src/features/resume/event-router.tsindex b46ed0220..c38391da3 100644--- a/packages/api/src/features/resume/event-router.ts+++ b/packages/api/src/features/resume/event-router.ts@@ -1,6 +1,7 @@import { eventIterator } from "@orpc/server";import z from "zod";import { protectedProcedure } from "../../context";+import { resumeUpdatesRateLimit, resumeUpdatesUserRateLimit } from "../../middleware/rate-limit";import { subscribeResumeUpdated } from "./events";import { resumeService } from "./service";@@ -28,6 +29,8 @@ export const updatesRouter = {}),),)+ .use(resumeUpdatesUserRateLimit)+ .use(resumeUpdatesRateLimit).handler(async function* ({ context, input, signal }) {const resume = await resumeService.getById({ id: input.id, userId: context.user.id });diff --git a/packages/api/src/features/resume/events.test.ts b/packages/api/src/features/resume/events.test.tsindex 312e57d44..f637d738f 100644--- a/packages/api/src/features/resume/events.test.ts+++ b/packages/api/src/features/resume/events.test.ts@@ -1,12 +1,15 @@-import { EventEmitter } from "node:events";-import { beforeEach, describe, expect, it, vi } from "vite-plus/test";+import { EventEmitter, getEventListeners } from "node:events";+import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";+import { Pool } from "pg";const pool = vi.hoisted(() => ({query: vi.fn().mockResolvedValue(undefined),connect: vi.fn(),}));+// Tests that need real checkout limits swap in a real pg Pool here.+const database = vi.hoisted(() => ({ pool: undefined as unknown }));-vi.mock("@reactive-resume/db/client", () => ({ getPool: () => pool }));+vi.mock("@reactive-resume/db/client", () => ({ getPool: () => database.pool ?? pool }));const redis = vi.hoisted(() => ({ getRedis: vi.fn(), publish: vi.fn(), duplicate: vi.fn() }));vi.mock("@reactive-resume/db/redis", () => ({getRedis: redis.getRedis,@@ -122,6 +125,34 @@ const makeFakeClient = () => {};describe("subscribeResumeUpdated", () => {+ it.each(["postgres", "redis"] as const)(+ "preserves %s connection errors during setup for every subscriber",+ async (backend) => {+ const client = makeFakeClient();+ const subscriber = makeSubscriber();+ if (backend === "postgres") {+ client.query.mockReturnValue(new Promise(() => {}));+ pool.connect.mockResolvedValueOnce(client);+ } else {+ subscriber.subscribe.mockReturnValue(new Promise(() => {}));+ redis.getRedis.mockReturnValue(redis);+ redis.duplicate.mockReturnValue(subscriber);+ }+ const results = Promise.allSettled(+ ["r1", "r2"].map((resumeId) => subscribeResumeUpdated({ resumeId, userId: "u1" }).next()),+ );+ await vi.waitFor(() => expect(backend === "postgres" ? client.query : subscriber.subscribe).toHaveBeenCalled());+ const error = new Error("connection failed during setup");+ (backend === "postgres" ? client : subscriber).emit("error", error);++ expect(await results).toEqual([+ { status: "rejected", reason: error },+ { status: "rejected", reason: error },+ ]);+ expect(backend === "postgres" ? client.release : subscriber.disconnect).toHaveBeenCalledTimes(1);+ },+ );+it("shares one listening connection between subscribers and yields only their events", async () => {const client = makeFakeClient();pool.connect.mockResolvedValueOnce(client);@@ -146,7 +177,219 @@ describe("subscribeResumeUpdated", () => {second.abort();expect((await mine.next()).done).toBe(true);expect((await theirs.next()).done).toBe(true);- // The connection stays for the next subscriber.- expect(client.release).not.toHaveBeenCalled();+ expect(client.query).toHaveBeenCalledWith("UNLISTEN resume_updated");+ expect(client.release).toHaveBeenCalledTimes(1);+ });+});++type Callback = (error: Error | null, result?: unknown) => void;++/** Stands in for a Postgres socket; the Pool around it is the real pg-pool with its checkout limits. */+class FakePostgresSocket extends EventEmitter {+ static opened: FakePostgresSocket[] = [];+ listening = false;+ _queryable = true;+ _ending = false;++ constructor() {+ super();+ FakePostgresSocket.opened.push(this);+ }++ connect(callback?: Callback) {+ if (callback) return void setImmediate(() => callback(null));+ return Promise.resolve();+ }++ query(text: unknown, values?: unknown, callback?: Callback) {+ if (text === "LISTEN resume_updated") this.listening = true;+ if (text === "UNLISTEN resume_updated") this.listening = false;+ const done = typeof values === "function" ? (values as Callback) : callback;+ const result = { rows: [], rowCount: 0 };+ if (done) return void setImmediate(() => done(null, result));+ return Promise.resolve(result);+ }++ notify(event: typeof exampleEvent) {+ this.emit("notification", { channel: "resume_updated", payload: JSON.stringify(event) });+ }++ end(callback?: () => void) {+ callback?.();+ return Promise.resolve();+ }+}++const tick = () => new Promise((resolve) => setTimeout(resolve, 20));++describe("Postgres resume subscriptions share one connection", () => {+ let realPool: Pool;+ type Handle = {+ controller: AbortController;+ iterator: ReturnType<typeof subscribeResumeUpdated>;+ next: Promise<IteratorResult<unknown>>;+ };+ const active: Handle[] = [];++ beforeEach(() => {+ FakePostgresSocket.opened = [];+ realPool = new Pool({ max: 10, connectionTimeoutMillis: 200, Client: FakePostgresSocket as never });+ database.pool = realPool;+ });++ afterEach(async () => {+ for (const handle of active.splice(0)) {+ handle.controller.abort();+ await handle.iterator.return().catch(() => {});+ }+ await tick();+ database.pool = undefined;+ await realPool.end();+ });++ function open(resumeId: string) {+ const controller = new AbortController();+ const iterator = subscribeResumeUpdated({ resumeId, userId: "u1", signal: controller.signal });+ const handle = { controller, iterator, next: iterator.next() };+ active.push(handle);+ return handle;+ }++ it("keeps the pool available to other queries with more open builders than pool slots", async () => {+ const subscriptions = Array.from({ length: 20 }, (_, index) => open(`r${index}`));+ for (const subscription of subscriptions) subscription.next.catch(() => {});+ await tick();++ expect(realPool.totalCount).toBe(1);+ await expect(realPool.query("SELECT 1")).resolves.toBeDefined();+ });++ it("delivers each subscription its own resume's events, then returns the connection when the last one leaves", async () => {+ const first = open("r1");+ const second = open("r2");+ await tick();+ const [socket] = FakePostgresSocket.opened;+ socket?.notify({ ...exampleEvent, resumeId: "r2" });+ socket?.notify(exampleEvent);++ expect(await first.next).toEqual({ done: false, value: exampleEvent });+ expect(await second.next).toEqual({ done: false, value: { ...exampleEvent, resumeId: "r2" } });++ first.controller.abort();+ expect((await first.iterator.next()).done).toBe(true);+ expect(socket?.listening).toBe(true);++ second.controller.abort();+ expect((await second.iterator.next()).done).toBe(true);+ expect(socket?.listening).toBe(false);+ expect(socket?.listenerCount("notification")).toBe(0);+ expect(realPool.idleCount).toBe(1);+ expect(realPool.totalCount).toBe(1);+ });++ it("ends every subscription when the shared connection breaks, and the next one reconnects", async () => {+ const first = open("r1");+ const second = open("r2");+ await tick();+ const [broken] = FakePostgresSocket.opened;+ broken?.emit("error", new Error("terminating connection due to administrator command"));++ await expect(first.next).rejects.toThrow("terminating connection");+ await expect(second.next).rejects.toThrow("terminating connection");+ await tick();+ expect(realPool.totalCount).toBe(0);++ const retry = open("r1");+ await tick();+ const [, fresh] = FakePostgresSocket.opened;+ expect(fresh?.listening).toBe(true);+ fresh?.notify(exampleEvent);+ expect(await retry.next).toEqual({ done: false, value: exampleEvent });+ });++ it("ends promptly when aborted while connection is hanging", async () => {+ const controller = new AbortController();+ const hangingPool = { connect: () => new Promise(() => {}) };+ database.pool = hangingPool;+ const iterator = subscribeResumeUpdated({ resumeId: "r1", userId: "u1", signal: controller.signal });+ const nextPromise = iterator.next();+ // Abort after readFeed started+ controller.abort();+ const result = await Promise.race([+ nextPromise,+ new Promise((_, reject) => setTimeout(() => reject(new Error("HUNG")), 200)),+ ]);+ expect(result).toEqual({ done: true, value: undefined });+ });++ it("does not leak abort listeners on signal when subscription completes or is closed", async () => {+ const controller = new AbortController();+ const iterator = subscribeResumeUpdated({ resumeId: "r1", userId: "u1", signal: controller.signal });+ const nextPromise = iterator.next();+ await tick();+ const [socket] = FakePostgresSocket.opened;+ socket?.notify(exampleEvent);+ await nextPromise;+ await iterator.return();+ expect(getEventListeners(controller.signal, "abort")).toHaveLength(0);+ });+});++describe("Redis resume subscriptions share one subscriber", () => {+ it("shares one duplicate connection across all open subscriptions", async () => {+ const subscriber = makeSubscriber();+ redis.getRedis.mockReturnValue(redis);+ redis.duplicate.mockReturnValue(subscriber);+ const controllers = [new AbortController(), new AbortController()];+ const iterators = controllers.map((controller, index) =>+ subscribeResumeUpdated({ resumeId: `r${index + 1}`, userId: "u1", signal: controller.signal }),+ );+ const nexts = iterators.map((iterator) => iterator.next());+ await tick();+ subscriber.send("reactive-resume:preview:resume_updated", JSON.stringify({ ...exampleEvent, resumeId: "r2" }));+ subscriber.send("reactive-resume:preview:resume_updated", JSON.stringify(exampleEvent));++ expect(await nexts[0]).toEqual({ done: false, value: exampleEvent });+ expect(await nexts[1]).toEqual({ done: false, value: { ...exampleEvent, resumeId: "r2" } });+ expect(redis.duplicate).toHaveBeenCalledTimes(1);++ controllers[0]?.abort();+ await iterators[0]?.next();+ expect(subscriber.disconnect).not.toHaveBeenCalled();+ controllers[1]?.abort();+ await iterators[1]?.next();+ expect(subscriber.disconnect).toHaveBeenCalledTimes(1);+ });++ it("ends promptly when signal is already aborted before subscribing", async () => {+ const controller = new AbortController();+ controller.abort();+ const subscriber = makeSubscriber();+ subscriber.subscribe = vi.fn(() => new Promise(() => {}));+ redis.getRedis.mockReturnValue(redis);+ redis.duplicate.mockReturnValue(subscriber);++ const iterator = subscribeResumeUpdated({ resumeId: "r1", userId: "u1", signal: controller.signal });+ const nextPromise = iterator.next();+ const result = await Promise.race([+ nextPromise,+ new Promise((_, reject) => setTimeout(() => reject(new Error("HUNG")), 200)),+ ]);++ expect(result).toEqual({ done: true, value: undefined });+ expect(subscriber.subscribe).not.toHaveBeenCalled();+ });++ it("ends cleanly when aborted with a custom error reason", async () => {+ const subscriber = makeSubscriber();+ redis.getRedis.mockReturnValue(redis);+ redis.duplicate.mockReturnValue(subscriber);+ const controller = new AbortController();+ const iterator = subscribeResumeUpdated({ resumeId: "r1", userId: "u1", signal: controller.signal });+ const nextPromise = iterator.next();+ await tick();+ controller.abort(new Error("custom cancellation"));+ expect(await nextPromise).toEqual({ done: true, value: undefined });+ expect(subscriber.disconnect).toHaveBeenCalledTimes(1);});});diff --git a/packages/api/src/features/resume/events.ts b/packages/api/src/features/resume/events.tsindex 6276731b4..4afe78840 100644--- a/packages/api/src/features/resume/events.ts+++ b/packages/api/src/features/resume/events.ts@@ -1,4 +1,4 @@-import { EventEmitter, on, once } from "node:events";+import { EventEmitter, on } from "node:events";import { getPool } from "@reactive-resume/db/client";import { getCoordination } from "@reactive-resume/db/coordination";import { getRedis, redisKey } from "@reactive-resume/db/redis";@@ -62,75 +62,196 @@ function readEvent(payload: string | undefined, resumeId: string, userId: stringreturn undefined;}-const isAbort = (error: unknown) => error instanceof Error && error.name === "AbortError";--// Without Redis, one PostgreSQL connection per process listens and fans notifications out in memory. A connection per-// open editor would use up the pool after a handful of subscribers.-let pgNotifications: Promise<EventEmitter> | undefined;-function sharedPgNotifications() {- pgNotifications ??= (async () => {- const client = await getPool().connect();- const emitter = new EventEmitter().setMaxListeners(0);- client.on("notification", (notification) => emitter.emit("notification", notification));- // A dropped connection is replaced on the next subscription. Open subscriptions end with the error; with none- // open, emitting an unheard "error" would crash the process.- client.on("error", (error) => {- pgNotifications = undefined;- client.release(error);- if (emitter.listenerCount("error") > 0) emitter.emit("error", error);- });- client.on("end", () => {- pgNotifications = undefined;- });- await client.query(`LISTEN ${RESUME_UPDATED_CHANNEL}`);- return emitter;- })().catch((error: unknown) => {- pgNotifications = undefined;- throw error;+const isAbort = (error: unknown, signal?: AbortSignal) =>+ Boolean(signal?.aborted && (error === signal.reason || (error instanceof Error && error.name === "AbortError")));+const asReleaseError = (error: unknown) => (error instanceof Error ? error : true);++/** Races a promise against an abort signal, removing the abort listener as soon as the promise settles. */+function raceSignal<T>(promise: Promise<T>, signal?: AbortSignal, onAbort?: (reason: unknown) => void): Promise<T> {+ if (!signal) return promise;+ if (signal.aborted) {+ onAbort?.(signal.reason);+ promise.catch(() => {});+ return Promise.reject(signal.reason);+ }+ return new Promise<T>((resolve, reject) => {+ const abortHandler = () => {+ onAbort?.(signal.reason);+ reject(signal.reason);+ };+ signal.addEventListener("abort", abortHandler, { once: true });+ promise.then(+ (value) => {+ signal.removeEventListener("abort", abortHandler);+ resolve(value);+ },+ (error) => {+ signal.removeEventListener("abort", abortHandler);+ reject(error);+ },+ );});- return pgNotifications;}-export async function* subscribeResumeUpdated({ resumeId, userId, signal }: SubscribeResumeUpdatedInput) {- if (signal?.aborted) return;- const shared = getCoordination();- if (shared) {- for await (const payload of shared.subscribe(redisKey(RESUME_UPDATED_CHANNEL, resumeId), signal)) {- const event = readEvent(payload, resumeId, userId);- if (event) yield event;- }- return;+type Upstream = { close(error?: unknown): Promise<void> | void };+/**+ * Opens the one upstream connection a feed reads from. Calling `fail` ends the feed for every subscriber. `signal`+ * aborts when the feed ends, so a connect that may hang can stop early; one that resolves late is closed by the feed.+ */+type ConnectUpstream = (+ emit: (payload: string | undefined) => void,+ fail: (error: unknown) => void,+ signal: AbortSignal,+) => Promise<Upstream>;+type Feed = {+ events: EventEmitter;+ ready: Promise<unknown>;+ cancel: AbortController;+ open?: Upstream;+ subscribers: number;+ ended: boolean;+};++type FeedOwner = ReturnType<typeof getPool> | NonNullable<ReturnType<typeof getRedis>>;++// One feed per pool or Redis client, so all open subscriptions in a process share one connection. A connection per+// subscription let open builder tabs check out the whole database pool and starve every other query.+const feeds = new WeakMap<FeedOwner, Feed>();++async function endFeed(owner: FeedOwner, feed: Feed, error?: unknown) {+ if (feed.ended) return;+ feed.ended = true;+ if (feeds.get(owner) === feed) feeds.delete(owner);+ feed.cancel.abort(error);+ // Subscribers end with the error, so clients reconnect and the next subscription opens a fresh connection.+ if (error !== undefined && feed.events.listenerCount("error") > 0) feed.events.emit("error", error);+ await feed.open?.close(error);+}++function joinFeed(owner: FeedOwner, connect: ConnectUpstream): Feed {+ const existing = feeds.get(owner);+ if (existing) {+ existing.subscribers += 1;+ return existing;}- const subscriber = getRedis()?.duplicate({ commandTimeout: 5_000 });- const listener = subscriber ? undefined : await sharedPgNotifications();- const channel = subscriber ? redisKey(RESUME_UPDATED_CHANNEL) : RESUME_UPDATED_CHANNEL;- // `on` queues notifications from now on, so none that arrive while subscribing are lost. It rethrows the- // connection's "error" event and ends with an AbortError when the signal aborts.- const notifications = subscriber- ? on(subscriber, "message", { signal })- : on(listener as EventEmitter, "notification", { signal });+ const feed: Feed = {+ events: new EventEmitter().setMaxListeners(0),+ ready: Promise.resolve(),+ cancel: new AbortController(),+ subscribers: 1,+ ended: false,+ };+ const fail = (error: unknown) => void endFeed(owner, feed, error).catch(() => {});+ feed.ready = connect((payload) => feed.events.emit("payload", payload), fail, feed.cancel.signal).then((upstream) => {+ // The feed ended while this connection was still opening.+ if (feed.ended) return upstream.close();+ feed.open = upstream;+ });+ feed.ready.catch(fail);+ feeds.set(owner, feed);+ return feed;+}+async function* readFeed(owner: FeedOwner, connect: ConnectUpstream, signal?: AbortSignal) {+ if (signal?.aborted) return;+ const feed = joinFeed(owner, connect);+ // `on` queues payloads from now on, so none that arrive while connecting are lost. It rethrows the feed's+ // "error" event and ends with an AbortError when the signal aborts.+ const payloads = on(feed.events, "payload", signal ? { signal } : {});try {- if (subscriber) {- // A subscription that never connects still ends when the caller goes away.- const aborted = signal ? once(signal, "abort") : new Promise<never>(() => {});- await Promise.race([subscriber.subscribe(channel), aborted]);- if (signal?.aborted) return;+ // A feed that never connects still ends when the caller goes away.+ await raceSignal(feed.ready, signal);+ if (signal?.aborted) return;+ for await (const [payload] of payloads) yield payload as string | undefined;+ } catch (error) {+ if (!isAbort(error, signal)) throw error;+ } finally {+ await payloads.return?.();+ feed.subscribers -= 1;+ if (feed.subscribers === 0) await endFeed(owner, feed);+ }+}++const listenOnPostgres =+ (pool: ReturnType<typeof getPool>): ConnectUpstream =>+ async (emit, fail, signal) => {+ const clientPromise = pool.connect();+ const client = await raceSignal(clientPromise, signal, () => {+ clientPromise.then((c) => c.release(true)).catch(() => {});+ });+ const onNotification = (notification: PgNotification) => {+ if (notification.channel === RESUME_UPDATED_CHANNEL) emit(notification.payload);+ };+ const detach = () => {+ client.off("notification", onNotification);+ client.off("error", fail);+ };+ client.on("notification", onNotification);+ client.on("error", fail);+ try {+ await raceSignal(client.query(`LISTEN ${RESUME_UPDATED_CHANNEL}`), signal);+ } catch (error) {+ detach();+ client.release(asReleaseError(error));+ throw error;}+ return {+ async close(error) {+ // A broken connection is discarded rather than returned to the pool.+ let releaseError = error === undefined ? undefined : asReleaseError(error);+ if (releaseError === undefined) {+ try {+ await client.query(`UNLISTEN ${RESUME_UPDATED_CHANNEL}`);+ } catch (unlistenError) {+ releaseError = asReleaseError(unlistenError);+ }+ }+ detach();+ client.release(releaseError);+ },+ };+ };- for await (const args of notifications) {- const [notificationChannel, payload] = subscriber- ? (args as [string, string])- : [(args[0] as PgNotification).channel, (args[0] as PgNotification).payload];- if (notificationChannel !== channel) continue;- const event = readEvent(payload, resumeId, userId);- if (event) yield event;+const subscribeOnRedis =+ (redis: NonNullable<ReturnType<typeof getRedis>>): ConnectUpstream =>+ async (emit, fail, signal) => {+ // A subscribed Redis connection can't run other commands, so the feed owns a duplicate.+ const subscriber = redis.duplicate({ commandTimeout: 5_000 });+ const channel = redisKey(RESUME_UPDATED_CHANNEL);+ const onMessage = (messageChannel: string, payload: string) => {+ if (messageChannel === channel) emit(payload);+ };+ const close = () => {+ subscriber.off("message", onMessage);+ subscriber.off("error", fail);+ // Closing the duplicate unsubscribes.+ subscriber.disconnect();+ };+ subscriber.on("message", onMessage);+ subscriber.on("error", fail);+ try {+ // A subscribe that never connects still ends when the feed does.+ await raceSignal(subscriber.subscribe(channel), signal);+ } catch (error) {+ close();+ throw error;}- } catch (error) {- if (!isAbort(error) || !signal?.aborted) throw error;- } finally {- // The duplicate connection exists only for this subscription; closing it unsubscribes. The shared PostgreSQL- // listener stays for the next subscriber.- subscriber?.disconnect();+ return { close };+ };++function readUpstream(signal?: AbortSignal) {+ const redis = getRedis();+ if (redis) return readFeed(redis, subscribeOnRedis(redis), signal);+ const pool = getPool();+ return readFeed(pool, listenOnPostgres(pool), signal);+}++export async function* subscribeResumeUpdated({ resumeId, userId, signal }: SubscribeResumeUpdatedInput) {+ if (signal?.aborted) return;+ const shared = getCoordination();+ const payloads = shared ? shared.subscribe(redisKey(RESUME_UPDATED_CHANNEL, resumeId), signal) : readUpstream(signal);+ for await (const payload of payloads) {+ const event = readEvent(payload, resumeId, userId);+ if (event) yield event;}}diff --git a/packages/api/src/middleware/rate-limit/index.test.ts b/packages/api/src/middleware/rate-limit/index.test.tsindex 2dca7b923..d07a18dbe 100644--- a/packages/api/src/middleware/rate-limit/index.test.ts+++ b/packages/api/src/middleware/rate-limit/index.test.ts@@ -58,4 +58,31 @@ describe("public resume rate limits", () => {"resume-password:owner:resume:ip:203.0.113.9",]);});++ it.each([+ {+ name: "per user and resume",+ middleware: "resumeUpdatesRateLimit",+ expectedKey: "resume-updates:user-123:resume-456",+ },+ {+ name: "per user across resumes",+ middleware: "resumeUpdatesUserRateLimit",+ expectedKey: "resume-updates-user:user-123",+ },+ ] as const)("rate limits resume updates subscription $name", async ({ middleware, expectedKey }) => {+ vi.stubEnv("NODE_ENV", "production");+ settings.FLAG_DISABLE_API_RATE_LIMIT = false;+ limit.mockResolvedValue({ success: false, remaining: 0, reset: Date.now() + 60_000 });+ const middlewares = await import("./index");+ const next = vi.fn(async () => "allowed");+ const request = middlewares[middleware](+ { context: { user: { id: "user-123" } }, next } as never,+ { id: "resume-456" },+ vi.fn(),+ );+ await expect(request).rejects.toMatchObject({ code: "TOO_MANY_REQUESTS" });+ expect(limit).toHaveBeenCalledWith(expectedKey);+ expect(next).not.toHaveBeenCalled();+ });});diff --git a/packages/api/src/middleware/rate-limit/index.ts b/packages/api/src/middleware/rate-limit/index.tsindex 9e513675c..e3b57f7f4 100644--- a/packages/api/src/middleware/rate-limit/index.ts+++ b/packages/api/src/middleware/rate-limit/index.ts@@ -51,6 +51,8 @@ const aiVoiceLimiter = createRateLimiter("aiVoiceLimiter", rateLimitConfig.orpc.const storageUploadLimiter = createRateLimiter("storageUploadLimiter", rateLimitConfig.orpc.storageUpload);const storageDeleteLimiter = createRateLimiter("storageDeleteLimiter", rateLimitConfig.orpc.storageDelete);const resumeMutationLimiter = createRateLimiter("resumeMutationLimiter", rateLimitConfig.orpc.resumeMutations);+const resumeUpdatesLimiter = createRateLimiter("resumeUpdatesLimiter", rateLimitConfig.orpc.resumeUpdates);+const resumeUpdatesUserLimiter = createRateLimiter("resumeUpdatesUserLimiter", rateLimitConfig.orpc.resumeUpdatesUser);const accountLimiter = createRateLimiter("accountLimiter", {maxRequests: rateLimitConfig.betterAuth.global.max,window: rateLimitConfig.betterAuth.global.window * 1000,@@ -144,3 +146,13 @@ export const pdfAnalysisRateLimit = createRatelimitMiddleware<ContextWithHeaderslimiter: productionLimiter(pdfAnalysisLimiter),key: ({ context }) => `pdf-analysis:${getClientKey(context.trustedClient)}`,});++export const resumeUpdatesRateLimit = createRatelimitMiddleware<ContextWithHeaders, { id: string }>({+ limiter: productionLimiter(resumeUpdatesLimiter),+ key: ({ context }, input) => `resume-updates:${getUserKey(context)}:${input.id}`,+});++export const resumeUpdatesUserRateLimit = createRatelimitMiddleware<ContextWithHeaders, unknown>({+ limiter: productionLimiter(resumeUpdatesUserLimiter),+ key: ({ context }) => `resume-updates-user:${getUserKey(context)}`,+});diff --git a/packages/utils/src/rate-limit.ts b/packages/utils/src/rate-limit.tsindex b81e03e21..17a868801 100644--- a/packages/utils/src/rate-limit.ts+++ b/packages/utils/src/rate-limit.ts@@ -46,5 +46,7 @@ export const rateLimitConfig = {storageUpload: { maxRequests: 20, window: 60 * 1000 },storageDelete: { maxRequests: 30, window: 60 * 1000 },resumeMutations: { maxRequests: 300, window: 60 * 1000 },+ resumeUpdates: { maxRequests: 20, window: 60 * 1000 },+ resumeUpdatesUser: { maxRequests: 60, window: 60 * 1000 },},} as const;