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
4 changes: 2 additions & 2 deletions .railway/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,6 @@ API retains the private database migration/start command and staging's 2 CPU /
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
`RAILWAY_WORKER_CRON='0 18 * * *'` is an opt-in local plan/apply input; production defaults to six-hour event-aware windows after the rollout. An
explicit empty `RAILWAY_WORKER_CRON` restores continuous mode. Merging this configuration does not enable
Cron or PostgreSQL Serverless.
69 changes: 64 additions & 5 deletions .railway/config.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,9 @@ for (const environment of ["production", "staging"]) {
assert.notEqual(resource.deploy.sleepApplication, true);
assert.equal(
resource.deploy.restartPolicyType ?? "ON_FAILURE",
"ON_FAILURE",
resource.name === "worker" && environment === "production"
? "NEVER"
: "ON_FAILURE",
);
// Keep source connections and credential values during adoption.
assert.equal(resource.source.repo, "HighlanderRobotics/lovat");
Expand All @@ -38,7 +40,11 @@ for (const environment of ["production", "staging"]) {
assert.deepEqual(
value,
resource.name === "worker" && name === "WORKER_MODE"
? { type: "literal", value: "continuous" }
? {
type: "literal",
value:
environment === "production" ? "scheduled" : "continuous",
}
: { type: "preserve" },
);
}
Expand All @@ -56,7 +62,14 @@ for (const environment of ["production", "staging"]) {
: undefined,
);
const worker = service("worker");
assert.equal(worker.deploy.healthcheckPath, "/health");
assert.equal(
worker.deploy.healthcheckPath,
environment === "production" ? undefined : "/health",
);
assert.equal(
worker.deploy.cronSchedule,
environment === "production" ? "0 */6 * * *" : undefined,
);
assert.equal(worker.deploy.drainingSeconds, 60);
assert.equal(worker.deploy.startCommand, "bun index.ts");
assert.deepEqual(worker.deploy.multiRegionConfig, {
Expand Down Expand Up @@ -115,6 +128,52 @@ test("offseason cron uses a finite batch without a health listener or restarts",
const worker = config(
createRailwayContext({ environment: "production" }),
).resources.find((r) => r.name === "worker");
assert.equal(worker.deploy.cronSchedule, undefined);
assert.equal(worker.deploy.healthcheckPath, "/health");
assert.equal(worker.deploy.cronSchedule, "0 */6 * * *");
assert.equal(worker.deploy.healthcheckPath, undefined);
});

test("scheduled event mode requires six-hour starts and retains automatic competition windows", () => {
const previousCron = process.env.RAILWAY_WORKER_CRON;
const previousMode = process.env.RAILWAY_WORKER_MODE;
try {
process.env.RAILWAY_WORKER_MODE = "scheduled";
process.env.RAILWAY_WORKER_CRON = "0 18 * * *";
assert.throws(
() => config(createRailwayContext({ environment: "production" })),
/six-hour Cron/,
);
process.env.RAILWAY_WORKER_CRON = "0 */6 * * *";
const worker = config(
createRailwayContext({ environment: "production" }),
).resources.find((r) => r.name === "worker");
assert.deepEqual(worker.variables.WORKER_MODE, {
type: "literal",
value: "scheduled",
});
assert.equal(worker.deploy.cronSchedule, "0 */6 * * *");
} finally {
if (previousCron === undefined) delete process.env.RAILWAY_WORKER_CRON;
else process.env.RAILWAY_WORKER_CRON = previousCron;
if (previousMode === undefined) delete process.env.RAILWAY_WORKER_MODE;
else process.env.RAILWAY_WORKER_MODE = previousMode;
}
});

test("an explicit empty Cron safely restores continuous production mode", () => {
const previous = process.env.RAILWAY_WORKER_CRON;
process.env.RAILWAY_WORKER_CRON = "";
try {
const worker = config(
createRailwayContext({ environment: "production" }),
).resources.find((r) => r.name === "worker");
assert.equal(worker.deploy.cronSchedule, undefined);
assert.equal(worker.deploy.healthcheckPath, "/health");
assert.deepEqual(worker.variables.WORKER_MODE, {
type: "literal",
value: "continuous",
});
} finally {
if (previous === undefined) delete process.env.RAILWAY_WORKER_CRON;
else process.env.RAILWAY_WORKER_CRON = previous;
}
});
17 changes: 14 additions & 3 deletions .railway/railway.ts
Original file line number Diff line number Diff line change
Expand Up @@ -141,13 +141,24 @@ export default defineRailway((ctx) => {
},
});

// Opt in only after preview validation; merging keeps the current service running.
const workerCron = process.env.RAILWAY_WORKER_CRON?.trim();
// Production uses event-aware windows. An explicit empty Cron restores continuous mode.
const configuredCron = process.env.RAILWAY_WORKER_CRON;
const workerCron =
configuredCron?.trim() ?? (production ? "0 */6 * * *" : undefined);
const cronMode =
process.env.RAILWAY_WORKER_MODE ??
(production && configuredCron === undefined ? "scheduled" : "batch");
if (workerCron && !["batch", "scheduled"].includes(cronMode)) {
throw new Error("RAILWAY_WORKER_MODE must be batch or scheduled");
}
if (workerCron && cronMode === "scheduled" && workerCron !== "0 */6 * * *") {
throw new Error("Scheduled event mode requires six-hour Cron: 0 */6 * * *");
}
const worker = service("worker", {
source: source("/"),
env: {
...keep("DATABASE_URL", "TBA_KEY", "WORKER_CONCURRENCY"),
WORKER_MODE: workerCron ? "batch" : "continuous",
WORKER_MODE: workerCron ? cronMode : "continuous",
},
build: {
builder: "DOCKERFILE",
Expand Down
9 changes: 9 additions & 0 deletions apps/worker/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -330,3 +330,12 @@ 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.


`WORKER_MODE=scheduled` combines six-hour external Cron with automatic event-day
continuous runs. Outside competition dates it exits after the batch. On an event's
local dates it keeps the minute-level loop until all current events finish, then
exits so later Cron executions return to batches. Use only with six-hour Cron;
daily starts cannot guarantee a start before the local morning. IaC selects this
mode with the local input `RAILWAY_WORKER_MODE=scheduled` alongside
`RAILWAY_WORKER_CRON='0 */6 * * *'`. No Railway credential is needed by Worker.
7 changes: 5 additions & 2 deletions apps/worker/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { db } from "./src/db";
import { tba } from "./src/tba";
import { runBatch, runWorker } from "./src/worker";
import { runScheduledWindow } from "./src/scheduled-window";
import { createHealthApp, healthPort } from "./src/server";

// Validate the provider configuration before starting any background work.
Expand All @@ -11,8 +12,8 @@ const stop = () => shutdown.abort();
let lastReconciledAt = 0;

const mode = process.env.WORKER_MODE ?? "continuous";
if (!["batch", "continuous"].includes(mode))
throw new Error("WORKER_MODE must be batch or continuous");
if (!["batch", "continuous", "scheduled"].includes(mode))
throw new Error("WORKER_MODE must be batch, scheduled or continuous");

const port = healthPort();
const concurrency = Number(process.env.WORKER_CONCURRENCY ?? 2);
Expand All @@ -34,6 +35,8 @@ try {
// Batch has no listener or readiness queries between windows.
if (mode === "batch") {
await runBatch(db, shutdown.signal, concurrency);
} else if (mode === "scheduled") {
await runScheduledWindow(db, shutdown.signal, concurrency);
} else {
// Migrations are owned by the release/API service.
await db.$queryRaw`SELECT 1 FROM "ImportJob", "FetchState", "TournamentGap" LIMIT 0`;
Expand Down
58 changes: 58 additions & 0 deletions apps/worker/src/scheduled-window.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import type { PrismaClient } from "@lovat/db";
import { day, tournamentCadence } from "./schedule";
import { runBatch, runWorker } from "./worker";

export async function hasCompetitionDates(db: PrismaClient, now = new Date()) {
// The date columns are UTC midnights, while phase boundaries are event-local.
const events = await db.tournament.findMany({
where: {
startDate: { lte: new Date(now.getTime() + day) },
endDate: { gte: new Date(now.getTime() - 2 * day) },
},
select: { startDate: true, endDate: true, timezone: true },
});
return events.some(
(event) => tournamentCadence(event, now).phase === "active",
);
}

/** Six-hour Cron starts before local 07:00; active dates keep the run alive. */
export async function runScheduledWindow(
db: PrismaClient,
signal: AbortSignal,
concurrency = 2,
dependencies = { hasCompetitionDates, runBatch, runWorker },
) {
try {
if (signal.aborted) return;
if (!(await dependencies.hasCompetitionDates(db))) {
const discovered = new AbortController();
await dependencies.runBatch(
db,
AbortSignal.any([signal, discovered.signal]),
concurrency,
undefined,
async () => {
if (await dependencies.hasCompetitionDates(db)) discovered.abort();
},
);
// Catalog imports can discover an event which is already in progress.
if (signal.aborted || !(await dependencies.hasCompetitionDates(db)))
return;
}

console.info(JSON.stringify({ event: "window.continuous" }));
const finished = new AbortController();
await dependencies.runWorker(
db,
AbortSignal.any([signal, finished.signal]),
concurrency,
async () => {
if (!(await dependencies.hasCompetitionDates(db))) finished.abort();
},
);
console.info(JSON.stringify({ event: "window.drained" }));
} finally {
await db.$disconnect();
}
}
Comment thread
jackshim415 marked this conversation as resolved.
Resolved
6 changes: 4 additions & 2 deletions apps/worker/src/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export async function runWorker(
db: PrismaClient,
signal: AbortSignal,
concurrency = 2,
onReconciled: () => void = () => {},
onReconciled: () => void | Promise<void> = () => {},
) {
if (
!Number.isSafeInteger(concurrency) ||
Expand All @@ -34,7 +34,7 @@ export async function runWorker(
while (!signal.aborted) {
try {
await reconcileSchedule(db);
onReconciled();
await onReconciled();
} catch {
console.error("Schedule reconciliation failed; retrying in 30 seconds");
}
Expand Down Expand Up @@ -67,6 +67,7 @@ export async function runBatch(
signal: AbortSignal,
concurrency = 2,
dependencies = { reconcileSchedule, runNextJob },
onJobSettled: () => Promise<void> = async () => {},
) {
const startedAt = Date.now();
try {
Expand Down Expand Up @@ -100,6 +101,7 @@ export async function runBatch(
await dependencies.runNextJob(db, undefined, { cutoff, id: job.id })
)
processed++;
await onJobSettled();
}
}),
);
Expand Down
127 changes: 127 additions & 0 deletions apps/worker/test/scheduled-window.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
import { expect, test } from "bun:test";
import type { PrismaClient } from "@lovat/db";
import {
hasCompetitionDates,
runScheduledWindow,
} from "../src/scheduled-window";

const event = {
startDate: new Date("2026-11-21Z"),
endDate: new Date("2026-11-21Z"),
timezone: "America/Chicago",
};
test("competition windows include local midnight and the last day after UTC midnight", async () => {
const db = {
tournament: { findMany: async () => [event] },
} as unknown as PrismaClient;
expect(await hasCompetitionDates(db, new Date("2026-11-21T05:59Z"))).toBe(
false,
);
expect(await hasCompetitionDates(db, new Date("2026-11-21T06:00Z"))).toBe(
true,
);
expect(await hasCompetitionDates(db, new Date("2026-11-22T05:59Z"))).toBe(
true,
);
expect(await hasCompetitionDates(db, new Date("2026-11-22T06:00Z"))).toBe(
false,
);
});

test("non-competition windows run a finite batch and disconnect", async () => {
let batches = 0;
let disconnected = false;
const db = {
$disconnect: async () => {
disconnected = true;
},
} as unknown as PrismaClient;
await runScheduledWindow(db, new AbortController().signal, 2, {
hasCompetitionDates: async () => false,
runBatch: async () => {
batches++;
},
runWorker: async () => {
throw new Error("unexpected continuous mode");
},
});
expect(batches).toBe(1);
expect(disconnected).toBe(true);
});

test("competition windows keep minute polling until all event-local dates finish, then drain", async () => {
let checks = 0;
let disconnected = false;
const db = {
$disconnect: async () => {
disconnected = true;
},
} as unknown as PrismaClient;
await runScheduledWindow(db, new AbortController().signal, 2, {
hasCompetitionDates: async () => ++checks < 3,
runBatch: async () => {
throw new Error("unexpected batch");
},
runWorker: async (_db, signal, _concurrency, onReconciled) => {
await onReconciled?.();
expect(signal.aborted).toBe(false);
await onReconciled?.();
expect(signal.aborted).toBe(true);
expect(disconnected).toBe(false);
},
});
expect(disconnected).toBe(true);
});

test("calendar query failure disconnects instead of starting stale event mode", async () => {
let disconnected = false;
const db = {
$disconnect: async () => {
disconnected = true;
},
} as unknown as PrismaClient;
await expect(
runScheduledWindow(db, new AbortController().signal, 2, {
hasCompetitionDates: async () => {
throw new Error("database unavailable");
},
runBatch: async () => {},
runWorker: async () => {},
}),
).rejects.toThrow("database unavailable");
expect(disconnected).toBe(true);
});

test("a catalog batch discovering today's event immediately enters continuous mode", async () => {
let discovered = false;
let continuous = false;
const db = { $disconnect: async () => {} } as unknown as PrismaClient;
await runScheduledWindow(db, new AbortController().signal, 2, {
hasCompetitionDates: async () => discovered,
runBatch: async () => {
discovered = true;
},
runWorker: async () => {
continuous = true;
},
});
expect(continuous).toBe(true);
});

test("catalog discovery stops new batch claims before draining the snapshot backlog", async () => {
let active = false;
let entered = false;
const db = { $disconnect: async () => {} } as unknown as PrismaClient;
await runScheduledWindow(db, new AbortController().signal, 2, {
hasCompetitionDates: async () => active,
runBatch: async (_db, signal, _concurrency, _deps, settled) => {
active = true;
await settled?.();
expect(signal.aborted).toBe(true);
},
runWorker: async () => {
entered = true;
},
});
expect(entered).toBe(true);
});
Loading
Loading