Swadhin Biswas fix(worker): fix stale reclaim and type errors, add CLI publish to CI · 4/21/2026
452d38e
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
import { getDatabase, schema } from "@/db";
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
import { cleanupAllRepos } from "@/lib/cron/cleanup-branches";
import { logger } from "@/lib/logger";
import { syncAllMirrors } from "@/lib/mirror-sync";
import { queueWorker } from "@/lib/queue-worker";
import { and, eq, lt } from "drizzle-orm";
import { createServer } from "http";
// ── Configuration ─────────────────────────────────────────────────────────────
const WORKER_INTERVAL = parseInt(process.env.WORKER_INTERVAL || "5000", 10);
const MIRROR_SYNC_INTERVAL = parseInt(
process.env.MIRROR_SYNC_INTERVAL || "60000",
10,
);
const CLEANUP_INTERVAL = parseInt(
process.env.CLEANUP_INTERVAL || "3600000",
10,
);
const HEALTH_PORT = parseInt(process.env.WORKER_HEALTH_PORT || "9090", 10);
const MAX_RETRIES = parseInt(process.env.WORKER_MAX_RETRIES || "3", 10);
const STALE_JOB_TIMEOUT_MS = parseInt(
process.env.WORKER_STALE_TIMEOUT || "300000",
10,
);
// ── State ─────────────────────────────────────────────────────────────────────
let isShuttingDown = false;
let isHealthy = true;
let lastQueueRun = Date.now();
let lastMirrorRun = 0;
let lastCleanupRun = 0;
let consecutiveErrors = 0;
const MAX_CONSECUTIVE_ERRORS = 10;
// ── Queue Processor ───────────────────────────────────────────────────────────
async function runQueueProcessor() {
const db = getDatabase();
try {
// 1. Reclaim stale jobs (stuck in "processing" too long)
try {
const staleThreshold = new Date(Date.now() - STALE_JOB_TIMEOUT_MS);
const staleItems = await db.query.mergeQueueItems.findMany({
where: eq(schema.mergeQueueItems.status, "processing"),
columns: { id: true, startedAt: true },
});
for (const item of staleItems) {
if (item.startedAt && new Date(item.startedAt) < staleThreshold) {
await (db as NodePgDatabase<typeof schema>)
.update(schema.mergeQueueItems)
.set({ status: "queued" })
.where(eq(schema.mergeQueueItems.id, item.id));
}
}
} catch {
// startedAt column may not exist yet — skip stale reclaim
}
// 2. Process pending items
const pendingItems = await db.query.mergeQueueItems.findMany({
where: eq(schema.mergeQueueItems.status, "queued"),
columns: { repositoryId: true },
});
const repoIds = [...new Set(pendingItems.map((item) => item.repositoryId))];
if (repoIds.length > 0) {
logger.info({ repoCount: repoIds.length }, "Processing merge queues");
// Process sequentially to avoid race conditions
for (const repoId of repoIds) {
if (isShuttingDown) break;
try {
await queueWorker.processQueue(repoId);
} catch (error) {
logger.error(
{ err: error, repoId },
"Failed to process queue for repo",
);
}
}
}
consecutiveErrors = 0;
lastQueueRun = Date.now();
} catch (error) {
consecutiveErrors++;
logger.error(
{ err: error, consecutiveErrors },
"Error in queue processor loop",
);
if (consecutiveErrors >= MAX_CONSECUTIVE_ERRORS) {
isHealthy = false;
logger.error("Too many consecutive errors. Worker marked unhealthy.");
}
}
}
// ── Controlled Loop (replaces setInterval) ────────────────────────────────────
async function runLoop(
name: string,
fn: () => Promise<void>,
intervalMs: number,
getLastRun: () => number,
setLastRun: (t: number) => void,
) {
while (!isShuttingDown) {
const elapsed = Date.now() - getLastRun();
if (elapsed >= intervalMs) {
try {
await fn();
} catch (error) {
logger.error({ err: error, task: name }, `${name} failed`);
}
setLastRun(Date.now());
}
await sleep(Math.min(intervalMs, 1000));
}
}
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
// ── Health Check Server ───────────────────────────────────────────────────────
function startHealthServer() {
const server = createServer((req, res) => {
if (req.url === "/healthz" || req.url === "/health") {
const timeSinceLastRun = Date.now() - lastQueueRun;
const healthy = isHealthy && timeSinceLastRun < WORKER_INTERVAL * 5;
res.writeHead(healthy ? 200 : 503, {
"Content-Type": "application/json",
});
res.end(
JSON.stringify({
status: healthy ? "healthy" : "unhealthy",
uptime: process.uptime(),
lastQueueRun: new Date(lastQueueRun).toISOString(),
consecutiveErrors,
shuttingDown: isShuttingDown,
}),
);
} else if (req.url === "/ready") {
res.writeHead(isHealthy ? 200 : 503);
res.end(isHealthy ? "ready" : "not ready");
} else {
res.writeHead(404);
res.end("Not Found");
}
});
server.listen(HEALTH_PORT, () => {
logger.info({ port: HEALTH_PORT }, "Worker health server started");
});
return server;
}
// ── Graceful Shutdown ─────────────────────────────────────────────────────────
function setupGracefulShutdown(healthServer: ReturnType<typeof createServer>) {
const shutdown = async (signal: string) => {
if (isShuttingDown) return;
isShuttingDown = true;
logger.info({ signal }, "Worker shutting down gracefully...");
healthServer.close();
// Give in-flight jobs up to 30s to complete
await sleep(2000);
logger.info("Worker shutdown complete.");
process.exit(0);
};
process.on("SIGINT", () => shutdown("SIGINT"));
process.on("SIGTERM", () => shutdown("SIGTERM"));
process.on("uncaughtException", (err) => {
logger.error({ err }, "Uncaught exception in worker");
isHealthy = false;
});
process.on("unhandledRejection", (reason) => {
logger.error({ reason }, "Unhandled rejection in worker");
});
}
// ── Main ──────────────────────────────────────────────────────────────────────
async function startWorker() {
logger.info(
{
queueInterval: WORKER_INTERVAL,
mirrorInterval: MIRROR_SYNC_INTERVAL,
cleanupInterval: CLEANUP_INTERVAL,
healthPort: HEALTH_PORT,
maxRetries: MAX_RETRIES,
},
"Starting OpenCodeHub Background Worker...",
);
const healthServer = startHealthServer();
setupGracefulShutdown(healthServer);
// Run initial processing immediately
await runQueueProcessor();
// Start concurrent task loops
await Promise.all([
runLoop(
"queue-processor",
runQueueProcessor,
WORKER_INTERVAL,
() => lastQueueRun,
(t) => {
lastQueueRun = t;
},
),
runLoop(
"mirror-sync",
async () => { await syncAllMirrors(); },
MIRROR_SYNC_INTERVAL,
() => lastMirrorRun,
(t) => {
lastMirrorRun = t;
},
),
runLoop(
"cleanup",
() => cleanupAllRepos(),
CLEANUP_INTERVAL,
() => lastCleanupRun,
(t) => {
lastCleanupRun = t;
},
),
]);
}
startWorker().catch((err) => {
logger.error({ err }, "Worker failed to start");
process.exit(1);
});