Skip to content
Merged
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
5 changes: 5 additions & 0 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,11 @@ updates:
# is not yet supported by our toolchain (typescript-eslint 8 crashes on it).
- dependency-name: "typescript"
update-types: ["version-update:semver-major"]
# pg 9 drops the internal query queue. @prisma/adapter-pg 7.10 still sends
# overlapping queries on one transaction connection (prisma/orm#31112,
# #30925), which pg 8 only warns about. Lift this once Prisma ships the fix.
- dependency-name: "pg"
update-types: ["version-update:semver-major"]

# --- GitHub Actions ------------------------------------------------------
- package-ecosystem: "github-actions"
Expand Down
9 changes: 7 additions & 2 deletions apps/realtime/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import { createHmac, timingSafeEqual } from "node:crypto";
import pg from "pg";
import { WebSocket, WebSocketServer } from "ws";

import { createSerialQueue } from "./serial-queue.js";

/**
* Realtime service (concept §10/§14) — live status updates for applicants.
*
Expand Down Expand Up @@ -158,14 +160,17 @@ async function listenForChanges(fanout: (topic: string) => void): Promise<void>

const connect = async (): Promise<void> => {
const client = new pg.Client({ connectionString });
// One lookup at a time on this client (see serial-queue.ts).
const serial = createSerialQueue();
client.on("notification", (msg) => {
if (msg.channel !== CHANNEL || !msg.payload) return;
const submissionId = msg.payload;
// The applicant's status page (UUID capability).
fanout(`submission:${submissionId}`);
// The guild dashboard/board: resolve the submission's guild and fan out.
void client
.query("SELECT guild_id FROM submissions WHERE id = $1", [submissionId])
void serial(() =>
client.query("SELECT guild_id FROM submissions WHERE id = $1", [submissionId]),
)
.then((res) => {
const guildId = res.rows[0]?.guild_id as string | undefined;
if (guildId) fanout(`guild:${guildId}`);
Expand Down
51 changes: 51 additions & 0 deletions apps/realtime/src/serial-queue.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { describe, expect, it } from "vitest";

import { createSerialQueue } from "./serial-queue.js";

/** A task that records when it starts and ends, and finishes on demand. */
function deferredTask(log: string[], name: string) {
let finish!: () => void;
const task = () =>
new Promise<string>((resolve) => {
log.push(`start ${name}`);
finish = () => {
log.push(`end ${name}`);
resolve(name);
};
});
return { task, finish: () => finish() };
}

describe("createSerialQueue", () => {
it("never starts a task while the previous one is still running", async () => {
const log: string[] = [];
const run = createSerialQueue();
const a = deferredTask(log, "a");
const b = deferredTask(log, "b");

const first = run(a.task);
const second = run(b.task);
await Promise.resolve();
await Promise.resolve();
expect(log).toEqual(["start a"]);

a.finish();
await first;
await new Promise((r) => setTimeout(r, 0));
expect(log).toEqual(["start a", "end a", "start b"]);

b.finish();
await expect(second).resolves.toBe("b");
});

it("keeps going after a task fails and still reports the failure", async () => {
const run = createSerialQueue();
const failing = run(async () => {
throw new Error("boom");
});
const next = run(async () => "ok");

await expect(failing).rejects.toThrow("boom");
await expect(next).resolves.toBe("ok");
});
});
19 changes: 19 additions & 0 deletions apps/realtime/src/serial-queue.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/**
* Runs async tasks strictly one after another.
*
* A single `pg.Client` must not get a new `query()` while one is still running:
* pg 8 queues it internally and logs a DeprecationWarning, pg 9 removes that
* queue. The LISTEN client in this service looks up the guild for every
* notification, and notifications can arrive faster than a lookup finishes, so
* those lookups go through this queue.
*/
export function createSerialQueue(): <T>(task: () => Promise<T>) => Promise<T> {
let tail: Promise<unknown> = Promise.resolve();

return <T>(task: () => Promise<T>): Promise<T> => {
const result = tail.then(task);
// The chain only waits for completion; a failure stays with its caller.
tail = result.catch(() => undefined);
return result;
};
}
6 changes: 6 additions & 0 deletions apps/web/src/lib/rate-limit.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import "server-only";

import { getRedis } from "./redis";
import { whenReady } from "./redis-ready";

export { clientIp } from "./client-ip";

Expand All @@ -11,6 +12,10 @@ export interface RateLimitResult {
retryAfter: number;
}

// Upper bound for waiting on the first connection after a process start.
// Redis runs on loopback, so a healthy connect takes a few milliseconds.
const CONNECT_WAIT_MS = 1000;

// Atomic fixed-window counter: INCR, set the TTL only on the first hit of a
// window, and return the count plus the remaining TTL.
const FIXED_WINDOW = `
Expand All @@ -33,6 +38,7 @@ export async function rateLimit(
if (!redis) return { allowed: true, remaining: limit, retryAfter: 0 };

try {
await whenReady(redis, CONNECT_WAIT_MS);
const [count, ttl] = (await redis.eval(
FIXED_WINDOW,
1,
Expand Down
90 changes: 90 additions & 0 deletions apps/web/src/lib/redis-ready.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import { EventEmitter } from "node:events";

import { afterEach, describe, expect, it, vi } from "vitest";

import { getRedis } from "./redis";
import { rateLimit } from "./rate-limit";
import { whenReady } from "./redis-ready";

vi.mock("./redis", () => ({ getRedis: vi.fn() }));

const mockedGetRedis = vi.mocked(getRedis);

/**
* Minimal stand-in for an ioredis client with `enableOfflineQueue: false`:
* commands sent before the connection is ready are rejected, exactly like the
* "Stream isn't writeable" error seen on the server.
*/
class FakeRedis extends EventEmitter {
status: string;
eval = vi.fn(async () => {
if (this.status !== "ready") {
throw new Error("Stream isn't writeable and enableOfflineQueue options is false");
}
return [1, 60];
});

constructor(status: string) {
super();
this.status = status;
}

becomeReady(): void {
this.status = "ready";
this.emit("ready");
}
}

afterEach(() => {
vi.useRealTimers();
vi.restoreAllMocks();
mockedGetRedis.mockReset();
});

describe("rateLimit on a client that is still connecting", () => {
it("waits for the connection and counts the very first request", async () => {
const client = new FakeRedis("connecting");
mockedGetRedis.mockReturnValue(client as never);
setTimeout(() => client.becomeReady(), 5);

const r = await rateLimit("k", 5, 60);

expect(client.eval).toHaveBeenCalledTimes(1);
expect(r.allowed).toBe(true);
expect(r.remaining).toBe(4);
expect(r.retryAfter).toBe(60);
});

it("does not wait while reconnecting during an outage and fails open at once", async () => {
vi.spyOn(console, "error").mockImplementation(() => {});
const client = new FakeRedis("reconnecting");
mockedGetRedis.mockReturnValue(client as never);

const r = await rateLimit("k", 5, 60);

expect(client.listenerCount("ready")).toBe(0);
expect(r.allowed).toBe(true);
expect(r.remaining).toBe(5);
});
});

describe("whenReady", () => {
it("resolves immediately when the client is ready", async () => {
const client = new FakeRedis("ready");
await whenReady(client, 1000);
expect(client.listenerCount("ready")).toBe(0);
});

it("gives up after the timeout and removes its listener", async () => {
vi.useFakeTimers();
const client = new FakeRedis("connecting");
const pending = whenReady(client, 1000);
expect(client.listenerCount("ready")).toBe(1);

await vi.advanceTimersByTimeAsync(1000);
await pending;

expect(client.listenerCount("ready")).toBe(0);
expect(client.status).toBe("connecting");
});
});
37 changes: 37 additions & 0 deletions apps/web/src/lib/redis-ready.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/**
* The part of an ioredis client that `whenReady` needs. Kept structural so the
* helper stays free of `server-only` and can be unit-tested with a fake.
*/
export interface ReadyAwareClient {
status: string;
once(event: "ready", listener: () => void): unknown;
off(event: "ready", listener: () => void): unknown;
}

// States of the *initial* connection attempt. "reconnecting" is deliberately
// missing: during an outage the caller should fail fast instead of waiting.
const CONNECTING = new Set(["wait", "connecting", "connect"]);

/**
* Resolves once the client is ready, or after `timeoutMs` at the latest.
*
* With `enableOfflineQueue: false`, ioredis rejects every command until the
* connection is ready ("Stream isn't writeable"). The client is created lazily
* on the first rate-limited request, so without this wait that first request
* after every process start skipped the limiter. Never rejects: if the
* connection does not come up in time, the command itself fails and the caller
* falls open as before.
*/
export function whenReady(client: ReadyAwareClient, timeoutMs: number): Promise<void> {
if (!CONNECTING.has(client.status)) return Promise.resolve();

return new Promise((resolve) => {
const done = (): void => {
clearTimeout(timer);
client.off("ready", done);
resolve();
};
const timer = setTimeout(done, timeoutMs);
client.once("ready", done);
});
}
Loading