-
Notifications
You must be signed in to change notification settings - Fork 0
Cron jobs #21
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
Open
digitalmio
wants to merge
4
commits into
main
Choose a base branch
from
feat/cron
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Cron jobs #21
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
d81462a
Add cron job scheduling support with Cloudflare Alarms
digitalmio aa7809d
Safely check cron next run instead of array access
digitalmio ed17a11
Use scheduled time instead of current time for cron execution
digitalmio a5f8283
Add explanatory comment for cold-start alarm scheduling
digitalmio 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| export const cronIndexTemplate = () => `// This is where you define your Edgepod cron jobs! | ||
| // Cron jobs run on a schedule inside your Durable Object using Cloudflare's alarm API. | ||
| // They execute even when no requests are incoming — perfect for cleanup, reminders, etc. | ||
| // | ||
| // Define a cron job using the schedule() helper and export it: | ||
| // | ||
| // import { createSchedule } from "@edgepod/server"; | ||
| // import type { CronCtx } from "../types"; | ||
| // | ||
| // export const cleanupExpiredSessions = createSchedule("0 */6 * * *", async (ctx: CronCtx) => { | ||
| // await ctx.db.delete(schema.sessions).where(lt(schema.sessions.expiresAt, new Date())); | ||
| // }); | ||
| // | ||
|
|
||
| export {}; | ||
| `; |
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
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 |
|---|---|---|
| @@ -1,3 +1,4 @@ | ||
| export * from "./types"; | ||
| export * from "./server"; | ||
| export * from "./tools/createMiddleware"; | ||
| export * from "./tools/createSchedule"; |
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,121 @@ | ||
| import { Cron } from "croner"; | ||
| import { createTrackedDb } from "../tools/createTrackedDb"; | ||
| import { createLogger } from "./logger"; | ||
| import { hashMetaTableNames } from "../tools/hashTableName"; | ||
| import type { CronContext, CronDefinition, EdgePodSessionMap } from "../types"; | ||
|
|
||
| export async function scheduleNextAlarm( | ||
| cronFunctions: Record<string, CronDefinition<any, any, any>>, | ||
| setAlarm: (ms: number) => Promise<void>, | ||
| ) { | ||
| const now = new Date(); | ||
| let soonestMs: number | null = null; | ||
|
|
||
| for (const entry of Object.values(cronFunctions)) { | ||
| try { | ||
| const cron = new Cron(entry.schedule, { timezone: "UTC" }); | ||
| const nextRuns = cron.nextRuns(1, now); | ||
| const nextRun = nextRuns[0]; | ||
| if (nextRun) { | ||
| const nextMs = nextRun.getTime(); | ||
| if (soonestMs === null || nextMs < soonestMs) { | ||
| soonestMs = nextMs; | ||
| } | ||
| } | ||
| } catch (e) { | ||
| console.error( | ||
| "[EdgePod] Failed to parse cron schedule:", | ||
| e instanceof Error ? e.message : String(e), | ||
| ); | ||
| } | ||
| } | ||
|
|
||
| if (soonestMs !== null) { | ||
| await setAlarm(soonestMs); | ||
| } | ||
| } | ||
|
|
||
| export async function executeCron( | ||
| name: string, | ||
| def: CronDefinition<any, any, any>, | ||
| scheduledTime: Date, | ||
| rawDb: any, | ||
| env: any, | ||
| activeSessions: EdgePodSessionMap, | ||
| cascadeGraph: Map<string, Set<string>>, | ||
| broadcastInvalidations: (tables: string[]) => void, | ||
| ) { | ||
| const traceId = `cron:${name}:${scheduledTime.getTime()}`; | ||
|
|
||
| const tablesRead = new Set<string>(); | ||
| const tablesWritten = new Set<string>(); | ||
| const warnings: string[] = []; | ||
| const variableStore = new Map(); | ||
|
|
||
| const dbProxy = createTrackedDb( | ||
| rawDb, | ||
| `cron:${name}`, | ||
| activeSessions, | ||
| tablesRead, | ||
| tablesWritten, | ||
| cascadeGraph, | ||
| warnings, | ||
| ); | ||
|
|
||
| const ctx: CronContext<any, any, Record<string, any>> = { | ||
| db: dbProxy as any, | ||
| unsafeRawDb: rawDb, | ||
| env, | ||
| log: createLogger(traceId), | ||
| subscribeTo: (_tables: string[]) => {}, | ||
| invalidate: (tables: string[]) => tables.forEach((t) => tablesWritten.add(t)), | ||
| set: (key: string, value: any) => variableStore.set(key, value), | ||
| get: (key: string) => variableStore.get(key) as any, | ||
| cron: def.schedule, | ||
| scheduledTime: scheduledTime.toISOString(), | ||
| }; | ||
|
|
||
| await def.handler(ctx); | ||
|
|
||
| if (tablesWritten.size > 0) { | ||
| const hashedTableNames = hashMetaTableNames(Array.from(tablesWritten)); | ||
| broadcastInvalidations(hashedTableNames); | ||
| } | ||
| } | ||
|
|
||
| export async function handleCronAlarm( | ||
| cronFunctions: Record<string, CronDefinition<any, any, any>>, | ||
| setAlarm: (ms: number) => Promise<void>, | ||
| rawDb: any, | ||
| env: any, | ||
| activeSessions: EdgePodSessionMap, | ||
| cascadeGraph: Map<string, Set<string>>, | ||
| broadcastInvalidations: (tables: string[]) => void, | ||
| ) { | ||
| const now = new Date(); | ||
| const checkFrom = new Date(now.getTime() - 120000); | ||
|
|
||
| for (const [name, entry] of Object.entries(cronFunctions)) { | ||
| try { | ||
| const cron = new Cron(entry.schedule, { timezone: "UTC" }); | ||
| const nextRuns = cron.nextRuns(1, checkFrom); | ||
| const nextRun = nextRuns[0]; | ||
| if (nextRun && nextRun.getTime() <= now.getTime()) { | ||
| await executeCron( | ||
| name, | ||
| entry, | ||
| nextRun, | ||
| rawDb, | ||
| env, | ||
| activeSessions, | ||
| cascadeGraph, | ||
| broadcastInvalidations, | ||
| ); | ||
| } | ||
| } catch (e) { | ||
| console.error(`[EdgePod] Cron "${name}" failed:`, e instanceof Error ? e.message : String(e)); | ||
| } | ||
| } | ||
|
|
||
| await scheduleNextAlarm(cronFunctions, setAlarm); | ||
| } | ||
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,12 @@ | ||
| import type { CronDefinition, CronContext } from "../types"; | ||
|
|
||
| export function createSchedule< | ||
| TSchema extends Record<string, unknown> = Record<string, unknown>, | ||
| TEnv = Record<string, string>, | ||
| TVariables extends Record<string, unknown> = Record<string, unknown>, | ||
| >( | ||
| schedule: string, | ||
| handler: (ctx: CronContext<TSchema, TEnv, TVariables>) => Promise<void>, | ||
| ): CronDefinition<TSchema, TEnv, TVariables> { | ||
| return { schedule, handler }; | ||
| } |
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,14 @@ | ||
| // This is where you define your Edgepod cron jobs! | ||
| // Cron jobs run on a schedule inside your Durable Object using Cloudflare's alarm API. | ||
| // They execute even when no requests are incoming — perfect for cleanup, reminders, etc. | ||
| // | ||
| // Define a cron job using the schedule() helper and export it: | ||
| // | ||
| // import { createSchedule } from "@edgepod/server"; | ||
| // import type { CronCtx } from "../types"; | ||
| // | ||
| // export const cleanupExpiredSessions = createSchedule("0 */6 * * *", async (ctx: CronCtx) => { | ||
| // await ctx.db.delete(schema.sessions).where(lt(schema.sessions.expiresAt, new Date())); | ||
| // }); | ||
| // | ||
| export {}; |
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
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
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.