@coreframe/jobs 0.1.2-next.1 → 0.1.3

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 ADDED
@@ -0,0 +1,50 @@
1
+ # Development job history
2
+
3
+ > Inspect local startup jobs without changing their cooldowns, leases, or execution.
4
+
5
+ The template enables the read-only Dev jobs page at `/__dashboard/dev-jobs`:
6
+
7
+ ```ts
8
+ import { defineConfig } from "@coreframe/dashboard/config"
9
+ import { devJobs } from "@coreframe/jobs/dashboard"
10
+
11
+ export default defineConfig({ plugins: [devJobs()] })
12
+ ```
13
+
14
+ Remove `devJobs()` to disable the page and its API. Recording continues independently.
15
+ The plugin has no deployed implementation and is excluded from deployed dashboard builds.
16
+ It reads only the existing managed local PostgreSQL or SQLite/libSQL database; it does not
17
+ create a missing database or use deployment credentials.
18
+
19
+ The Jobs view combines configured jobs with persisted scheduling state. The History view
20
+ shows attempts, including checks skipped because of cooldowns or active leases. Filters apply
21
+ to the retained history. Expand an attempt for its timestamps, skip reason, and error summary.
22
+ The page refreshes every three seconds while visible.
23
+
24
+ ## Connect project-owned storage
25
+
26
+ `runDevelopmentJobs` accepts an optional `history: DevelopmentJobHistoryStore` alongside its
27
+ scheduling `state`. The store upserts observations by attempt ID: a claimed job first records
28
+ `running`, then its final outcome. Skipped checks record one completed observation. No dashboard
29
+ connection is required for recording.
30
+
31
+ Expose the same store from the configured `jobs.entry` module through
32
+ `developmentJobs.createHistoryStore(database)`. The template implements both paths in
33
+ `src/db/jobs.ts`; downstream SQLite/libSQL projects provide their corresponding Drizzle adapter.
34
+ The shared contracts do not depend on a database dialect.
35
+
36
+ After adopting the template schema change, run `pnpm db migrate-local` against an existing local
37
+ database. A fresh local setup includes the history table. The template retains observations for
38
+ 30 days, capped at 1,000 attempts. Writes prune older records; reads also exclude records older
39
+ than 30 days. Resetting job scheduling state preserves history; resetting the local database clears it.
40
+
41
+ ## Interpret history
42
+
43
+ History is best effort. Failed writes emit a development debug message and never change execution
44
+ or lease completion. Missing observations do not establish that a job never ran. An unfinished
45
+ attempt becomes `unknown` after its lease expires; expiry alone does not establish failure or stop
46
+ the original process. An active lease also does not prove that a process is still alive.
47
+
48
+ The template stores generic error summaries, not thrown payloads, inputs, or environment values.
49
+ Inspect local development logs for the underlying error. Those logs may contain sensitive data.
50
+ A missing history adapter or unreadable history table is reported separately from scheduling state.
@@ -0,0 +1 @@
1
+ function e(){var e=typeof SuppressedError==`function`?SuppressedError:function(e,t){var n=Error();return n.name=`SuppressedError`,n.error=e,n.suppressed=t,n},t={},n=[];function r(e,t){if(t!=null){if(Object(t)!==t)throw TypeError(`using declarations can only be used with objects, functions, null, or undefined.`);if(e)var r=t[Symbol.asyncDispose||Symbol.for(`Symbol.asyncDispose`)];if(r===void 0&&(r=t[Symbol.dispose||Symbol.for(`Symbol.dispose`)],e))var i=r;if(typeof r!=`function`)throw TypeError(`Object is not disposable.`);i&&(r=function(){try{i.call(t)}catch(e){return Promise.reject(e)}}),n.push({v:t,d:r,a:e})}else e&&n.push({d:t,a:e});return t}return{e:t,u:r.bind(null,!1),a:r.bind(null,!0),d:function(){var r,i=this.e,a=0;function o(){for(;r=n.pop();)try{if(!r.a&&a===1)return a=0,n.push(r),Promise.resolve().then(o);if(r.d){var e=r.d.call(r.v);if(r.a)return a|=2,Promise.resolve(e).then(o,s)}else a|=1}catch(e){return s(e)}if(a===1)return i===t?Promise.resolve():Promise.reject(i);if(i!==t)throw i}function s(n){return i=i===t?n:new e(n,i),o()}return o()}}}export{e as default};
@@ -0,0 +1,57 @@
1
+ import { DashboardPluginApi, DashboardQuery } from "@coreframe/dashboard/api";
2
+ import { z } from "zod";
3
+
4
+ //#region src/dashboard/api.d.ts
5
+ declare const job: z.ZodObject<{
6
+ id: z.ZodString;
7
+ lastSucceededAt: z.ZodNullable<z.ZodString>;
8
+ nextEligibleAt: z.ZodNullable<z.ZodString>;
9
+ eligibility: z.ZodEnum<{
10
+ cooldown: "cooldown";
11
+ due: "due";
12
+ "never-run": "never-run";
13
+ unknown: "unknown";
14
+ }>;
15
+ lease: z.ZodEnum<{
16
+ active: "active";
17
+ expired: "expired";
18
+ none: "none";
19
+ }>;
20
+ leaseUntil: z.ZodNullable<z.ZodString>;
21
+ registration: z.ZodEnum<{
22
+ configured: "configured";
23
+ orphaned: "orphaned";
24
+ }>;
25
+ }, z.core.$strip>;
26
+ declare const attempt: z.ZodObject<{
27
+ id: z.ZodString;
28
+ jobId: z.ZodString;
29
+ startedAt: z.ZodString;
30
+ finishedAt: z.ZodNullable<z.ZodString>;
31
+ outcome: z.ZodEnum<{
32
+ unknown: "unknown";
33
+ running: "running";
34
+ succeeded: "succeeded";
35
+ failed: "failed";
36
+ skipped: "skipped";
37
+ }>;
38
+ skipReason: z.ZodNullable<z.ZodEnum<{
39
+ cooldown: "cooldown";
40
+ "already-running": "already-running";
41
+ }>>;
42
+ durationMs: z.ZodNullable<z.ZodNumber>;
43
+ errorSummary: z.ZodNullable<z.ZodString>;
44
+ }, z.core.$strip>;
45
+ /** Serialized local observations returned by the read-only dashboard API. */
46
+ type DevelopmentJobsSnapshot = {
47
+ jobs: z.infer<typeof job>[];
48
+ attempts: z.infer<typeof attempt>[];
49
+ notice: string | null;
50
+ historyAvailable: boolean;
51
+ };
52
+ /** Shared contract; it contains no Node or Worker implementation code. */
53
+ declare const api: DashboardPluginApi<"dev-jobs", {
54
+ snapshot: DashboardQuery<undefined, DevelopmentJobsSnapshot>;
55
+ }, Record<never, never>>;
56
+ //#endregion
57
+ export { DevelopmentJobsSnapshot, api };
@@ -0,0 +1 @@
1
+ import{api as e,query as t}from"@coreframe/dashboard/api";import{z as n}from"zod";const r=n.string().datetime().nullable(),i=n.object({id:n.string(),lastSucceededAt:r,nextEligibleAt:r,eligibility:n.enum([`cooldown`,`due`,`never-run`,`unknown`]),lease:n.enum([`active`,`expired`,`none`]),leaseUntil:r,registration:n.enum([`configured`,`orphaned`])}),a=n.object({id:n.string(),jobId:n.string(),startedAt:n.string().datetime(),finishedAt:r,outcome:n.enum([`running`,`succeeded`,`failed`,`skipped`,`unknown`]),skipReason:n.enum([`cooldown`,`already-running`]).nullable(),durationMs:n.number().nonnegative().nullable(),errorSummary:n.string().nullable()}),o=e({id:`dev-jobs`,queries:{snapshot:t({output:n.object({jobs:n.array(i),attempts:n.array(a),notice:n.string().nullable(),historyAvailable:n.boolean()})})},commands:{}});export{o as api};
@@ -0,0 +1,7 @@
1
+ import { DashboardPlugin } from "@coreframe/dashboard/config";
2
+
3
+ //#region src/dashboard/index.d.ts
4
+ /** Read-only project-local job status and attempt history. */
5
+ declare function devJobs(): DashboardPlugin;
6
+ //#endregion
7
+ export { devJobs };
@@ -0,0 +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};
@@ -0,0 +1,8 @@
1
+ import { api as api$1 } from "./api.js";
2
+ import { DashboardPluginImplementationFactory } from "@coreframe/dashboard/api";
3
+ import { DashboardLocalHostData } from "@coreframe/dashboard/server";
4
+
5
+ //#region src/dashboard/local.d.ts
6
+ declare const createImplementation: DashboardPluginImplementationFactory<typeof api$1, DashboardLocalHostData>;
7
+ //#endregion
8
+ export { createImplementation };
@@ -0,0 +1 @@
1
+ import{inspectDevelopmentJobStates as e}from"../development-state.js";import{developmentJobAttemptOutcome as t}from"../development-history.js";import{withExistingLocalJobDatabase as n}from"../local.js";import{api as r}from"./api.js";import{defineImplementation as i}from"@coreframe/dashboard/api";import{importProjectModule as a,readProjectConfig as o}from"@coreframe/config";const s=e=>e?.toISOString()??null,c=()=>i(r,{queries:{async snapshot({host:r}){let i=await o({cwd:r.projectRoot});if(!i.jobs?.entry)return{jobs:[],attempts:[],notice:`No development jobs entry is configured in coreframe.config.ts.`,historyAvailable:!1};let{developmentJobs:c}=await a(i.jobs.entry,r.projectRoot),l=new Date,u=await n(i,r.projectRoot,async e=>{let t=await c.createStateAdmin(e).list();try{let n=c.createHistoryStore?.(e);return{records:t,attempts:await n?.list()??[],historyAvailable:!!n}}catch{return{records:t,attempts:[],historyAvailable:!1}}});return{jobs:e({jobs:c.jobs,records:u?.records??[],now:l}).map(e=>({...e,lastSucceededAt:s(e.lastSucceededAt),nextEligibleAt:s(e.nextEligibleAt),leaseUntil:s(e.leaseUntil)})),attempts:(u?.attempts??[]).map(e=>({...e,startedAt:e.startedAt.toISOString(),finishedAt:s(e.finishedAt),outcome:t(e,l)})),historyAvailable:u?.historyAvailable??!1,notice:u?u.historyAvailable?null:`History is unavailable. Configure createHistoryStore and run coreframe db migrate-local.`:`Local database is missing; no database was created.`}}},commands:{}});export{c as createImplementation};
@@ -0,0 +1,4 @@
1
+ //#region src/dashboard/page.d.ts
2
+ declare function DevJobsPage(): import("react").JSX.Element;
3
+ //#endregion
4
+ export { DevJobsPage as default };
@@ -0,0 +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};
@@ -0,0 +1,24 @@
1
+ //#region src/development-history.d.ts
2
+ /** Local development observations, independent of scheduling and lease ownership. */
3
+ type DevelopmentJobAttempt = {
4
+ id: string;
5
+ jobId: string;
6
+ startedAt: Date;
7
+ finishedAt: Date | null;
8
+ leaseUntil: Date | null;
9
+ outcome: "running" | "succeeded" | "failed" | "skipped";
10
+ skipReason: "cooldown" | "already-running" | null;
11
+ durationMs: number | null;
12
+ errorSummary: string | null;
13
+ };
14
+ /** Project-owned storage. Writes upsert by attempt ID; reads return newest first, at most 1,000. */
15
+ type DevelopmentJobHistoryStore = {
16
+ write(attempt: DevelopmentJobAttempt): Promise<void>;
17
+ list(): Promise<DevelopmentJobAttempt[]>;
18
+ };
19
+ declare const developmentJobHistoryRetentionDays = 30;
20
+ declare const developmentJobHistoryLimit = 1000;
21
+ /** An unfinished attempt is not proof of failure, even after its lease expires. */
22
+ declare function developmentJobAttemptOutcome(attempt: DevelopmentJobAttempt, now: Date): "unknown" | "running" | "succeeded" | "failed" | "skipped";
23
+ //#endregion
24
+ export { DevelopmentJobAttempt, DevelopmentJobHistoryStore, developmentJobAttemptOutcome, developmentJobHistoryLimit, developmentJobHistoryRetentionDays };
@@ -0,0 +1 @@
1
+ const e=30,t=1e3;function n(e,t){return e.outcome===`running`&&(!e.leaseUntil||e.leaseUntil<=t)?`unknown`:e.outcome}export{n as developmentJobAttemptOutcome,t as developmentJobHistoryLimit,e as developmentJobHistoryRetentionDays};
@@ -1,12 +1,12 @@
1
1
  import { JobCooldown } from "./definition.js";
2
+ import { DevelopmentJobHistoryStore } from "./development-history.js";
2
3
 
3
4
  //#region src/development-state.d.ts
4
5
  /** A startup job whose local cooldown and lease state can be administered. */
5
6
  type DevelopmentJobDefinition = {
6
7
  id: string;
7
8
  dev: {
8
- /** Minimum time since success. Defaults to zero. */cooldown?: JobCooldown; /** Consume at most one attempt per coreframe dev session, including failures. */
9
- oncePerSession?: boolean;
9
+ cooldown: JobCooldown;
10
10
  leaseMs?: number;
11
11
  onStartup: true;
12
12
  };
@@ -34,6 +34,7 @@ type DevelopmentJobStateAdmin = {
34
34
  };
35
35
  /** Project module contract loaded by local development job tooling. */
36
36
  type DevelopmentJobs<TDatabase> = {
37
+ createHistoryStore?(database: TDatabase): DevelopmentJobHistoryStore;
37
38
  createStateAdmin(database: TDatabase): DevelopmentJobStateAdmin;
38
39
  jobs: readonly DevelopmentJobDefinition[];
39
40
  };
@@ -1 +1 @@
1
- import{parseJobCooldown as e}from"./definition.js";function t(t){if(!t.id.trim())throw Error(`Coreframe job IDs cannot be empty.`);e(t.dev.cooldown??0);let n=t.dev.leaseMs??6e5;if(!Number.isSafeInteger(n)||n<=0)throw Error(`Coreframe job ${JSON.stringify(t.id)} must have a positive lease.`);return t}function n(e){let n=new Set;for(let r of e.jobs){if(t(r),n.has(r.id))throw Error(`Duplicate Coreframe development job ID ${JSON.stringify(r.id)}.`);n.add(r.id)}return e}function r({jobs:t,now:n,records:r}){let i=new Map(t.map(e=>[e.id,e])),a=new Map(r.map(e=>[e.jobId,e]));return[...new Set([...i.keys(),...a.keys()])].sort().map(t=>{let r=i.get(t),o=a.get(t),s=r?e(r.dev.cooldown??0):null,c=o?.lastSucceededAt??null,l=o?.leaseUntil??null,u=l?l>n?`active`:`expired`:`none`,d;return d=r?!o||!c?`never-run`:c.getTime()+s>n.getTime()?`cooldown`:`due`:`unknown`,{cooldownMs:s,eligibility:d,id:t,lastSucceededAt:c,lease:u,leaseMs:r?.dev.leaseMs??(r?6e5:null),leaseUntil:l,nextEligibleAt:s===null||!c?null:new Date(c.getTime()+s),persisted:!!o,registration:r?`configured`:`orphaned`}})}export{t as defineDevelopmentJob,n as defineDevelopmentJobs,r as inspectDevelopmentJobStates};
1
+ import{parseJobCooldown as e}from"./definition.js";function t(t){if(!t.id.trim())throw Error(`Coreframe job IDs cannot be empty.`);e(t.dev.cooldown);let n=t.dev.leaseMs??6e5;if(!Number.isSafeInteger(n)||n<=0)throw Error(`Coreframe job ${JSON.stringify(t.id)} must have a positive lease.`);return t}function n(e){let n=new Set;for(let r of e.jobs){if(t(r),n.has(r.id))throw Error(`Duplicate Coreframe development job ID ${JSON.stringify(r.id)}.`);n.add(r.id)}return e}function r({jobs:t,now:n,records:r}){let i=new Map(t.map(e=>[e.id,e])),a=new Map(r.map(e=>[e.jobId,e]));return[...new Set([...i.keys(),...a.keys()])].sort().map(t=>{let r=i.get(t),o=a.get(t),s=r?e(r.dev.cooldown):null,c=o?.lastSucceededAt??null,l=o?.leaseUntil??null,u=l?l>n?`active`:`expired`:`none`,d;return d=r?!o||!c?`never-run`:c.getTime()+s>n.getTime()?`cooldown`:`due`:`unknown`,{cooldownMs:s,eligibility:d,id:t,lastSucceededAt:c,lease:u,leaseMs:r?.dev.leaseMs??(r?6e5:null),leaseUntil:l,nextEligibleAt:s===null||!c?null:new Date(c.getTime()+s),persisted:!!o,registration:r?`configured`:`orphaned`}})}export{t as defineDevelopmentJob,n as defineDevelopmentJobs,r as inspectDevelopmentJobStates};
package/dist/index.d.ts CHANGED
@@ -1,18 +1,17 @@
1
1
  import { JobCooldown, defaultJobLeaseMs, parseJobCooldown } from "./definition.js";
2
+ import { DevelopmentJobAttempt, DevelopmentJobHistoryStore, developmentJobAttemptOutcome, developmentJobHistoryLimit, developmentJobHistoryRetentionDays } from "./development-history.js";
2
3
  import { DevelopmentJobDefinition, DevelopmentJobStateAdmin, DevelopmentJobStateRecord, DevelopmentJobStateResetResult, DevelopmentJobStatus, DevelopmentJobs, defineDevelopmentJob, defineDevelopmentJobs, inspectDevelopmentJobStates } from "./development-state.js";
3
4
 
4
5
  //#region src/index.d.ts
5
6
  type JobInvocation<TContext> = {
6
7
  context: TContext;
7
- now: Date; /** Stable for one coreframe dev invocation; absent for scheduled runs. */
8
- sessionId?: string;
8
+ now: Date;
9
9
  };
10
10
  type JobDefinition<TContext> = {
11
11
  id: string;
12
12
  run(invocation: JobInvocation<TContext>): Promise<void> | void;
13
13
  dev?: {
14
- /** Minimum time since success, in milliseconds or a duration string. Defaults to zero. */cooldown?: JobCooldown; /** Consume one attempt per session, even when the handler fails or the Worker restarts. */
15
- oncePerSession?: boolean;
14
+ cooldown: JobCooldown;
16
15
  leaseMs?: number;
17
16
  onStartup?: boolean;
18
17
  };
@@ -27,15 +26,6 @@ type JobStateClaim = {
27
26
  status: "running";
28
27
  };
29
28
  type JobStateStore = {
30
- /**
31
- * Atomically persist a receipt for (sessionId, jobId) before execution. Return false if already
32
- * claimed. Receipts must survive failures, lease expiry, Worker restarts, and scheduling-state
33
- * resets. Required for oncePerSession jobs.
34
- */
35
- claimSession?(input: {
36
- jobId: string;
37
- sessionId: string;
38
- }): Promise<boolean>;
39
29
  claim(input: {
40
30
  cooldownMs: number;
41
31
  jobId: string;
@@ -57,7 +47,7 @@ type JobExecutionResult = {
57
47
  durationMs: number;
58
48
  error?: unknown;
59
49
  id: string;
60
- status: "completed" | "failed" | "skipped-cooldown" | "skipped-running" | "skipped-session";
50
+ status: "completed" | "failed" | "skipped-cooldown" | "skipped-running";
61
51
  };
62
52
  declare function defineJob<TContext>(definition: JobDefinition<TContext>): JobDefinition<TContext>;
63
53
  declare function defineJobRegistry<TContext>(jobs: JobRegistry<TContext>): JobRegistry<TContext>;
@@ -72,37 +62,20 @@ declare function runJobs<TContext>({
72
62
  now?: Date;
73
63
  onError?: "continue" | "throw";
74
64
  }): Promise<JobExecutionResult[]>;
75
- /**
76
- * Checks startup jobs against persisted cooldowns and leases. Session jobs also consume a durable
77
- * receipt before calling the handler. A crash after that claim can leave the handler unexecuted;
78
- * this is at-most-once, not a guarantee of successful execution. Missing session identity or
79
- * claimSession support is rejected before creating context or claiming any jobs.
80
- *
81
- * @example
82
- * ```ts
83
- * defineJob({
84
- * id: "development.prepare",
85
- * dev: { onStartup: true, oncePerSession: true },
86
- * run({ sessionId }) {
87
- * console.log(`Preparing session ${sessionId}`)
88
- * },
89
- * })
90
- * ```
91
- */
92
65
  declare function runDevelopmentJobs<TContext>({
93
66
  createContext,
67
+ history,
94
68
  jobs,
95
69
  now,
96
70
  onError,
97
- state,
98
- sessionId
71
+ state
99
72
  }: {
100
73
  createContext(now: Date): Promise<TContext> | TContext;
74
+ history?: DevelopmentJobHistoryStore;
101
75
  jobs: JobRegistry<TContext>;
102
76
  now?: Date;
103
77
  onError?: "continue" | "throw";
104
- state: JobStateStore; /** Session identity supplied by coreframe dev. Required for oncePerSession jobs. */
105
- sessionId?: string;
78
+ state: JobStateStore;
106
79
  }): Promise<JobExecutionResult[]>;
107
80
  //#endregion
108
- export { DevelopmentJobDefinition, DevelopmentJobStateAdmin, DevelopmentJobStateRecord, DevelopmentJobStateResetResult, DevelopmentJobStatus, DevelopmentJobs, JobCooldown, JobDefinition, JobExecutionResult, JobInvocation, JobRegistry, JobStateClaim, JobStateStore, defaultJobLeaseMs, defineDevelopmentJob, defineDevelopmentJobs, defineJob, defineJobRegistry, inspectDevelopmentJobStates, parseJobCooldown, runDevelopmentJobs, runJobs };
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 };
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";function a(e){return u(e),e}function o(e){let t=new Set;for(let n of e){if(u(n),t.has(n.id))throw Error(`Duplicate Coreframe job ID ${JSON.stringify(n.id)}.`);t.add(n.id)}return e}async function s({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 l({context:i,job:e,now:n,onError:r}));return a}async function c({createContext:e,jobs:n,now:r=new Date,onError:i=`continue`,state:a,sessionId:o}){let s=n.filter(e=>e.dev?.onStartup);if(s.length===0)return[];if(s.some(e=>e.dev?.oncePerSession)){if(!o?.trim())throw Error(`Once-per-session development jobs require a session ID.`);if(!a.claimSession)throw Error(`Once-per-session development jobs require state.claimSession.`)}let c=await e(r),u=[];for(let e of s){let n=e.dev;if(!n)continue;let s=await a.claim({cooldownMs:t(n.cooldown??0),jobId:e.id,leaseMs:n.leaseMs??6e5,now:r});if(s.status!==`claimed`){u.push({durationMs:0,id:e.id,status:s.status===`cooldown`?`skipped-cooldown`:`skipped-running`});continue}try{let t=await l({context:c,job:e,now:r,onError:i,state:a,leaseId:s.leaseId,sessionId:o});u.push(t)}catch(t){if(i===`throw`)throw t;u.push({durationMs:0,error:t,id:e.id,status:`failed`})}}return u}async function l({context:e,job:t,leaseId:n,now:r,onError:i,state:a,sessionId:o}){let s=Date.now();try{return a&&n&&t.dev?.oncePerSession&&!await a.claimSession({jobId:t.id,sessionId:o})?(await a.fail({jobId:t.id,leaseId:n,now:r}),{durationMs:0,id:t.id,status:`skipped-session`}):(await t.run({context:e,now:r,...o===void 0?{}:{sessionId:o}}),a&&n&&await a.complete({jobId:t.id,leaseId:n,now:r}),{durationMs:Date.now()-s,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()-s,error:e,id:t.id,status:`failed`}}}function u(e){if(!e.id.trim())throw Error(`Coreframe job IDs cannot be empty.`);if(e.dev){let n=t(e.dev.cooldown??0);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,a as defineJob,o as defineJobRegistry,i as inspectDevelopmentJobStates,t as parseJobCooldown,c as runDevelopmentJobs,s as runJobs};
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};
@@ -0,0 +1,7 @@
1
+ import { CoreframeConfig } from "@coreframe/config";
2
+
3
+ //#region src/local.d.ts
4
+ /** Inspect an existing project-local database, without creating one or using deploy credentials. */
5
+ declare function withExistingLocalJobDatabase<Result>(config: CoreframeConfig, cwd: string, run: (database: unknown) => Promise<Result>): Promise<Result | undefined>;
6
+ //#endregion
7
+ export { withExistingLocalJobDatabase };
package/dist/local.js ADDED
@@ -0,0 +1 @@
1
+ import e from"./_virtual/_@oxc-project_runtime@0.138.0/helpers/esm/usingCtx.js";import{stat as t}from"node:fs/promises";import n from"node:path";import{createLocalPostgresDb as r,createProjectSqliteDrizzleDatabase as i,startProjectPostgres as a,startProjectTurso as o}from"@coreframe/db";async function s(s,l,u){try{var d=e();let p=s.database?.dialect??`postgres`,m=p===`sqlite`?n.resolve(l,`.coreframe/turso.db`):n.resolve(l,`.coreframe/postgres/PG_VERSION`);try{await t(m)}catch(e){if(c(e)&&e.code===`ENOENT`)return;throw e}if(p===`sqlite`)try{var f=e();let t=await i({cwd:l,env:f.a(await o({config:s,cwd:l,useSupervisorLease:!0})).env});try{return await u(t)}finally{t.$client.close()}}catch(e){f.e=e}finally{await f.d()}let h=await r({cwd:l,env:d.a(await a({config:s,cwd:l,useSupervisorLease:!0})).env});try{return await u(h)}finally{await h.$client.end()}}catch(e){d.e=e}finally{await d.d()}}function c(e){return e instanceof Error&&`code`in e}export{s as withExistingLocalJobDatabase};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@coreframe/jobs",
3
- "version": "0.1.2-next.1",
3
+ "version": "0.1.3",
4
4
  "description": "Shared scheduled-job contracts and execution helpers for Coreframe apps",
5
5
  "repository": {
6
6
  "type": "git",
@@ -15,9 +15,39 @@
15
15
  ".": {
16
16
  "types": "./dist/index.d.ts",
17
17
  "default": "./dist/index.js"
18
+ },
19
+ "./local": {
20
+ "types": "./dist/local.d.ts",
21
+ "default": "./dist/local.js"
22
+ },
23
+ "./dashboard": {
24
+ "types": "./dist/dashboard/index.d.ts",
25
+ "default": "./dist/dashboard/index.js"
26
+ },
27
+ "./dashboard/api": {
28
+ "types": "./dist/dashboard/api.d.ts",
29
+ "default": "./dist/dashboard/api.js"
30
+ },
31
+ "./dashboard/local": {
32
+ "types": "./dist/dashboard/local.d.ts",
33
+ "default": "./dist/dashboard/local.js"
34
+ },
35
+ "./dashboard/page": {
36
+ "types": "./dist/dashboard/page.d.ts",
37
+ "default": "./dist/dashboard/page.js"
18
38
  }
19
39
  },
40
+ "dependencies": {
41
+ "@tanstack/react-query": "^5.101.2",
42
+ "react": "19.2.8",
43
+ "zod": "4.4.3",
44
+ "@coreframe/dashboard": "^0.4.0",
45
+ "@coreframe/db": "^0.2.1",
46
+ "@coreframe/config": "^0.3.0"
47
+ },
20
48
  "devDependencies": {
49
+ "@types/node": "^26.1.0",
50
+ "@types/react": "19.2.18",
21
51
  "tsdown": "0.22.3",
22
52
  "typescript": "6.0.3",
23
53
  "vitest": "^4.1.9"