@coreframe/jobs 0.1.2 → 0.2.0
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 +112 -4
- package/dist/dashboard/api.d.ts +2 -2
- package/dist/development-history.d.ts +1 -1
- package/dist/history/postgres.d.ts +168 -0
- package/dist/history/postgres.js +1 -0
- package/dist/history/sqlite.d.ts +176 -0
- package/dist/history/sqlite.js +1 -0
- package/dist/index.d.ts +54 -3
- package/dist/index.js +1 -1
- package/dist/scheduled-dashboard/api.d.ts +43 -0
- package/dist/scheduled-dashboard/api.js +1 -0
- package/dist/scheduled-dashboard/index.d.ts +11 -0
- package/dist/scheduled-dashboard/index.js +1 -0
- package/dist/scheduled-dashboard/page.d.ts +11 -0
- package/dist/scheduled-dashboard/page.js +1 -0
- package/dist/scheduled-history.d.ts +42 -0
- package/dist/scheduled-history.js +1 -0
- package/package.json +37 -4
package/README.md
CHANGED
|
@@ -1,6 +1,114 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Jobs
|
|
2
2
|
|
|
3
|
-
>
|
|
3
|
+
> Run explicitly registered cron jobs in production and inspect local development jobs separately.
|
|
4
|
+
|
|
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 through `DashboardAppSessionBoundary`. This preserves the dashboard's
|
|
99
|
+
boundary: deployed plugins do not receive app databases or credentials.
|
|
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. It shows recorded facts rather than next-run guarantees, leases,
|
|
108
|
+
retries, or manual controls. Worker logs remain the place for failure investigation. For logs-only
|
|
109
|
+
operation, omit `history` and the plugin; preserve previously applied migrations.
|
|
110
|
+
|
|
111
|
+
## Development job history
|
|
4
112
|
|
|
5
113
|
The template enables the read-only Dev jobs page at `/__dashboard/dev-jobs`:
|
|
6
114
|
|
|
@@ -21,7 +129,7 @@ shows attempts, including checks skipped because of cooldowns or active leases.
|
|
|
21
129
|
to the retained history. Expand an attempt for its timestamps, skip reason, and error summary.
|
|
22
130
|
The page refreshes every three seconds while visible.
|
|
23
131
|
|
|
24
|
-
|
|
132
|
+
### Connect project-owned storage
|
|
25
133
|
|
|
26
134
|
`runDevelopmentJobs` accepts an optional `history: DevelopmentJobHistoryStore` alongside its
|
|
27
135
|
scheduling `state`. The store upserts observations by attempt ID: a claimed job first records
|
|
@@ -38,7 +146,7 @@ database. A fresh local setup includes the history table. The template retains o
|
|
|
38
146
|
30 days, capped at 1,000 attempts. Writes prune older records; reads also exclude records older
|
|
39
147
|
than 30 days. Resetting job scheduling state preserves history; resetting the local database clears it.
|
|
40
148
|
|
|
41
|
-
|
|
149
|
+
### Interpret history
|
|
42
150
|
|
|
43
151
|
History is best effort. Failed writes emit a development debug message and never change execution
|
|
44
152
|
or lease completion. Missing observations do not establish that a job never ran. An unfinished
|
package/dist/dashboard/api.d.ts
CHANGED
|
@@ -7,10 +7,10 @@ declare const job: z.ZodObject<{
|
|
|
7
7
|
lastSucceededAt: z.ZodNullable<z.ZodString>;
|
|
8
8
|
nextEligibleAt: z.ZodNullable<z.ZodString>;
|
|
9
9
|
eligibility: z.ZodEnum<{
|
|
10
|
+
unknown: "unknown";
|
|
10
11
|
cooldown: "cooldown";
|
|
11
12
|
due: "due";
|
|
12
13
|
"never-run": "never-run";
|
|
13
|
-
unknown: "unknown";
|
|
14
14
|
}>;
|
|
15
15
|
lease: z.ZodEnum<{
|
|
16
16
|
active: "active";
|
|
@@ -30,9 +30,9 @@ declare const attempt: z.ZodObject<{
|
|
|
30
30
|
finishedAt: z.ZodNullable<z.ZodString>;
|
|
31
31
|
outcome: z.ZodEnum<{
|
|
32
32
|
unknown: "unknown";
|
|
33
|
-
running: "running";
|
|
34
33
|
succeeded: "succeeded";
|
|
35
34
|
failed: "failed";
|
|
35
|
+
running: "running";
|
|
36
36
|
skipped: "skipped";
|
|
37
37
|
}>;
|
|
38
38
|
skipReason: z.ZodNullable<z.ZodEnum<{
|
|
@@ -19,6 +19,6 @@ type DevelopmentJobHistoryStore = {
|
|
|
19
19
|
declare const developmentJobHistoryRetentionDays = 30;
|
|
20
20
|
declare const developmentJobHistoryLimit = 1000;
|
|
21
21
|
/** An unfinished attempt is not proof of failure, even after its lease expires. */
|
|
22
|
-
declare function developmentJobAttemptOutcome(attempt: DevelopmentJobAttempt, now: Date): "unknown" | "
|
|
22
|
+
declare function developmentJobAttemptOutcome(attempt: DevelopmentJobAttempt, now: Date): "unknown" | "succeeded" | "failed" | "running" | "skipped";
|
|
23
23
|
//#endregion
|
|
24
24
|
export { DevelopmentJobAttempt, DevelopmentJobHistoryStore, developmentJobAttemptOutcome, developmentJobHistoryLimit, developmentJobHistoryRetentionDays };
|
|
@@ -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{
|
|
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,11 @@
|
|
|
1
|
+
import { 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
|
+
}: {
|
|
8
|
+
pageModule: string;
|
|
9
|
+
}): DashboardPlugin;
|
|
10
|
+
//#endregion
|
|
11
|
+
export { scheduledJobs };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{definePlugin as e}from"@coreframe/dashboard/config";function t({pageModule:t}){return e({id:`scheduled-jobs`,navigation:{path:`jobs`,title:`Jobs`,icon:`list-check`},pageModule:t})}export{t as scheduledJobs};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { ScheduledJobsSnapshot } from "./api.js";
|
|
2
|
+
|
|
3
|
+
//#region src/scheduled-dashboard/page.d.ts
|
|
4
|
+
/** The app owns authorization, environment selection and the database connection. */
|
|
5
|
+
declare function ScheduledJobsPage({
|
|
6
|
+
loadSnapshot
|
|
7
|
+
}: {
|
|
8
|
+
loadSnapshot(signal: AbortSignal): Promise<ScheduledJobsSnapshot>;
|
|
9
|
+
}): import("react").JSX.Element;
|
|
10
|
+
//#endregion
|
|
11
|
+
export { ScheduledJobsPage as default };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Button as e,Field as t,Page as n,Section as r,Status as i,Tabs as a}from"@coreframe/dashboard/ui";import{useQuery as o}from"@tanstack/react-query";import{useState as s}from"react";import{jsx as c,jsxs as l}from"react/jsx-runtime";const u={padding:`10px 14px`,textAlign:`left`,borderBottom:`1px solid var(--colors-border, #8884)`,verticalAlign:`top`},d=e=>e?new Date(e).toLocaleString():`—`;function f({loadSnapshot:i}){let[f,h]=s(`jobs`),[g,_]=s(``),[v,y]=s(``),b=o({queryKey:[`dashboard`,`scheduled-jobs`,`snapshot`],queryFn:({signal:e})=>i(e),refetchInterval:3e4,retry:!1}),x=b.data,S=x?.attempts.filter(e=>(!g||e.jobId===g)&&(!v||e.outcome===v))??[];return c(n,{children:l(r,{title:`Jobs`,description:x?`Scheduled jobs · ${x.environment}`:`Scheduled jobs`,actions:c(e,{variant:`outline`,busy:b.isFetching,onClick:()=>void b.refetch(),children:`Refresh`}),children:[b.isPending&&c(`p`,{role:`status`,children:`Loading scheduled jobs…`}),b.isError&&l(`p`,{role:`alert`,children:[`Could not load scheduled jobs. Check your admin access and refresh.`,x?` Showing the last successful snapshot.`:``]}),x?.notice&&c(`p`,{role:`status`,children:x.notice}),c(`p`,{children:`Observations cover up to 30 days and 1,000 attempts per environment. Unknown outcomes may be unfinished or unrecorded. History does not confirm that a job is running or that every trigger was delivered.`}),x&&l(a,{value:f,onValueChange:h,children:[l(a.List,{children:[l(a.Trigger,{value:`jobs`,children:[`Jobs (`,x.jobs.length,`)`]}),l(a.Trigger,{value:`history`,children:[`History (`,x.attempts.length,`)`]})]}),c(a.Panel,{value:`jobs`,children:x.jobs.length===0?c(`p`,{children:`No scheduled jobs are configured or recorded.`}):c(m,{headings:[`Job`,`Cron triggers (UTC)`,`Latest outcome`,`Last attempt`,`Last recorded success`],children:x.jobs.map(e=>l(`tr`,{children:[l(`td`,{style:u,children:[c(`code`,{children:e.id}),e.registration===`orphaned`&&c(`p`,{children:`No longer configured`})]}),c(`td`,{style:u,children:e.crons.map(e=>c(`div`,{children:c(`code`,{children:e})},e))}),c(`td`,{style:u,children:c(p,{value:e.latestOutcome})}),c(`td`,{style:u,children:d(e.lastAttemptAt)}),c(`td`,{style:u,children:d(e.lastSucceededAt)})]},e.id))})}),l(a.Panel,{value:`history`,children:[c(t,{label:`Job`,children:l(`select`,{value:g,onChange:e=>_(e.target.value),children:[c(`option`,{value:``,children:`All jobs`}),x.jobs.map(e=>c(`option`,{children:e.id},e.id))]})}),c(t,{label:`Outcome`,children:l(`select`,{value:v,onChange:e=>y(e.target.value),children:[c(`option`,{value:``,children:`All outcomes`}),[`unknown`,`succeeded`,`failed`].map(e=>c(`option`,{children:e},e))]})}),S.length===0?c(`p`,{children:`No matching attempts are recorded.`}):c(m,{headings:[`Job`,`Environment`,`Outcome`,`Scheduled / started`,`Finished`,`Duration`,`Details`],children:S.map(e=>l(`tr`,{children:[c(`td`,{style:u,children:c(`code`,{children:e.jobId})}),c(`td`,{style:u,children:e.environment}),c(`td`,{style:u,children:c(p,{value:e.outcome})}),l(`td`,{style:u,children:[d(e.scheduledAt),c(`p`,{children:d(e.startedAt)})]}),c(`td`,{style:u,children:d(e.finishedAt)}),c(`td`,{style:u,children:e.durationMs===null?`—`:`${e.durationMs} ms`}),c(`td`,{style:u,children:l(`details`,{children:[c(`summary`,{children:`Attempt details`}),l(`p`,{children:[`ID: `,c(`code`,{children:e.id})]}),l(`p`,{children:[`Cron: `,c(`code`,{children:e.cron})]}),e.errorSummary&&c(`p`,{children:e.errorSummary})]})})]},e.id))})]})]})]})})}function p({value:e}){return c(i,{tone:e===`succeeded`?`success`:e===`failed`?`danger`:`neutral`,children:e})}function m({children:e,headings:t}){return c(`div`,{style:{overflowX:`auto`},children:l(`table`,{style:{width:`100%`,borderCollapse:`collapse`},children:[c(`thead`,{children:c(`tr`,{children:t.map(e=>c(`th`,{style:u,children:e},e))})}),c(`tbody`,{children:e})]})})}export{f as default};
|
|
@@ -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.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "Shared scheduled-job contracts and execution helpers for Coreframe apps",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -35,23 +35,56 @@
|
|
|
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",
|
|
42
62
|
"react": "19.2.8",
|
|
43
63
|
"zod": "4.4.3",
|
|
44
|
-
"@coreframe/config": "^0.
|
|
45
|
-
"@coreframe/dashboard": "^0.
|
|
46
|
-
"@coreframe/db": "^0.2.
|
|
64
|
+
"@coreframe/config": "^0.3.1",
|
|
65
|
+
"@coreframe/dashboard": "^0.4.1",
|
|
66
|
+
"@coreframe/db": "^0.2.3"
|
|
47
67
|
},
|
|
48
68
|
"devDependencies": {
|
|
69
|
+
"@libsql/client": "^0.17.4",
|
|
49
70
|
"@types/node": "^26.1.0",
|
|
71
|
+
"@types/pg": "^8.20.0",
|
|
50
72
|
"@types/react": "19.2.18",
|
|
73
|
+
"drizzle-orm": "1.0.0-rc.4",
|
|
74
|
+
"local-postgres": "0.3.1",
|
|
75
|
+
"pg": "^8.22.0",
|
|
51
76
|
"tsdown": "0.22.3",
|
|
52
77
|
"typescript": "6.0.3",
|
|
53
78
|
"vitest": "^4.1.9"
|
|
54
79
|
},
|
|
80
|
+
"peerDependencies": {
|
|
81
|
+
"drizzle-orm": "1.0.0-rc.4"
|
|
82
|
+
},
|
|
83
|
+
"peerDependenciesMeta": {
|
|
84
|
+
"drizzle-orm": {
|
|
85
|
+
"optional": true
|
|
86
|
+
}
|
|
87
|
+
},
|
|
55
88
|
"scripts": {
|
|
56
89
|
"build": "tsdown",
|
|
57
90
|
"test": "vitest run --reporter=minimal",
|