@coreframe/jobs 0.1.3 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,8 +1,118 @@
1
- # Development job history
1
+ # Jobs
2
2
 
3
- > Inspect local startup jobs without changing their cooldowns, leases, or execution.
3
+ > Run explicitly registered cron jobs in production and inspect local development jobs separately.
4
4
 
5
- The template enables the read-only Dev jobs page at `/__dashboard/dev-jobs`:
5
+ ## Scheduled jobs
6
+
7
+ Add `scheduled` metadata to jobs that should run for delivered cron events. A job may have
8
+ `dev`, `scheduled`, both, or neither. `runJobs` still runs every supplied job without filtering;
9
+ `runDevelopmentJobs` selects development startup jobs; `runScheduledJobs` selects exact matching
10
+ cron expressions.
11
+
12
+ ```ts
13
+ import { defineJob, defineJobRegistry, runScheduledJobs } from "@coreframe/jobs"
14
+
15
+ const jobs = defineJobRegistry([
16
+ defineJob({
17
+ id: "cache.refresh",
18
+ scheduled: { crons: ["17 */6 * * *"] },
19
+ async run({ now }) {
20
+ const response = await fetch("https://example.com/cache/refresh", {
21
+ method: "POST",
22
+ body: JSON.stringify({ scheduledAt: now.toISOString() }),
23
+ headers: { "content-type": "application/json" },
24
+ })
25
+ if (!response.ok) throw new Error("Cache refresh failed.")
26
+ },
27
+ }),
28
+ ])
29
+
30
+ const results = await runScheduledJobs({
31
+ createContext: () => ({}),
32
+ cron: controller.cron,
33
+ jobs,
34
+ scheduledAt: new Date(controller.scheduledTime),
35
+ })
36
+ ```
37
+
38
+ Configure the same expressions in the host, such as Wrangler's `triggers.crons`. The package does
39
+ not create timers or provision triggers. Expressions match character-for-character, including
40
+ spaces. Unmatched events return no results without creating context. Handlers run sequentially in
41
+ registry order and receive the scheduled time as `now`; durations measure actual execution.
42
+
43
+ Results include ID, cron, scheduled time, duration, completed/failed status, and the thrown error
44
+ on failure. By default, a failed handler does not stop later jobs. The Worker should inspect all
45
+ results and reject its invocation if any failed. `onError: "throw"` instead stops at the first
46
+ handler failure. Context-creation failures always reject.
47
+
48
+ There is no required database, lease, cooldown, duplicate suppression, automatic retry, or recovery
49
+ of interrupted work. Dev cooldowns do not apply to scheduled execution. Repeated events execute
50
+ again, and separate invocations may overlap. Choose jobs where repetition is safe and a later
51
+ scheduled run can repair incomplete work, or use an explicit queue/workflow integration.
52
+
53
+ ## Optional scheduled job history
54
+
55
+ Pass `history: { environment, store }` to `runScheduledJobs` to record start and finish
56
+ observations. Omitting it keeps the runner database-free. History failures never change execution
57
+ or error behavior. An attempt starts with outcome `unknown` and ends as `succeeded` or `failed`.
58
+ An unfinished record stays unknown; it does not establish that execution is still running.
59
+ Thrown values and job inputs are never persisted; failed attempts receive a fixed safe summary.
60
+
61
+ The provided native Drizzle adapters export `scheduledJobAttempts` and
62
+ `createScheduledJobHistoryStore(db)` from either `@coreframe/jobs/history/postgres` or
63
+ `@coreframe/jobs/history/sqlite`. Re-export the selected table from the app's schema and generate
64
+ an additive migration for `coreframe_job_attempts`. Factories use the native database
65
+ `$client` and own their observation transactions; pass a database connection rather than an active
66
+ transaction. These entry points require the optional
67
+ `drizzle-orm` peer; the core runner does not import a database driver.
68
+
69
+ ```ts
70
+ import { createScheduledJobHistoryStore } from "@coreframe/jobs/history/postgres"
71
+
72
+ const results = await runScheduledJobs({
73
+ createContext: () => context,
74
+ cron: controller.cron,
75
+ scheduledAt: new Date(controller.scheduledTime),
76
+ jobs,
77
+ history: { environment: "production", store: createScheduledJobHistoryStore(db) },
78
+ })
79
+ ```
80
+
81
+ Adapters scope reads and pruning to an environment. Reads return at most 1,000 observations
82
+ from the last 30 days; writes prune old and excess observations in their environment. Stopped
83
+ environments need separate cleanup for physical deletion. This history is independent of the
84
+ `coreframe_dev_job_*` tables, dev cooldowns, and local reset/status commands. Use distinct
85
+ environment names when sharing a database. Applications may instead implement
86
+ `ScheduledJobHistoryStore` for another storage backend.
87
+
88
+ `readScheduledJobsSnapshot({ environment, history, jobs })` returns a safe browser projection:
89
+ registered schedules, latest outcomes, last attempt/success within retention, and recent
90
+ observations, including removed jobs. Missing or unreadable history yields `historyAvailable: false`.
91
+ Only explicit fields and the fixed safe summary reach the projection, even with a custom store.
92
+
93
+ ### Dashboard page
94
+
95
+ The generated template enables the Jobs page at `/__dashboard/jobs`. Its app-owned
96
+ `GET /api/jobs` endpoint checks a current durable session and active admin role, selects the
97
+ current deployment environment, and returns a private, non-cacheable snapshot. The page uses
98
+ the typed app client and passes its session to the shared Jobs page. During development, the page
99
+ also queries the local startup job plugin. Each job has one row with an icon for each trigger.
100
+
101
+ For another app, register `scheduledJobs({ pageModule: "./scheduled-jobs.tsx" })` from
102
+ `@coreframe/jobs/scheduled-dashboard` and supply an app-owned page wrapper. Render the default
103
+ component from `@coreframe/jobs/scheduled-dashboard/page` with
104
+ `loadSnapshot(signal): Promise<ScheduledJobsSnapshot>`, backed by an equivalently protected
105
+ app API. The schema/type is available from `@coreframe/jobs/scheduled-dashboard/api`.
106
+
107
+ The page is read-only. Cron status comes from retained observations, and local startup status
108
+ includes cooldown and lease information. Consult Worker logs to investigate cron failures.
109
+
110
+ ## Development job history
111
+
112
+ The template uses `devJobs({ jobsPageModule })` to mount its combined Jobs page locally at
113
+ `/__dashboard/jobs`. In that wrapper, pass `includeLocalStartup` to the shared Jobs page, and set
114
+ `environments: ["deployed"]` on the `scheduledJobs` registration. A project that only needs local
115
+ startup jobs can register the standalone Dev jobs page at `/__dashboard/dev-jobs`:
6
116
 
7
117
  ```ts
8
118
  import { defineConfig } from "@coreframe/dashboard/config"
@@ -21,7 +131,7 @@ shows attempts, including checks skipped because of cooldowns or active leases.
21
131
  to the retained history. Expand an attempt for its timestamps, skip reason, and error summary.
22
132
  The page refreshes every three seconds while visible.
23
133
 
24
- ## Connect project-owned storage
134
+ ### Connect project-owned storage
25
135
 
26
136
  `runDevelopmentJobs` accepts an optional `history: DevelopmentJobHistoryStore` alongside its
27
137
  scheduling `state`. The store upserts observations by attempt ID: a claimed job first records
@@ -38,7 +148,7 @@ database. A fresh local setup includes the history table. The template retains o
38
148
  30 days, capped at 1,000 attempts. Writes prune older records; reads also exclude records older
39
149
  than 30 days. Resetting job scheduling state preserves history; resetting the local database clears it.
40
150
 
41
- ## Interpret history
151
+ ### Interpret history
42
152
 
43
153
  History is best effort. Failed writes emit a development debug message and never change execution
44
154
  or lease completion. Missing observations do not establish that a job never ran. An unfinished
@@ -2,6 +2,10 @@ import { DashboardPlugin } from "@coreframe/dashboard/config";
2
2
 
3
3
  //#region src/dashboard/index.d.ts
4
4
  /** Read-only project-local job status and attempt history. */
5
- declare function devJobs(): DashboardPlugin;
5
+ declare function devJobs({
6
+ jobsPageModule
7
+ }?: {
8
+ jobsPageModule?: string;
9
+ }): DashboardPlugin;
6
10
  //#endregion
7
11
  export { devJobs };
@@ -1 +1 @@
1
- import{api as e}from"./api.js";import{definePlugin as t}from"@coreframe/dashboard/config";function n(){return t({id:`dev-jobs`,navigation:{path:`dev-jobs`,title:`Dev jobs`,icon:`list-check`,environments:[`local`]},pageModule:`@coreframe/jobs/dashboard/page`,api:e},{apiModule:`@coreframe/jobs/dashboard/api`,localImplementationModule:`@coreframe/jobs/dashboard/local`})}export{n as devJobs};
1
+ import{api as e}from"./api.js";import{definePlugin as t}from"@coreframe/dashboard/config";function n({jobsPageModule:n}={}){return t({id:`dev-jobs`,navigation:{path:n?`jobs`:`dev-jobs`,title:n?`Jobs`:`Dev jobs`,icon:`list-check`,environments:[`local`]},pageModule:n??`@coreframe/jobs/dashboard/page`,api:e},{apiModule:`@coreframe/jobs/dashboard/api`,localImplementationModule:`@coreframe/jobs/dashboard/local`})}export{n as devJobs};
@@ -1 +1 @@
1
- import{api as e}from"./api.js";import{createClient as t}from"@coreframe/dashboard/api";import{Button as n,Field as r,Page as i,Section as a,Status as o,Tabs as s}from"@coreframe/dashboard/ui";import{useQuery as c}from"@tanstack/react-query";import{useState as l}from"react";import{Fragment as u,jsx as d,jsxs as f}from"react/jsx-runtime";const p={padding:`10px 14px`,textAlign:`left`,borderBottom:`1px solid var(--colors-border, #8884)`,verticalAlign:`top`},m=e=>e?new Date(e).toLocaleString():`—`;function h(){let[o,u]=l(`jobs`),[h,y]=l(``),[b,x]=l(``),S=c({queryKey:[`dashboard`,`dev-jobs`,`snapshot`],queryFn:({signal:n})=>t(e).queries.snapshot({signal:n}),refetchInterval:3e3,retry:!1}),C=S.data,w=C?.attempts.filter(e=>(!h||e.jobId===h)&&(!b||e.outcome===b))??[],T=[...new Set([...C?.jobs.map(e=>e.id)??[],...C?.attempts.map(e=>e.jobId)??[]])].sort();return d(i,{children:f(a,{title:`Dev jobs`,description:`Local startup jobs and their recent attempts.`,actions:d(n,{variant:`outline`,busy:S.isFetching,onClick:()=>void S.refetch(),children:`Refresh`}),children:[S.isPending&&d(`p`,{role:`status`,children:`Loading development jobs…`}),S.isError&&f(`p`,{role:`alert`,children:[`Could not refresh development jobs. Check the local database and migrations, then refresh.`,C?` Showing the last successful snapshot.`:``]}),C?.notice&&d(`p`,{role:`status`,children:C.notice}),C&&f(s,{value:o,onValueChange:u,children:[f(s.List,{children:[f(s.Trigger,{value:`jobs`,children:[`Jobs (`,C.jobs.length,`)`]}),f(s.Trigger,{value:`history`,children:[`History (`,C.attempts.length,`)`]})]}),d(s.Panel,{value:`jobs`,children:C.jobs.length===0?d(`p`,{children:`No development jobs are configured.`}):d(v,{headings:[`Job`,`Latest outcome`,`Scheduling`,`Last success`,`Next eligible`,`Lease`],children:C.jobs.map(e=>f(`tr`,{children:[f(`td`,{style:p,children:[d(`code`,{children:e.id}),e.registration===`orphaned`&&d(`p`,{children:`No longer configured`})]}),d(`td`,{style:p,children:d(_,{value:C.attempts.find(t=>t.jobId===e.id)?.outcome??`No recorded attempts`})}),d(`td`,{style:p,children:e.eligibility===`cooldown`?`Cooling down`:e.eligibility===`never-run`?`No recorded success`:e.eligibility}),d(`td`,{style:p,children:m(e.lastSucceededAt)}),d(`td`,{style:p,children:m(e.nextEligibleAt)}),f(`td`,{style:p,children:[e.lease,e.leaseUntil&&f(`p`,{children:[`Until `,m(e.leaseUntil)]})]})]},e.id))})}),f(s.Panel,{value:`history`,children:[f(`div`,{style:{display:`flex`,gap:16,flexWrap:`wrap`,marginBottom:16},children:[d(r,{label:`Job`,children:f(`select`,{value:h,onChange:e=>y(e.target.value),children:[d(`option`,{value:``,children:`All jobs`}),T.map(e=>d(`option`,{children:e},e))]})}),d(r,{label:`Outcome`,children:f(`select`,{value:b,onChange:e=>x(e.target.value),children:[d(`option`,{value:``,children:`All outcomes`}),[`running`,`succeeded`,`failed`,`skipped`,`unknown`].map(e=>d(`option`,{children:e},e))]})})]}),d(`p`,{children:`Up to 1,000 attempts from the last 30 days. History is best effort; missing records do not prove a job never ran. Unknown means the lease expired without a recorded result.`}),w.length===0?d(`p`,{children:C.historyAvailable?`No recorded attempts match these filters.`:`Attempt history is unavailable.`}):d(v,{headings:[`Job`,`Started`,`Duration`,`Outcome`,`Details`],children:w.map(e=>d(g,{attempt:e},e.id))})]})]})]})})}function g({attempt:e}){return f(`tr`,{children:[d(`td`,{style:p,children:d(`code`,{children:e.jobId})}),d(`td`,{style:p,children:m(e.startedAt)}),d(`td`,{style:p,children:e.durationMs===null?`—`:`${(e.durationMs/1e3).toFixed(2)}s`}),d(`td`,{style:p,children:d(_,{value:e.outcome})}),d(`td`,{style:p,children:f(`details`,{children:[d(`summary`,{children:`View attempt`}),f(`dl`,{children:[d(`dt`,{children:`Attempt`}),d(`dd`,{children:d(`code`,{children:e.id})}),d(`dt`,{children:`Started`}),d(`dd`,{children:m(e.startedAt)}),d(`dt`,{children:`Finished`}),d(`dd`,{children:m(e.finishedAt)}),e.skipReason&&f(u,{children:[d(`dt`,{children:`Skipped because`}),d(`dd`,{children:e.skipReason===`cooldown`?`Cooldown has not elapsed`:`Another attempt holds the lease`})]}),e.errorSummary&&f(u,{children:[d(`dt`,{children:`Error`}),d(`dd`,{children:e.errorSummary})]})]})]})})]})}function _({value:e}){return d(o,{role:`presentation`,tone:e===`failed`?`danger`:e===`succeeded`?`success`:e===`running`?`info`:e===`unknown`?`warning`:`neutral`,children:e})}function v({headings:e,children:t}){return d(`div`,{style:{overflowX:`auto`},children:f(`table`,{style:{width:`100%`,borderCollapse:`collapse`,fontVariantNumeric:`tabular-nums`},children:[d(`thead`,{children:d(`tr`,{children:e.map(e=>d(`th`,{style:p,scope:`col`,children:e},e))})}),d(`tbody`,{children:t})]})})}export{h as default};
1
+ import{api as e}from"./api.js";import{OutcomeIcon as t}from"../dashboard-ui/outcome-icon.js";import{RefreshButton as n}from"../dashboard-ui/refresh-button.js";import{createClient as r}from"@coreframe/dashboard/api";import{Field as i,Page as a,PageHeader as o,Section as s,Tabs as c}from"@coreframe/dashboard/ui";import{useQuery as l}from"@tanstack/react-query";import{useState as u}from"react";import{Fragment as d,jsx as f,jsxs as p}from"react/jsx-runtime";const m={padding:`10px 14px`,textAlign:`left`,borderBottom:`1px solid var(--colors-border, #8884)`,verticalAlign:`top`},h=e=>e?new Date(e).toLocaleString():`—`;function g(){let[d,g]=u(`jobs`),[y,b]=u(``),[x,S]=u(``),C=l({queryKey:[`dashboard`,`dev-jobs`,`snapshot`],queryFn:({signal:t})=>r(e).queries.snapshot({signal:t}),refetchInterval:3e3,retry:!1}),w=C.data,T=w?.attempts.filter(e=>(!y||e.jobId===y)&&(!x||e.outcome===x))??[],E=[...new Set([...w?.jobs.map(e=>e.id)??[],...w?.attempts.map(e=>e.jobId)??[]])].sort();return p(a,{children:[p(o,{style:{marginBottom:`0.75rem`},children:[p(`div`,{children:[f(`h1`,{style:{fontSize:`1.25rem`},children:`Dev jobs`}),f(`p`,{children:`Local startup jobs and their recent attempts.`})]}),f(n,{busy:C.isFetching,onRefresh:()=>void C.refetch()})]}),p(s,{"aria-label":`Dev jobs activity`,style:{paddingBlockStart:`0.5rem`},children:[C.isPending&&f(`p`,{role:`status`,children:`Loading development jobs…`}),C.isError&&p(`p`,{role:`alert`,children:[`Could not refresh development jobs. Check the local database and migrations, then refresh.`,w?` Showing the last successful snapshot.`:``]}),w?.notice&&f(`p`,{role:`status`,children:w.notice}),w&&p(c,{value:d,onValueChange:g,children:[p(c.List,{children:[p(c.Trigger,{value:`jobs`,children:[`Jobs (`,w.jobs.length,`)`]}),p(c.Trigger,{value:`history`,children:[`History (`,w.attempts.length,`)`]})]}),f(c.Panel,{value:`jobs`,children:w.jobs.length===0?f(`p`,{children:`No development jobs are configured.`}):f(v,{headings:[`Job`,`Latest outcome`,`Scheduling`,`Last success`,`Next eligible`,`Lease`],children:w.jobs.map(e=>p(`tr`,{children:[p(`td`,{style:m,children:[f(`code`,{children:e.id}),e.registration===`orphaned`&&f(`p`,{children:`No longer configured`})]}),f(`td`,{style:m,children:f(t,{value:w.attempts.find(t=>t.jobId===e.id)?.outcome})}),f(`td`,{style:m,children:e.eligibility===`cooldown`?`Cooling down`:e.eligibility===`never-run`?`No recorded success`:e.eligibility}),f(`td`,{style:m,children:h(e.lastSucceededAt)}),f(`td`,{style:m,children:h(e.nextEligibleAt)}),p(`td`,{style:m,children:[e.lease,e.leaseUntil&&p(`p`,{children:[`Until `,h(e.leaseUntil)]})]})]},e.id))})}),p(c.Panel,{value:`history`,children:[p(`div`,{style:{display:`flex`,gap:16,flexWrap:`wrap`,marginBottom:16},children:[f(i,{label:`Job`,children:p(`select`,{value:y,onChange:e=>b(e.target.value),children:[f(`option`,{value:``,children:`All jobs`}),E.map(e=>f(`option`,{children:e},e))]})}),f(i,{label:`Outcome`,children:p(`select`,{value:x,onChange:e=>S(e.target.value),children:[f(`option`,{value:``,children:`All outcomes`}),[`running`,`succeeded`,`failed`,`skipped`,`unknown`].map(e=>f(`option`,{children:e},e))]})})]}),f(`p`,{children:`Up to 1,000 attempts from the last 30 days. History is best effort; missing records do not prove a job never ran. Unknown means the lease expired without a recorded result.`}),T.length===0?f(`p`,{children:w.historyAvailable?`No recorded attempts match these filters.`:`Attempt history is unavailable.`}):f(v,{headings:[`Job`,`Started`,`Duration`,`Outcome`,`Details`],children:T.map(e=>f(_,{attempt:e},e.id))})]})]})]})]})}function _({attempt:e}){return p(`tr`,{children:[f(`td`,{style:m,children:f(`code`,{children:e.jobId})}),f(`td`,{style:m,children:h(e.startedAt)}),f(`td`,{style:m,children:e.durationMs===null?`—`:`${(e.durationMs/1e3).toFixed(2)}s`}),f(`td`,{style:m,children:f(t,{value:e.outcome})}),f(`td`,{style:m,children:p(`details`,{children:[f(`summary`,{children:`View attempt`}),p(`dl`,{children:[f(`dt`,{children:`Attempt`}),f(`dd`,{children:f(`code`,{children:e.id})}),f(`dt`,{children:`Started`}),f(`dd`,{children:h(e.startedAt)}),f(`dt`,{children:`Finished`}),f(`dd`,{children:h(e.finishedAt)}),e.skipReason&&p(d,{children:[f(`dt`,{children:`Skipped because`}),f(`dd`,{children:e.skipReason===`cooldown`?`Cooldown has not elapsed`:`Another attempt holds the lease`})]}),e.errorSummary&&p(d,{children:[f(`dt`,{children:`Error`}),f(`dd`,{children:e.errorSummary})]})]})]})})]})}function v({headings:e,children:t}){return f(`div`,{style:{overflowX:`auto`},children:p(`table`,{style:{width:`100%`,borderCollapse:`collapse`,fontVariantNumeric:`tabular-nums`},children:[f(`thead`,{children:f(`tr`,{children:e.map(e=>f(`th`,{style:m,scope:`col`,children:e},e))})}),f(`tbody`,{children:t})]})})}export{g as default};
@@ -0,0 +1 @@
1
+ import{ValueTooltip as e}from"./value-tooltip.js";import{jsx as t}from"react/jsx-runtime";const n={succeeded:{label:`Succeeded`,color:`var(--colors-dashboard-success, #15803d)`,path:`M22 12a10 10 0 1 1-20 0 10 10 0 0 1 20 0ZM8 12l3 3 5-6`},failed:{label:`Failed`,color:`var(--colors-dashboard-danger, #dc2626)`,path:`M22 12a10 10 0 1 1-20 0 10 10 0 0 1 20 0ZM9 9l6 6m0-6-6 6`},running:{label:`Running`,color:`var(--colors-dashboard-info, #2563eb)`,path:`M12 3a9 9 0 1 1-9 9`},skipped:{label:`Skipped`,color:`var(--colors-dashboard-muted, #68717d)`,path:`m5 5 11 7-11 7V5Zm14 0v14`},unknown:{label:`Unknown`,color:`var(--colors-dashboard-warning, #b45309)`,path:`M22 12a10 10 0 1 1-20 0 10 10 0 0 1 20 0ZM9 9a3 3 0 1 1 4.8 2.4c-1.2.9-1.8 1.6-1.8 2.6m0 3h.01`},missing:{label:`No recorded attempts`,color:`var(--colors-dashboard-muted, #68717d)`,path:`M7 12h10`}};function r({value:r=`missing`}){let{label:i,color:a,path:o}=n[r];return t(e,{label:i,detail:i,style:{color:a,display:`inline-grid`,placeItems:`center`,width:28,height:28},children:t(`svg`,{"aria-hidden":`true`,width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.75`,strokeLinecap:`round`,strokeLinejoin:`round`,children:t(`path`,{d:o})})})}export{r as OutcomeIcon};
@@ -0,0 +1 @@
1
+ import{ValueTooltip as e}from"./value-tooltip.js";import{jsx as t}from"react/jsx-runtime";function n({busy:n,onRefresh:r}){return t(e,{label:`Refresh`,detail:`Refresh`,isPending:n,onPress:({target:e})=>{globalThis.matchMedia(`(prefers-reduced-motion: reduce)`).matches||e.querySelector(`svg`)?.animate([{scale:`0.88`},{scale:`1.1`,offset:.55},{scale:`1`}],{duration:240,easing:`ease-out`}),r()},style:({isHovered:e,isPending:t})=>({display:`inline-grid`,placeItems:`center`,width:36,height:36,borderRadius:8,backgroundColor:e?`color-mix(in srgb, var(--colors-dashboard-ink, #1f2937) 7%, transparent)`:`transparent`,transition:`background-color 150ms ease, opacity 150ms ease`,opacity:t?.55:1}),children:t(`svg`,{"aria-hidden":`true`,width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.75`,strokeLinecap:`round`,strokeLinejoin:`round`,children:t(`path`,{d:`M20 10a8 8 0 0 0-14-3L4 9m0-5v5h5m-5 5a8 8 0 0 0 14 3l2-2m0 5v-5h-5`})})})}export{n as RefreshButton};
@@ -0,0 +1 @@
1
+ import{Button as e,Tooltip as t,TooltipTrigger as n}from"react-aria-components";import{jsx as r,jsxs as i}from"react/jsx-runtime";function a({children:a,label:o,detail:s,isPending:c,onPress:l,style:u}){return i(n,{delay:200,children:[r(e,{"aria-label":o,isPending:c,onPress:l,style:e=>({padding:0,border:0,borderRadius:4,background:`transparent`,color:`inherit`,font:`inherit`,...typeof u==`function`?u(e):u}),children:a}),r(t,{offset:6,style:{zIndex:50,padding:`5px 8px`,borderRadius:4,background:`var(--colors-dashboard-ink, #242424)`,color:`var(--colors-dashboard-panel, #fff)`,fontSize:`0.8rem`},children:s})]})}export{a as ValueTooltip};
@@ -0,0 +1,168 @@
1
+ import { ScheduledJobHistoryStore } from "../scheduled-history.js";
2
+ import { NodePgClient } from "drizzle-orm/node-postgres";
3
+
4
+ //#region src/history/postgres.d.ts
5
+ /** Optional observation table. Re-export from the app schema and generate an additive migration. */
6
+ declare const scheduledJobAttempts: import("drizzle-orm/pg-core").PgTableWithColumns<{
7
+ name: "coreframe_job_attempts";
8
+ schema: undefined;
9
+ columns: {
10
+ id: import("drizzle-orm/pg-core").PgBuildColumn<"coreframe_job_attempts", import("drizzle-orm/pg-core").SetIsPrimaryKey<import("drizzle-orm/pg-core").PgTextBuilder<[string, ...string[]]>>, {
11
+ name: string;
12
+ tableName: "coreframe_job_attempts";
13
+ dataType: "string";
14
+ data: string;
15
+ driverParam: string;
16
+ notNull: true;
17
+ hasDefault: false;
18
+ isPrimaryKey: false;
19
+ isAutoincrement: false;
20
+ hasRuntimeDefault: false;
21
+ enumValues: undefined;
22
+ identity: undefined;
23
+ generated: undefined;
24
+ }>;
25
+ jobId: import("drizzle-orm/pg-core").PgBuildColumn<"coreframe_job_attempts", import("drizzle-orm/pg-core").SetNotNull<import("drizzle-orm/pg-core").PgTextBuilder<[string, ...string[]]>>, {
26
+ name: string;
27
+ tableName: "coreframe_job_attempts";
28
+ dataType: "string";
29
+ data: string;
30
+ driverParam: string;
31
+ notNull: true;
32
+ hasDefault: false;
33
+ isPrimaryKey: false;
34
+ isAutoincrement: false;
35
+ hasRuntimeDefault: false;
36
+ enumValues: undefined;
37
+ identity: undefined;
38
+ generated: undefined;
39
+ }>;
40
+ environment: import("drizzle-orm/pg-core").PgBuildColumn<"coreframe_job_attempts", import("drizzle-orm/pg-core").SetNotNull<import("drizzle-orm/pg-core").PgTextBuilder<[string, ...string[]]>>, {
41
+ name: string;
42
+ tableName: "coreframe_job_attempts";
43
+ dataType: "string";
44
+ data: string;
45
+ driverParam: string;
46
+ notNull: true;
47
+ hasDefault: false;
48
+ isPrimaryKey: false;
49
+ isAutoincrement: false;
50
+ hasRuntimeDefault: false;
51
+ enumValues: undefined;
52
+ identity: undefined;
53
+ generated: undefined;
54
+ }>;
55
+ cron: import("drizzle-orm/pg-core").PgBuildColumn<"coreframe_job_attempts", import("drizzle-orm/pg-core").SetNotNull<import("drizzle-orm/pg-core").PgTextBuilder<[string, ...string[]]>>, {
56
+ name: string;
57
+ tableName: "coreframe_job_attempts";
58
+ dataType: "string";
59
+ data: string;
60
+ driverParam: string;
61
+ notNull: true;
62
+ hasDefault: false;
63
+ isPrimaryKey: false;
64
+ isAutoincrement: false;
65
+ hasRuntimeDefault: false;
66
+ enumValues: undefined;
67
+ identity: undefined;
68
+ generated: undefined;
69
+ }>;
70
+ scheduledAt: import("drizzle-orm/pg-core").PgBuildColumn<"coreframe_job_attempts", import("drizzle-orm/pg-core").SetNotNull<import("drizzle-orm/pg-core").PgTimestampBuilder>, {
71
+ name: string;
72
+ tableName: "coreframe_job_attempts";
73
+ dataType: "object date";
74
+ data: Date;
75
+ driverParam: string;
76
+ notNull: true;
77
+ hasDefault: false;
78
+ isPrimaryKey: false;
79
+ isAutoincrement: false;
80
+ hasRuntimeDefault: false;
81
+ enumValues: undefined;
82
+ identity: undefined;
83
+ generated: undefined;
84
+ }>;
85
+ startedAt: import("drizzle-orm/pg-core").PgBuildColumn<"coreframe_job_attempts", import("drizzle-orm/pg-core").SetNotNull<import("drizzle-orm/pg-core").PgTimestampBuilder>, {
86
+ name: string;
87
+ tableName: "coreframe_job_attempts";
88
+ dataType: "object date";
89
+ data: Date;
90
+ driverParam: string;
91
+ notNull: true;
92
+ hasDefault: false;
93
+ isPrimaryKey: false;
94
+ isAutoincrement: false;
95
+ hasRuntimeDefault: false;
96
+ enumValues: undefined;
97
+ identity: undefined;
98
+ generated: undefined;
99
+ }>;
100
+ finishedAt: import("drizzle-orm/pg-core").PgBuildColumn<"coreframe_job_attempts", import("drizzle-orm/pg-core").PgTimestampBuilder, {
101
+ name: string;
102
+ tableName: "coreframe_job_attempts";
103
+ dataType: "object date";
104
+ data: Date;
105
+ driverParam: string;
106
+ notNull: false;
107
+ hasDefault: false;
108
+ isPrimaryKey: false;
109
+ isAutoincrement: false;
110
+ hasRuntimeDefault: false;
111
+ enumValues: undefined;
112
+ identity: undefined;
113
+ generated: undefined;
114
+ }>;
115
+ outcome: import("drizzle-orm/pg-core").PgBuildColumn<"coreframe_job_attempts", import("drizzle-orm/pg-core").SetNotNull<import("drizzle-orm/pg-core").PgTextBuilder<["unknown", "succeeded", "failed"]>>, {
116
+ name: string;
117
+ tableName: "coreframe_job_attempts";
118
+ dataType: "string enum";
119
+ data: "unknown" | "succeeded" | "failed";
120
+ driverParam: string;
121
+ notNull: true;
122
+ hasDefault: false;
123
+ isPrimaryKey: false;
124
+ isAutoincrement: false;
125
+ hasRuntimeDefault: false;
126
+ enumValues: ["unknown", "succeeded", "failed"];
127
+ identity: undefined;
128
+ generated: undefined;
129
+ }>;
130
+ durationMs: import("drizzle-orm/pg-core").PgBuildColumn<"coreframe_job_attempts", import("drizzle-orm/pg-core").PgIntegerBuilder, {
131
+ name: string;
132
+ tableName: "coreframe_job_attempts";
133
+ dataType: "number int32";
134
+ data: number;
135
+ driverParam: string | number;
136
+ notNull: false;
137
+ hasDefault: false;
138
+ isPrimaryKey: false;
139
+ isAutoincrement: false;
140
+ hasRuntimeDefault: false;
141
+ enumValues: undefined;
142
+ identity: undefined;
143
+ generated: undefined;
144
+ }>;
145
+ errorSummary: import("drizzle-orm/pg-core").PgBuildColumn<"coreframe_job_attempts", import("drizzle-orm/pg-core").PgTextBuilder<[string, ...string[]]>, {
146
+ name: string;
147
+ tableName: "coreframe_job_attempts";
148
+ dataType: "string";
149
+ data: string;
150
+ driverParam: string;
151
+ notNull: false;
152
+ hasDefault: false;
153
+ isPrimaryKey: false;
154
+ isAutoincrement: false;
155
+ hasRuntimeDefault: false;
156
+ enumValues: undefined;
157
+ identity: undefined;
158
+ generated: undefined;
159
+ }>;
160
+ };
161
+ dialect: "pg";
162
+ }>;
163
+ /** PostgreSQL observations only; never used to claim work or decide whether a job should run. */
164
+ declare function createScheduledJobHistoryStore(database: {
165
+ $client: NodePgClient;
166
+ }): ScheduledJobHistoryStore;
167
+ //#endregion
168
+ export { createScheduledJobHistoryStore, scheduledJobAttempts };
@@ -0,0 +1 @@
1
+ import{scheduledJobHistoryLimit as e}from"../scheduled-history.js";import{and as t,desc as n,eq as r,gte as i,inArray as a,lt as o,sql as s}from"drizzle-orm";import{drizzle as c}from"drizzle-orm/node-postgres";import{check as l,index as u,snakeCase as d}from"drizzle-orm/pg-core";const f=d.table(`coreframe_job_attempts`,e=>({id:e.text().primaryKey(),jobId:e.text().notNull(),environment:e.text().notNull(),cron:e.text().notNull(),scheduledAt:e.timestamp({withTimezone:!0}).notNull(),startedAt:e.timestamp({withTimezone:!0}).notNull(),finishedAt:e.timestamp({withTimezone:!0}),outcome:e.text({enum:[`unknown`,`succeeded`,`failed`]}).notNull(),durationMs:e.integer(),errorSummary:e.text()}),e=>[u(`coreframe_job_attempts_environment_started_idx`).on(e.environment,e.startedAt,e.id),l(`coreframe_job_attempts_outcome_check`,s`${e.outcome} in ('unknown', 'succeeded', 'failed')`),l(`coreframe_job_attempts_finished_check`,s`(${e.outcome} = 'unknown' and ${e.finishedAt} is null and ${e.durationMs} is null) or (${e.outcome} <> 'unknown' and ${e.finishedAt} is not null and ${e.durationMs} is not null)`),l(`coreframe_job_attempts_duration_check`,s`${e.durationMs} is null or ${e.durationMs} >= 0`)]);function p(s){let l=c({client:s.$client}),u={id:f.id,jobId:f.jobId,environment:f.environment,cron:f.cron,scheduledAt:f.scheduledAt,startedAt:f.startedAt,finishedAt:f.finishedAt,outcome:f.outcome,durationMs:f.durationMs,errorSummary:f.errorSummary};return{async write(i){await l.transaction(async s=>{await s.insert(f).values(i).onConflictDoUpdate({target:f.id,set:i});let c=new Date(Date.now()-30*864e5);await s.delete(f).where(t(r(f.environment,i.environment),o(f.startedAt,c)));let l=await s.select({id:f.id}).from(f).where(r(f.environment,i.environment)).orderBy(n(f.startedAt),n(f.id)).offset(e);l.length&&await s.delete(f).where(a(f.id,l.map(e=>e.id)))})},async list({environment:a}){let o=new Date(Date.now()-30*864e5);return l.select(u).from(f).where(t(r(f.environment,a),i(f.startedAt,o))).orderBy(n(f.startedAt),n(f.id)).limit(e)}}}export{p as createScheduledJobHistoryStore,f as scheduledJobAttempts};
@@ -0,0 +1,176 @@
1
+ import { ScheduledJobHistoryStore } from "../scheduled-history.js";
2
+ import { drizzle } from "drizzle-orm/libsql/web";
3
+
4
+ //#region src/history/sqlite.d.ts
5
+ /** Optional observation table. Re-export from the app schema and generate an additive migration. */
6
+ declare const scheduledJobAttempts: import("drizzle-orm/sqlite-core").SQLiteTableWithColumns<{
7
+ name: "coreframe_job_attempts";
8
+ schema: undefined;
9
+ columns: {
10
+ id: import("drizzle-orm/sqlite-core").SQLiteColumn<{
11
+ name: string;
12
+ tableName: "coreframe_job_attempts";
13
+ dataType: "string";
14
+ data: string;
15
+ driverParam: string;
16
+ notNull: true;
17
+ hasDefault: false;
18
+ isPrimaryKey: true;
19
+ isAutoincrement: false;
20
+ hasRuntimeDefault: false;
21
+ enumValues: [string, ...string[]];
22
+ baseColumn: never;
23
+ identity: undefined;
24
+ generated: undefined;
25
+ }, {}>;
26
+ jobId: import("drizzle-orm/sqlite-core").SQLiteColumn<{
27
+ name: string;
28
+ tableName: "coreframe_job_attempts";
29
+ dataType: "string";
30
+ data: string;
31
+ driverParam: string;
32
+ notNull: true;
33
+ hasDefault: false;
34
+ isPrimaryKey: false;
35
+ isAutoincrement: false;
36
+ hasRuntimeDefault: false;
37
+ enumValues: [string, ...string[]];
38
+ baseColumn: never;
39
+ identity: undefined;
40
+ generated: undefined;
41
+ }, {}>;
42
+ environment: import("drizzle-orm/sqlite-core").SQLiteColumn<{
43
+ name: string;
44
+ tableName: "coreframe_job_attempts";
45
+ dataType: "string";
46
+ data: string;
47
+ driverParam: string;
48
+ notNull: true;
49
+ hasDefault: false;
50
+ isPrimaryKey: false;
51
+ isAutoincrement: false;
52
+ hasRuntimeDefault: false;
53
+ enumValues: [string, ...string[]];
54
+ baseColumn: never;
55
+ identity: undefined;
56
+ generated: undefined;
57
+ }, {}>;
58
+ cron: import("drizzle-orm/sqlite-core").SQLiteColumn<{
59
+ name: string;
60
+ tableName: "coreframe_job_attempts";
61
+ dataType: "string";
62
+ data: string;
63
+ driverParam: string;
64
+ notNull: true;
65
+ hasDefault: false;
66
+ isPrimaryKey: false;
67
+ isAutoincrement: false;
68
+ hasRuntimeDefault: false;
69
+ enumValues: [string, ...string[]];
70
+ baseColumn: never;
71
+ identity: undefined;
72
+ generated: undefined;
73
+ }, {}>;
74
+ scheduledAt: import("drizzle-orm/sqlite-core").SQLiteColumn<{
75
+ name: string;
76
+ tableName: "coreframe_job_attempts";
77
+ dataType: "object date";
78
+ data: Date;
79
+ driverParam: number;
80
+ notNull: true;
81
+ hasDefault: false;
82
+ isPrimaryKey: false;
83
+ isAutoincrement: false;
84
+ hasRuntimeDefault: false;
85
+ enumValues: undefined;
86
+ baseColumn: never;
87
+ identity: undefined;
88
+ generated: undefined;
89
+ }, {}>;
90
+ startedAt: import("drizzle-orm/sqlite-core").SQLiteColumn<{
91
+ name: string;
92
+ tableName: "coreframe_job_attempts";
93
+ dataType: "object date";
94
+ data: Date;
95
+ driverParam: number;
96
+ notNull: true;
97
+ hasDefault: false;
98
+ isPrimaryKey: false;
99
+ isAutoincrement: false;
100
+ hasRuntimeDefault: false;
101
+ enumValues: undefined;
102
+ baseColumn: never;
103
+ identity: undefined;
104
+ generated: undefined;
105
+ }, {}>;
106
+ finishedAt: import("drizzle-orm/sqlite-core").SQLiteColumn<{
107
+ name: string;
108
+ tableName: "coreframe_job_attempts";
109
+ dataType: "object date";
110
+ data: Date;
111
+ driverParam: number;
112
+ notNull: false;
113
+ hasDefault: false;
114
+ isPrimaryKey: false;
115
+ isAutoincrement: false;
116
+ hasRuntimeDefault: false;
117
+ enumValues: undefined;
118
+ baseColumn: never;
119
+ identity: undefined;
120
+ generated: undefined;
121
+ }, {}>;
122
+ outcome: import("drizzle-orm/sqlite-core").SQLiteColumn<{
123
+ name: string;
124
+ tableName: "coreframe_job_attempts";
125
+ dataType: "string enum";
126
+ data: "unknown" | "succeeded" | "failed";
127
+ driverParam: string;
128
+ notNull: true;
129
+ hasDefault: false;
130
+ isPrimaryKey: false;
131
+ isAutoincrement: false;
132
+ hasRuntimeDefault: false;
133
+ enumValues: ["unknown", "succeeded", "failed"];
134
+ baseColumn: never;
135
+ identity: undefined;
136
+ generated: undefined;
137
+ }, {}>;
138
+ durationMs: import("drizzle-orm/sqlite-core").SQLiteColumn<{
139
+ name: string;
140
+ tableName: "coreframe_job_attempts";
141
+ dataType: "number int53";
142
+ data: number;
143
+ driverParam: number;
144
+ notNull: false;
145
+ hasDefault: false;
146
+ isPrimaryKey: false;
147
+ isAutoincrement: false;
148
+ hasRuntimeDefault: false;
149
+ enumValues: undefined;
150
+ baseColumn: never;
151
+ identity: undefined;
152
+ generated: undefined;
153
+ }, {}>;
154
+ errorSummary: import("drizzle-orm/sqlite-core").SQLiteColumn<{
155
+ name: string;
156
+ tableName: "coreframe_job_attempts";
157
+ dataType: "string";
158
+ data: string;
159
+ driverParam: string;
160
+ notNull: false;
161
+ hasDefault: false;
162
+ isPrimaryKey: false;
163
+ isAutoincrement: false;
164
+ hasRuntimeDefault: false;
165
+ enumValues: [string, ...string[]];
166
+ baseColumn: never;
167
+ identity: undefined;
168
+ generated: undefined;
169
+ }, {}>;
170
+ };
171
+ dialect: "sqlite";
172
+ }>;
173
+ /** SQLite/libSQL observations only; never used to claim work or decide whether a job should run. */
174
+ declare function createScheduledJobHistoryStore(database: Pick<ReturnType<typeof drizzle>, "$client">): ScheduledJobHistoryStore;
175
+ //#endregion
176
+ export { createScheduledJobHistoryStore, scheduledJobAttempts };
@@ -0,0 +1 @@
1
+ import{scheduledJobHistoryLimit as e}from"../scheduled-history.js";import{and as t,desc as n,eq as r,gte as i,inArray as a,lt as o,sql as s}from"drizzle-orm";import{drizzle as c}from"drizzle-orm/libsql/web";import{check as l,index as u,snakeCase as d}from"drizzle-orm/sqlite-core";const f=d.table(`coreframe_job_attempts`,e=>({id:e.text().primaryKey(),jobId:e.text().notNull(),environment:e.text().notNull(),cron:e.text().notNull(),scheduledAt:e.integer({mode:`timestamp_ms`}).notNull(),startedAt:e.integer({mode:`timestamp_ms`}).notNull(),finishedAt:e.integer({mode:`timestamp_ms`}),outcome:e.text({enum:[`unknown`,`succeeded`,`failed`]}).notNull(),durationMs:e.integer(),errorSummary:e.text()}),e=>[u(`coreframe_job_attempts_environment_started_idx`).on(e.environment,e.startedAt,e.id),l(`coreframe_job_attempts_outcome_check`,s`${e.outcome} in ('unknown', 'succeeded', 'failed')`),l(`coreframe_job_attempts_finished_check`,s`(${e.outcome} = 'unknown' and ${e.finishedAt} is null and ${e.durationMs} is null) or (${e.outcome} <> 'unknown' and ${e.finishedAt} is not null and ${e.durationMs} is not null)`),l(`coreframe_job_attempts_duration_check`,s`${e.durationMs} is null or ${e.durationMs} >= 0`)]);function p(s){let l=c({client:s.$client}),u={id:f.id,jobId:f.jobId,environment:f.environment,cron:f.cron,scheduledAt:f.scheduledAt,startedAt:f.startedAt,finishedAt:f.finishedAt,outcome:f.outcome,durationMs:f.durationMs,errorSummary:f.errorSummary};return{async write(i){await l.transaction(async s=>{await s.insert(f).values(i).onConflictDoUpdate({target:f.id,set:i});let c=new Date(Date.now()-30*864e5);await s.delete(f).where(t(r(f.environment,i.environment),o(f.startedAt,c)));let l=await s.select({id:f.id}).from(f).where(r(f.environment,i.environment)).orderBy(n(f.startedAt),n(f.id)).limit(2147483647).offset(e);l.length&&await s.delete(f).where(a(f.id,l.map(e=>e.id)))})},async list({environment:a}){let o=new Date(Date.now()-30*864e5);return l.select(u).from(f).where(t(r(f.environment,a),i(f.startedAt,o))).orderBy(n(f.startedAt),n(f.id)).limit(e)}}}export{p as createScheduledJobHistoryStore,f as scheduledJobAttempts};
package/dist/index.d.ts CHANGED
@@ -1,15 +1,23 @@
1
1
  import { JobCooldown, defaultJobLeaseMs, parseJobCooldown } from "./definition.js";
2
2
  import { DevelopmentJobAttempt, DevelopmentJobHistoryStore, developmentJobAttemptOutcome, developmentJobHistoryLimit, developmentJobHistoryRetentionDays } from "./development-history.js";
3
3
  import { DevelopmentJobDefinition, DevelopmentJobStateAdmin, DevelopmentJobStateRecord, DevelopmentJobStateResetResult, DevelopmentJobStatus, DevelopmentJobs, defineDevelopmentJob, defineDevelopmentJobs, inspectDevelopmentJobStates } from "./development-state.js";
4
+ import { ScheduledJobAttempt, ScheduledJobHistoryStore, readScheduledJobsSnapshot, scheduledJobFailureSummary, scheduledJobHistoryLimit, scheduledJobHistoryRetentionDays } from "./scheduled-history.js";
4
5
 
5
6
  //#region src/index.d.ts
7
+ /** Context and logical invocation time supplied to a job handler. */
6
8
  type JobInvocation<TContext> = {
7
- context: TContext;
9
+ context: TContext; /** The trigger's scheduled time for scheduled jobs; not their actual start time. */
8
10
  now: Date;
9
11
  };
12
+ /** Host cron expressions that opt a job into scheduled execution. */
13
+ type JobSchedule = {
14
+ /** Exact host expressions, including spacing. Registration does not provision triggers. */crons: readonly string[];
15
+ };
16
+ /** A reusable handler with independent development and scheduled opt-ins. */
10
17
  type JobDefinition<TContext> = {
11
18
  id: string;
12
- run(invocation: JobInvocation<TContext>): Promise<void> | void;
19
+ run(invocation: JobInvocation<TContext>): Promise<void> | void; /** Selects this job for matching delivered cron events, without persistence or leases. */
20
+ scheduled?: JobSchedule;
13
21
  dev?: {
14
22
  cooldown: JobCooldown;
15
23
  leaseMs?: number;
@@ -49,8 +57,17 @@ type JobExecutionResult = {
49
57
  id: string;
50
58
  status: "completed" | "failed" | "skipped-cooldown" | "skipped-running";
51
59
  };
60
+ /** One completed handler attempt for a delivered cron event; not durable execution state. */
61
+ type ScheduledJobExecutionResult = JobExecutionResult & {
62
+ cron: string;
63
+ scheduledAt: Date;
64
+ status: "completed" | "failed";
65
+ };
66
+ /** Validates a job's ID and optional development and scheduled policies. */
52
67
  declare function defineJob<TContext>(definition: JobDefinition<TContext>): JobDefinition<TContext>;
68
+ /** Validates job policies and rejects duplicate IDs within a registry. */
53
69
  declare function defineJobRegistry<TContext>(jobs: JobRegistry<TContext>): JobRegistry<TContext>;
70
+ /** Runs every supplied job sequentially, without applying development or scheduled policies. */
54
71
  declare function runJobs<TContext>({
55
72
  createContext,
56
73
  jobs,
@@ -62,6 +79,40 @@ declare function runJobs<TContext>({
62
79
  now?: Date;
63
80
  onError?: "continue" | "throw";
64
81
  }): Promise<JobExecutionResult[]>;
82
+ /**
83
+ * Runs only jobs explicitly registered for the delivered cron expression, in registry order.
84
+ *
85
+ * @remarks
86
+ * Matching is exact; this does not parse cron expressions or create timers. An unmatched event
87
+ * returns an empty array without creating context. Each handler receives `scheduledAt` as `now`.
88
+ * There are no leases, retries, duplicate suppression, or interrupted-work recovery. Handlers
89
+ * must tolerate overlapping or repeated invocations. Optional history records best-effort start
90
+ * and finish observations independently of execution. Returned results may contain sensitive
91
+ * thrown payloads in `error`; never persist these directly. Handler failures return failed
92
+ * results by default so independent jobs can finish. Hosts should inspect those results and
93
+ * reject their invocation when a job failed. `onError: "throw"` instead stops at the first
94
+ * handler failure. Context-creation failures always reject.
95
+ * @throws When the cron is empty, the scheduled date is invalid, context creation fails, or a
96
+ * handler fails with `onError: "throw"`.
97
+ */
98
+ declare function runScheduledJobs<TContext>({
99
+ createContext,
100
+ cron,
101
+ history,
102
+ jobs,
103
+ onError,
104
+ scheduledAt
105
+ }: {
106
+ createContext(scheduledAt: Date): Promise<TContext> | TContext;
107
+ cron: string;
108
+ history?: {
109
+ environment: string;
110
+ store: ScheduledJobHistoryStore;
111
+ };
112
+ jobs: JobRegistry<TContext>;
113
+ onError?: "continue" | "throw";
114
+ scheduledAt: Date;
115
+ }): Promise<ScheduledJobExecutionResult[]>;
65
116
  declare function runDevelopmentJobs<TContext>({
66
117
  createContext,
67
118
  history,
@@ -78,4 +129,4 @@ declare function runDevelopmentJobs<TContext>({
78
129
  state: JobStateStore;
79
130
  }): Promise<JobExecutionResult[]>;
80
131
  //#endregion
81
- export { DevelopmentJobAttempt, DevelopmentJobDefinition, DevelopmentJobHistoryStore, DevelopmentJobStateAdmin, DevelopmentJobStateRecord, DevelopmentJobStateResetResult, DevelopmentJobStatus, DevelopmentJobs, JobCooldown, JobDefinition, JobExecutionResult, JobInvocation, JobRegistry, JobStateClaim, JobStateStore, defaultJobLeaseMs, defineDevelopmentJob, defineDevelopmentJobs, defineJob, defineJobRegistry, developmentJobAttemptOutcome, developmentJobHistoryLimit, developmentJobHistoryRetentionDays, inspectDevelopmentJobStates, parseJobCooldown, runDevelopmentJobs, runJobs };
132
+ export { DevelopmentJobAttempt, DevelopmentJobDefinition, DevelopmentJobHistoryStore, DevelopmentJobStateAdmin, DevelopmentJobStateRecord, DevelopmentJobStateResetResult, DevelopmentJobStatus, DevelopmentJobs, JobCooldown, JobDefinition, JobExecutionResult, JobInvocation, JobRegistry, JobSchedule, JobStateClaim, JobStateStore, ScheduledJobAttempt, ScheduledJobExecutionResult, ScheduledJobHistoryStore, defaultJobLeaseMs, defineDevelopmentJob, defineDevelopmentJobs, defineJob, defineJobRegistry, developmentJobAttemptOutcome, developmentJobHistoryLimit, developmentJobHistoryRetentionDays, inspectDevelopmentJobStates, parseJobCooldown, readScheduledJobsSnapshot, runDevelopmentJobs, runJobs, runScheduledJobs, scheduledJobFailureSummary, scheduledJobHistoryLimit, scheduledJobHistoryRetentionDays };
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{defaultJobLeaseMs as e,parseJobCooldown as t}from"./definition.js";import{defineDevelopmentJob as n,defineDevelopmentJobs as r,inspectDevelopmentJobStates as i}from"./development-state.js";import{developmentJobAttemptOutcome as a,developmentJobHistoryLimit as o,developmentJobHistoryRetentionDays as s}from"./development-history.js";function c(e){return p(e),e}function l(e){let t=new Set;for(let n of e){if(p(n),t.has(n.id))throw Error(`Duplicate Coreframe job ID ${JSON.stringify(n.id)}.`);t.add(n.id)}return e}async function u({createContext:e,jobs:t,now:n=new Date,onError:r=`continue`}){let i=await e(n),a=[];for(let e of t)a.push(await f({context:i,job:e,now:n,onError:r}));return a}async function d({createContext:e,history:n,jobs:r,now:i=new Date,onError:a=`continue`,state:o}){let s=r.filter(e=>e.dev?.onStartup);if(s.length===0)return[];let c=await e(i),l=[];for(let e of s){let r=e.dev,s=new Date,u=r.leaseMs??6e5,d={id:crypto.randomUUID(),jobId:e.id,startedAt:s,finishedAt:null,leaseUntil:new Date(i.getTime()+u),outcome:`running`,skipReason:null,durationMs:null,errorSummary:null},p=async()=>{try{await n?.write({...d})}catch{console.debug(`Coreframe development job history could not be recorded.`,{jobId:e.id})}},m=!1;try{let n=await o.claim({cooldownMs:t(r.cooldown),jobId:e.id,leaseMs:u,now:i});if(n.status!==`claimed`)d.outcome=`skipped`,d.skipReason=n.status===`cooldown`?`cooldown`:`already-running`,d.leaseUntil=null,l.push({durationMs:0,id:e.id,status:n.status===`cooldown`?`skipped-cooldown`:`skipped-running`});else{m=!0,await p();let t=await f({context:c,job:e,now:i,onError:a,state:o,leaseId:n.leaseId});d.outcome=t.status===`completed`?`succeeded`:`failed`,d.errorSummary=d.outcome===`failed`?`Job execution or state finalization failed. Inspect local dev logs for details.`:null,l.push(t)}}catch(t){if(d.outcome=`failed`,d.errorSummary=`Job claim, execution, or state finalization failed. Inspect local dev logs for details.`,!m||a===`throw`)throw t;l.push({durationMs:0,error:t,id:e.id,status:`failed`})}finally{d.finishedAt=new Date,d.durationMs=Math.max(0,d.finishedAt.getTime()-s.getTime()),await p()}}return l}async function f({context:e,job:t,leaseId:n,now:r,onError:i,state:a}){let o=Date.now();try{return await t.run({context:e,now:r}),a&&n&&await a.complete({jobId:t.id,leaseId:n,now:r}),{durationMs:Date.now()-o,id:t.id,status:`completed`}}catch(e){if(a&&n&&await a.fail({jobId:t.id,leaseId:n,now:r}),i===`throw`)throw e;return{durationMs:Date.now()-o,error:e,id:t.id,status:`failed`}}}function p(e){if(!e.id.trim())throw Error(`Coreframe job IDs cannot be empty.`);if(e.dev){let n=t(e.dev.cooldown);if(!Number.isSafeInteger(e.dev.leaseMs??6e5)||(e.dev.leaseMs??6e5)<=0)throw Error(`Coreframe job ${JSON.stringify(e.id)} must have a positive lease.`);if(n<0)throw Error(`Coreframe job ${JSON.stringify(e.id)} must have a non-negative cooldown.`)}}export{e as defaultJobLeaseMs,n as defineDevelopmentJob,r as defineDevelopmentJobs,c as defineJob,l as defineJobRegistry,a as developmentJobAttemptOutcome,o as developmentJobHistoryLimit,s as developmentJobHistoryRetentionDays,i as inspectDevelopmentJobStates,t as parseJobCooldown,d as runDevelopmentJobs,u as runJobs};
1
+ import{defaultJobLeaseMs as e,parseJobCooldown as t}from"./definition.js";import{readScheduledJobsSnapshot as n,scheduledJobFailureSummary as r,scheduledJobHistoryLimit as i,scheduledJobHistoryRetentionDays as a}from"./scheduled-history.js";import{defineDevelopmentJob as o,defineDevelopmentJobs as s,inspectDevelopmentJobStates as c}from"./development-state.js";import{developmentJobAttemptOutcome as l,developmentJobHistoryLimit as u,developmentJobHistoryRetentionDays as d}from"./development-history.js";function f(e){return v(e),e}function p(e){let t=new Set;for(let n of e){if(v(n),t.has(n.id))throw Error(`Duplicate Coreframe job ID ${JSON.stringify(n.id)}.`);t.add(n.id)}return e}async function m({createContext:e,jobs:t,now:n=new Date,onError:r=`continue`}){let i=await e(n),a=[];for(let e of t)a.push(await _({context:i,job:e,now:n,onError:r}));return a}async function h({createContext:e,cron:t,history:n,jobs:i,onError:a=`continue`,scheduledAt:o}){if(!t.trim())throw Error(`Coreframe scheduled jobs require a non-empty cron expression.`);if(!Number.isFinite(o.getTime()))throw Error(`Coreframe scheduled jobs require a valid scheduled time.`);if(n&&!n.environment.trim())throw Error(`Coreframe scheduled job history requires a non-empty environment.`);let s=i.filter(e=>e.scheduled?.crons.includes(t));if(s.length===0)return[];let c,l=!1,u=[];for(let i of s){let s={id:crypto.randomUUID(),jobId:i.id,environment:n?.environment??``,cron:t,scheduledAt:o,startedAt:new Date,finishedAt:null,outcome:`unknown`,durationMs:null,errorSummary:null},d=async()=>{try{await n?.store.write({...s})}catch{console.warn(`Coreframe scheduled job history could not be recorded.`,{jobId:i.id})}};await d();try{l||=(c=await e(o),!0);let n=await _({context:c,job:i,now:o,onError:a});s.outcome=n.status===`completed`?`succeeded`:`failed`,u.push({...n,cron:t,scheduledAt:o})}catch(e){throw s.outcome=`failed`,e}finally{s.finishedAt=new Date,s.durationMs=Math.max(0,s.finishedAt.getTime()-s.startedAt.getTime()),s.errorSummary=s.outcome===`failed`?r:null,await d()}}return u}async function g({createContext:e,history:n,jobs:r,now:i=new Date,onError:a=`continue`,state:o}){let s=r.filter(e=>e.dev?.onStartup);if(s.length===0)return[];let c=await e(i),l=[];for(let e of s){let r=e.dev,s=new Date,u=r.leaseMs??6e5,d={id:crypto.randomUUID(),jobId:e.id,startedAt:s,finishedAt:null,leaseUntil:new Date(i.getTime()+u),outcome:`running`,skipReason:null,durationMs:null,errorSummary:null},f=async()=>{try{await n?.write({...d})}catch{console.debug(`Coreframe development job history could not be recorded.`,{jobId:e.id})}},p=!1;try{let n=await o.claim({cooldownMs:t(r.cooldown),jobId:e.id,leaseMs:u,now:i});if(n.status!==`claimed`)d.outcome=`skipped`,d.skipReason=n.status===`cooldown`?`cooldown`:`already-running`,d.leaseUntil=null,l.push({durationMs:0,id:e.id,status:n.status===`cooldown`?`skipped-cooldown`:`skipped-running`});else{p=!0,await f();let t=await _({context:c,job:e,now:i,onError:a,state:o,leaseId:n.leaseId});d.outcome=t.status===`completed`?`succeeded`:`failed`,d.errorSummary=d.outcome===`failed`?`Job execution or state finalization failed. Inspect local dev logs for details.`:null,l.push(t)}}catch(t){if(d.outcome=`failed`,d.errorSummary=`Job claim, execution, or state finalization failed. Inspect local dev logs for details.`,!p||a===`throw`)throw t;l.push({durationMs:0,error:t,id:e.id,status:`failed`})}finally{d.finishedAt=new Date,d.durationMs=Math.max(0,d.finishedAt.getTime()-s.getTime()),await f()}}return l}async function _({context:e,job:t,leaseId:n,now:r,onError:i,state:a}){let o=Date.now();try{return await t.run({context:e,now:r}),a&&n&&await a.complete({jobId:t.id,leaseId:n,now:r}),{durationMs:Date.now()-o,id:t.id,status:`completed`}}catch(e){if(a&&n&&await a.fail({jobId:t.id,leaseId:n,now:r}),i===`throw`)throw e;return{durationMs:Date.now()-o,error:e,id:t.id,status:`failed`}}}function v(e){if(!e.id.trim())throw Error(`Coreframe job IDs cannot be empty.`);if(e.scheduled){let{crons:t}=e.scheduled;if(t.length===0||t.some(e=>!e.trim()))throw Error(`Coreframe job ${JSON.stringify(e.id)} must declare non-empty crons.`);if(new Set(t).size!==t.length)throw Error(`Coreframe job ${JSON.stringify(e.id)} has duplicate cron expressions.`)}if(e.dev){let n=t(e.dev.cooldown);if(!Number.isSafeInteger(e.dev.leaseMs??6e5)||(e.dev.leaseMs??6e5)<=0)throw Error(`Coreframe job ${JSON.stringify(e.id)} must have a positive lease.`);if(n<0)throw Error(`Coreframe job ${JSON.stringify(e.id)} must have a non-negative cooldown.`)}}export{e as defaultJobLeaseMs,o as defineDevelopmentJob,s as defineDevelopmentJobs,f as defineJob,p as defineJobRegistry,l as developmentJobAttemptOutcome,u as developmentJobHistoryLimit,d as developmentJobHistoryRetentionDays,c as inspectDevelopmentJobStates,t as parseJobCooldown,n as readScheduledJobsSnapshot,g as runDevelopmentJobs,m as runJobs,h as runScheduledJobs,r as scheduledJobFailureSummary,i as scheduledJobHistoryLimit,a as scheduledJobHistoryRetentionDays};
@@ -0,0 +1,43 @@
1
+ import { z } from "zod";
2
+
3
+ //#region src/scheduled-dashboard/api.d.ts
4
+ /** Safe browser projection of retained observations, separate from execution state. */
5
+ declare const ScheduledJobsSnapshot: z.ZodObject<{
6
+ environment: z.ZodString;
7
+ historyAvailable: z.ZodBoolean;
8
+ notice: z.ZodNullable<z.ZodString>;
9
+ jobs: z.ZodArray<z.ZodObject<{
10
+ id: z.ZodString;
11
+ crons: z.ZodArray<z.ZodString>;
12
+ registration: z.ZodEnum<{
13
+ configured: "configured";
14
+ orphaned: "orphaned";
15
+ }>;
16
+ lastAttemptAt: z.ZodNullable<z.ZodString>;
17
+ latestOutcome: z.ZodEnum<{
18
+ unknown: "unknown";
19
+ succeeded: "succeeded";
20
+ failed: "failed";
21
+ }>;
22
+ lastSucceededAt: z.ZodNullable<z.ZodString>;
23
+ }, z.core.$strip>>;
24
+ attempts: z.ZodArray<z.ZodObject<{
25
+ id: z.ZodString;
26
+ jobId: z.ZodString;
27
+ environment: z.ZodString;
28
+ cron: z.ZodString;
29
+ scheduledAt: z.ZodString;
30
+ startedAt: z.ZodString;
31
+ finishedAt: z.ZodNullable<z.ZodString>;
32
+ outcome: z.ZodEnum<{
33
+ unknown: "unknown";
34
+ succeeded: "succeeded";
35
+ failed: "failed";
36
+ }>;
37
+ durationMs: z.ZodNullable<z.ZodNumber>;
38
+ errorSummary: z.ZodNullable<z.ZodString>;
39
+ }, z.core.$strip>>;
40
+ }, z.core.$strip>;
41
+ type ScheduledJobsSnapshot = z.infer<typeof ScheduledJobsSnapshot>;
42
+ //#endregion
43
+ export { ScheduledJobsSnapshot };
@@ -0,0 +1 @@
1
+ import{z as e}from"zod";const t=e.enum([`unknown`,`succeeded`,`failed`]),n=e.object({environment:e.string(),historyAvailable:e.boolean(),notice:e.string().nullable(),jobs:e.array(e.object({id:e.string(),crons:e.array(e.string()),registration:e.enum([`configured`,`orphaned`]),lastAttemptAt:e.string().nullable(),latestOutcome:t,lastSucceededAt:e.string().nullable()})),attempts:e.array(e.object({id:e.string(),jobId:e.string(),environment:e.string(),cron:e.string(),scheduledAt:e.string(),startedAt:e.string(),finishedAt:e.string().nullable(),outcome:t,durationMs:e.number().nullable(),errorSummary:e.string().nullable()}))});export{n as ScheduledJobsSnapshot};
@@ -0,0 +1,13 @@
1
+ import { DashboardEnvironment, DashboardPlugin } from "@coreframe/dashboard/config";
2
+
3
+ //#region src/scheduled-dashboard/index.d.ts
4
+ /** A read-only page backed by the hosting app's authenticated history API. */
5
+ declare function scheduledJobs({
6
+ pageModule,
7
+ environments
8
+ }: {
9
+ pageModule: string;
10
+ environments?: readonly DashboardEnvironment[];
11
+ }): DashboardPlugin;
12
+ //#endregion
13
+ export { scheduledJobs };
@@ -0,0 +1 @@
1
+ import{definePlugin as e}from"@coreframe/dashboard/config";function t({pageModule:t,environments:n}){return e({id:`scheduled-jobs`,navigation:{path:`jobs`,title:`Jobs`,icon:`list-check`,environments:n},pageModule:t})}export{t as scheduledJobs};
@@ -0,0 +1,18 @@
1
+ import { ScheduledJobsSnapshot } from "./api.js";
2
+ import { DashboardAppSession } from "@coreframe/dashboard/app-client";
3
+
4
+ //#region src/scheduled-dashboard/page.d.ts
5
+ /** The app owns authorization, environment selection and the scheduled database connection. */
6
+ declare function ScheduledJobsPage({
7
+ cronDayOfWeekStartIndexZero,
8
+ includeLocalStartup,
9
+ loadSnapshot,
10
+ session
11
+ }: {
12
+ /** Set to false for schedulers that number Sunday as 1, including Cloudflare Workers. */cronDayOfWeekStartIndexZero?: boolean;
13
+ includeLocalStartup?: boolean;
14
+ loadSnapshot(signal: AbortSignal): Promise<ScheduledJobsSnapshot>;
15
+ session?: DashboardAppSession;
16
+ }): import("react").JSX.Element;
17
+ //#endregion
18
+ export { ScheduledJobsPage as default };
@@ -0,0 +1 @@
1
+ import{api as e}from"../dashboard/api.js";import{ValueTooltip as t}from"../dashboard-ui/value-tooltip.js";import{OutcomeIcon as n}from"../dashboard-ui/outcome-icon.js";import{RefreshButton as r}from"../dashboard-ui/refresh-button.js";import{TriggerIcon as i,triggerLabels as a}from"./trigger-icon.js";import{createClient as o}from"@coreframe/dashboard/api";import{Field as s,Page as c,PageHeader as l,Section as u,Tabs as d}from"@coreframe/dashboard/ui";import{skipToken as f,useQuery as p}from"@tanstack/react-query";import{useEffect as m,useState as h,useSyncExternalStore as g}from"react";import{Fragment as _,jsx as v,jsxs as y}from"react/jsx-runtime";import{DashboardAppResponseError as b}from"@coreframe/dashboard/app-client";import x from"cronstrue";const S={padding:`10px 14px`,textAlign:`left`,borderBottom:`1px solid var(--colors-dashboard-border, #8884)`,verticalAlign:`top`},C={display:`flex`,gap:16,flexWrap:`wrap`,marginBottom:16},w=new Intl.DateTimeFormat(void 0,{year:`numeric`,month:`short`,day:`numeric`,hour:`numeric`,minute:`2-digit`,second:`2-digit`,timeZoneName:`short`}),T=()=>()=>{},E=()=>void 0;function D({cronDayOfWeekStartIndexZero:t=!0,includeLocalStartup:n=!1,loadSnapshot:i,session:a}){let[_,x]=h(`jobs`),[S,w]=h(``),[D,A]=h(``),[j,M]=h(``),[N,I]=h(``),[L,R]=h(Date.now);m(()=>{let e=globalThis.setInterval(()=>R(Date.now()),1e3);return()=>globalThis.clearInterval(e)},[]);let z=g(a?.subscribe??T,a?.get??E,a?.get??E)?.status,B=!a||z===`authenticated`,V=p({queryKey:[`dashboard`,`scheduled-jobs`,`snapshot`],queryFn:B?({signal:e})=>i(e):f,refetchInterval:3e4,retry:!1}),H=p({queryKey:[`dashboard`,`dev-jobs`,`snapshot`],queryFn:n?({signal:t})=>o(e).queries.snapshot({signal:t}):f,refetchInterval:3e3,retry:!1}),U=V.error instanceof b&&(V.error.status===401||V.error.status===403),W=B&&!U?V.data:void 0,G=n?H.data:void 0,K=new Map;for(let e of W?.jobs??[])K.set(e.id,{id:e.id,cron:e});for(let e of G?.jobs??[])K.set(e.id,{...K.get(e.id),id:e.id,local:e});let q=[...K.values()].sort((e,t)=>e.id.localeCompare(t.id)),J=[...(G?.attempts??[]).map(e=>({trigger:`local`,record:e})),...(W?.attempts??[]).map(e=>({trigger:`cron`,record:e}))];J.sort((e,t)=>Date.parse(t.record.startedAt)-Date.parse(e.record.startedAt));let Y=new Map;for(let e of J)e.trigger===`local`&&!Y.has(e.record.jobId)&&Y.set(e.record.jobId,e.record);let X=[...new Set([...K.keys(),...J.map(({record:e})=>e.jobId)])].sort((e,t)=>e.localeCompare(t)),Z=q.filter(e=>!S||(S===`local`?e.local:e.cron)),Q=J.filter(({trigger:e,record:t})=>(!D||e===D)&&(!j||t.jobId===j)&&(!N||t.outcome===N));function $(){n&&H.refetch(),B?V.refetch():a?.refresh()}return y(c,{children:[y(l,{style:{marginBottom:`0.75rem`},children:[v(`h1`,{style:{alignSelf:`center`,fontSize:`0.875rem`},children:`Jobs`}),v(r,{busy:V.isFetching||H.isFetching||z===`checking`,onRefresh:$})]}),y(u,{"aria-label":`Jobs activity`,style:{paddingBlockStart:`0.5rem`},children:[z===`checking`&&v(`p`,{role:`status`,children:`Checking app session for cron jobs…`}),z===`unauthenticated`&&v(`p`,{role:`alert`,children:`Sign in to the app to view cron jobs.`}),z===`unknown`&&v(`p`,{role:`alert`,children:`Could not check the app session for cron jobs. Try refreshing.`}),B&&V.isPending&&v(`p`,{role:`status`,children:`Loading cron jobs…`}),B&&V.isError&&y(`p`,{role:`alert`,children:[U?`Cron jobs require current admin access.`:`Could not refresh cron jobs.`,W?` Showing the last successful snapshot.`:``]}),W?.notice&&y(`p`,{role:`status`,children:[`Cron: `,W.notice]}),n&&H.isPending&&v(`p`,{role:`status`,children:`Loading local startup jobs…`}),n&&H.isError&&y(`p`,{role:`alert`,children:[`Could not refresh local startup jobs. Check the local database and migrations.`,G?` Showing the last successful snapshot.`:``]}),G?.notice&&y(`p`,{role:`status`,children:[`Local startup: `,G.notice]}),(W||G)&&y(d,{value:_,onValueChange:x,children:[y(d.List,{children:[y(d.Trigger,{value:`jobs`,children:[`Jobs (`,q.length,`)`]}),y(d.Trigger,{value:`history`,children:[`History (`,J.length,`)`]})]}),y(d.Panel,{value:`jobs`,children:[n&&v(`div`,{style:C,children:v(O,{label:`Runs on`,value:S,onChange:w})}),Z.length?v(F,{headings:[`Job`,`Runs on`,`Latest outcome`,`Schedule`,`Last attempt`,`Last recorded success`],children:Z.map(e=>v(k,{id:e.id,local:S===`cron`?void 0:e.local,cron:S===`local`?void 0:e.cron,cronDayOfWeekStartIndexZero:t,latestLocal:Y.get(e.id),now:L},e.id))}):v(`p`,{children:`No matching jobs in the loaded sources.`})]}),y(d.Panel,{value:`history`,children:[y(`div`,{style:C,children:[v(s,{label:`Job`,children:y(`select`,{value:j,onChange:e=>M(e.target.value),children:[v(`option`,{value:``,children:`All jobs`}),X.map(e=>v(`option`,{children:e},e))]})}),n&&v(O,{label:`Trigger`,value:D,onChange:A}),v(s,{label:`Outcome`,children:y(`select`,{value:N,onChange:e=>I(e.target.value),children:[v(`option`,{value:``,children:`All outcomes`}),[`succeeded`,`failed`,`unknown`,...n?[`running`,`skipped`]:[]].map(e=>v(`option`,{children:e},e))]})})]}),v(`p`,{children:`Each source retains up to 1,000 attempts from the last 30 days. History may be incomplete. Unknown means no final outcome was recorded.`}),Q.length?v(F,{headings:[`Job`,`Trigger`,`Started`,`Duration`,`Outcome`,`Details`],children:v(`tbody`,{children:Q.map(e=>v(P,{attempt:e,now:L},`${e.trigger}:${e.record.id}`))})}):v(`p`,{children:`No matching attempts in the loaded history.`})]})]})]})]})}function O({label:e,value:t,onChange:n}){return v(s,{label:e,children:y(`select`,{value:t,onChange:e=>n(e.target.value),children:[v(`option`,{value:``,children:`All triggers`}),v(`option`,{value:`local`,children:a.local}),v(`option`,{value:`cron`,children:a.cron})]})})}function k({id:e,local:t,cron:r,cronDayOfWeekStartIndexZero:a,latestLocal:o,now:s}){let c=v(`th`,{scope:`rowgroup`,rowSpan:t&&r?2:1,style:{...S,fontWeight:`normal`},children:v(`code`,{children:e})});return y(`tbody`,{children:[t&&y(`tr`,{children:[c,v(`td`,{style:S,children:v(i,{trigger:`local`,orphaned:t.registration===`orphaned`})}),v(`td`,{style:S,children:v(n,{value:o?.outcome})}),v(`td`,{style:S,children:v(M,{job:t,now:s})}),v(`td`,{style:S,children:v(N,{value:o?.startedAt??null,now:s})}),v(`td`,{style:S,children:v(N,{value:t.lastSucceededAt,now:s})})]}),r&&y(`tr`,{children:[!t&&c,v(`td`,{style:S,children:v(i,{trigger:`cron`,orphaned:r.registration===`orphaned`})}),v(`td`,{style:S,children:v(n,{value:r.lastAttemptAt?r.latestOutcome:void 0})}),r.registration===`orphaned`?v(`td`,{style:S,children:`No longer configured`}):v(`td`,{style:{...S,padding:0},children:v(A,{expressions:r.crons,dayOfWeekStartIndexZero:a})}),v(`td`,{style:S,children:v(N,{value:r.lastAttemptAt,now:s})}),v(`td`,{style:S,children:v(N,{value:r.lastSucceededAt,now:s})})]})]})}function A({expressions:e,dayOfWeekStartIndexZero:n}){return e.length?v(t,{detail:e.map(e=>v(`div`,{children:v(`code`,{children:e})},e)),style:{display:`block`,width:`100%`,textAlign:`left`,padding:S.padding},children:e.map(e=>v(`span`,{style:{display:`block`},children:j(e,n)},e))}):v(`span`,{style:{display:`block`,padding:S.padding},children:`—`})}function j(e,t){try{return`${x.toString(e,{use24HourTimeFormat:!0,dayOfWeekStartIndexZero:t})} (UTC)`}catch{return`Schedule description unavailable`}}function M({job:e,now:t}){let n={cooldown:`Due`,due:`Due`,"never-run":`No recorded success`,unknown:`Unknown`}[e.eligibility],r=e.nextEligibleAt;return y(_,{children:[e.registration===`orphaned`?`No longer configured`:r&&Date.parse(r)>t?v(N,{value:r,now:t,context:`Eligible`}):n,e.lease===`active`&&e.leaseUntil&&y(`div`,{children:[`Lease ends `,v(N,{value:e.leaseUntil,now:t})]}),e.lease===`expired`&&v(`div`,{children:`Lease expired`})]})}function N({value:e,now:n,context:r}){let i=e===null?NaN:Date.parse(e);if(!Number.isFinite(i))return`—`;let a=i-n,o=Math.floor(Math.abs(a)/1e3),s=o>=86400?`${Math.floor(o/86400)}d`:o>=3600?`${Math.floor(o/3600)}h`:o>=60?`${Math.floor(o/60)}m`:`${o}s`,c=o===0?`now`:a>0?`in ${s}`:`${s} ago`,l=w.format(i);return v(t,{label:r&&`${r} ${c}`,detail:r?`${r} ${l}`:l,style:{whiteSpace:`nowrap`},children:v(`time`,{dateTime:new Date(i).toISOString(),children:c})})}function P({attempt:e,now:t}){let{record:r,trigger:i}=e;return y(`tr`,{children:[v(`td`,{style:S,children:v(`code`,{children:r.jobId})}),v(`td`,{style:S,children:a[i]}),v(`td`,{style:S,children:v(N,{value:r.startedAt,now:t})}),v(`td`,{style:S,children:r.durationMs===null?`—`:`${r.durationMs} ms`}),v(`td`,{style:S,children:v(n,{value:r.outcome})}),v(`td`,{style:S,children:y(`details`,{children:[v(`summary`,{children:`Attempt details`}),y(`dl`,{children:[v(`dt`,{children:`Attempt`}),v(`dd`,{children:v(`code`,{children:r.id})}),e.trigger===`cron`&&y(_,{children:[v(`dt`,{children:`Environment`}),v(`dd`,{children:e.record.environment}),v(`dt`,{children:`Cron`}),v(`dd`,{children:v(`code`,{children:e.record.cron})}),v(`dt`,{children:`Scheduled`}),v(`dd`,{children:v(N,{value:e.record.scheduledAt,now:t})})]}),v(`dt`,{children:`Finished`}),v(`dd`,{children:v(N,{value:r.finishedAt,now:t})}),e.trigger===`local`&&e.record.skipReason&&y(_,{children:[v(`dt`,{children:`Skipped because`}),v(`dd`,{children:e.record.skipReason===`cooldown`?`Cooldown has not elapsed`:`Another attempt holds the lease`})]}),r.errorSummary&&y(_,{children:[v(`dt`,{children:`Error`}),v(`dd`,{children:r.errorSummary})]})]})]})})]})}function F({children:e,headings:t}){return v(`div`,{style:{overflowX:`auto`},children:y(`table`,{style:{width:`100%`,borderCollapse:`collapse`,fontVariantNumeric:`tabular-nums`},children:[v(`thead`,{children:v(`tr`,{children:t.map(e=>v(`th`,{scope:`col`,style:S,children:e},e))})}),e]})})}export{D as default};
@@ -0,0 +1 @@
1
+ import{ValueTooltip as e}from"../dashboard-ui/value-tooltip.js";import{jsx as t}from"react/jsx-runtime";const n={local:`Local startup`,cron:`Cron`};function r({trigger:r,orphaned:i}){let a=n[r];return t(e,{label:a,detail:i?`${a} (no longer configured)`:a,style:{display:`inline-grid`,placeItems:`center`,width:28,height:28,opacity:i?.6:1},children:t(`svg`,{"aria-hidden":`true`,width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.75`,strokeLinecap:`round`,strokeLinejoin:`round`,children:r===`local`?t(`path`,{d:`m5 7 5 5-5 5m8 0h6`}):t(`path`,{d:`M12 7v5l3 2m6-2a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z`})})})}export{r as TriggerIcon,n as triggerLabels};
@@ -0,0 +1,42 @@
1
+ import { JobRegistry } from "./index.js";
2
+ import { ScheduledJobsSnapshot } from "./scheduled-dashboard/api.js";
3
+
4
+ //#region src/scheduled-history.d.ts
5
+ /** Best-effort observations; an unfinished attempt has an unknown outcome, not a live lease. */
6
+ type ScheduledJobAttempt = {
7
+ id: string;
8
+ jobId: string;
9
+ environment: string;
10
+ cron: string;
11
+ scheduledAt: Date;
12
+ startedAt: Date;
13
+ finishedAt: Date | null;
14
+ outcome: "unknown" | "succeeded" | "failed";
15
+ durationMs: number | null;
16
+ errorSummary: string | null;
17
+ };
18
+ /** Optional app-owned observations. Writes upsert by attempt ID; reads are environment-scoped. */
19
+ type ScheduledJobHistoryStore = {
20
+ write(attempt: ScheduledJobAttempt): Promise<void>;
21
+ list(input: {
22
+ environment: string;
23
+ }): Promise<ScheduledJobAttempt[]>;
24
+ };
25
+ /** Retention for the provided adapters; it is independent of execution and delivery semantics. */
26
+ declare const scheduledJobHistoryRetentionDays = 30;
27
+ /** Maximum retained observations per environment, and maximum returned by a snapshot. */
28
+ declare const scheduledJobHistoryLimit = 1000;
29
+ /** The runner's safe persisted summary. Thrown payloads are never copied into history. */
30
+ declare const scheduledJobFailureSummary = "Job execution or context creation failed. Check Worker logs.";
31
+ /** Reads a bounded snapshot without running jobs. Missing or unreadable history stays unknown. */
32
+ declare function readScheduledJobsSnapshot({
33
+ environment,
34
+ history,
35
+ jobs
36
+ }: {
37
+ environment: string;
38
+ history?: ScheduledJobHistoryStore;
39
+ jobs: ReadonlyArray<Pick<JobRegistry<unknown>[number], "id" | "scheduled">>;
40
+ }): Promise<ScheduledJobsSnapshot>;
41
+ //#endregion
42
+ export { ScheduledJobAttempt, ScheduledJobHistoryStore, readScheduledJobsSnapshot, scheduledJobFailureSummary, scheduledJobHistoryLimit, scheduledJobHistoryRetentionDays };
@@ -0,0 +1 @@
1
+ const e=30,t=1e3,n=`Job execution or context creation failed. Check Worker logs.`;async function r({environment:e,history:r,jobs:i}){let a=[],o=!1;if(r)try{let n=Date.now()-30*864e5;a=(await r.list({environment:e})).filter(t=>t.environment===e&&t.startedAt.getTime()>=n).sort((e,t)=>t.startedAt.getTime()-e.startedAt.getTime()||t.id.localeCompare(e.id)).slice(0,t),o=!0}catch{}let s=new Map(i.filter(e=>e.scheduled).map(e=>[e.id,e])),c=new Set([...s.keys(),...a.map(e=>e.jobId)]);return{environment:e,historyAvailable:o,notice:o?null:`History is unavailable. Configure a history store and apply its migration.`,jobs:[...c].sort().map(e=>{let t=s.get(e),n=a.find(t=>t.jobId===e),r=a.filter(t=>t.jobId===e&&t.outcome===`succeeded`&&t.finishedAt).reduce((e,t)=>!e||t.finishedAt>e?t.finishedAt:e,null);return{id:e,crons:[...t?.scheduled?.crons??[]],registration:t?`configured`:`orphaned`,lastAttemptAt:n?.startedAt.toISOString()??null,latestOutcome:n?.outcome??`unknown`,lastSucceededAt:r?.toISOString()??null}}),attempts:a.map(e=>({id:e.id,jobId:e.jobId,environment:e.environment,cron:e.cron,outcome:e.outcome,durationMs:e.durationMs,scheduledAt:e.scheduledAt.toISOString(),startedAt:e.startedAt.toISOString(),finishedAt:e.finishedAt?.toISOString()??null,errorSummary:e.outcome===`failed`?n:null}))}}export{r as readScheduledJobsSnapshot,n as scheduledJobFailureSummary,t as scheduledJobHistoryLimit,e as scheduledJobHistoryRetentionDays};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@coreframe/jobs",
3
- "version": "0.1.3",
3
+ "version": "0.2.1",
4
4
  "description": "Shared scheduled-job contracts and execution helpers for Coreframe apps",
5
5
  "repository": {
6
6
  "type": "git",
@@ -35,23 +35,58 @@
35
35
  "./dashboard/page": {
36
36
  "types": "./dist/dashboard/page.d.ts",
37
37
  "default": "./dist/dashboard/page.js"
38
+ },
39
+ "./history/postgres": {
40
+ "types": "./dist/history/postgres.d.ts",
41
+ "default": "./dist/history/postgres.js"
42
+ },
43
+ "./history/sqlite": {
44
+ "types": "./dist/history/sqlite.d.ts",
45
+ "default": "./dist/history/sqlite.js"
46
+ },
47
+ "./scheduled-dashboard": {
48
+ "types": "./dist/scheduled-dashboard/index.d.ts",
49
+ "default": "./dist/scheduled-dashboard/index.js"
50
+ },
51
+ "./scheduled-dashboard/api": {
52
+ "types": "./dist/scheduled-dashboard/api.d.ts",
53
+ "default": "./dist/scheduled-dashboard/api.js"
54
+ },
55
+ "./scheduled-dashboard/page": {
56
+ "types": "./dist/scheduled-dashboard/page.d.ts",
57
+ "default": "./dist/scheduled-dashboard/page.js"
38
58
  }
39
59
  },
40
60
  "dependencies": {
41
61
  "@tanstack/react-query": "^5.101.2",
62
+ "cronstrue": "^3.41.0",
42
63
  "react": "19.2.8",
64
+ "react-aria-components": "^1.22.1",
43
65
  "zod": "4.4.3",
44
- "@coreframe/dashboard": "^0.4.0",
45
- "@coreframe/db": "^0.2.1",
46
- "@coreframe/config": "^0.3.0"
66
+ "@coreframe/config": "^0.3.2",
67
+ "@coreframe/dashboard": "^0.4.2",
68
+ "@coreframe/db": "^0.2.4"
47
69
  },
48
70
  "devDependencies": {
71
+ "@libsql/client": "^0.17.4",
49
72
  "@types/node": "^26.1.0",
73
+ "@types/pg": "^8.20.0",
50
74
  "@types/react": "19.2.18",
75
+ "drizzle-orm": "1.0.0-rc.4",
76
+ "local-postgres": "0.3.1",
77
+ "pg": "^8.22.0",
51
78
  "tsdown": "0.22.3",
52
79
  "typescript": "6.0.3",
53
80
  "vitest": "^4.1.9"
54
81
  },
82
+ "peerDependencies": {
83
+ "drizzle-orm": "1.0.0-rc.4"
84
+ },
85
+ "peerDependenciesMeta": {
86
+ "drizzle-orm": {
87
+ "optional": true
88
+ }
89
+ },
55
90
  "scripts": {
56
91
  "build": "tsdown",
57
92
  "test": "vitest run --reporter=minimal",