@xeplr/ui-jobs 1.0.1 → 1.0.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 CHANGED
@@ -1,14 +1,30 @@
1
1
  # @xeplr/ui-jobs
2
2
 
3
- **The screens for [`@xeplr/jobs`](https://www.npmjs.com/package/@xeplr/jobs).** Create a job, schedule it with cron, run it now, pause and resume it, and watch its occurrences and logs. It ships as React routes your app registers, or as a small standalone app.
3
+ **The screens for [`@xeplr/jobs`](https://www.npmjs.com/package/@xeplr/jobs).** Create a job, schedule it with cron, run it now, pause and resume it, and watch its runs, live progress and logs. It ships as React routes your app registers, or as a small standalone app.
4
4
 
5
- (The package name on npm is `@xeplr/ui-jobs` — the GitHub repo and folder are named `xeplr-ui-jobs`.)
5
+ ```jsx
6
+ import { registerJobsUI } from '@xeplr/ui-jobs'
7
+
8
+ const jobs = registerJobsUI({ basePath: '/workspace' }) // page at /workspace/jobs
9
+
10
+ <Routes>
11
+ {/* …your routes… */}
12
+ {jobs.routes}
13
+ </Routes>
14
+ ```
6
15
 
7
- ## Why
16
+ ## How the pieces fit
8
17
 
9
- Jobs is a product: a scheduler, an HTTP API **and** the screens for both. Without this package, every app that wanted to schedule something rebuilt those screens itself, and each copy drifted from the backend it talked to.
18
+ | what | where |
19
+ |---|---|
20
+ | The jobs page | `registerJobsUI()` → `<Route>` elements for your `<Routes>` |
21
+ | Router, auth gate, layout, breadcrumb | **your app** — the package owns only the jobs screen |
22
+ | Authenticated requests (token, tenant headers) | `authFetch` from `@xeplr/ui-account` |
23
+ | Confirm dialogs, error toasts | `raiseConfirm`, `raiseSnackbar` from `@xeplr/ui-utils` |
24
+ | The API, the scheduler, the action registry | `@xeplr/jobs` on the server: `init()`, then `router()`, then `startScheduler()` |
25
+ | The input form for a job | generated from the chosen action's `inputSchema`, as served by `GET /actions` |
10
26
 
11
- So the UI belongs to the jobs product, and a host supplies only the **infrastructure** it already has: the router, the auth gate, the layout. That is the same split the backend makes — `registerJobs()` mounts into an Express app you already have, or stands up its own.
27
+ Why the UI lives here: jobs is one product — a scheduler, an HTTP API **and** its screens. Before this package, a host that wanted to schedule something rebuilt the screens, and each copy drifted from the backend. A host now supplies only the infrastructure it already has, the same split the backend makes (`@xeplr/jobs`' `router()` mounts in your Express app, or `start()` / `xeplr-jobs-server` stands up its own).
12
28
 
13
29
  ## Install
14
30
 
@@ -16,104 +32,148 @@ So the UI belongs to the jobs product, and a host supplies only the **infrastruc
16
32
  npm i @xeplr/ui-jobs
17
33
  ```
18
34
 
19
- Peer dependencies: `react ^18 || ^19`, `react-router-dom ^6 || ^7`, `@xeplr/ui-account` (authenticated requests) and `@xeplr/ui-utils` (confirm dialogs and snackbars).
35
+ Peers: `react` 18 or 19, `react-router-dom` 6 or 7, `@xeplr/ui-account`, `@xeplr/ui-utils`.
36
+
37
+ The package ships `src/` untranspiled — JSX, and CSS imported from the components — so your bundler must compile both (Vite does).
38
+
39
+ ### The backend
20
40
 
21
- Your bundler must compile JSX and import CSS from the package (Vite does both out of the box).
41
+ ```js
42
+ // server
43
+ var jobs = require('@xeplr/jobs')
44
+
45
+ await jobs.init({ database: process.env.DB_JOBS, connection: appConnection, mts: appMtConfig })
46
+ app.use(jobs.router({ auth: authMiddleware }))
47
+ jobs.startScheduler()
48
+ ```
22
49
 
23
- The backend is [`@xeplr/jobs`](https://www.npmjs.com/package/@xeplr/jobs). By default the screens call its routes at your API root: `/jobs`, `/job-occurrences` and `/actions`.
50
+ See the [`@xeplr/jobs` README](https://www.npmjs.com/package/@xeplr/jobs) for migrations, the permissions in `migrations-auth/` (`jobs:view`, `jobs:create`, `jobs:run`, `jobs:manage`) and which actions a job may run.
24
51
 
25
52
  ## Embed it in your app
26
53
 
27
54
  ```jsx
28
- import { BrowserRouter, Routes, Route } from 'react-router-dom'
29
- import { AccessProvider } from '@xeplr/ui-account'
55
+ import { BrowserRouter, Routes, Route, Link } from 'react-router-dom'
56
+ import { configure, AccessProvider } from '@xeplr/ui-account'
30
57
  import { registerJobsUI } from '@xeplr/ui-jobs'
31
58
 
32
- const jobs = registerJobsUI({ basePath: '/workspace' }) // → /workspace/jobs
59
+ configure(import.meta.env.VITE_API_URL) // where authFetch sends requests
60
+ const jobs = registerJobsUI({ basePath: '/workspace', breadcrumb: MyBreadcrumb })
33
61
 
34
62
  export function App() {
35
63
  return (
36
64
  <BrowserRouter>
37
65
  <AccessProvider>
66
+ <nav><Link to={jobs.path}>Jobs</Link></nav>
38
67
  <Routes>
39
- {/* ...your routes... */}
40
68
  {jobs.routes}
41
69
  </Routes>
42
70
  </AccessProvider>
43
71
  </BrowserRouter>
44
72
  )
45
73
  }
46
-
47
- // Point your own navigation at the same path instead of retyping it:
48
- // <Link to={jobs.path}>Jobs</Link>
49
74
  ```
50
75
 
51
- There is no embedded/standalone switch. `registerJobsUI()` returns `<Route>` elements; what differs is who wraps them.
76
+ There is no embedded / standalone switch: `registerJobsUI()` returns `<Route>` elements, and what differs is who wraps them.
52
77
 
53
78
  ## `registerJobsUI(config)`
54
79
 
55
- | option | type | default | notes |
56
- |---|---|---|---|
57
- | `basePath` | string | `''` | prefix for the jobs page path, e.g. `'/workspace'` → `/workspace/jobs` |
58
- | `apiBase` | string | `''` | prefix for API calls, if you mounted the jobs router somewhere other than the root |
59
- | `optionSources` | object | — | where a *kind* of thing is listed, for action inputs that declare `optionsFrom` (see below) |
60
- | `breadcrumb` | component | — | your breadcrumb, rendered above the page |
61
- | `uploadLink` | element \| string | — | a link to wherever your app loads files, shown in the empty state |
62
- | `connectLink` | element | — | a link to a workflow canvas, for starting one job when another finishes |
80
+ | option | default | |
81
+ |---|---|---|
82
+ | `basePath` | `''` | prefix for the page path: `'/workspace'` → `/workspace/jobs` |
83
+ | `apiBase` | `''` | prefix for the jobs API paths, when `router()` is mounted under a path rather than at your API root |
84
+ | `optionSources` | `{}` | where a kind of thing is listed, for action inputs with `optionsFrom` — see below |
85
+ | `breadcrumb` | — | a component, rendered as `<Breadcrumb items={[{ label: 'Jobs' }]} />` above the page |
86
+ | `uploadLink` | — | element or string, shown in the page footnote ("Loading a file into a table is recorded separately — see …"); without it the footnote says "the upload screen" |
87
+ | `connectLink` | — | element shown in the header before **+ New job** — a link to a workflow canvas for chaining jobs. Passed in rather than imported, so this package does not depend on workflow (which already calls jobs over HTTP) |
63
88
 
64
- Returns `{ routes, path }`.
89
+ Returns `{ routes, path }`: one `<Route>` at `path`, and the path itself so your navigation does not retype it.
65
90
 
66
- ### Option sources
91
+ `apiBase` and `optionSources` are module-level settings — the last `registerJobsUI()` call wins.
92
+
93
+ ## Requests
94
+
95
+ Every call goes through `authFetch`, which prefixes the base URL `@xeplr/ui-account` was `configure`d with and adds the token and tenant headers.
96
+
97
+ | call | route (after `apiBase`) |
98
+ |---|---|
99
+ | job list | `GET /jobs?limit=0` |
100
+ | what is running (polled) | `GET /jobs/active` |
101
+ | last run per job, recent runs | `GET /job-occurrences?limit=0` |
102
+ | one job's history | `GET /jobs/:id/occurrences?limit=50` |
103
+ | action catalogue | `GET /actions` |
104
+ | save | `POST /jobs/save` with `[job]` |
105
+ | delete | `POST /jobs/delete` with `{ ids: [id] }` |
106
+ | run now | `POST /jobs/:id/trigger` |
107
+ | pause / resume | `POST /jobs/:id/pause`, `POST /jobs/:id/resume` |
108
+ | a run's log lines | `GET /logs?referenceId=<occurrenceId>` — **not** under `apiBase` |
109
+ | an option list | `GET <source.url>?limit=0` — under `apiBase` |
67
110
 
68
- An action input can say it wants a choice from a kind of thing — `optionsFrom: 'connections'`. This package never learns what a connection is; your app says once where each kind is listed:
111
+ `/logs` is the platform's generic log route, not part of `@xeplr/jobs`. A host without it answers 404 and the panel shows an error in place of the log. Log lines are keyed by occurrence id because an action writes under the `referenceId` it is handed.
112
+
113
+ ## The screen
114
+
115
+ - **Jobs table** — name, state (Running, Paused, Manual only, Scheduled), schedule in words (`describeCron`, else "Custom"), next run ("in 3 hours", "due now"), last run, an **on / paused switch**, and **Run now**, **Edit**, **Delete** (confirmed; run history is kept). Search matches name, description and action; sort by name, next run or action.
116
+ - **Run history** — the last-run cell opens that job's newest 50 runs, each with its log.
117
+ - **Recent runs** — the 12 latest runs across all jobs, with duration, trigger and error message.
118
+ - **Live updates** (on by default) — polls `GET /jobs/active` every **2 s** while anything runs and every **15 s** otherwise, so a cron run that starts by itself appears; when the last run finishes, the page reloads once to pick up the final status. Rows show rows read and when the run last made progress (`1.2K rows · last seen 8 s ago`); a run with no progress for **5 minutes** (`SILENT_MS`) reads "Not responding", because the work beats on every batch it moves. Uncheck to stop polling.
119
+
120
+ State shows **Running** over **Paused**: a pause takes effect at the next pick, and "paused" over a live run invites starting a second one. A job with no schedule has its switch off and disabled — there is nothing for the scheduler to pick.
121
+
122
+ ### The editor
123
+
124
+ Three steps, all reachable at any time, with **Save job** on each:
125
+
126
+ 1. **Job** — name, description, action.
127
+ 2. **Inputs** — a control per field of the action's `inputSchema`: a select for `options`, true/false for `boolean`, a number input, a JSON textarea for `object` / `array` (invalid JSON blocks the save), text otherwise. Fields marked `system: true` are never shown — the server fills them, and rendering them would ask for a credential. Optional fields with a `default` are under **Advanced**, whose summary lists their values. Values are converted to the declared types on save, since `@xeplr/schema-handler` rejects `"1000"` for a number.
128
+ 3. **Schedule** — cron (`CronScheduleField`), status, **Start from** (`startAt`), **Retry on failure** (0–3, default 0), **Give up after** (`timeoutMinutes`, blank = server default of 30).
129
+
130
+ A new job with a schedule defaults to **Paused**, so it can be written now and started later. A job with no schedule is saved as `ready` and runs only when triggered.
131
+
132
+ ## Option sources
133
+
134
+ An input field can ask for a choice from a kind of thing — `optionsFrom: 'connections'`. This package never learns what a connection is; your app says where each kind is listed:
69
135
 
70
136
  ```js
71
137
  registerJobsUI({
72
138
  optionSources: {
73
139
  connections: { url: '/connectioninfo', label: 'label' },
74
- databases: { url: '/databases', label: 'name' }
140
+ tables: { url: '/warehouse/tables', key: 'tables', value: 'name', label: 'name' }
75
141
  }
76
142
  })
77
143
  ```
78
144
 
79
- A kind with no source gets a plain text input. Standalone, with no catalogue to pick from, a text box is the right answer; an empty dropdown would look broken.
145
+ | source key | default | |
146
+ |---|---|---|
147
+ | `url` | — | fetched with `?limit=0` |
148
+ | `label` | — | row field shown |
149
+ | `value` | `'id'` | row field stored |
150
+ | `key` | `'dataArray'` | response property holding the rows — named, not guessed, because a wrong guess is an empty dropdown with no error |
151
+
152
+ - **A kind with no source gets a plain text input.** An empty dropdown looks broken; a text box is what you have without a catalogue.
153
+ - A field with `dependsOn: 'connectionInfoId'` stays disabled until that field has a value, then requests `?connectionInfoId=<value>` and keeps only rows whose `connectionId` equals it.
154
+ - A failed fetch says "Could not load the list" rather than showing an empty one.
80
155
 
81
156
  ## Other exports
82
157
 
83
- | export | what |
158
+ | export | |
84
159
  |---|---|
85
- | `CronScheduleField` | the cron input with presets and a plain-English reading — `<CronScheduleField value={cron} onChange={setCron} />` |
86
- | `CRON_PRESETS` | the presets it offers |
87
- | `describeCron(expr)` | a cron expression as a sentence — `'*/15 * * * *'` → "Every 15 minutes", `'0 0 1 * *'` → "Monthly on day 1 at 00:00"; `null` for a pattern it has no sentence for |
88
- | `jobsRoutes` | `{ jobs(base) }` — the page path, for building links |
160
+ | `CronScheduleField` | `<CronScheduleField value={cron} onChange={setCron} id? />` — presets, a custom cron input and a plain-English reading |
161
+ | `CRON_PRESETS` | manual only, every 15 minutes, hourly, daily 02:00, weekly Monday 06:00, monthly 1st 03:00 |
162
+ | `describeCron(expr)` | five-field cron → sentence: `'*/15 * * * *'` → "Every 15 minutes", `'30 */6 * * *'` → "Every 6 hours, at 30 past", `'0 6 * * 1'` → "Every Monday at 06:00", `'0 3 1 * *'` → "Monthly on day 1 at 03:00". **`null` for ranges, lists or anything else** — a wrong reading is worse than the raw cron |
163
+ | `jobsRoutes` | `{ jobs(base) }` → `base + '/jobs'` |
89
164
 
90
165
  ## Run it standalone
91
166
 
92
167
  ```sh
93
168
  npm install
94
- npm run dev # http://localhost:19004 — set API_URL, AUTH_URL, UI_PORT in .env to change
169
+ npm run dev # http://localhost:19004
95
170
  ```
96
171
 
97
- `dev/` holds the standalone shell: login screens from `@xeplr/ui-account`, an auth gate, and one call to `registerJobsUI({})`, the same call a host makes. `vite.config.js` proxies the API paths to `API_URL` (default `http://localhost:19003`). None of `dev/` is published.
172
+ `dev/` is the shell a host would otherwise provide: `@xeplr/ui-account`'s login routes, a `ProtectedRoute`, tenancy headers `x-company-id` / `x-workspace-id` (keep them in step with the API's `registerMTs`), and the same `registerJobsUI({})` call. `vite.config.js` proxies `/auth/api` to `AUTH_URL` and `/me`, `/companies`, `/workspaces`, `/jobs`, `/job-occurrences`, `/actions` to `API_URL` (default `http://localhost:19003`, the `xeplr-jobs-server` port). `UI_PORT` changes the dev port. `/logs` is not proxied. `dev/` is not published.
98
173
 
99
174
  ## Theming
100
175
 
101
- Styles use the xeplr theme variables — `--accent`, `--surface`, `--ink`, `--muted`, `--hair`, `--plane` and the `--xeplr-*` status, tag and input colours. Each has a light-theme fallback, so the screens look right in an app that defines none of them. Define them to restyle.
102
-
103
- ## Files
104
-
105
- ```
106
- src/
107
- index.jsx ─ registerJobsUI and the public exports
108
- routes.js ─ page paths
109
- api/jobs.js ─ API calls, option sources
110
- pages/Jobs.jsx · Jobs.css ─ the jobs screen
111
- pages/jobsList.js ─ pure: job state, cron descriptions, next run, durations
112
- pages/relativeTime.js ─ pure: "3 minutes ago"
113
- components/CronScheduleField.jsx · .css
114
- dev/ ─ standalone app shell (not published)
115
- test/ ─ plain Node scripts, no framework
116
- ```
176
+ Styles read `--accent`, `--surface`, `--ink`, `--muted`, `--hair`, `--plane` and `--xeplr-*` tokens (`--xeplr-accent`, `--xeplr-accent-soft`, `--xeplr-text`, `--xeplr-text-secondary`, `--xeplr-muted-2`, `--xeplr-hover`, `--xeplr-border-secondary`, `--xeplr-border-strong`, `--xeplr-input-bg`, `--xeplr-input-border`, `--xeplr-input-text`, `--xeplr-tag-bg`, `--xeplr-tag-text`, `--xeplr-success`, `--xeplr-warning`, `--xeplr-danger`, `--xeplr-error`, `--xeplr-status-good`, `--xeplr-status-warn`, `--xeplr-status-critical` and their `-soft` variants), each with a fallback. Class names are prefixed `jb-` (page) and `csf-` (cron field).
117
177
 
118
178
  ## Tests
119
179
 
@@ -121,6 +181,8 @@ test/ ─ plain Node scripts, no framework
121
181
  npm test
122
182
  ```
123
183
 
184
+ Plain Node scripts, no framework (`test/run.mjs` runs each `*.test.*` file): job state, `describeCron`, next-run and duration labels, latest run per job, search and sort.
185
+
124
186
  ## License
125
187
 
126
188
  MIT
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xeplr/ui-jobs",
3
- "version": "1.0.1",
3
+ "version": "1.0.3",
4
4
  "description": "The screens for @xeplr/jobs — schedule, run, pause and watch jobs — as routes a host app registers, or a standalone app",
5
5
  "type": "module",
6
6
  "main": "src/index.jsx",
@@ -8,7 +8,7 @@ import {
8
8
  } from '../api/jobs.js'
9
9
  import {
10
10
  jobState, STATE_LABELS, describeCron, nextRunLabel, durationLabel,
11
- latestByJob, prepareJobs, progressLabel, progressStale
11
+ latestByJob, prepareJobs, progressLabel, progressStale, lastSeenLabel
12
12
  } from './jobsList.js'
13
13
  import CronScheduleField from '../components/CronScheduleField.jsx'
14
14
  import './Jobs.css'
@@ -1069,10 +1069,12 @@ export default function Jobs({ breadcrumb: Breadcrumb, uploadLink, connectLink }
1069
1069
  <span
1070
1070
  className={progressStale(liveRun) ? 'jb-progress jb-progress--stale' : 'jb-progress'}
1071
1071
  title={progressStale(liveRun)
1072
- ? 'No update recently — the run may be in a long final write, or the worker may have died.'
1072
+ ? 'No progress for five minutes: the worker doing this has most likely died.'
1073
1073
  : `Rows read so far. Last update ${new Date(liveRun.progress.at).toLocaleTimeString()}.`}
1074
1074
  >
1075
+ {progressStale(liveRun) ? 'Not responding · ' : ''}
1075
1076
  {progressLabel(liveRun)}
1077
+ {lastSeenLabel(liveRun) ? ` · ${lastSeenLabel(liveRun)}` : ''}
1076
1078
  </span>
1077
1079
  )}
1078
1080
  </td>
@@ -186,11 +186,28 @@ export function formatCount(n) {
186
186
  * what lets a row say "no update for 9m" instead of showing a stale count as
187
187
  * though it were current.
188
188
  *
189
- * Advisory only — a movement legitimately goes quiet during a long final
190
- * drain. It is a prompt to look, not a verdict.
189
+ * Five minutes (SILENT_MS): the work beats on every batch it moves, so a
190
+ * run silent that long is not running, whatever its status says.
191
191
  */
192
- export function progressStale(occurrence, now = Date.now(), toleranceMs = 120000) {
192
+ export function progressStale(occurrence, now = Date.now(), toleranceMs = SILENT_MS) {
193
193
  const at = occurrence && occurrence.progress && occurrence.progress.at
194
194
  if (!at) return false
195
195
  return now - new Date(at).getTime() > toleranceMs
196
196
  }
197
+
198
+ /**
199
+ * How long a run may go without progress before it is treated as not
200
+ * running: five minutes, the same rule the host applies to the action runs
201
+ * it records (a job's progress IS its action's progress).
202
+ */
203
+ export const SILENT_MS = 5 * 60 * 1000
204
+
205
+ /** "last seen 8 s ago" / "last seen 7 min ago" from progress.at, or null. */
206
+ export function lastSeenLabel(occurrence, now = Date.now()) {
207
+ const at = occurrence && occurrence.progress && occurrence.progress.at
208
+ if (!at) return null
209
+ const secs = Math.max(0, Math.round((now - new Date(at).getTime()) / 1000))
210
+ if (secs < 60) return `last seen ${secs} s ago`
211
+ if (secs < 3600) return `last seen ${Math.floor(secs / 60)} min ago`
212
+ return `last seen ${Math.floor(secs / 3600)} h ago`
213
+ }