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 .railway/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,3 +75,8 @@ API retains the private database migration/start command and staging's 2 CPU /
`bun run enqueue tournaments 2025` or `bun run backfill 1992 2025`.

See [Railway's IaC migration guide](https://docs.railway.com/infrastructure-as-code#migrating-from-config-as-code).

For finite offseason batches, see [Worker batch rollout](../docs/worker-batch-rollout.md).
`RAILWAY_WORKER_CRON='0 18 * * *'` is an opt-in local plan/apply input; omitting
it keeps/restores continuous mode. Merging this configuration does not enable
Cron or PostgreSQL Serverless.
33 changes: 31 additions & 2 deletions .railway/config.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,13 @@ for (const environment of ["production", "staging"]) {
: "offseason/mock-game-charged-up",
);
assert(Object.keys(resource.variables).length > 0);
for (const value of Object.values(resource.variables)) {
assert.deepEqual(value, { type: "preserve" });
for (const [name, value] of Object.entries(resource.variables)) {
assert.deepEqual(
value,
resource.name === "worker" && name === "WORKER_MODE"
? { type: "literal", value: "continuous" }
: { type: "preserve" },
);
}
}
const api = service("api");
Expand Down Expand Up @@ -89,3 +94,27 @@ test("refuses preview plans without an explicit source branch", () => {
else process.env.RAILWAY_CONFIG_BRANCH = previous;
}
});

test("offseason cron uses a finite batch without a health listener or restarts", () => {
const previous = process.env.RAILWAY_WORKER_CRON;
process.env.RAILWAY_WORKER_CRON = "0 18 * * *";
try {
const graph = config(createRailwayContext({ environment: "production" }));
const worker = graph.resources.find((r) => r.name === "worker");
assert.deepEqual(worker.variables.WORKER_MODE, {
type: "literal",
value: "batch",
});
assert.equal(worker.deploy.cronSchedule, "0 18 * * *");
assert.equal(worker.deploy.restartPolicyType, "NEVER");
assert.equal(worker.deploy.healthcheckPath, undefined);
} finally {
if (previous === undefined) delete process.env.RAILWAY_WORKER_CRON;
else process.env.RAILWAY_WORKER_CRON = previous;
}
const worker = config(
createRailwayContext({ environment: "production" }),
).resources.find((r) => r.name === "worker");
assert.equal(worker.deploy.cronSchedule, undefined);
assert.equal(worker.deploy.healthcheckPath, "/health");
});
16 changes: 13 additions & 3 deletions .railway/railway.ts
Original file line number Diff line number Diff line change
Expand Up @@ -141,9 +141,14 @@ export default defineRailway((ctx) => {
},
});

// Opt in only after preview validation; merging keeps the current service running.
const workerCron = process.env.RAILWAY_WORKER_CRON?.trim();
const worker = service("worker", {
source: source("/"),
env: keep("DATABASE_URL", "TBA_KEY", "WORKER_CONCURRENCY"),
env: {
...keep("DATABASE_URL", "TBA_KEY", "WORKER_CONCURRENCY"),
WORKER_MODE: workerCron ? "batch" : "continuous",
},
build: {
builder: "DOCKERFILE",
dockerfilePath: "apps/worker/Dockerfile",
Expand All @@ -152,8 +157,13 @@ export default defineRailway((ctx) => {
deploy: {
runtime: "V2",
startCommand: "bun index.ts",
healthcheckPath: "/health",
healthcheckTimeout: 120,
...(workerCron
? { cronSchedule: workerCron, restartPolicyType: "NEVER" as const }
: {
cronSchedule: null,
healthcheckPath: "/health",
healthcheckTimeout: 120,
}),
drainingSeconds: 60,
multiRegionConfig: {
"us-west2": {
Expand Down
64 changes: 2 additions & 62 deletions apps/server/src/lib/scheduleJobs.ts
Original file line number Diff line number Diff line change
@@ -1,64 +1,4 @@
import fetchTeams from "./fetchTeams.js";
import fetchMatches from "./fetchMatches.js";
import prisma from "../prismaClient.js";
import expireReportsInProgress from "./expireReportsInProgress.js";
import deleteOldRequests from "./deleteOldRequests.js";
import { runBackgroundTask } from "./errors.js";

/** Imports and maintenance belong to the durable Worker queue. */
export default async function scheduleJobs(): Promise<void> {
const skipTba =
process.env.NODE_ENV === "development" && !process.env.TBA_KEY?.trim();

if (skipTba) {
console.log("Skipping TBA background jobs: set TBA_KEY to enable imports.");
} else {
// Prevent unnecessary fetching in dev mode which is frequently restarted
if (
process.env.NODE_ENV === "development" &&
(await prisma.team.count()) > 0
) {
console.log("Skipping initial TBA data fetch");
} else {
// Import teams
console.log("Fetching teams from TBA...");
await fetchTeams();
console.log("Done fetching teams from TBA.");
}

// repeat every 24 hours
setInterval(
() =>
runBackgroundTask(async () => {
console.log("Fetching teams from TBA...");
await fetchTeams();
console.log("Done fetching teams from TBA.");
}, "TBA daily refresh failed"),
1000 * 60 * 60 * 24,
);

//repeat hourly
setInterval(
() =>
runBackgroundTask(async () => {
await fetchMatches();
console.log("Done fetching matches from TBA.");
}, "TBA match refresh failed"),
1000 * 60 * 60,
);
}

// repeat every 12 hours
setInterval(
async () => {
await runBackgroundTask(async () => {
await deleteOldRequests();
console.log("Done deleting old requests.");
}, "Old request cleanup failed");
await runBackgroundTask(
expireReportsInProgress,
"Report draft cleanup failed",
);
},
1000 * 60 * 60 * 12,
);
// Retain the startup hook for consumers; never start API-owned DB timers.
}
155 changes: 9 additions & 146 deletions apps/server/test/scheduleJobs.unit.test.ts
Original file line number Diff line number Diff line change
@@ -1,149 +1,12 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";

vi.mock("../src/lib/fetchTeams.js", () => ({ default: vi.fn() }));
vi.mock("../src/lib/fetchMatches.js", () => ({ default: vi.fn() }));
vi.mock("../src/lib/expireReportsInProgress.js", () => ({
default: vi.fn().mockResolvedValue(undefined),
}));
vi.mock("../src/lib/deleteOldRequests.js", () => ({ default: vi.fn() }));
vi.mock("../src/prismaClient.js", () => ({
default: {
team: { count: vi.fn().mockResolvedValue(0) },
},
}));

import prisma from "../src/prismaClient.js";
import { expect, test, vi } from "vitest";
import scheduleJobs from "../src/lib/scheduleJobs.js";
import fetchTeams from "../src/lib/fetchTeams.js";
import fetchMatches from "../src/lib/fetchMatches.js";
import expireReportsInProgress from "../src/lib/expireReportsInProgress.js";
import deleteOldRequests from "../src/lib/deleteOldRequests.js";

describe("background jobs at startup", () => {
beforeEach(() => {
vi.useFakeTimers();
vi.clearAllMocks();
vi.mocked(prisma.team.count).mockResolvedValue(0);
vi.stubEnv("NODE_ENV", "development");
vi.stubEnv("TBA_KEY", "");
vi.spyOn(console, "log").mockImplementation(() => undefined);
});

afterEach(() => {
vi.clearAllTimers();
vi.useRealTimers();
vi.unstubAllEnvs();
vi.restoreAllMocks();
});

it("starts without a TBA key and keeps local cleanup running", async () => {
await scheduleJobs();
await vi.advanceTimersByTimeAsync(24 * 60 * 60 * 1000);
expect(fetchTeams).not.toHaveBeenCalled();
expect(fetchMatches).not.toHaveBeenCalled();
expect(deleteOldRequests).toHaveBeenCalledTimes(2);
expect(expireReportsInProgress).toHaveBeenCalledTimes(2);
});

it("logs draft cleanup failures without stopping the scheduled job", async () => {
const error = new Error("database unavailable");
vi.spyOn(console, "error").mockImplementation(() => undefined);
vi.mocked(expireReportsInProgress).mockRejectedValueOnce(error);
await scheduleJobs();
await vi.advanceTimersByTimeAsync(12 * 60 * 60 * 1000);
expect(console.error).toHaveBeenCalledWith(
"Report draft cleanup failed",
expect.objectContaining({ name: "Error" }),
);
expect(JSON.stringify(vi.mocked(console.error).mock.calls)).not.toContain(
error.message,
);
expect(deleteOldRequests).toHaveBeenCalledTimes(1);
await vi.advanceTimersByTimeAsync(12 * 60 * 60 * 1000);
expect(expireReportsInProgress).toHaveBeenCalledTimes(2);
});

it("imports and refreshes TBA data when development has a key", async () => {
vi.stubEnv("TBA_KEY", "synthetic-test-key");
await scheduleJobs();
expect(fetchTeams).toHaveBeenCalledTimes(1);
await vi.advanceTimersByTimeAsync(24 * 60 * 60 * 1000);
expect(fetchTeams).toHaveBeenCalledTimes(2);
expect(fetchMatches).toHaveBeenCalledTimes(24);
});

it("reports failed request cleanup without skipping draft cleanup or the next run", async () => {
vi.spyOn(console, "error").mockImplementation(() => undefined);
vi.mocked(deleteOldRequests).mockRejectedValueOnce(
new Error("private database details"),
);
await scheduleJobs();
await vi.advanceTimersByTimeAsync(12 * 60 * 60 * 1000);
expect(expireReportsInProgress).toHaveBeenCalledOnce();
expect(console.error).toHaveBeenCalledWith(
"Old request cleanup failed",
expect.objectContaining({ name: "Error" }),
);
expect(JSON.stringify(vi.mocked(console.error).mock.calls)).not.toContain(
"private database details",
);
await vi.advanceTimersByTimeAsync(12 * 60 * 60 * 1000);
expect(deleteOldRequests).toHaveBeenCalledTimes(2);
expect(expireReportsInProgress).toHaveBeenCalledTimes(2);
});

it.each(["teams", "matches"] as const)(
"reports a failed %s refresh and runs again on schedule",
async (job) => {
vi.stubEnv("TBA_KEY", "synthetic-test-key");
vi.spyOn(console, "error").mockImplementation(() => undefined);
await scheduleJobs();
const task = {
teams: fetchTeams,
matches: fetchMatches,
}[job];
vi.mocked(task).mockRejectedValueOnce(
new Error("private provider details"),
);
const period = (job === "matches" ? 1 : 24) * 60 * 60 * 1000;
const initialCalls = vi.mocked(task).mock.calls.length;
await vi.advanceTimersByTimeAsync(period);
expect(console.error).toHaveBeenCalledWith(
job === "matches"
? "TBA match refresh failed"
: "TBA daily refresh failed",
expect.objectContaining({ name: "Error" }),
);
expect(JSON.stringify(vi.mocked(console.error).mock.calls)).not.toContain(
"private provider details",
);
await vi.advanceTimersByTimeAsync(period);
expect(vi.mocked(task).mock.calls.length).toBe(initialCalls + 2);
},
);

it("preserves production imports when a key is absent", async () => {
vi.stubEnv("NODE_ENV", "production");
vi.mocked(fetchTeams).mockRejectedValueOnce(new Error("TBA unauthorized"));
await expect(scheduleJobs()).rejects.toThrow("TBA unauthorized");
});
test("API scheduler starts without provider credentials or periodic work", async () => {
const interval = vi.spyOn(globalThis, "setInterval");
try {
await expect(scheduleJobs()).resolves.toBeUndefined();
expect(interval).not.toHaveBeenCalled();
} finally {
interval.mockRestore();
}
});

it.each([true, false])(
"skips the team import when the dev team table has data (%s)",
async (hasTeams) => {
vi.useFakeTimers();
vi.stubEnv("NODE_ENV", "development");
vi.stubEnv("TBA_KEY", "synthetic-test-key");
vi.mocked(prisma.team.count).mockResolvedValue(hasTeams ? 1 : 0);
vi.clearAllMocks();
try {
await scheduleJobs();
expect(fetchTeams).toHaveBeenCalledTimes(hasTeams ? 0 : 1);
} finally {
vi.clearAllTimers();
vi.useRealTimers();
vi.unstubAllEnvs();
}
},
);
40 changes: 36 additions & 4 deletions apps/worker/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -171,10 +171,10 @@ Match refresh intervals use event-local dates and hours:
| ------------------------------ | ------------- | -------------- |
| Event dates, 07:00–21:00 local | 1 minute | 1 hour |
| Event dates, overnight | 15 minutes | 1 hour |
| Starts within 7 days | 30 minutes | 6 hours |
| Starts within 7 days | 6 hours | 6 hours |
| Starts later, or dates unknown | 1 day | 1 day |
| Ended within 7 days | 6 hours | 1 day |
| Older event | 7 days | 7 days |
| Older event | Explicit only | Explicit only |

Missing or invalid timezones fall back to UTC. Activity is inferred from dates,
not from a live event status feed. Due match jobs near the event's date window
Expand Down Expand Up @@ -238,8 +238,7 @@ import { refreshTournamentGaps } from "./src/jobs/gaps";
await refreshTournamentGaps("2026casj");
```

Or queue `bun run enqueue gaps 2026casj` for the worker. Explicit gap jobs repeat
daily; normal match jobs already recalculate gaps on every refresh. Apply the
Or queue `bun run enqueue gaps 2026casj` for the worker. Explicit gap jobs run once; normal match jobs already recalculate gaps on every refresh. Apply the
shared database migration and rebuild the database package before running the
updated worker.

Expand Down Expand Up @@ -298,3 +297,36 @@ data. A fresh empty response clears withdrawn data, while HTTP 304 preserves it.
### Historical seasons

Run `bun run backfill 1992 2025` with the target database and TBA credentials configured to queue archived season imports. With no arguments, it queues every season from 1992 through the current year. Existing jobs keep their leases and retry schedules. Tournament and district imports queue event and district details through the existing scheduler, so the backfill continues on the worker.


## Finite batches (LVT-382)

`bun run batch` (`WORKER_MODE=batch bun index.ts`) reconciles once, snapshots
eligible due job IDs, runs each at most once with `WORKER_CONCURRENCY` consumers,
then disconnects Prisma and exits. It opens no health listener and has no polling
between executions. The process owns its client; do not share a batch client with
another service. The default `WORKER_MODE=continuous` retains the existing active
event loop and `/health` readiness checks.

Snapshot jobs are claimed atomically with fresh leases at execution time. Other
replicas, changed schedules, and active leases can make an ID ineligible; it is
left for the next window. Retry delays and TBA Retry-After remain durable. A
failed job does not stop other jobs. Claim/planner/database errors fail the batch
after other consumers drain. Shutdown stops new claims and waits for running
imports and lease heartbeats before disconnecting.

Jobs discovered by a catalog import wait until the next batch. For a new/empty
database, run another batch after catalogs complete to import child events and
districts before accepting traffic. Never promise active-event freshness with a
daily batch. Archived events (more than seven event-local days after completion),
old season catalogs and explicit gap jobs finalize after one successful run;
failures remain queued. Existing archived recurring jobs get one final execution.
Normal planning does not recreate archived events. Use `backfill` for historical
years or explicitly enqueue individual archived event jobs when needed.

Daily `maintenance global` work now removes expired verification requests,
unverified registrations older than a day, abandons expired report drafts and
scrubs their payloads at day thirty. API startup creates no import or cleanup
timers and needs no TBA key. Read-time report and verification expiry checks stay
in the API. Import ownership overlaps LVT-335; resource/pool tuning remains with
LVT-376. See [batch rollout](../../docs/worker-batch-rollout.md) before cutover.
Loading
Loading