@xeplr/ui-jobs 1.6.1 → 1.6.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
@@ -84,7 +84,7 @@ There is no embedded / standalone switch: `registerJobsUI()` returns `<Route>` e
84
84
  | `optionSources` | `{}` | where a kind of thing is listed, for action inputs with `optionsFrom` — see below |
85
85
  | `breadcrumb` | — | a component, rendered as `<Breadcrumb items={[{ label: 'Jobs' }]} />` above the page |
86
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
- | `chainsApiBase` | `null` | where the **workflow** API is mounted (e.g. `'/workflow'`). It keeps each job's "After this job" rules (`/job-chains/:jobId`), because jobs never start each other: the workflow engine does every hand-off. `null` (no workflow on the install) leaves the editor's **After this job** step out. HTTP only; this package does not import workflow |
87
+ | `chainsApiBase` | `null` | where the **workflow** API is mounted (e.g. `'/workflow'`). A job's "After this job" rules are an ordinary workflow there, triggered by the job finishing, because jobs never start each other: the workflow engine does every hand-off. `null` (no workflow on the install) leaves the editor's **After this job** step out. HTTP only; this package does not import workflow |
88
88
 
89
89
  Returns `{ routes, path }`: one `<Route>` at `path`, and the path itself so your navigation does not retype it.
90
90
 
@@ -108,7 +108,7 @@ Every call goes through `authFetch`, which prefixes the base URL `@xeplr/ui-acco
108
108
  | a run's log lines | `GET /logs?referenceId=<occurrenceId>` — **not** under `apiBase` |
109
109
  | an option list | `GET <source.url>?limit=0` — under `apiBase` |
110
110
  | name suggestions | `GET <source.url>?limit=0&<param>=<value>…` for each of the field's `suggestWith` — under `apiBase` |
111
- | a job's "After this job" rules | `GET` / `PUT <chainsApiBase>/job-chains/:jobId` with `{ rules, jobName }` — **not** under `apiBase` |
111
+ | a job's "After this job" rules | the workflow API's ordinary routes, **not** under `apiBase`. `GET <chainsApiBase>/workflows/by-key/after-job-<jobId>` reads this job's shortcut workflow, `GET <chainsApiBase>/workflows/by-trigger?kind=job&jobId=<jobId>` finds every workflow the job starts, and `POST <chainsApiBase>/workflows/save` saves the shortcut |
112
112
 
113
113
  `/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.
114
114
 
@@ -137,6 +137,13 @@ Three steps (four with `chainsApiBase`), all reachable at any time, with **Save
137
137
 
138
138
  The period this job ran for passes to the next job by itself. Text that is not JSON, a missing job, or an "otherwise" that is not last is refused before anything is saved; the server checks the meaning and names the rule. An existing job's rules are saved before the job, and a new job's right after it (it needs its id).
139
139
 
140
+ **The rules are an ordinary workflow.** It is triggered by this job finishing (`{ kind: 'job', jobId, when: 'finished' }`) and kept under the key `after-job-<jobId>`:
141
+ - a `decide` step with one `when` arrow per rule, which the engine compiles;
142
+ - one `job-run` step per rule;
143
+ - conditions and bindings stored against the trigger (`trigger.status`, `{trigger.output.region}`), while the form keeps the short names.
144
+
145
+ Removing every rule keeps the workflow as a draft, so it stops running. If the workflow is reshaped in the workflow screens (another step, another trigger, an arrow without `when`), this step says so and shows nothing to edit, rather than rules that are not what runs. Other workflows the job's finish starts are listed by name.
146
+
140
147
  An input the action marks `control: 'parameters'` (a procedure's parameters) is shown as rows, not JSON (`ParametersField`, `lib/parametersModel.js`): a parameter's name, and where its value comes from: **Start of the window**, **End of the window** (saved as `{window.from}` / `{window.to}`, which `@xeplr/jobs` fills in with the run's dates) or a **Fixed value**. The choices are the jobs package's run contract (`GET /jobs/run-contract`, `useRunContract`), grouped: **This run** (start / end of the window) and **The job before** (the range it was given and the range it actually used, start / end). A job with no parameters starts with none (**+ Add parameter**). When the action names a `suggestFrom` source (`db-procedure`: `procedureParams`, asked with the connection, database and procedure), clicking a name box opens a list of the procedure's own parameter names (`NameBox`), minus those already used and narrowed by what is typed; when it cannot have them yet it says which of connection, database and procedure is still to be chosen. A row with neither name nor value is not saved. An input marked `hidden` (the procedure's old **Window**) is shown only when a job already holds one.
141
148
 
142
149
  A job's saved `acceptsInputs` (what the job before may fill) is kept as it is but no longer edited here: a job takes what it needs from the job before through its parameters. The **After this job** rules offer a condition, the job to run and values to **carry** for later jobs.
@@ -195,7 +202,7 @@ Styles read `--accent`, `--surface`, `--ink`, `--muted`, `--hair`, `--plane` and
195
202
  npm test
196
203
  ```
197
204
 
198
- 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; and the "After this job" form's rules: text to rules and back, what is refused, what the job before may fill (`jobChainModel.test.mjs`).
205
+ 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; and the "After this job" form's rules: text to rules and back, what is refused, what the job before may fill, and rules ⇄ the workflow they are (its trigger, `when` arrows, `job-run` steps, reused and deleted steps, a draft, and every reshape that counts as edited elsewhere) (`jobChainModel.test.mjs`).
199
206
 
200
207
  ## License
201
208
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xeplr/ui-jobs",
3
- "version": "1.6.1",
3
+ "version": "1.6.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",
@@ -1,15 +1,19 @@
1
1
  import { authFetch } from '@xeplr/ui-account'
2
+ import { rulesToWorkflow, shortcutKey, workflowToRules } from '../lib/jobChainModel.js'
2
3
 
3
- // "AFTER THIS JOB" RULES — served by the WORKFLOW API, not by jobs.
4
+ // "AFTER THIS JOB" — kept as an ORDINARY WORKFLOW in the workflow API, not by
5
+ // jobs: a workflow triggered by this job finishing (see lib/jobChainModel.js
6
+ // for its shape). Jobs never start each other; the workflow engine does every
7
+ // hand-off. These are the workflow API's ordinary routes:
8
+ //
9
+ // GET <workflow>/workflows/by-key/after-job-<jobId> this job's shortcut
10
+ // GET <workflow>/workflows/by-trigger?kind=job&jobId= every workflow it starts
11
+ // POST <workflow>/workflows/save save the shortcut
4
12
  //
5
- // Jobs never start each other; the workflow engine does every hand-off, and a
6
- // job's rules are a workflow it keeps (GET/PUT <workflow>/job-chains/:jobId).
7
13
  // So this is where that API is mounted, set by the host — and null when there
8
14
  // is no workflow on the install, which hides the section rather than showing
9
- // one that cannot save.
10
- //
11
- // Over HTTP only: this package does not import workflow's code, so each can be
12
- // installed on its own.
15
+ // one that cannot save. Over HTTP only: this package does not import
16
+ // workflow's code, so each can be installed on its own.
13
17
  let CHAINS_BASE = null
14
18
 
15
19
  export function configureChainsApi(base) {
@@ -20,17 +24,38 @@ export function chainsEnabled() {
20
24
  return CHAINS_BASE !== null
21
25
  }
22
26
 
23
- const url = (jobId) => `${CHAINS_BASE}/job-chains/${encodeURIComponent(jobId)}`
27
+ async function shortcut(jobId) {
28
+ try {
29
+ const res = await authFetch(`${CHAINS_BASE}/workflows/by-key/${encodeURIComponent(shortcutKey(jobId))}`)
30
+ return (res && res.dataArray && res.dataArray[0]) || null
31
+ } catch (err) {
32
+ if (err && (err.status === 404 || err.statusCode === 404)) return null
33
+ throw err
34
+ }
35
+ }
24
36
 
25
- /** { jobId, workflowId, rules } — an empty list for a job with none. */
37
+ /**
38
+ * { jobId, workflowId, rules, editedElsewhere, others } — an empty list for a
39
+ * job with none. `editedElsewhere`: the shortcut was reshaped outside this
40
+ * form, so its rules are not shown (open it in the workflow screens).
41
+ * `others`: the other workflows this job's finish starts, by name.
42
+ */
26
43
  export async function getChain(jobId) {
27
- return authFetch(url(jobId))
44
+ const [own, all] = await Promise.all([
45
+ shortcut(jobId),
46
+ authFetch(`${CHAINS_BASE}/workflows/by-trigger?kind=job&jobId=${encodeURIComponent(jobId)}`)
47
+ ])
48
+ const read = workflowToRules(own)
49
+ const others = ((all && all.dataArray) || [])
50
+ .filter((w) => w.key !== shortcutKey(jobId) && w.status === 'published')
51
+ .map((w) => ({ id: w.id, name: w.name }))
52
+ return { jobId, workflowId: own ? own.id : null, rules: read.rules, editedElsewhere: Boolean(read.editedElsewhere), others }
28
53
  }
29
54
 
30
- /** Replace a job's rules. An empty list removes them. */
55
+ /** Replace a job's rules. An empty list keeps the workflow as a draft, so it no longer runs. */
31
56
  export async function putChain(jobId, rules, jobName) {
32
- return authFetch(url(jobId), {
33
- method: 'PUT',
34
- body: JSON.stringify({ rules: rules, jobName: jobName })
35
- })
57
+ const own = await shortcut(jobId)
58
+ const entry = rulesToWorkflow(jobId, jobName, rules, own)
59
+ await authFetch(`${CHAINS_BASE}/workflows/save`, { method: 'POST', body: JSON.stringify([entry]) })
60
+ return { jobId, rules }
36
61
  }
@@ -19,6 +19,28 @@ export default function JobChainSection({ chain, jobs, jobId }) {
19
19
  }
20
20
 
21
21
  const others = (jobs || []).filter((j) => j.id !== jobId)
22
+ // Other workflows this job's finish starts, made in the workflow screens.
23
+ const alsoRuns = (chain.others || []).length > 0 && (
24
+ <p className="jb-help">
25
+ This job also starts {chain.others.length === 1 ? 'the workflow' : 'these workflows'}{' '}
26
+ {chain.others.map((w, i) => <span key={w.id}>{i ? ', ' : ''}<strong>{w.name}</strong></span>)} when it finishes.
27
+ They are edited in the workflow screens.
28
+ </p>
29
+ )
30
+
31
+ // Reshaped outside this form (another step, another trigger): the rules it
32
+ // shows would not be what runs, so it says so instead of showing them.
33
+ if (chain.editedElsewhere) {
34
+ return (
35
+ <div className="jb-chain">
36
+ <p className="jb-help jb-warn">
37
+ What runs after this job has been changed in the workflow screens, beyond what simple rules can say,
38
+ so it is not shown or changed here. Open the workflow “After …” for this job to see or change it.
39
+ </p>
40
+ {alsoRuns}
41
+ </div>
42
+ )
43
+ }
22
44
 
23
45
  return (
24
46
  <div className="jb-chain">
@@ -28,14 +50,17 @@ export default function JobChainSection({ chain, jobs, jobId }) {
28
50
  </label>
29
51
 
30
52
  {!chain.on && (
31
- <p className="jb-help">Nothing runs after this job. Tick the box to choose what should, and when.</p>
53
+ <p className="jb-help">Nothing runs after this job from here. Tick the box to choose what should, and when.</p>
32
54
  )}
55
+ {alsoRuns}
33
56
 
34
57
  {chain.on && (
35
58
  <>
36
59
  <p className="jb-help">
37
60
  Rules are checked top to bottom and the first that matches runs its job. A rule with no
38
61
  condition means “otherwise”. The period this job ran for passes to the next job by itself.
62
+ The rules are saved as an ordinary workflow that starts when this job finishes, so they can
63
+ also be seen and grown in the workflow screens.
39
64
  </p>
40
65
 
41
66
  <ol className="jb-chain-rules">
@@ -1,12 +1,22 @@
1
1
  // "AFTER THIS JOB" — the rules a job's screen writes, as pure logic.
2
2
  //
3
- // The rules are kept by the workflow engine, not by jobs: each becomes a branch
4
- // of one hidden workflow that runs when the job finishes (see
5
- // @xeplr-workflow/engine's lib/jobChains.js). This file is only the form's
6
- // half — the text a person types, turned into the rules the server takes,
7
- // and back — so it can be tested with plain node.
3
+ // The rules are an ORDINARY WORKFLOW, triggered by this job finishing
4
+ // ({ kind: 'job', jobId, when: 'finished' } — @xeplr/workflow-engine's
5
+ // triggers). This screen is a shortcut for one shape of it:
8
6
  //
9
- // A rule as the server takes it:
7
+ // decide one arrow per rule, written as `when` (the engine compiles
8
+ // it), first match wins; no match ends the run
9
+ // run steps one per rule: job-run, which starts that job and waits
10
+ //
11
+ // kept under the key `after-job-<jobId>`, so this job's own shortcut is told
12
+ // apart from any other workflow the same job triggers. Reshape it somewhere
13
+ // else (another step, another trigger) and it no longer fits this form: the
14
+ // screen then says so and points there, rather than showing rules that are
15
+ // not what runs. Everything here is pure, so it can be tested with plain node.
16
+ //
17
+ // A rule as this form writes it — fields and bindings relative to the job
18
+ // that finished (`status`, `output.x`, `{output.region}`); stored, they read
19
+ // the workflow's trigger (`trigger.status`, `{trigger.output.region}`):
10
20
  //
11
21
  // { when: { field, op, value } | { all: [...] } | { any: [...] } | null,
12
22
  // run: '<jobId>', inputs: { … }, carry: { … } }
@@ -120,3 +130,134 @@ export function toggleAccepted(list, name, on) {
120
130
  else set.delete(name)
121
131
  return Array.from(set)
122
132
  }
133
+
134
+ // ── the rules ⇄ the workflow they are ───────────────────────────────────
135
+
136
+ /** The workflow key this job's "After this job" shortcut keeps its rules under. */
137
+ export function shortcutKey(jobId) {
138
+ return 'after-job-' + jobId
139
+ }
140
+
141
+ // What a rule's fields and bindings start with — the finished job's values,
142
+ // which the workflow reads from its trigger.
143
+ const ROOTS = ['status', 'error', 'output', 'carry', 'window', 'jobId', 'given', 'used']
144
+ const ROOT_FIELD = new RegExp('^(' + ROOTS.join('|') + ')(\\.|$)')
145
+
146
+ function mapWhen(when, fn) {
147
+ if (!when || typeof when !== 'object') return when
148
+ if (Array.isArray(when.all)) return { all: when.all.map((w) => mapWhen(w, fn)) }
149
+ if (Array.isArray(when.any)) return { any: when.any.map((w) => mapWhen(w, fn)) }
150
+ return { ...when, field: fn(String(when.field || '')) }
151
+ }
152
+
153
+ function mapBindings(value, fn) {
154
+ if (typeof value === 'string') return fn(value)
155
+ if (Array.isArray(value)) return value.map((v) => mapBindings(v, fn))
156
+ if (value && typeof value === 'object') {
157
+ const out = {}
158
+ Object.keys(value).forEach((k) => { out[k] = mapBindings(value[k], fn) })
159
+ return out
160
+ }
161
+ return value
162
+ }
163
+
164
+ const toTriggerField = (f) => (ROOT_FIELD.test(f) ? 'trigger.' + f : f)
165
+ const fromTriggerField = (f) => (f.startsWith('trigger.') ? f.slice('trigger.'.length) : f)
166
+ const BINDING_ROOT = new RegExp('\\{\\s*(' + ROOTS.join('|') + ')\\b', 'g')
167
+ const toTriggerBindings = (text) => text.replace(BINDING_ROOT, '{trigger.$1')
168
+ const fromTriggerBindings = (text) => text.replace(/\{\s*trigger\./g, '{')
169
+
170
+ function freshKey() {
171
+ return 'run_' + Math.random().toString(36).slice(2, 8)
172
+ }
173
+
174
+ /**
175
+ * The workflow changeset for a job's rules — one entry for POST
176
+ * /workflows/save. `existing` is the shortcut's workflow as GET returned it
177
+ * (with `steps`), or null for a job that has none yet. Steps are reused by
178
+ * position and removed ones sent as deleted, so a save never collides with a
179
+ * step key it used before. No rules: kept as a draft, so it no longer runs.
180
+ */
181
+ export function rulesToWorkflow(jobId, jobName, rules, existing) {
182
+ const list = Array.isArray(rules) ? rules : []
183
+ const steps = existing && Array.isArray(existing.steps) ? existing.steps : []
184
+ const oldDecide = steps.find((s) => s.stepKey === 'decide')
185
+ const oldRuns = steps.filter((s) => s.stepKey !== 'decide').sort((a, b) => (a.position || 0) - (b.position || 0))
186
+
187
+ const runs = list.map((rule, i) => {
188
+ const reuse = oldRuns[i]
189
+ return {
190
+ ...(reuse ? { id: reuse.id } : {}),
191
+ stepKey: reuse ? reuse.stepKey : freshKey(),
192
+ name: 'Run job ' + rule.run,
193
+ actionName: 'job-run',
194
+ kind: 'wait',
195
+ onError: 'stop',
196
+ position: i + 1,
197
+ values: {
198
+ jobId: rule.run,
199
+ inputs: mapBindings(rule.inputs || {}, toTriggerBindings),
200
+ carry: mapBindings(rule.carry || {}, toTriggerBindings),
201
+ callbackUrl: '{resumeUrl}'
202
+ },
203
+ transitions: [{ when: null, mode: 'single', target: 'end_success' }]
204
+ }
205
+ })
206
+ const arrows = list.map((rule, i) => ({ when: mapWhen(rule.when || null, toTriggerField), mode: 'single', target: runs[i].stepKey }))
207
+ // Nothing matching ends the run: "if this, run that" is not a failure when
208
+ // neither applies.
209
+ if (!list.length || list[list.length - 1].when) arrows.push({ when: null, mode: 'single', target: 'end_success' })
210
+
211
+ const decide = {
212
+ ...(oldDecide ? { id: oldDecide.id } : {}),
213
+ stepKey: 'decide', name: 'Decide what runs next', actionName: 'decide',
214
+ kind: 'auto', onError: 'stop', position: 0, values: {}, transitions: arrows
215
+ }
216
+ const removed = oldRuns.slice(list.length).map((s) => ({ id: s.id, deleted: true }))
217
+
218
+ return {
219
+ ...(existing && existing.id ? { id: existing.id } : {}),
220
+ name: ('After ' + (String(jobName || '').trim() || 'job ' + jobId)).slice(0, 255),
221
+ description: 'Made by the "After this job" setting of job ' + jobId + '.',
222
+ kind: 'workflow',
223
+ key: shortcutKey(jobId),
224
+ status: list.length ? 'published' : 'draft',
225
+ trigger: { kind: 'job', jobId: jobId, when: 'finished' },
226
+ steps: [decide, ...runs, ...removed]
227
+ }
228
+ }
229
+
230
+ /**
231
+ * The rules a shortcut workflow says, or `{ editedElsewhere: true }` when it
232
+ * has been reshaped so that this form can no longer say it truthfully.
233
+ * A draft (rules removed) reads as no rules.
234
+ */
235
+ export function workflowToRules(workflow) {
236
+ if (!workflow) return { rules: [] }
237
+ const t = workflow.trigger || {}
238
+ const steps = Array.isArray(workflow.steps) ? workflow.steps : []
239
+ const decide = steps.find((s) => s.stepKey === 'decide')
240
+ const others = steps.filter((s) => s.stepKey !== 'decide')
241
+ const fits = t.kind === 'job' && t.when === 'finished' && decide && decide.actionName === 'decide' &&
242
+ others.every((s) => s.actionName === 'job-run' && s.values && s.values.jobId)
243
+ if (!fits) return { editedElsewhere: true, rules: [] }
244
+ if (workflow.status !== 'published') return { rules: [] }
245
+ const byKey = Object.fromEntries(others.map((s) => [s.stepKey, s]))
246
+ const arrows = Array.isArray(decide.transitions) ? decide.transitions : []
247
+ const rules = []
248
+ for (const a of arrows) {
249
+ // An arrow with no condition at all is "otherwise", however it was written.
250
+ const when = a.when !== undefined ? a.when : (a.condition == null ? null : undefined)
251
+ if (a.target === 'end_success' && !when) continue
252
+ const step = byKey[a.target]
253
+ if (!step || when === undefined) return { editedElsewhere: true, rules: [] }
254
+ rules.push({
255
+ when: mapWhen(when, fromTriggerField),
256
+ run: step.values.jobId,
257
+ inputs: mapBindings(step.values.inputs || {}, fromTriggerBindings),
258
+ carry: mapBindings(step.values.carry || {}, fromTriggerBindings)
259
+ })
260
+ }
261
+ if (rules.length !== others.length) return { editedElsewhere: true, rules: [] }
262
+ return { rules }
263
+ }
@@ -17,6 +17,10 @@ export function useJobChainController(jobId) {
17
17
  const [on, setOn] = useState(false)
18
18
  const [loading, setLoading] = useState(Boolean(enabled && jobId))
19
19
  const [loadError, setLoadError] = useState(null)
20
+ // Reshaped outside this form: its rules are not shown or saved from here.
21
+ const [editedElsewhere, setEditedElsewhere] = useState(false)
22
+ // The other workflows this job's finish starts, made elsewhere.
23
+ const [others, setOthers] = useState([])
20
24
 
21
25
  useEffect(() => {
22
26
  if (!enabled || !jobId) return
@@ -29,6 +33,8 @@ export function useJobChainController(jobId) {
29
33
  setSaved(rules)
30
34
  setRows(rulesToRows(rules))
31
35
  setOn(rules.length > 0)
36
+ setEditedElsewhere(Boolean(res && res.editedElsewhere))
37
+ setOthers((res && res.others) || [])
32
38
  setLoadError(null)
33
39
  })
34
40
  .catch((err) => { if (live) setLoadError(err.message || 'Could not load the rules') })
@@ -62,7 +68,7 @@ export function useJobChainController(jobId) {
62
68
 
63
69
  /** The rules this form would save, and anything wrong with them. */
64
70
  function check(ownJobId) {
65
- if (!on) return { rules: [], problems: [] }
71
+ if (!on || editedElsewhere) return { rules: [], problems: [] }
66
72
  return rowsToRules(rows, ownJobId)
67
73
  }
68
74
 
@@ -71,7 +77,7 @@ export function useJobChainController(jobId) {
71
77
  * changed, so saving a job's schedule does not rewrite its chain.
72
78
  */
73
79
  async function save(savedJobId, jobName) {
74
- if (!enabled || !savedJobId || loadError) return
80
+ if (!enabled || !savedJobId || loadError || editedElsewhere) return
75
81
  const { rules, problems } = check(savedJobId)
76
82
  if (problems.length) throw new Error(problems.join(' '))
77
83
  if (sameRules(rules, saved)) return
@@ -79,5 +85,5 @@ export function useJobChainController(jobId) {
79
85
  setSaved((res && res.rules) || rules)
80
86
  }
81
87
 
82
- return { enabled, on, setOn: setTurnedOn, rows, updateRow, addRow, removeRow, moveUp, loading, loadError, check, save }
88
+ return { enabled, on, setOn: setTurnedOn, rows, updateRow, addRow, removeRow, moveUp, loading, loadError, editedElsewhere, others, check, save }
83
89
  }