@skaile/forge-layer-jobs 0.0.0 → 0.1.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/CHANGELOG.md +7 -0
- package/LICENSE +21 -0
- package/README.md +150 -1
- package/app/app.config.ts +5 -0
- package/app/components/JobControls.vue +51 -0
- package/app/components/JobDetailSlideover.vue +88 -0
- package/app/components/JobsActions.vue +10 -0
- package/app/pages/jobs.vue +274 -0
- package/app/utils/jobs.ts +22 -0
- package/nuxt.config.ts +9 -0
- package/package.json +44 -5
- package/server/jobs/actions.ts +266 -0
- package/server/jobs/boss.ts +229 -0
- package/server/jobs/define.ts +103 -0
- package/server/jobs/role.ts +33 -0
- package/server/middleware/worker-role.ts +19 -0
- package/server/plugins/jobs.ts +48 -0
- package/shared/jobs.ts +8 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
# @skaile/forge-layer-jobs
|
|
2
|
+
|
|
3
|
+
## 0.1.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 064fbe0: New package: the jobs layer of forge-template-app as a versioned Nuxt layer (`extends: ['@skaile/forge-layer-jobs']`) instead of a copy in each app. Background jobs on pg-boss in the app's own database: `defineJob` / `registerJobs`, `APP_ROLE` web/worker, the `jobs.*` actions and the Jobs page. The template's example jobs (`tasks.import`, `tasks.overdue-digest`) and the import form stay in the app: it registers its jobs from its own Nitro plugin and adds header buttons by overriding the `JobsActions` component. Host contract in the README.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Matthias Ortegro
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,152 @@
|
|
|
1
1
|
# @skaile/forge-layer-jobs
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A Nuxt layer for apps built on [forge-template-app](https://github.com/skaile-ai/forge/tree/main/templates/app):
|
|
4
|
+
background jobs on the app's own database with [pg-boss 12](https://github.com/timgit/pg-boss). PGlite locally (no
|
|
5
|
+
extra service), Postgres in production. Jobs are typed, run as a system principal and call the server-action
|
|
6
|
+
catalogue, so a job is "an action that runs later". It ships as source; the app `extends` it and registers its own
|
|
7
|
+
jobs.
|
|
8
|
+
|
|
9
|
+
## Install
|
|
10
|
+
|
|
11
|
+
```sh
|
|
12
|
+
bun add @skaile/forge-layer-jobs pg-boss
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
// nuxt.config.ts
|
|
17
|
+
export default defineNuxtConfig({
|
|
18
|
+
extends: ['@skaile/forge-layer-jobs'],
|
|
19
|
+
})
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
```css
|
|
23
|
+
/* app/assets/css/main.css: Tailwind skips node_modules, so name the layer's sources */
|
|
24
|
+
@source "../../../node_modules/@skaile/forge-layer-jobs/app";
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
Remove the `extends` entry (and the `@source` line, and the app's own jobs) to drop background jobs.
|
|
28
|
+
|
|
29
|
+
## Host contract
|
|
30
|
+
|
|
31
|
+
The layer runs on the core of forge-template-app and uses these parts of it by name. An app copied from the template
|
|
32
|
+
has all of them; an app that renamed or removed one overrides the layer file that uses it.
|
|
33
|
+
|
|
34
|
+
| Kind | Used | Where in the template |
|
|
35
|
+
|---|---|---|
|
|
36
|
+
| Server imports (`~~/`) | `server/utils/actions/define` (`defineAppAction`, `requireFound`, `AppActionContext`), `server/utils/actions/registry` (`registerActions`), `server/utils/db` (`dbReady`, `onBeforeDatabaseClose`, `DbTarget`, `Tx`), `server/utils/principal` (`requireScope`, `systemPrincipal`, `Principal`) | `server/utils/` |
|
|
37
|
+
| Composables, utils | `useActions`, `actionErrorMessage`, `useDates` | `app/composables/` |
|
|
38
|
+
| Components | `AppHeader` | `app/components/` |
|
|
39
|
+
| App config | `appShell.nav` (adds Jobs, order 60) | `app/app.config.ts` |
|
|
40
|
+
|
|
41
|
+
Peers: `nuxt ^4`, `@nuxt/ui ^4.11`, `vue ^3.5`, `@skaile/forge-app-actions ^0.6`, `pg-boss ^12`, `zod ^4`,
|
|
42
|
+
`drizzle-orm ^0.45`, `h3 ^1.15`.
|
|
43
|
+
|
|
44
|
+
## What you get
|
|
45
|
+
|
|
46
|
+
- `defineJob(...)` registry and pg-boss lifecycle (`server/jobs/`), started from `server/plugins/jobs.ts` after
|
|
47
|
+
`dbReady()` and stopped before the database closes on shutdown.
|
|
48
|
+
- Actions (reach UI, HTTP, MCP, CLI and chat automatically):
|
|
49
|
+
|
|
50
|
+
| Action | Kind | Audience | Needs |
|
|
51
|
+
|---|---|---|---|
|
|
52
|
+
| `jobs.list` | query | user, llm | `jobs:read` |
|
|
53
|
+
| `jobs.get` | query | user, llm | `jobs:read` |
|
|
54
|
+
| `jobs.schedules` | query | user, llm | `jobs:read` |
|
|
55
|
+
| `jobs.enqueue` | effect | user, llm | `jobs:write` + the job's own `authorize`; agents only jobs with `llm` in their audience |
|
|
56
|
+
| `jobs.retry` | effect | user | `jobs:write` |
|
|
57
|
+
| `jobs.cancel` | effect | user | `jobs:write` |
|
|
58
|
+
|
|
59
|
+
- Jobs page `/jobs` (nav order 60): state and job filters, auto-refresh every 3 s, detail drawer (payload, output,
|
|
60
|
+
error, retry/cancel), schedules with next run and "Run now".
|
|
61
|
+
- `JobsActions`: an empty component in the page header. The app overrides it (`app/components/JobsActions.vue`) with
|
|
62
|
+
its own buttons, e.g. an import form; emitting `enqueued` with a job id opens that job.
|
|
63
|
+
|
|
64
|
+
## Overrides
|
|
65
|
+
|
|
66
|
+
A Nuxt layer is overridden piece by piece; the app's piece wins, the rest keeps coming from the package, so fixes in
|
|
67
|
+
the other files still arrive with updates:
|
|
68
|
+
|
|
69
|
+
- a component: a file with the same name in the app's `app/components/` (`JobsActions.vue` is the intended one: the
|
|
70
|
+
page header's slot for the app's own buttons)
|
|
71
|
+
- a page: a page at the same route in the app's `app/pages/`
|
|
72
|
+
- an auto-imported composable or util: an export with the same name in the app's `app/composables/` or `app/utils/`
|
|
73
|
+
(override the whole file: the app's file replaces every export of that name)
|
|
74
|
+
- `app/app.config.ts`: the app's own `app.config.ts` is merged over the layer's, so set only the keys you change.
|
|
75
|
+
Arrays such as `appShell.nav` are joined, the app's entries first; an app entry with the same `to` replaces the
|
|
76
|
+
layer's when the app's `useAppShell` keeps the first entry per route, as forge-template-app's does
|
|
77
|
+
(`firstPerRoute`), e.g. `{ label: 'Hintergrundjobs', icon: 'i-lucide-cog', to: '/jobs', order: 60, roles: ['owner'] }`
|
|
78
|
+
|
|
79
|
+
Server code (`server/`) and `shared/` are imported by path inside the package and cannot be overridden this way; a
|
|
80
|
+
change there belongs in the package.
|
|
81
|
+
|
|
82
|
+
## Add a job
|
|
83
|
+
|
|
84
|
+
```ts
|
|
85
|
+
// server/jobs/reports-export.ts (in the app)
|
|
86
|
+
import { defineJob } from '@skaile/forge-layer-jobs/server/jobs/define'
|
|
87
|
+
|
|
88
|
+
export const reportsExportJob = defineJob({
|
|
89
|
+
name: 'reports.export', // also the pg-boss queue name
|
|
90
|
+
description: 'For the Jobs page, jobs.enqueue and LLMs: what it does, its output.',
|
|
91
|
+
payload: z.object({ projectId: z.string().uuid().describe('...') }).strict(),
|
|
92
|
+
audience: ['user', 'llm'], // without 'llm', agents cannot enqueue it
|
|
93
|
+
authorize: (payload, ctx) => { requireScope(ctx, 'tasks:read') }, // checked on enqueue
|
|
94
|
+
retry: { limit: 2, delay: 30, backoff: true }, // default: 2 retries
|
|
95
|
+
schedule: '0 6 * * *', // optional cron (UTC)
|
|
96
|
+
singleton: { seconds: 300 }, // optional: one job per slot
|
|
97
|
+
handler: async (payload, ctx) => {
|
|
98
|
+
// ctx.principal = systemPrincipal('worker:reports.export'); also ctx.requestedBy, ctx.job, ctx.signal
|
|
99
|
+
const tasks = await useDataService().list(ctx.principal, 'tasks', {
|
|
100
|
+
where: { where: [{ field: 'projectId', op: 'eq', value: payload.projectId }] }, limit: 1
|
|
101
|
+
})
|
|
102
|
+
return { count: tasks.total } // stored as the job's output
|
|
103
|
+
}
|
|
104
|
+
})
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
Register it from a Nitro plugin of the app; the boss reads the registry once the database is up:
|
|
108
|
+
|
|
109
|
+
```ts
|
|
110
|
+
// server/plugins/jobs.ts (in the app)
|
|
111
|
+
import { registerJobs } from '@skaile/forge-layer-jobs/server/jobs/define'
|
|
112
|
+
import { reportsExportJob } from '../jobs/reports-export'
|
|
113
|
+
|
|
114
|
+
export default defineNitroPlugin(() => registerJobs([reportsExportJob]))
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
Enqueue from server code with `enqueueJob(name, payload, { requestedBy })` from
|
|
118
|
+
`@skaile/forge-layer-jobs/server/jobs/boss`; the payload is validated against the job's schema first.
|
|
119
|
+
|
|
120
|
+
### Transactions and the PGlite deadlock rule
|
|
121
|
+
|
|
122
|
+
Inside `withTx(async tx => ...)` every query must use `tx`, pg-boss included. A plain `enqueueJob(...)` inside the
|
|
123
|
+
transaction waits for the lock the transaction holds and hangs the process with no error on PGlite (on Postgres it does
|
|
124
|
+
not hang but is not transactional). Use `enqueueInTx(tx, name, payload)`: the job exists only if the transaction
|
|
125
|
+
commits.
|
|
126
|
+
|
|
127
|
+
Long handlers on PGlite share the one connection with web requests: a transaction holds it until it commits, so keep
|
|
128
|
+
transactions short. Work that need not be atomic should run in chunks and yield between them with
|
|
129
|
+
`await setImmediate()` from `node:timers/promises`, not with a microtask, and check `ctx.signal` between chunks.
|
|
130
|
+
|
|
131
|
+
## Roles: `APP_ROLE`
|
|
132
|
+
|
|
133
|
+
| Role | Serves app | Enqueues | Runs handlers + cron |
|
|
134
|
+
|---|---|---|---|
|
|
135
|
+
| `all` (default) | yes | yes | yes |
|
|
136
|
+
| `web` | yes | yes | no |
|
|
137
|
+
| `worker` | `/api/health` only (503 elsewhere) | - | yes |
|
|
138
|
+
|
|
139
|
+
PGlite is one process per data directory, so `web`/`worker` need `DATABASE_URL`; the app refuses to start with
|
|
140
|
+
`APP_ROLE=worker` (or `web`) on PGlite and says why. Run `web` and `worker` from the same image; start the worker after
|
|
141
|
+
the app is healthy so only one process migrates a fresh database. Its health check `/api/health` keeps working.
|
|
142
|
+
|
|
143
|
+
Env: `APP_ROLE`, `JOBS_POLL_SECONDS` (default 2), `JOBS_POOL_MAX` (pg-boss's own pool on Postgres, default 5; budget it
|
|
144
|
+
next to the app's pool). pg-boss keeps its tables in the `pgboss` schema, which it installs and migrates itself in
|
|
145
|
+
`start()`.
|
|
146
|
+
|
|
147
|
+
## Tests
|
|
148
|
+
|
|
149
|
+
The layer needs the host's database and actions, so its tests live in the template (`templates/app/test/jobs.test.ts`:
|
|
150
|
+
in-memory PGlite + pg-boss: role split, handler run, validation, authorization, cron registration, `enqueueInTx`
|
|
151
|
+
commit/rollback, cancel/retry) and run against the installed package. `bun scripts/check-templates.ts --local app`
|
|
152
|
+
checks an unpublished change of this package against the template.
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
<script setup lang="ts">
|
|
2
|
+
import type { JobActions, JobDto } from '../../server/jobs/actions'
|
|
3
|
+
|
|
4
|
+
const props = defineProps<{ job: JobDto }>()
|
|
5
|
+
const emit = defineEmits<{ changed: [] }>()
|
|
6
|
+
|
|
7
|
+
const jobs = useActions<JobActions>()
|
|
8
|
+
const toast = useToast()
|
|
9
|
+
const busy = ref(false)
|
|
10
|
+
|
|
11
|
+
const canCancel = computed(() => ['created', 'retry', 'active'].includes(props.job.state))
|
|
12
|
+
const canRetry = computed(() => props.job.state === 'failed' || props.job.state === 'cancelled')
|
|
13
|
+
|
|
14
|
+
async function run(label: string, id: 'jobs.cancel' | 'jobs.retry') {
|
|
15
|
+
busy.value = true
|
|
16
|
+
try {
|
|
17
|
+
await jobs.call(id, { id: props.job.id })
|
|
18
|
+
toast.add({ title: label, color: 'success' })
|
|
19
|
+
emit('changed')
|
|
20
|
+
} catch (error) {
|
|
21
|
+
toast.add({ title: `${label} failed`, description: actionErrorMessage(error), color: 'error' })
|
|
22
|
+
} finally {
|
|
23
|
+
busy.value = false
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
</script>
|
|
27
|
+
|
|
28
|
+
<template>
|
|
29
|
+
<div class="flex gap-2">
|
|
30
|
+
<UButton
|
|
31
|
+
v-if="canCancel"
|
|
32
|
+
icon="i-lucide-ban"
|
|
33
|
+
label="Cancel"
|
|
34
|
+
color="neutral"
|
|
35
|
+
variant="outline"
|
|
36
|
+
size="xs"
|
|
37
|
+
:loading="busy"
|
|
38
|
+
@click="run('Job cancelled', 'jobs.cancel')"
|
|
39
|
+
/>
|
|
40
|
+
<UButton
|
|
41
|
+
v-if="canRetry"
|
|
42
|
+
icon="i-lucide-rotate-ccw"
|
|
43
|
+
label="Retry"
|
|
44
|
+
color="neutral"
|
|
45
|
+
variant="outline"
|
|
46
|
+
size="xs"
|
|
47
|
+
:loading="busy"
|
|
48
|
+
@click="run('Job queued again', 'jobs.retry')"
|
|
49
|
+
/>
|
|
50
|
+
</div>
|
|
51
|
+
</template>
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
<script setup lang="ts">
|
|
2
|
+
import type { JobDto } from '../../server/jobs/actions'
|
|
3
|
+
|
|
4
|
+
const props = defineProps<{ job?: JobDto }>()
|
|
5
|
+
const open = defineModel<boolean>('open', { default: false })
|
|
6
|
+
const emit = defineEmits<{ changed: [] }>()
|
|
7
|
+
|
|
8
|
+
const { formatDateTime } = useDates()
|
|
9
|
+
|
|
10
|
+
const pretty = (value: unknown) => JSON.stringify(value, null, 2)
|
|
11
|
+
|
|
12
|
+
const facts = computed(() => {
|
|
13
|
+
const job = props.job
|
|
14
|
+
if (!job) return []
|
|
15
|
+
return [
|
|
16
|
+
{ label: 'Id', value: job.id },
|
|
17
|
+
{ label: 'Requested by', value: job.requestedBy?.name ?? 'System (cron)' },
|
|
18
|
+
{ label: 'Created', value: formatDateTime(job.createdAt) },
|
|
19
|
+
{ label: 'Started', value: formatDateTime(job.startedAt) },
|
|
20
|
+
{ label: 'Finished', value: formatDateTime(job.completedAt) },
|
|
21
|
+
{ label: 'Duration', value: jobDuration(job) },
|
|
22
|
+
{ label: 'Attempts', value: `${job.retryCount + 1} of ${job.retryLimit + 1}` },
|
|
23
|
+
]
|
|
24
|
+
})
|
|
25
|
+
</script>
|
|
26
|
+
|
|
27
|
+
<template>
|
|
28
|
+
<USlideover
|
|
29
|
+
v-model:open="open"
|
|
30
|
+
:title="job?.name ?? 'Job'"
|
|
31
|
+
:description="job ? JOB_STATE_META[job.state].label : undefined"
|
|
32
|
+
:ui="{ content: 'sm:max-w-xl' }"
|
|
33
|
+
>
|
|
34
|
+
<template #body>
|
|
35
|
+
<div
|
|
36
|
+
v-if="job"
|
|
37
|
+
class="space-y-5"
|
|
38
|
+
data-testid="job-detail"
|
|
39
|
+
>
|
|
40
|
+
<div class="flex items-center gap-2">
|
|
41
|
+
<UBadge
|
|
42
|
+
:color="JOB_STATE_META[job.state].color"
|
|
43
|
+
:icon="JOB_STATE_META[job.state].icon"
|
|
44
|
+
variant="subtle"
|
|
45
|
+
:label="JOB_STATE_META[job.state].label"
|
|
46
|
+
/>
|
|
47
|
+
<JobControls
|
|
48
|
+
:job="job"
|
|
49
|
+
@changed="emit('changed')"
|
|
50
|
+
/>
|
|
51
|
+
</div>
|
|
52
|
+
<dl class="grid grid-cols-[8rem_1fr] gap-x-3 gap-y-1.5 text-sm">
|
|
53
|
+
<template
|
|
54
|
+
v-for="fact in facts"
|
|
55
|
+
:key="fact.label"
|
|
56
|
+
>
|
|
57
|
+
<dt class="text-muted">
|
|
58
|
+
{{ fact.label }}
|
|
59
|
+
</dt>
|
|
60
|
+
<dd class="break-all text-highlighted">
|
|
61
|
+
{{ fact.value }}
|
|
62
|
+
</dd>
|
|
63
|
+
</template>
|
|
64
|
+
</dl>
|
|
65
|
+
<UAlert
|
|
66
|
+
v-if="job.error"
|
|
67
|
+
color="error"
|
|
68
|
+
variant="subtle"
|
|
69
|
+
icon="i-lucide-circle-x"
|
|
70
|
+
title="Error"
|
|
71
|
+
:description="job.error"
|
|
72
|
+
/>
|
|
73
|
+
<section>
|
|
74
|
+
<h3 class="mb-1.5 text-sm font-medium text-highlighted">
|
|
75
|
+
Payload
|
|
76
|
+
</h3>
|
|
77
|
+
<pre class="max-h-72 overflow-auto rounded-md bg-elevated p-3 text-xs">{{ pretty(job.payload) }}</pre>
|
|
78
|
+
</section>
|
|
79
|
+
<section v-if="job.output">
|
|
80
|
+
<h3 class="mb-1.5 text-sm font-medium text-highlighted">
|
|
81
|
+
Output
|
|
82
|
+
</h3>
|
|
83
|
+
<pre class="max-h-72 overflow-auto rounded-md bg-elevated p-3 text-xs">{{ pretty(job.output) }}</pre>
|
|
84
|
+
</section>
|
|
85
|
+
</div>
|
|
86
|
+
</template>
|
|
87
|
+
</USlideover>
|
|
88
|
+
</template>
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
<script setup lang="ts">
|
|
2
|
+
// Extension point of the Jobs page header: the app's own buttons, e.g. a form
|
|
3
|
+
// that enqueues one of its jobs. Override it with `app/components/JobsActions.vue`
|
|
4
|
+
// in the app; emit `enqueued` with the job id and the page opens that job.
|
|
5
|
+
defineEmits<{ enqueued: [id: string] }>()
|
|
6
|
+
</script>
|
|
7
|
+
|
|
8
|
+
<template>
|
|
9
|
+
<span class="contents" />
|
|
10
|
+
</template>
|
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
<!-- eslint-disable vue/multi-word-component-names -- a page (route /jobs), not a reusable component; @nuxt/eslint only exempts the root app's pages -->
|
|
2
|
+
<script setup lang="ts">
|
|
3
|
+
import type { TableColumn } from '@nuxt/ui'
|
|
4
|
+
import { h } from 'vue'
|
|
5
|
+
import type { JobActions, JobDto } from '../../server/jobs/actions'
|
|
6
|
+
import type { JobState } from '../../shared/jobs'
|
|
7
|
+
import { JOB_STATES } from '../../shared/jobs'
|
|
8
|
+
|
|
9
|
+
useHead({ title: 'Jobs' })
|
|
10
|
+
|
|
11
|
+
const jobs = useActions<JobActions>()
|
|
12
|
+
const { formatDateTime } = useDates()
|
|
13
|
+
const toast = useToast()
|
|
14
|
+
|
|
15
|
+
const PAGE_SIZE = 25
|
|
16
|
+
const state = ref<JobState | 'all'>('all')
|
|
17
|
+
const name = ref<string>('all')
|
|
18
|
+
const page = ref(1)
|
|
19
|
+
const autoRefresh = ref(true)
|
|
20
|
+
|
|
21
|
+
watch([state, name], () => {
|
|
22
|
+
page.value = 1
|
|
23
|
+
})
|
|
24
|
+
|
|
25
|
+
const {
|
|
26
|
+
data,
|
|
27
|
+
status: loadStatus,
|
|
28
|
+
refresh,
|
|
29
|
+
} = await useAsyncData(
|
|
30
|
+
'jobs:list',
|
|
31
|
+
() =>
|
|
32
|
+
jobs.call('jobs.list', {
|
|
33
|
+
state: state.value === 'all' ? undefined : state.value,
|
|
34
|
+
name: name.value === 'all' ? undefined : name.value,
|
|
35
|
+
limit: PAGE_SIZE,
|
|
36
|
+
offset: (page.value - 1) * PAGE_SIZE,
|
|
37
|
+
}),
|
|
38
|
+
{ watch: [state, name, page] },
|
|
39
|
+
)
|
|
40
|
+
const { data: schedules, refresh: refreshSchedules } = await useAsyncData('jobs:schedules', () =>
|
|
41
|
+
jobs.call('jobs.schedules', {}),
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
const selected = ref<JobDto>()
|
|
45
|
+
const detailOpen = ref(false)
|
|
46
|
+
|
|
47
|
+
async function openJob(id: string) {
|
|
48
|
+
try {
|
|
49
|
+
selected.value = await jobs.call('jobs.get', { id })
|
|
50
|
+
detailOpen.value = true
|
|
51
|
+
} catch (error) {
|
|
52
|
+
toast.add({ title: 'Could not load the job', description: actionErrorMessage(error), color: 'error' })
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
async function refreshAll() {
|
|
57
|
+
await Promise.all([refresh(), refreshSchedules()])
|
|
58
|
+
if (detailOpen.value && selected.value) selected.value = await jobs.call('jobs.get', { id: selected.value.id })
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// Live view while anything is queued or running; the toggle stops it.
|
|
62
|
+
const { pause, resume } = useIntervalFn(
|
|
63
|
+
() => {
|
|
64
|
+
if (!document.hidden) void refreshAll()
|
|
65
|
+
},
|
|
66
|
+
3000,
|
|
67
|
+
{ immediate: false },
|
|
68
|
+
)
|
|
69
|
+
onMounted(() => {
|
|
70
|
+
watch(autoRefresh, on => (on ? resume() : pause()), { immediate: true })
|
|
71
|
+
})
|
|
72
|
+
|
|
73
|
+
async function onEnqueued(id: string) {
|
|
74
|
+
await refreshAll()
|
|
75
|
+
await openJob(id)
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
async function runNow(jobName: string) {
|
|
79
|
+
try {
|
|
80
|
+
const result = await jobs.call('jobs.enqueue', { name: jobName })
|
|
81
|
+
toast.add({
|
|
82
|
+
title: result.skipped ? `${jobName} is already queued` : `${jobName} queued`,
|
|
83
|
+
color: result.skipped ? 'neutral' : 'success',
|
|
84
|
+
})
|
|
85
|
+
await refreshAll()
|
|
86
|
+
} catch (error) {
|
|
87
|
+
toast.add({ title: `Could not queue ${jobName}`, description: actionErrorMessage(error), color: 'error' })
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const stateItems = computed(() => [
|
|
92
|
+
{ value: 'all', label: 'All states' },
|
|
93
|
+
...JOB_STATES.map(value => ({ value, label: `${JOB_STATE_META[value].label} (${data.value?.counts[value] ?? 0})` })),
|
|
94
|
+
])
|
|
95
|
+
const nameItems = computed(() => [
|
|
96
|
+
{ value: 'all', label: 'All jobs' },
|
|
97
|
+
...(data.value?.names ?? []).map(value => ({ value, label: value })),
|
|
98
|
+
])
|
|
99
|
+
|
|
100
|
+
const columns: TableColumn<JobDto>[] = [
|
|
101
|
+
{ accessorKey: 'name', header: 'Job' },
|
|
102
|
+
{ accessorKey: 'state', header: 'State' },
|
|
103
|
+
{ accessorKey: 'requestedBy', header: 'Requested by' },
|
|
104
|
+
{ accessorKey: 'createdAt', header: 'Created' },
|
|
105
|
+
{ id: 'duration', header: 'Duration' },
|
|
106
|
+
{ id: 'actions', header: () => h('span', { class: 'sr-only' }, 'Actions') },
|
|
107
|
+
]
|
|
108
|
+
</script>
|
|
109
|
+
|
|
110
|
+
<template>
|
|
111
|
+
<UDashboardPanel id="jobs">
|
|
112
|
+
<template #header>
|
|
113
|
+
<AppHeader
|
|
114
|
+
title="Jobs"
|
|
115
|
+
:badge="data?.total"
|
|
116
|
+
>
|
|
117
|
+
<template #actions>
|
|
118
|
+
<!-- The app's own buttons (e.g. an import form that enqueues a job): override `JobsActions`. -->
|
|
119
|
+
<JobsActions @enqueued="onEnqueued" />
|
|
120
|
+
</template>
|
|
121
|
+
</AppHeader>
|
|
122
|
+
<UDashboardToolbar>
|
|
123
|
+
<template #left>
|
|
124
|
+
<USelect
|
|
125
|
+
v-model="state"
|
|
126
|
+
:items="stateItems"
|
|
127
|
+
class="w-44"
|
|
128
|
+
aria-label="State"
|
|
129
|
+
/>
|
|
130
|
+
<USelect
|
|
131
|
+
v-model="name"
|
|
132
|
+
:items="nameItems"
|
|
133
|
+
class="w-52"
|
|
134
|
+
aria-label="Job"
|
|
135
|
+
/>
|
|
136
|
+
</template>
|
|
137
|
+
<template #right>
|
|
138
|
+
<USwitch
|
|
139
|
+
v-model="autoRefresh"
|
|
140
|
+
label="Auto-refresh"
|
|
141
|
+
/>
|
|
142
|
+
<UButton
|
|
143
|
+
icon="i-lucide-refresh-cw"
|
|
144
|
+
color="neutral"
|
|
145
|
+
variant="ghost"
|
|
146
|
+
aria-label="Refresh"
|
|
147
|
+
@click="refreshAll"
|
|
148
|
+
/>
|
|
149
|
+
</template>
|
|
150
|
+
</UDashboardToolbar>
|
|
151
|
+
</template>
|
|
152
|
+
|
|
153
|
+
<template #body>
|
|
154
|
+
<UTable
|
|
155
|
+
:data="data?.items ?? []"
|
|
156
|
+
:columns="columns"
|
|
157
|
+
:loading="loadStatus === 'pending'"
|
|
158
|
+
empty="No jobs yet. Run a scheduled job, or enqueue one."
|
|
159
|
+
class="shrink-0 [&_tbody_tr]:cursor-pointer"
|
|
160
|
+
data-testid="jobs-table"
|
|
161
|
+
@select="(_event: Event, row: { original: JobDto }) => openJob(row.original.id)"
|
|
162
|
+
>
|
|
163
|
+
<template #name-cell="{ row }">
|
|
164
|
+
<span class="font-medium text-highlighted">{{ row.original.name }}</span>
|
|
165
|
+
</template>
|
|
166
|
+
<template #state-cell="{ row }">
|
|
167
|
+
<UBadge
|
|
168
|
+
:color="JOB_STATE_META[row.original.state].color"
|
|
169
|
+
:icon="JOB_STATE_META[row.original.state].icon"
|
|
170
|
+
variant="subtle"
|
|
171
|
+
:label="JOB_STATE_META[row.original.state].label"
|
|
172
|
+
/>
|
|
173
|
+
</template>
|
|
174
|
+
<template #requestedBy-cell="{ row }">
|
|
175
|
+
<span class="text-muted">{{ row.original.requestedBy?.name ?? 'System (cron)' }}</span>
|
|
176
|
+
</template>
|
|
177
|
+
<template #createdAt-cell="{ row }">
|
|
178
|
+
<span class="text-muted">{{ formatDateTime(row.original.createdAt) }}</span>
|
|
179
|
+
</template>
|
|
180
|
+
<template #duration-cell="{ row }">
|
|
181
|
+
<span class="text-muted tabular-nums">{{ jobDuration(row.original) }}</span>
|
|
182
|
+
</template>
|
|
183
|
+
<template #actions-cell="{ row }">
|
|
184
|
+
<div
|
|
185
|
+
class="flex justify-end"
|
|
186
|
+
@click.stop
|
|
187
|
+
>
|
|
188
|
+
<JobControls
|
|
189
|
+
:job="row.original"
|
|
190
|
+
@changed="refreshAll"
|
|
191
|
+
/>
|
|
192
|
+
</div>
|
|
193
|
+
</template>
|
|
194
|
+
</UTable>
|
|
195
|
+
<div
|
|
196
|
+
v-if="(data?.total ?? 0) > PAGE_SIZE"
|
|
197
|
+
class="flex justify-end"
|
|
198
|
+
>
|
|
199
|
+
<UPagination
|
|
200
|
+
v-model:page="page"
|
|
201
|
+
:total="data?.total ?? 0"
|
|
202
|
+
:items-per-page="PAGE_SIZE"
|
|
203
|
+
/>
|
|
204
|
+
</div>
|
|
205
|
+
|
|
206
|
+
<UCard :ui="{ body: 'p-0 sm:p-0' }">
|
|
207
|
+
<template #header>
|
|
208
|
+
<div class="flex items-center gap-2">
|
|
209
|
+
<UIcon
|
|
210
|
+
name="i-lucide-calendar-clock"
|
|
211
|
+
class="size-5 text-primary"
|
|
212
|
+
/>
|
|
213
|
+
<h2 class="font-semibold text-highlighted">
|
|
214
|
+
Schedules
|
|
215
|
+
</h2>
|
|
216
|
+
<span class="text-sm text-muted">cron, UTC</span>
|
|
217
|
+
</div>
|
|
218
|
+
</template>
|
|
219
|
+
<ul
|
|
220
|
+
v-if="schedules?.items.length"
|
|
221
|
+
class="divide-y divide-default"
|
|
222
|
+
data-testid="jobs-schedules"
|
|
223
|
+
>
|
|
224
|
+
<li
|
|
225
|
+
v-for="schedule in schedules.items"
|
|
226
|
+
:key="`${schedule.name}:${schedule.key}`"
|
|
227
|
+
class="flex flex-wrap items-center gap-x-4 gap-y-1 px-4 py-3"
|
|
228
|
+
>
|
|
229
|
+
<div class="min-w-0 flex-1">
|
|
230
|
+
<p class="font-medium text-highlighted">
|
|
231
|
+
{{ schedule.name }}
|
|
232
|
+
<code class="ml-2 rounded bg-elevated px-1.5 py-0.5 text-xs text-muted">{{ schedule.cron }}</code>
|
|
233
|
+
</p>
|
|
234
|
+
<p class="text-sm text-muted">
|
|
235
|
+
{{ schedule.description }}
|
|
236
|
+
</p>
|
|
237
|
+
</div>
|
|
238
|
+
<div class="text-sm text-muted">
|
|
239
|
+
Next: {{ formatDateTime(schedule.nextRunAt) }}
|
|
240
|
+
</div>
|
|
241
|
+
<UButton
|
|
242
|
+
v-if="schedule.lastJobId"
|
|
243
|
+
label="Last run"
|
|
244
|
+
color="neutral"
|
|
245
|
+
variant="ghost"
|
|
246
|
+
size="xs"
|
|
247
|
+
@click="openJob(schedule.lastJobId)"
|
|
248
|
+
/>
|
|
249
|
+
<UButton
|
|
250
|
+
icon="i-lucide-play"
|
|
251
|
+
label="Run now"
|
|
252
|
+
color="neutral"
|
|
253
|
+
variant="outline"
|
|
254
|
+
size="xs"
|
|
255
|
+
@click="runNow(schedule.name)"
|
|
256
|
+
/>
|
|
257
|
+
</li>
|
|
258
|
+
</ul>
|
|
259
|
+
<p
|
|
260
|
+
v-else
|
|
261
|
+
class="px-4 py-3 text-sm text-muted"
|
|
262
|
+
>
|
|
263
|
+
No schedules. They are registered by the process that runs handlers (APP_ROLE all or worker).
|
|
264
|
+
</p>
|
|
265
|
+
</UCard>
|
|
266
|
+
|
|
267
|
+
<JobDetailSlideover
|
|
268
|
+
v-model:open="detailOpen"
|
|
269
|
+
:job="selected"
|
|
270
|
+
@changed="refreshAll"
|
|
271
|
+
/>
|
|
272
|
+
</template>
|
|
273
|
+
</UDashboardPanel>
|
|
274
|
+
</template>
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { BadgeProps } from '@nuxt/ui'
|
|
2
|
+
import type { JobState } from '../../shared/jobs'
|
|
3
|
+
|
|
4
|
+
type Color = NonNullable<BadgeProps['color']>
|
|
5
|
+
|
|
6
|
+
export const JOB_STATE_META: Record<JobState, { label: string; color: Color; icon: string }> = {
|
|
7
|
+
created: { label: 'Queued', color: 'neutral', icon: 'i-lucide-clock' },
|
|
8
|
+
retry: { label: 'Retrying', color: 'warning', icon: 'i-lucide-rotate-cw' },
|
|
9
|
+
active: { label: 'Running', color: 'info', icon: 'i-lucide-loader-circle' },
|
|
10
|
+
completed: { label: 'Completed', color: 'success', icon: 'i-lucide-circle-check' },
|
|
11
|
+
cancelled: { label: 'Cancelled', color: 'neutral', icon: 'i-lucide-ban' },
|
|
12
|
+
failed: { label: 'Failed', color: 'error', icon: 'i-lucide-circle-x' },
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** `1.2 s`, `3 min`: how long a finished job ran (no clock reads, so server and browser render the same). */
|
|
16
|
+
export function jobDuration(job: { startedAt: string | null; completedAt: string | null }): string {
|
|
17
|
+
if (!job.startedAt || !job.completedAt) return '—'
|
|
18
|
+
const ms = new Date(job.completedAt).getTime() - new Date(job.startedAt).getTime()
|
|
19
|
+
if (ms < 1000) return `${Math.max(ms, 0)} ms`
|
|
20
|
+
if (ms < 60_000) return `${(ms / 1000).toFixed(1)} s`
|
|
21
|
+
return `${Math.round(ms / 60_000)} min`
|
|
22
|
+
}
|
package/nuxt.config.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { defineNuxtConfig } from 'nuxt/config'
|
|
2
|
+
|
|
3
|
+
// Layer: `extends: ['@skaile/forge-layer-jobs']` in an app built on forge-template-app.
|
|
4
|
+
//
|
|
5
|
+
// pg-boss on the app's database, APP_ROLE, the `jobs.*` actions and the Jobs
|
|
6
|
+
// page. The app defines its jobs with `defineJob` and registers them from its
|
|
7
|
+
// own Nitro plugin (host contract in README.md). Remove the `extends` entry to
|
|
8
|
+
// drop background jobs.
|
|
9
|
+
export default defineNuxtConfig({})
|