-
Notifications
You must be signed in to change notification settings - Fork 99
feat(workers): implement Cron Trigger for outbox re-enqueue #1813
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
willbakst
merged 2 commits into
v2
from
01-06-feat_workers_implement_cron_trigger_for_outbox_re-enqueue
Jan 9, 2026
+264
−6
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,38 @@ | ||
| import { | ||
| createStartHandler, | ||
| defaultStreamHandler, | ||
| } from "@tanstack/react-start/server"; | ||
| import clickhouseCron, { type CronTriggerEnv } from "@/workers/clickhouseCron"; | ||
|
|
||
| interface ScheduledEvent { | ||
| readonly scheduledTime: number; | ||
| readonly cron: string; | ||
| } | ||
|
|
||
| const fetchHandler = createStartHandler(defaultStreamHandler); | ||
| const scheduled = clickhouseCron.scheduled.bind(clickhouseCron); | ||
|
|
||
| const fetch: ExportedHandlerFetchHandler<CronTriggerEnv> = ( | ||
| request, | ||
| env, | ||
| ctx, | ||
| ) => { | ||
| if (env.ENVIRONMENT === "local") { | ||
| const { pathname } = new URL(request.url); | ||
| if (pathname === "/__scheduled") { | ||
| const event: ScheduledEvent = { | ||
| cron: "local", | ||
| scheduledTime: Date.now(), | ||
| }; | ||
| ctx.waitUntil(scheduled(event, env)); | ||
| return new Response("Ran scheduled event"); | ||
| } | ||
| } | ||
|
|
||
| return fetchHandler(request); | ||
| }; | ||
|
|
||
| export default { | ||
| fetch, | ||
| scheduled, | ||
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,215 @@ | ||
| /** | ||
| * @fileoverview Cloudflare Cron Trigger for outbox re-enqueue. | ||
| * | ||
| * Periodically processes pending outbox rows that failed to be | ||
| * synced or were not processed within the timeout. | ||
| * | ||
| * ## Responsibilities | ||
| * | ||
| * 1. **Lock Recovery**: Reclaims stale processing rows where the worker | ||
| * died mid-processing (lockedAt > LOCK_TIMEOUT) | ||
| * | ||
| * 2. **Process**: Polls pending rows and syncs them to ClickHouse | ||
| * | ||
| * ## Trigger Configuration | ||
| * | ||
| * Configure in wrangler.jsonc with a cron expression like "0/5 * * * *" (every 5 min). | ||
| */ | ||
|
|
||
| import { Effect, Layer } from "effect"; | ||
| import { DrizzleORM } from "@/db/client"; | ||
| import { spansOutbox } from "@/db/schema"; | ||
| import { and, eq, lt, or, isNull, lte } from "drizzle-orm"; | ||
| import { ClickHouse } from "@/clickhouse/client"; | ||
| import { | ||
| SettingsService, | ||
| getSettingsFromEnvironment, | ||
| type CloudflareEnvironment, | ||
| } from "@/settings"; | ||
| import { DatabaseError } from "@/errors"; | ||
| import { processOutboxMessages } from "@/workers/outboxProcessor"; | ||
|
|
||
| // ============================================================================= | ||
| // Constants | ||
| // ============================================================================= | ||
|
|
||
| /** | ||
| * Lock timeout in milliseconds. | ||
| * If a row has been in 'processing' state longer than this, it's considered stale. | ||
| */ | ||
| const LOCK_TIMEOUT_MS = 30000; // 30 seconds | ||
|
|
||
| /** | ||
| * Maximum retry count before a row is marked as failed. | ||
| */ | ||
| const MAX_RETRIES = 5; | ||
|
|
||
| /** | ||
| * Maximum number of rows to process per cron invocation. | ||
| * Prevents overwhelming the queue. | ||
| */ | ||
| const BATCH_LIMIT = 500; | ||
|
|
||
| // ============================================================================= | ||
| // Types | ||
| // ============================================================================= | ||
|
|
||
| /** | ||
| * Cloudflare Scheduled Event type. | ||
| */ | ||
| interface ScheduledEvent { | ||
| readonly scheduledTime: number; | ||
| readonly cron: string; | ||
| } | ||
|
|
||
| /** | ||
| * Extended Cloudflare environment bindings for Cron Trigger. | ||
| */ | ||
| export interface CronTriggerEnv extends CloudflareEnvironment { | ||
| /** Hyperdrive binding for PostgreSQL connection pooling */ | ||
| readonly HYPERDRIVE?: { | ||
| readonly connectionString: string; | ||
| }; | ||
| /** Direct database URL (fallback when Hyperdrive is not configured) */ | ||
| readonly DATABASE_URL?: string; | ||
| } | ||
|
|
||
| // ============================================================================= | ||
| // Cron Handler | ||
| // ============================================================================= | ||
|
|
||
| export default { | ||
| /** | ||
| * Scheduled event handler. | ||
| * | ||
| * @param _event - Cloudflare scheduled event (unused, but required by interface) | ||
| * @param env - Cloudflare Workers environment bindings | ||
| */ | ||
| async scheduled(_event: ScheduledEvent, env: CronTriggerEnv): Promise<void> { | ||
| // Database connection string from Hyperdrive or direct URL | ||
| const databaseUrl = env.HYPERDRIVE?.connectionString ?? env.DATABASE_URL; | ||
| if (!databaseUrl) { | ||
| console.error( | ||
| "No database connection available (HYPERDRIVE or DATABASE_URL required)", | ||
| ); | ||
| return; | ||
| } | ||
|
|
||
| const program = Effect.gen(function* () { | ||
| const client = yield* DrizzleORM; | ||
| const workerId = `workers-cron-${Date.now()}`; | ||
|
|
||
| const staleTime = new Date(Date.now() - LOCK_TIMEOUT_MS); | ||
| const now = new Date(); | ||
|
|
||
| // ===================================================================== | ||
| // 1. Reclaim stale processing rows | ||
| // ===================================================================== | ||
| // Rows that have been in 'processing' state longer than LOCK_TIMEOUT | ||
| // are likely from a worker that crashed. Reset them to 'pending'. | ||
|
|
||
| yield* client | ||
| .update(spansOutbox) | ||
| .set({ | ||
| status: "pending", | ||
| lockedAt: null, | ||
| lockedBy: null, | ||
| }) | ||
| .where( | ||
| and( | ||
| eq(spansOutbox.status, "processing"), | ||
| lt(spansOutbox.lockedAt, staleTime), | ||
| ), | ||
| ) | ||
| .pipe( | ||
| Effect.mapError( | ||
| (e) => | ||
| new DatabaseError({ | ||
| message: "Failed to reclaim stale locks", | ||
| cause: e, | ||
| }), | ||
| ), | ||
| ); | ||
|
|
||
| // ===================================================================== | ||
| // 2. Query pending rows ready for processing | ||
| // ===================================================================== | ||
| // Conditions: | ||
| // - status = 'pending' | ||
| // - processAfter <= now (backoff expired) | ||
| // - retryCount < MAX_RETRIES | ||
| // - not currently locked (lockedAt is null or stale) | ||
|
|
||
| const pendingRows = yield* client | ||
| .select({ | ||
| spanId: spansOutbox.spanId, | ||
| operation: spansOutbox.operation, | ||
| }) | ||
| .from(spansOutbox) | ||
| .where( | ||
| and( | ||
| eq(spansOutbox.status, "pending"), | ||
| lte(spansOutbox.processAfter, now), | ||
| lt(spansOutbox.retryCount, MAX_RETRIES), | ||
| or( | ||
| isNull(spansOutbox.lockedAt), | ||
| lt(spansOutbox.lockedAt, staleTime), | ||
| ), | ||
| ), | ||
| ) | ||
| .orderBy(spansOutbox.createdAt) | ||
| .limit(BATCH_LIMIT) | ||
| .pipe( | ||
| Effect.mapError( | ||
| (e) => | ||
| new DatabaseError({ | ||
| message: "Failed to query pending rows", | ||
| cause: e, | ||
| }), | ||
| ), | ||
| ); | ||
|
|
||
| if (pendingRows.length === 0) { | ||
| return; | ||
| } | ||
|
|
||
| console.log(`Processing ${pendingRows.length} pending outbox rows`); | ||
|
|
||
| const messages = pendingRows.map((row) => ({ | ||
| spanId: row.spanId, | ||
| operation: row.operation as "INSERT" | "UPDATE" | "DELETE", | ||
| messageKey: `${row.spanId}:${row.operation}`, | ||
| })); | ||
|
|
||
| yield* processOutboxMessages( | ||
| messages, | ||
| () => {}, | ||
| () => {}, | ||
| workerId, | ||
| ); | ||
| }); | ||
|
|
||
| // Build layers | ||
| const settingsLayer = Layer.succeed( | ||
| SettingsService, | ||
| getSettingsFromEnvironment(env), | ||
| ); | ||
| const drizzleLayer = DrizzleORM.layer({ connectionString: databaseUrl }); | ||
| const clickhouseLayer = ClickHouse.Default.pipe( | ||
| Layer.provide(settingsLayer), | ||
| ); | ||
|
|
||
| // Run the program | ||
| await Effect.runPromise( | ||
| program.pipe( | ||
| Effect.provide(drizzleLayer), | ||
| Effect.provide(clickhouseLayer), | ||
| Effect.provide(settingsLayer), | ||
| Effect.catchAll((error) => { | ||
| console.error("Cron trigger error:", error); | ||
| return Effect.void; | ||
| }), | ||
| ), | ||
| ); | ||
| }, | ||
| }; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.