@jive-sh/workflow-platform 0.7.0 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +66 -435
- package/component/_generated/api.ts +72 -0
- package/component/_generated/component.ts +621 -0
- package/component/_generated/dataModel.ts +60 -0
- package/component/_generated/server.ts +169 -0
- package/component/convex.config.ts +3 -0
- package/component/engine.ts +755 -0
- package/component/errors.ts +66 -0
- package/component/events.ts +17 -0
- package/component/notes.ts +13 -0
- package/component/places.ts +136 -0
- package/component/retention.ts +205 -0
- package/component/runEngine.ts +25 -0
- package/component/schema.ts +132 -0
- package/component/steps.ts +188 -0
- package/component/store.ts +512 -0
- package/component/tasks.ts +289 -0
- package/component/worker.ts +109 -0
- package/component/workflows.ts +83 -0
- package/dist/definition/agent-runner.js +9 -0
- package/dist/definition/agent-runner.js.map +1 -0
- package/dist/definition/file-store.js +9 -0
- package/dist/definition/file-store.js.map +1 -0
- package/dist/definition/program-build.js +10 -0
- package/dist/definition/program-build.js.map +1 -0
- package/dist/definition/step.js +1 -0
- package/dist/definition/step.js.map +1 -0
- package/dist/definition/task-schema.js +5 -0
- package/dist/definition/task-schema.js.map +1 -0
- package/dist/definition/tasks.js +9 -0
- package/dist/definition/tasks.js.map +1 -0
- package/dist/definition/workflow.js +111 -0
- package/dist/definition/workflow.js.map +1 -0
- package/dist/graph.js +301 -9
- package/dist/graph.js.map +1 -1
- package/dist/index.js +7 -196
- package/dist/index.js.map +1 -1
- package/package.json +9 -4
- package/src/definition/agent-runner.ts +59 -0
- package/src/definition/file-store.ts +20 -0
- package/src/definition/program-build.ts +30 -0
- package/src/definition/step.ts +106 -0
- package/src/definition/task-schema.ts +15 -0
- package/src/definition/tasks.ts +43 -0
- package/src/definition/workflow.ts +255 -0
- package/src/graph.ts +341 -19
- package/src/index.ts +8 -238
- package/worker/directory-file-store.ts +42 -0
- package/worker/index.ts +12 -0
- package/worker/platform-client.ts +138 -0
- package/worker/step-meter.ts +80 -0
- package/worker/worker-tasks.ts +27 -0
- package/worker/worker.test.ts +200 -0
- package/worker/worker.ts +240 -0
- package/dist/budget-states.js +0 -30
- package/dist/budget-states.js.map +0 -1
- package/dist/cpu-limit/limiter.js +0 -839
- package/dist/cpu-limit/limiter.js.map +0 -1
- package/dist/cpu-limit/use.js +0 -139
- package/dist/cpu-limit/use.js.map +0 -1
- package/dist/dashboard/agent-usage.js +0 -25
- package/dist/dashboard/agent-usage.js.map +0 -1
- package/dist/dashboard/dashboard.css +0 -148
- package/dist/dashboard/drilldown.js +0 -47
- package/dist/dashboard/drilldown.js.map +0 -1
- package/dist/dashboard/queue-lines.js +0 -44
- package/dist/dashboard/queue-lines.js.map +0 -1
- package/dist/dashboard/queue-table.js +0 -16
- package/dist/dashboard/queue-table.js.map +0 -1
- package/dist/dashboard/run-doing-words.js +0 -29
- package/dist/dashboard/run-doing-words.js.map +0 -1
- package/dist/dashboard/setting-words.js +0 -18
- package/dist/dashboard/setting-words.js.map +0 -1
- package/dist/dashboard/spending-words.js +0 -24
- package/dist/dashboard/spending-words.js.map +0 -1
- package/dist/failure.js +0 -35
- package/dist/failure.js.map +0 -1
- package/dist/keep-running.js +0 -79
- package/dist/keep-running.js.map +0 -1
- package/dist/outside-failure.js +0 -31
- package/dist/outside-failure.js.map +0 -1
- package/dist/pick-wakes.js +0 -125
- package/dist/pick-wakes.js.map +0 -1
- package/dist/project.js +0 -1
- package/dist/project.js.map +0 -1
- package/dist/queue-counts.js +0 -51
- package/dist/queue-counts.js.map +0 -1
- package/dist/reasons.js +0 -33
- package/dist/reasons.js.map +0 -1
- package/dist/retention.js +0 -59
- package/dist/retention.js.map +0 -1
- package/dist/settings.js +0 -88
- package/dist/settings.js.map +0 -1
- package/dist/spending-limit.js +0 -82
- package/dist/spending-limit.js.map +0 -1
- package/dist/step-files.js +0 -200
- package/dist/step-files.js.map +0 -1
- package/dist/step-meter.js +0 -97
- package/dist/step-meter.js.map +0 -1
- package/dist/step-times.js +0 -114
- package/dist/step-times.js.map +0 -1
- package/dist/step-usage.js +0 -19
- package/dist/step-usage.js.map +0 -1
- package/dist/steps.js +0 -1205
- package/dist/steps.js.map +0 -1
- package/dist/storage/agent-claims.js +0 -3
- package/dist/storage/agent-claims.js.map +0 -1
- package/dist/storage/budgets.js +0 -121
- package/dist/storage/budgets.js.map +0 -1
- package/dist/storage/engine-records.js +0 -91
- package/dist/storage/engine-records.js.map +0 -1
- package/dist/storage/engine-storage.js +0 -67
- package/dist/storage/engine-storage.js.map +0 -1
- package/dist/storage/input-records.js +0 -12
- package/dist/storage/input-records.js.map +0 -1
- package/dist/storage/move-store.js +0 -251
- package/dist/storage/move-store.js.map +0 -1
- package/dist/storage/sqlite-store.js +0 -901
- package/dist/storage/sqlite-store.js.map +0 -1
- package/dist/storage/step-records.js +0 -11
- package/dist/storage/step-records.js.map +0 -1
- package/dist/storage/storage-error.js +0 -19
- package/dist/storage/storage-error.js.map +0 -1
- package/dist/storage/task-store.js +0 -30
- package/dist/storage/task-store.js.map +0 -1
- package/dist/system-workflows.js +0 -54
- package/dist/system-workflows.js.map +0 -1
- package/dist/tasks.js +0 -500
- package/dist/tasks.js.map +0 -1
- package/dist/views/format.js +0 -37
- package/dist/views/format.js.map +0 -1
- package/dist/views/runs-now.js +0 -117
- package/dist/views/runs-now.js.map +0 -1
- package/dist/views/step-funnel.js +0 -98
- package/dist/views/step-funnel.js.map +0 -1
- package/dist/views/step-graph.js +0 -39
- package/dist/views/step-graph.js.map +0 -1
- package/dist/views/workflows-view.js +0 -236
- package/dist/views/workflows-view.js.map +0 -1
- package/src/budget-states.ts +0 -54
- package/src/cpu-limit/limiter.ts +0 -935
- package/src/cpu-limit/use.ts +0 -166
- package/src/dashboard/agent-usage-line.tsx +0 -28
- package/src/dashboard/agent-usage.ts +0 -48
- package/src/dashboard/dashboard.css +0 -148
- package/src/dashboard/drilldown.ts +0 -70
- package/src/dashboard/index.tsx +0 -4
- package/src/dashboard/limits-and-runs.tsx +0 -191
- package/src/dashboard/machine-controls.tsx +0 -53
- package/src/dashboard/queue-bar.tsx +0 -62
- package/src/dashboard/queue-chart.tsx +0 -149
- package/src/dashboard/queue-lines.ts +0 -87
- package/src/dashboard/queue-table.ts +0 -37
- package/src/dashboard/run-doing-words.ts +0 -41
- package/src/dashboard/setting-words.ts +0 -30
- package/src/dashboard/spending-limit-control.tsx +0 -47
- package/src/dashboard/spending-words.ts +0 -32
- package/src/dashboard/time-distribution.tsx +0 -61
- package/src/dashboard/workflow-dag.tsx +0 -322
- package/src/dashboard/workflow-drilldown.tsx +0 -31
- package/src/dashboard/workflows-dashboard.tsx +0 -532
- package/src/failure.ts +0 -36
- package/src/keep-running.ts +0 -85
- package/src/outside-failure.ts +0 -39
- package/src/pick-wakes.ts +0 -182
- package/src/project.ts +0 -127
- package/src/queue-counts.ts +0 -64
- package/src/reasons.ts +0 -30
- package/src/retention.ts +0 -90
- package/src/settings.ts +0 -171
- package/src/spending-limit.ts +0 -139
- package/src/step-files.ts +0 -208
- package/src/step-meter.ts +0 -120
- package/src/step-times.ts +0 -151
- package/src/step-usage.ts +0 -23
- package/src/steps.ts +0 -1616
- package/src/storage/agent-claims.ts +0 -63
- package/src/storage/budgets.ts +0 -152
- package/src/storage/engine-records.ts +0 -119
- package/src/storage/engine-storage.ts +0 -82
- package/src/storage/input-records.ts +0 -43
- package/src/storage/move-store.ts +0 -265
- package/src/storage/sqlite-store.ts +0 -1022
- package/src/storage/step-records.ts +0 -358
- package/src/storage/storage-error.ts +0 -35
- package/src/storage/task-store.ts +0 -235
- package/src/system-workflows.ts +0 -70
- package/src/tasks.ts +0 -586
- package/src/views/format.ts +0 -40
- package/src/views/runs-now.ts +0 -188
- package/src/views/step-funnel.ts +0 -163
- package/src/views/step-graph.ts +0 -77
- package/src/views/workflows-view.ts +0 -484
- package/src/workflow-dag.test.tsx +0 -89
- package/src/workflow-page.test.tsx +0 -170
|
@@ -0,0 +1,755 @@
|
|
|
1
|
+
import { Effect, Option } from "effect"
|
|
2
|
+
import {
|
|
3
|
+
budgetOfStepKind,
|
|
4
|
+
type Budgets,
|
|
5
|
+
createsTasks,
|
|
6
|
+
everySubWorkflowTaskEnded,
|
|
7
|
+
endStateOfPlace,
|
|
8
|
+
type GraphLine,
|
|
9
|
+
type GraphStep,
|
|
10
|
+
inputPlacesOf,
|
|
11
|
+
lineFrom,
|
|
12
|
+
type LineStart,
|
|
13
|
+
placeAtEndOf,
|
|
14
|
+
problemsOf,
|
|
15
|
+
stepOfPlace,
|
|
16
|
+
type SkippedOther,
|
|
17
|
+
type StepMeasurements,
|
|
18
|
+
type TaskFile,
|
|
19
|
+
type TaskNote,
|
|
20
|
+
type WorkflowGraph,
|
|
21
|
+
} from "../src/graph"
|
|
22
|
+
import type { Id } from "./_generated/dataModel"
|
|
23
|
+
import {
|
|
24
|
+
type EngineError,
|
|
25
|
+
InvalidGraph,
|
|
26
|
+
InvalidTaskFields,
|
|
27
|
+
StepNotFound,
|
|
28
|
+
StepRunNotRunning,
|
|
29
|
+
TaskInProgress,
|
|
30
|
+
TaskNotFound,
|
|
31
|
+
UnknownEndState,
|
|
32
|
+
UnknownEvent,
|
|
33
|
+
WorkflowNotRegistered,
|
|
34
|
+
} from "./errors"
|
|
35
|
+
import { type FlowRow, type TaskRow, type WorkflowRow, WorkflowStore } from "./store"
|
|
36
|
+
import type { ParentRef, WorkforceHooks } from "../src/graph"
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* The workflow engine: every decision about where a task goes next. Code and agent steps are run by workers, which
|
|
40
|
+
* take a task through `take` and report through `complete` or `fail`; sub-workflow steps run here, inside Convex.
|
|
41
|
+
*/
|
|
42
|
+
|
|
43
|
+
type Run<A> = Effect.fn.Return<A, EngineError, WorkflowStore>
|
|
44
|
+
|
|
45
|
+
const stepPlace = (step: string) => `step:${step}`
|
|
46
|
+
|
|
47
|
+
const workflowNamed = function* (name: string): Run<WorkflowRow> {
|
|
48
|
+
const store = yield* WorkflowStore
|
|
49
|
+
const maybeWorkflow = yield* store.getWorkflow(name)
|
|
50
|
+
if (Option.isNone(maybeWorkflow)) return yield* Effect.fail(new WorkflowNotRegistered({ workflow: name }))
|
|
51
|
+
return maybeWorkflow.value
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const stepNamed = function* (input: { readonly workflow: WorkflowRow; readonly step: string }): Run<GraphStep> {
|
|
55
|
+
const step = input.workflow.graph.steps.find((candidate) => candidate.id === input.step)
|
|
56
|
+
if (step === undefined) return yield* Effect.fail(new StepNotFound({ workflow: input.workflow.name, step: input.step }))
|
|
57
|
+
return step
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const taskWithId = function* (id: Id<"tasks">): Run<TaskRow> {
|
|
61
|
+
const store = yield* WorkflowStore
|
|
62
|
+
const maybeTask = yield* store.getTask(id)
|
|
63
|
+
if (Option.isNone(maybeTask)) return yield* Effect.fail(new TaskNotFound({ task: id }))
|
|
64
|
+
return maybeTask.value
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const flowWithId = function* (id: Id<"flows">): Run<FlowRow> {
|
|
68
|
+
const store = yield* WorkflowStore
|
|
69
|
+
const maybeFlow = yield* store.getFlow(id)
|
|
70
|
+
if (Option.isNone(maybeFlow)) return yield* Effect.die(new Error(`flow ${id} is referenced but missing`))
|
|
71
|
+
return maybeFlow.value
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const lineOutOf = function* (input: { readonly workflow: WorkflowRow; readonly start: LineStart }): Run<GraphLine> {
|
|
75
|
+
const maybeLine = lineFrom(input.workflow.graph, input.start)
|
|
76
|
+
if (Option.isNone(maybeLine)) {
|
|
77
|
+
return yield* Effect.fail(new InvalidGraph({ workflow: input.workflow.name, problems: [`no line leaves ${JSON.stringify(input.start)}`] }))
|
|
78
|
+
}
|
|
79
|
+
return maybeLine.value
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** How deep a step looks past tasks its workflow's in-progress limit holds back for the first it may start. */
|
|
83
|
+
const ADMISSION_DEPTH = 50
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Which flows waiting in front of a step may go in, by the workflow's in-progress limit (`inProgress` in `graph.ts`): a
|
|
87
|
+
* flow on a line an event started may start its task only while fewer than `limit` tasks (of its `per` value) are past
|
|
88
|
+
* such a line and not ended. Any other flow's task is in progress already. Absent a limit, every flow may.
|
|
89
|
+
*/
|
|
90
|
+
const admissionOf = function* (workflow: WorkflowRow): Run<Option.Option<(flow: FlowRow) => Run<boolean>>> {
|
|
91
|
+
const store = yield* WorkflowStore
|
|
92
|
+
const inProgress = workflow.graph.inProgress
|
|
93
|
+
if (inProgress === undefined) return Option.none()
|
|
94
|
+
const graph = workflow.graph
|
|
95
|
+
const arrivalEvents = new Set(graph.events.filter(createsTasks).map((event) => event.id))
|
|
96
|
+
const arrivalPlaces = new Set(graph.lines.filter((line) => "event" in line.from).map((line) => `line:${line.id}`))
|
|
97
|
+
const progressPlaces = [
|
|
98
|
+
...graph.steps.map((step) => `step:${step.id}`),
|
|
99
|
+
...graph.lines.filter((line) => !("event" in line.from) && "step" in line.to).map((line) => `line:${line.id}`),
|
|
100
|
+
...graph.endStates.filter((end) => Option.isSome(lineFrom(graph, { end }))).map((end) => `end:${end}`),
|
|
101
|
+
]
|
|
102
|
+
const keyOf = function* (task: Id<"tasks">): Run<string> {
|
|
103
|
+
if (inProgress.per === undefined) return ""
|
|
104
|
+
const row = yield* taskWithId(task)
|
|
105
|
+
return JSON.stringify((row.fields as Record<string, unknown>)[inProgress.per])
|
|
106
|
+
}
|
|
107
|
+
const counts = new Map<string, number>()
|
|
108
|
+
const counted = new Set<string>()
|
|
109
|
+
for (const place of progressPlaces) {
|
|
110
|
+
for (const flow of yield* store.flowsAt({ workflow: workflow.name, place })) {
|
|
111
|
+
if (!arrivalEvents.has(flow.startedBy) || counted.has(flow.task)) continue
|
|
112
|
+
counted.add(flow.task)
|
|
113
|
+
const key = yield* keyOf(flow.task)
|
|
114
|
+
counts.set(key, (counts.get(key) ?? 0) + 1)
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
return Option.some(function* (flow: FlowRow) {
|
|
118
|
+
if (!arrivalPlaces.has(flow.place)) return true
|
|
119
|
+
return (counts.get(yield* keyOf(flow.task)) ?? 0) < inProgress.limit
|
|
120
|
+
})
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* The head of the queue in front of a step: the task that has waited longest across every line into it, among those
|
|
125
|
+
* its workflow's in-progress limit lets start.
|
|
126
|
+
*/
|
|
127
|
+
const headInFrontOf = function* (input: { readonly workflow: WorkflowRow; readonly step: string }): Run<Option.Option<FlowRow>> {
|
|
128
|
+
const store = yield* WorkflowStore
|
|
129
|
+
const maybeAdmits = yield* admissionOf(input.workflow)
|
|
130
|
+
let maybeOldest: Option.Option<FlowRow> = Option.none()
|
|
131
|
+
for (const place of inputPlacesOf(input.workflow.graph, input.step)) {
|
|
132
|
+
let maybeHead: Option.Option<FlowRow> = Option.none()
|
|
133
|
+
if (Option.isNone(maybeAdmits)) maybeHead = yield* store.headOf({ workflow: input.workflow.name, place })
|
|
134
|
+
else {
|
|
135
|
+
for (const candidate of yield* store.headsOf({ workflow: input.workflow.name, place, upTo: ADMISSION_DEPTH })) {
|
|
136
|
+
if (!(yield* maybeAdmits.value(candidate))) continue
|
|
137
|
+
maybeHead = Option.some(candidate)
|
|
138
|
+
break
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
if (Option.isNone(maybeHead)) continue
|
|
142
|
+
const head = maybeHead.value
|
|
143
|
+
if (
|
|
144
|
+
Option.isNone(maybeOldest) ||
|
|
145
|
+
head.enteredAt < maybeOldest.value.enteredAt ||
|
|
146
|
+
(head.enteredAt === maybeOldest.value.enteredAt && head._creationTime < maybeOldest.value._creationTime)
|
|
147
|
+
) {
|
|
148
|
+
maybeOldest = maybeHead
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
return maybeOldest
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** Puts a flow on the line that starts at `start`, or straight into the end state that line leads to. */
|
|
155
|
+
const sendAlong = function* (input: { readonly workflow: WorkflowRow; readonly flow: FlowRow; readonly start: LineStart }): Run<void> {
|
|
156
|
+
const store = yield* WorkflowStore
|
|
157
|
+
const line = yield* lineOutOf({ workflow: input.workflow, start: input.start })
|
|
158
|
+
const moved = yield* store.moveFlow({ flow: input.flow._id, place: placeAtEndOf(line), enteredAt: store.now })
|
|
159
|
+
yield* afterArriving({ workflow: input.workflow, flow: moved })
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
const startFlow = function* (input: { readonly workflow: WorkflowRow; readonly task: TaskRow; readonly event: string }): Run<void> {
|
|
163
|
+
const store = yield* WorkflowStore
|
|
164
|
+
const line = yield* lineOutOf({ workflow: input.workflow, start: { event: input.event } })
|
|
165
|
+
const flow = yield* store.insertFlow({ workflow: input.workflow.name, task: input.task._id, startedBy: input.event, place: placeAtEndOf(line) })
|
|
166
|
+
yield* afterArriving({ workflow: input.workflow, flow })
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* A flow that reached an end state no step consumes has ended. When it is the flow that brought its task in and the
|
|
171
|
+
* task belongs to a parent's sub-workflow step, the parent hears of it.
|
|
172
|
+
*/
|
|
173
|
+
const afterArriving = function* (input: { readonly workflow: WorkflowRow; readonly flow: FlowRow }): Run<void> {
|
|
174
|
+
const store = yield* WorkflowStore
|
|
175
|
+
const maybeEndState = endStateOfPlace(input.flow.place)
|
|
176
|
+
if (Option.isNone(maybeEndState)) return
|
|
177
|
+
const endState = maybeEndState.value
|
|
178
|
+
if (Option.isSome(lineFrom(input.workflow.graph, { end: endState }))) return
|
|
179
|
+
const startedBy = input.workflow.graph.events.find((event) => event.id === input.flow.startedBy)
|
|
180
|
+
if (startedBy === undefined || !createsTasks(startedBy)) return
|
|
181
|
+
yield* store.markTaskEnded({ task: input.flow.task, endState })
|
|
182
|
+
const task = yield* taskWithId(input.flow.task)
|
|
183
|
+
if (task.parent === undefined) return
|
|
184
|
+
const hooks = yield* workforceHooksOf(input.workflow)
|
|
185
|
+
yield* store.scheduleHook({
|
|
186
|
+
hook: hooks.subWorkflowTaskEnded,
|
|
187
|
+
args: { parent: task.parent, task: task._id, workflow: input.workflow.name, endState, fields: task.fields },
|
|
188
|
+
})
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** The workforce mutations that carry tasks between workflows; a workflow gets them when a workforce registers it. */
|
|
192
|
+
const workforceHooksOf = function* (workflow: WorkflowRow): Run<WorkforceHooks> {
|
|
193
|
+
if (workflow.hooks === undefined) {
|
|
194
|
+
return yield* Effect.fail(new InvalidGraph({ workflow: workflow.name, problems: ["it has sub-workflow tasks but was not registered by a workforce"] }))
|
|
195
|
+
}
|
|
196
|
+
return workflow.hooks
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* A task this workflow's sub-workflow step created in another workflow has ended there (the workforce relays it). Its
|
|
201
|
+
* fields are collected when the step asks for them; once every such task of the step has ended, the step ends.
|
|
202
|
+
*/
|
|
203
|
+
export const subWorkflowTaskEnded = function* (input: {
|
|
204
|
+
readonly flow: Id<"flows">
|
|
205
|
+
readonly entryIndex: number
|
|
206
|
+
readonly endState: string
|
|
207
|
+
readonly fields: unknown
|
|
208
|
+
}): Run<void> {
|
|
209
|
+
const store = yield* WorkflowStore
|
|
210
|
+
const parentFlow = yield* flowWithId(input.flow)
|
|
211
|
+
const parentWorkflow = yield* workflowNamed(parentFlow.workflow)
|
|
212
|
+
const maybeStep = stepOfPlace(parentFlow.place)
|
|
213
|
+
if (Option.isNone(maybeStep)) return yield* Effect.die(new Error(`flow ${parentFlow._id} waits on sub-workflow tasks but is at ${parentFlow.place}`))
|
|
214
|
+
const step = yield* stepNamed({ workflow: parentWorkflow, step: maybeStep.value })
|
|
215
|
+
const subWorkflow = step.workflow
|
|
216
|
+
if (subWorkflow === undefined) return yield* Effect.die(new Error(`step ${step.id} has sub-workflow tasks but no sub-workflow`))
|
|
217
|
+
yield* store.markSubWorkflowTaskEnded({ flow: parentFlow._id, entryIndex: input.entryIndex, endState: input.endState })
|
|
218
|
+
|
|
219
|
+
if (subWorkflow.collect !== undefined && subWorkflow.collect.endState === input.endState) {
|
|
220
|
+
const parentTask = yield* taskWithId(parentFlow.task)
|
|
221
|
+
const into = subWorkflow.collect.into
|
|
222
|
+
const collected: ReadonlyArray<unknown> = Array.isArray(parentTask.fields[into]) ? parentTask.fields[into] : []
|
|
223
|
+
yield* changeTask({
|
|
224
|
+
workflow: parentWorkflow,
|
|
225
|
+
task: parentTask,
|
|
226
|
+
fields: { ...parentTask.fields, [into]: [...collected, input.fields] },
|
|
227
|
+
files: parentTask.files,
|
|
228
|
+
})
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
const subWorkflowTasks = yield* store.subWorkflowTasksOf(parentFlow._id)
|
|
232
|
+
if (subWorkflowTasks.some((subWorkflowTask) => subWorkflowTask.endedAs === undefined)) return
|
|
233
|
+
const endState = subWorkflow.each !== undefined ? everySubWorkflowTaskEnded : input.endState
|
|
234
|
+
yield* leaveStep({ workflow: parentWorkflow, flow: parentFlow, step, endState, measurements: Option.none(), note: Option.none() })
|
|
235
|
+
yield* advance(parentWorkflow.name)
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/** The workforce created the sub-workflow task for one entry; recorded so the parent can show its sub-workflow tasks. */
|
|
239
|
+
export const recordSubWorkflowTask = function* (input: { readonly flow: Id<"flows">; readonly entryIndex: number; readonly task: string }): Run<void> {
|
|
240
|
+
const store = yield* WorkflowStore
|
|
241
|
+
yield* store.setSubWorkflowTask(input)
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
const leaveStep = function* (input: {
|
|
245
|
+
readonly workflow: WorkflowRow
|
|
246
|
+
readonly flow: FlowRow
|
|
247
|
+
readonly step: GraphStep
|
|
248
|
+
readonly endState: string
|
|
249
|
+
readonly measurements: Option.Option<StepMeasurements>
|
|
250
|
+
/** What the step said about the task, kept on its run. */
|
|
251
|
+
readonly note: Option.Option<string>
|
|
252
|
+
}): Run<void> {
|
|
253
|
+
const store = yield* WorkflowStore
|
|
254
|
+
if (!input.step.endStates.includes(input.endState)) {
|
|
255
|
+
return yield* Effect.fail(new UnknownEndState({ workflow: input.workflow.name, step: input.step.id, endState: input.endState }))
|
|
256
|
+
}
|
|
257
|
+
const maybeRun = yield* store.runningStepRunOf(input.flow._id)
|
|
258
|
+
if (Option.isSome(maybeRun)) {
|
|
259
|
+
yield* store.finishStepRun({ run: maybeRun.value._id, status: "ended", endState: Option.some(input.endState), error: Option.none(), measurements: input.measurements, note: input.note })
|
|
260
|
+
}
|
|
261
|
+
if (input.step.workflow !== undefined) yield* store.clearSubWorkflowTasks(input.flow._id)
|
|
262
|
+
yield* sendAlong({ workflow: input.workflow, flow: input.flow, start: { step: input.step.id, endState: input.endState } })
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/**
|
|
266
|
+
* Writes a task's fields and files, then starts a flow from every change event watching a field that changed. A change
|
|
267
|
+
* event already waiting on its first line for this task is not started twice: that flow will see the latest fields. A
|
|
268
|
+
* change event that resumes an end state moves the task's flows waiting there onto its line instead, and starts none
|
|
269
|
+
* when no flow waits there.
|
|
270
|
+
*/
|
|
271
|
+
const changeTask = function* (input: { readonly workflow: WorkflowRow; readonly task: TaskRow; readonly fields: Record<string, unknown>; readonly files: ReadonlyArray<TaskFile> }): Run<void> {
|
|
272
|
+
const store = yield* WorkflowStore
|
|
273
|
+
const changed = new Set(
|
|
274
|
+
[...new Set([...Object.keys(input.task.fields), ...Object.keys(input.fields)])].filter(
|
|
275
|
+
(field) => JSON.stringify(input.task.fields[field]) !== JSON.stringify(input.fields[field]),
|
|
276
|
+
),
|
|
277
|
+
)
|
|
278
|
+
yield* store.setTaskData({ task: input.task._id, fields: input.fields, files: input.files })
|
|
279
|
+
const task: TaskRow = { ...input.task, fields: input.fields, files: [...input.files] }
|
|
280
|
+
for (const event of input.workflow.graph.events) {
|
|
281
|
+
if (event.kind !== "change" || !changed.has(event.field)) continue
|
|
282
|
+
if (event.resumes !== undefined) {
|
|
283
|
+
const waiting = (yield* store.flowsOfTask(task._id)).filter((flow) => flow.place === `end:${event.resumes}`)
|
|
284
|
+
if (waiting.length === 0) continue
|
|
285
|
+
const line = yield* lineOutOf({ workflow: input.workflow, start: { event: event.id } })
|
|
286
|
+
yield* store.markTaskResumed(task._id)
|
|
287
|
+
for (const flow of waiting) {
|
|
288
|
+
const moved = yield* store.moveFlow({ flow: flow._id, place: placeAtEndOf(line), enteredAt: store.now })
|
|
289
|
+
yield* afterArriving({ workflow: input.workflow, flow: moved })
|
|
290
|
+
}
|
|
291
|
+
continue
|
|
292
|
+
}
|
|
293
|
+
const flows = yield* store.flowsOfTaskStartedBy({ task: task._id, startedBy: event.id })
|
|
294
|
+
if (flows.some((flow) => flow.place.startsWith("line:"))) continue
|
|
295
|
+
yield* startFlow({ workflow: input.workflow, task, event: event.id })
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/** Moves every task waiting in front of a sub-workflow step into it, creating its sub-workflow tasks. */
|
|
300
|
+
const advance = function* (workflowName: string): Run<void> {
|
|
301
|
+
const workflow = yield* workflowNamed(workflowName)
|
|
302
|
+
for (const step of workflow.graph.steps) {
|
|
303
|
+
if (step.workflow === undefined) continue
|
|
304
|
+
while (true) {
|
|
305
|
+
const maybeHead = yield* headInFrontOf({ workflow, step: step.id })
|
|
306
|
+
if (Option.isNone(maybeHead)) break
|
|
307
|
+
yield* enterSubWorkflowStep({ workflow, step, flow: maybeHead.value })
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
const enterSubWorkflowStep = function* (input: { readonly workflow: WorkflowRow; readonly step: GraphStep; readonly flow: FlowRow }): Run<void> {
|
|
313
|
+
const store = yield* WorkflowStore
|
|
314
|
+
const subWorkflow = input.step.workflow
|
|
315
|
+
if (subWorkflow === undefined) return
|
|
316
|
+
yield* store.insertStepRun({ flow: input.flow, step: input.step.id, version: input.workflow.version, budget: "none", worker: Option.none(), leaseMs: Option.none() })
|
|
317
|
+
const flow = yield* store.moveFlow({ flow: input.flow._id, place: stepPlace(input.step.id), enteredAt: store.now })
|
|
318
|
+
const task = yield* taskWithId(flow.task)
|
|
319
|
+
|
|
320
|
+
const list: unknown = subWorkflow.each === undefined ? undefined : task.fields[subWorkflow.each]
|
|
321
|
+
if (subWorkflow.each !== undefined && !Array.isArray(list)) {
|
|
322
|
+
return yield* Effect.fail(new InvalidTaskFields({ task: task._id, problem: `field ${subWorkflow.each} is not a list` }))
|
|
323
|
+
}
|
|
324
|
+
const entries: ReadonlyArray<{ readonly fields: unknown; readonly files: ReadonlyArray<TaskFile> }> = Array.isArray(list)
|
|
325
|
+
? list.map((entry: unknown) => ({ fields: entry, files: [] }))
|
|
326
|
+
: [{ fields: task.fields, files: task.files }]
|
|
327
|
+
if (entries.length === 0) {
|
|
328
|
+
return yield* leaveStep({ workflow: input.workflow, flow, step: input.step, endState: everySubWorkflowTaskEnded, measurements: Option.none(), note: Option.none() })
|
|
329
|
+
}
|
|
330
|
+
const hooks = yield* workforceHooksOf(input.workflow)
|
|
331
|
+
for (const [entryIndex] of entries.entries()) {
|
|
332
|
+
yield* store.insertSubWorkflowTask({ flow: flow._id, entryIndex, workflow: subWorkflow.name })
|
|
333
|
+
}
|
|
334
|
+
yield* store.scheduleHook({
|
|
335
|
+
hook: hooks.startSubWorkflowTasks,
|
|
336
|
+
args: {
|
|
337
|
+
parent: { workflow: input.workflow.name, step: input.step.id, task: task._id, flow: flow._id },
|
|
338
|
+
workflow: subWorkflow.name,
|
|
339
|
+
entries: entries.map((entry, entryIndex) => ({ entryIndex, fields: entry.fields, files: [...entry.files] })),
|
|
340
|
+
},
|
|
341
|
+
})
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
export const register = function* (input: { readonly graph: WorkflowGraph; readonly hooks: Option.Option<WorkforceHooks> }): Run<void> {
|
|
345
|
+
const store = yield* WorkflowStore
|
|
346
|
+
const graph = input.graph
|
|
347
|
+
const problems = problemsOf(graph)
|
|
348
|
+
if (problems.length > 0) return yield* Effect.fail(new InvalidGraph({ workflow: graph.name, problems }))
|
|
349
|
+
const maybeExisting = yield* store.getWorkflow(graph.name)
|
|
350
|
+
const workflow = Option.isSome(maybeExisting)
|
|
351
|
+
? yield* store.replaceGraph({ workflow: maybeExisting.value, graph, hooks: input.hooks })
|
|
352
|
+
: yield* store.insertWorkflow({ graph, hooks: input.hooks })
|
|
353
|
+
yield* store.startTimers({ workflow })
|
|
354
|
+
yield* advance(graph.name)
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
export const setBudgets = function* (input: { readonly workflow: string; readonly budgets: Budgets }): Run<void> {
|
|
358
|
+
const store = yield* WorkflowStore
|
|
359
|
+
const workflow = yield* workflowNamed(input.workflow)
|
|
360
|
+
yield* store.setBudgets({ workflow, budgets: input.budgets })
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
export const createTask = function* (input: {
|
|
364
|
+
readonly workflow: string
|
|
365
|
+
readonly event: Option.Option<string>
|
|
366
|
+
readonly fields: unknown
|
|
367
|
+
readonly files: ReadonlyArray<TaskFile>
|
|
368
|
+
/** Set when a sub-workflow step of another workflow made this task. */
|
|
369
|
+
readonly parent: Option.Option<ParentRef>
|
|
370
|
+
}): Run<Id<"tasks">> {
|
|
371
|
+
const store = yield* WorkflowStore
|
|
372
|
+
const workflow = yield* workflowNamed(input.workflow)
|
|
373
|
+
const maybeEventId = input.event
|
|
374
|
+
const event = Option.isSome(maybeEventId)
|
|
375
|
+
? workflow.graph.events.find((candidate) => candidate.id === maybeEventId.value && createsTasks(candidate))
|
|
376
|
+
: workflow.graph.events.find((candidate) => candidate.kind === "task")
|
|
377
|
+
if (event === undefined || event.kind === "list") {
|
|
378
|
+
return yield* Effect.fail(new UnknownEvent({ workflow: input.workflow, event: Option.getOrElse(input.event, () => "task") }))
|
|
379
|
+
}
|
|
380
|
+
const task = yield* store.insertTask({ workflow: workflow.name, fields: input.fields, files: input.files, parent: input.parent, listedAs: Option.none() })
|
|
381
|
+
yield* startFlow({ workflow, task, event: event.id })
|
|
382
|
+
yield* advance(workflow.name)
|
|
383
|
+
return task._id
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
export const timerFired = function* (input: { readonly workflow: string; readonly event: string; readonly generation?: number | undefined }): Run<void> {
|
|
387
|
+
const store = yield* WorkflowStore
|
|
388
|
+
// A tick of a workflow since removed, or of a registration since replaced, ends its line of ticks here.
|
|
389
|
+
const maybeWorkflow = yield* store.getWorkflow(input.workflow)
|
|
390
|
+
if (Option.isNone(maybeWorkflow) || maybeWorkflow.value.timerGeneration !== input.generation) return
|
|
391
|
+
const workflow = maybeWorkflow.value
|
|
392
|
+
const event = workflow.graph.events.find((candidate) => candidate.id === input.event)
|
|
393
|
+
if (event === undefined || event.kind !== "timer") return
|
|
394
|
+
yield* store.rescheduleTimer({ workflow, event: event.id, everyMs: event.everyMs })
|
|
395
|
+
const task = yield* store.insertTask({ workflow: workflow.name, fields: event.fields, files: [], parent: Option.none(), listedAs: Option.none() })
|
|
396
|
+
yield* startFlow({ workflow, task, event: event.id })
|
|
397
|
+
yield* advance(workflow.name)
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
export const setTaskFields = function* (input: { readonly task: Id<"tasks">; readonly fields: Record<string, unknown>; readonly files: Option.Option<ReadonlyArray<TaskFile>> }): Run<void> {
|
|
401
|
+
const task = yield* taskWithId(input.task)
|
|
402
|
+
const workflow = yield* workflowNamed(task.workflow)
|
|
403
|
+
yield* changeTask({ workflow, task, fields: input.fields, files: Option.getOrElse(input.files, () => task.files) })
|
|
404
|
+
yield* advance(workflow.name)
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
/**
|
|
408
|
+
* Sends a task back through one of its workflow's task or request events: the task's flow that ended at an end state
|
|
409
|
+
* moves onto that event's line, with `fields` when given and `note` kept as why. A task still waiting on a line keeps its
|
|
410
|
+
* place and gets the fields and the note. A task in a step now is refused, so no step's run is overtaken.
|
|
411
|
+
*/
|
|
412
|
+
export const requeue = function* (input: {
|
|
413
|
+
readonly task: Id<"tasks">
|
|
414
|
+
readonly event: string
|
|
415
|
+
readonly fields: Option.Option<Record<string, unknown>>
|
|
416
|
+
readonly note: string
|
|
417
|
+
}): Run<void> {
|
|
418
|
+
const store = yield* WorkflowStore
|
|
419
|
+
const task = yield* taskWithId(input.task)
|
|
420
|
+
const workflow = yield* workflowNamed(task.workflow)
|
|
421
|
+
const event = workflow.graph.events.find((candidate) => candidate.id === input.event && createsTasks(candidate))
|
|
422
|
+
if (event === undefined) return yield* Effect.fail(new UnknownEvent({ workflow: workflow.name, event: input.event }))
|
|
423
|
+
const arrivals = (yield* store.flowsOfTask(task._id)).filter((flow) =>
|
|
424
|
+
workflow.graph.events.some((candidate) => candidate.id === flow.startedBy && createsTasks(candidate)),
|
|
425
|
+
)
|
|
426
|
+
const inStep = arrivals.find((flow) => Option.isSome(stepOfPlace(flow.place)))
|
|
427
|
+
if (inStep !== undefined) return yield* Effect.fail(new TaskInProgress({ task: task._id, step: Option.getOrElse(stepOfPlace(inStep.place), () => "") }))
|
|
428
|
+
yield* store.insertTaskNote({ task: task._id, note: input.note })
|
|
429
|
+
if (Option.isSome(input.fields)) yield* changeTask({ workflow, task, fields: input.fields.value, files: task.files })
|
|
430
|
+
const ended = (yield* store.flowsOfTask(task._id)).filter(
|
|
431
|
+
(flow) => arrivals.some((arrival) => arrival._id === flow._id) && Option.isSome(endStateOfPlace(flow.place)),
|
|
432
|
+
)
|
|
433
|
+
if (ended.length > 0) {
|
|
434
|
+
const line = yield* lineOutOf({ workflow, start: { event: event.id } })
|
|
435
|
+
yield* store.markTaskResumed(task._id)
|
|
436
|
+
for (const flow of ended) {
|
|
437
|
+
const moved = yield* store.moveFlow({ flow: flow._id, place: placeAtEndOf(line), enteredAt: store.now })
|
|
438
|
+
yield* afterArriving({ workflow, flow: moved })
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
yield* advance(workflow.name)
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
/**
|
|
445
|
+
* THE ESCAPE HATCH: moves tasks waiting in a queue to its front, in the order given, ahead of every task moved before,
|
|
446
|
+
* with `note` kept on each as why. A task's flow waiting on a line, or at an end state a step consumes, moves; a retry
|
|
447
|
+
* delay it was waiting out is dropped, since a person asked for it now. A task in a step or ended is named as not waiting,
|
|
448
|
+
* and so is an id that is no task of this workflow.
|
|
449
|
+
*/
|
|
450
|
+
export const moveToFront = function* (input: {
|
|
451
|
+
readonly workflow: string
|
|
452
|
+
readonly tasks: ReadonlyArray<{ readonly id: string; readonly task: Option.Option<Id<"tasks">> }>
|
|
453
|
+
readonly note: string
|
|
454
|
+
}): Run<{ readonly moved: ReadonlyArray<string>; readonly notWaiting: ReadonlyArray<string> }> {
|
|
455
|
+
const store = yield* WorkflowStore
|
|
456
|
+
const workflow = yield* workflowNamed(input.workflow)
|
|
457
|
+
const queues = new Set([
|
|
458
|
+
...workflow.graph.lines.filter((line) => "step" in line.to && !("end" in line.from)).map((line) => `line:${line.id}`),
|
|
459
|
+
...workflow.graph.endStates.filter((end) => Option.isSome(lineFrom(workflow.graph, { end }))).map((end) => `end:${end}`),
|
|
460
|
+
])
|
|
461
|
+
const waiting: Array<{ readonly id: string; readonly flows: ReadonlyArray<FlowRow> }> = []
|
|
462
|
+
const notWaiting: Array<string> = []
|
|
463
|
+
for (const entry of input.tasks) {
|
|
464
|
+
const maybeTask = Option.isNone(entry.task) ? Option.none() : yield* store.getTask(entry.task.value)
|
|
465
|
+
const flows = Option.isSome(maybeTask) && maybeTask.value.workflow === workflow.name ? (yield* store.flowsOfTask(maybeTask.value._id)).filter((flow) => queues.has(flow.place)) : []
|
|
466
|
+
if (flows.length === 0) notWaiting.push(entry.id)
|
|
467
|
+
else waiting.push({ id: entry.id, flows })
|
|
468
|
+
}
|
|
469
|
+
// Ahead of the oldest flow now waiting at any of these places, the first named first.
|
|
470
|
+
let front = Number.POSITIVE_INFINITY
|
|
471
|
+
for (const place of new Set(waiting.flatMap((entry) => entry.flows.map((flow) => flow.place)))) {
|
|
472
|
+
const maybeFirst = yield* store.firstAt({ workflow: workflow.name, place })
|
|
473
|
+
if (Option.isSome(maybeFirst)) front = Math.min(front, maybeFirst.value.enteredAt)
|
|
474
|
+
}
|
|
475
|
+
for (const [index, entry] of waiting.entries()) {
|
|
476
|
+
for (const flow of entry.flows) yield* store.moveFlow({ flow: flow._id, place: flow.place, enteredAt: front - (waiting.length - index) })
|
|
477
|
+
yield* store.insertTaskNote({ task: entry.flows[0]!.task, note: `moved to the front of its queue: ${input.note}` })
|
|
478
|
+
}
|
|
479
|
+
yield* advance(workflow.name)
|
|
480
|
+
return { moved: waiting.map((entry) => entry.id), notWaiting }
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
export interface TakenStep {
|
|
484
|
+
readonly run: Id<"stepRuns">
|
|
485
|
+
readonly workflow: string
|
|
486
|
+
readonly step: string
|
|
487
|
+
/** The task with everything said about it so far, oldest first. */
|
|
488
|
+
readonly task: { readonly id: Id<"tasks">; readonly fields: unknown; readonly files: Array<TaskFile>; readonly notes: Array<TaskNote> }
|
|
489
|
+
/** For an inputs gate: the fingerprint its last settled turn recorded, absent when none has. */
|
|
490
|
+
readonly lastFingerprint?: string
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
/**
|
|
494
|
+
* Gives a worker the task that has waited longest in front of any step it can run whose workflow budget has a unit
|
|
495
|
+
* free. One transaction reads the queue head and the budget and moves the task, so no two workers take the same task.
|
|
496
|
+
*/
|
|
497
|
+
export const take = function* (input: {
|
|
498
|
+
readonly worker: string
|
|
499
|
+
readonly steps: ReadonlyArray<{ readonly workflow: string; readonly step: string }>
|
|
500
|
+
readonly leaseMs: number
|
|
501
|
+
}): Run<Option.Option<TakenStep>> {
|
|
502
|
+
const store = yield* WorkflowStore
|
|
503
|
+
const maybeChoice = yield* nextTakeable(input.steps)
|
|
504
|
+
if (Option.isNone(maybeChoice)) return Option.none()
|
|
505
|
+
const choice = maybeChoice.value
|
|
506
|
+
const run = yield* store.insertStepRun({ flow: choice.flow, step: choice.step.id, version: choice.workflow.version, budget: choice.budget, worker: Option.some(input.worker), leaseMs: Option.some(input.leaseMs) })
|
|
507
|
+
yield* store.moveFlow({ flow: choice.flow._id, place: stepPlace(choice.step.id), enteredAt: store.now })
|
|
508
|
+
yield* store.scheduleLeaseCheck({ run: run._id, at: store.now + input.leaseMs })
|
|
509
|
+
const task = yield* taskWithId(choice.flow.task)
|
|
510
|
+
const notes = yield* store.notesOfTask(task)
|
|
511
|
+
const settledBy = choice.step.inputsSettledBy
|
|
512
|
+
const maybeFingerprint =
|
|
513
|
+
settledBy === undefined ? Option.none() : yield* store.lastFingerprintOf({ workflow: choice.workflow.name, step: choice.step.id, settledBy })
|
|
514
|
+
return Option.some({
|
|
515
|
+
run: run._id,
|
|
516
|
+
workflow: choice.workflow.name,
|
|
517
|
+
step: choice.step.id,
|
|
518
|
+
task: { id: task._id, fields: task.fields, files: [...task.files], notes: [...notes] },
|
|
519
|
+
...(Option.isSome(maybeFingerprint) ? { lastFingerprint: maybeFingerprint.value } : {}),
|
|
520
|
+
})
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
/**
|
|
524
|
+
* When the task `take` would give for these steps entered its queue, so a workforce running several workflow
|
|
525
|
+
* components can take from whichever has waited longest. Read in the same transaction as the `take` that follows.
|
|
526
|
+
*/
|
|
527
|
+
export const oldestTakeable = function* (input: { readonly steps: ReadonlyArray<{ readonly workflow: string; readonly step: string }> }): Run<Option.Option<number>> {
|
|
528
|
+
const maybeChoice = yield* nextTakeable(input.steps)
|
|
529
|
+
return Option.map(maybeChoice, (choice) => choice.flow.enteredAt)
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
const nextTakeable = function* (
|
|
533
|
+
steps: ReadonlyArray<{ readonly workflow: string; readonly step: string }>,
|
|
534
|
+
): Run<Option.Option<{ readonly workflow: WorkflowRow; readonly step: GraphStep; readonly budget: keyof Budgets; readonly flow: FlowRow }>> {
|
|
535
|
+
const store = yield* WorkflowStore
|
|
536
|
+
let maybeChoice: Option.Option<{ readonly workflow: WorkflowRow; readonly step: GraphStep; readonly budget: keyof Budgets; readonly flow: FlowRow }> = Option.none()
|
|
537
|
+
for (const wanted of steps) {
|
|
538
|
+
const workflow = yield* workflowNamed(wanted.workflow)
|
|
539
|
+
const step = yield* stepNamed({ workflow, step: wanted.step })
|
|
540
|
+
const budget = budgetOfStepKind(step.kind)
|
|
541
|
+
if (budget === "none") continue
|
|
542
|
+
const running = yield* store.countRunning({ workflow: workflow.name, budget, upTo: workflow.budgets[budget] })
|
|
543
|
+
if (running >= workflow.budgets[budget]) continue
|
|
544
|
+
const maybeHead = yield* headInFrontOf({ workflow, step: step.id })
|
|
545
|
+
if (Option.isNone(maybeHead)) continue
|
|
546
|
+
const head = maybeHead.value
|
|
547
|
+
if (
|
|
548
|
+
Option.isNone(maybeChoice) ||
|
|
549
|
+
head.enteredAt < maybeChoice.value.flow.enteredAt ||
|
|
550
|
+
(head.enteredAt === maybeChoice.value.flow.enteredAt && head._creationTime < maybeChoice.value.flow._creationTime)
|
|
551
|
+
) {
|
|
552
|
+
maybeChoice = Option.some({ workflow, step, budget, flow: head })
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
return maybeChoice
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
const runningRun = function* (run: Id<"stepRuns">) {
|
|
559
|
+
const store = yield* WorkflowStore
|
|
560
|
+
const maybeRun = yield* store.getStepRun(run)
|
|
561
|
+
if (Option.isNone(maybeRun)) return yield* Effect.fail(new StepRunNotRunning({ run, status: "missing" }))
|
|
562
|
+
if (maybeRun.value.status !== "running") return yield* Effect.fail(new StepRunNotRunning({ run, status: maybeRun.value.status }))
|
|
563
|
+
return maybeRun.value
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
/** `workflow` is the one the worker checked the fields against; a run of another workflow is refused. */
|
|
567
|
+
export const complete = function* (input: {
|
|
568
|
+
readonly run: Id<"stepRuns">
|
|
569
|
+
readonly workflow: string
|
|
570
|
+
readonly endState: string
|
|
571
|
+
readonly fields: Option.Option<Record<string, unknown>>
|
|
572
|
+
readonly files: Option.Option<ReadonlyArray<TaskFile>>
|
|
573
|
+
readonly measurements: Option.Option<StepMeasurements>
|
|
574
|
+
readonly note: Option.Option<string>
|
|
575
|
+
/** From a step that syncs a declared item list: every item on it, each as its task's encoded fields. */
|
|
576
|
+
readonly listed: Option.Option<ReadonlyArray<unknown>>
|
|
577
|
+
/** Writes to other tasks the workforce could not apply, each with why; kept on the run. */
|
|
578
|
+
readonly skippedOthers: ReadonlyArray<SkippedOther>
|
|
579
|
+
}): Run<void> {
|
|
580
|
+
const store = yield* WorkflowStore
|
|
581
|
+
const run = yield* runningRun(input.run)
|
|
582
|
+
if (run.workflow !== input.workflow) {
|
|
583
|
+
return yield* Effect.fail(new InvalidTaskFields({ task: run.task, problem: `checked against workflow ${input.workflow}, but the run is in ${run.workflow}` }))
|
|
584
|
+
}
|
|
585
|
+
const workflow = yield* workflowNamed(run.workflow)
|
|
586
|
+
const step = yield* stepNamed({ workflow, step: run.step })
|
|
587
|
+
if (!step.endStates.includes(input.endState)) {
|
|
588
|
+
return yield* Effect.fail(new UnknownEndState({ workflow: workflow.name, step: step.id, endState: input.endState }))
|
|
589
|
+
}
|
|
590
|
+
if ((step.syncs !== undefined) !== Option.isSome(input.listed)) {
|
|
591
|
+
const problem = step.syncs !== undefined ? `step ${step.id} syncs a list but reported none` : `step ${step.id} reported a list but syncs none`
|
|
592
|
+
return yield* Effect.fail(new InvalidTaskFields({ task: run.task, problem }))
|
|
593
|
+
}
|
|
594
|
+
const synced = step.syncs !== undefined && Option.isSome(input.listed)
|
|
595
|
+
? Option.some(yield* syncList({ workflow, event: step.syncs, step: step.id, task: run.task, listed: input.listed.value }))
|
|
596
|
+
: Option.none<string>()
|
|
597
|
+
const task = yield* taskWithId(run.task)
|
|
598
|
+
if (Option.isSome(input.fields) || Option.isSome(input.files)) {
|
|
599
|
+
yield* changeTask({
|
|
600
|
+
workflow,
|
|
601
|
+
task,
|
|
602
|
+
fields: Option.getOrElse(input.fields, () => task.fields),
|
|
603
|
+
files: Option.getOrElse(input.files, () => task.files),
|
|
604
|
+
})
|
|
605
|
+
}
|
|
606
|
+
if (input.skippedOthers.length > 0) yield* store.recordSkippedOthers({ run: run._id, skipped: input.skippedOthers })
|
|
607
|
+
const flow = yield* flowWithId(run.flow)
|
|
608
|
+
yield* leaveStep({ workflow, flow, step, endState: input.endState, measurements: input.measurements, note: Option.orElse(input.note, () => synced) })
|
|
609
|
+
yield* advance(workflow.name)
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
/**
|
|
613
|
+
* Another task's run writes to this task (`StepOutcome.others`), in the transaction that completes that run: the note,
|
|
614
|
+
* saying whose run wrote it, then the fields and files, which start this task's change events as any change does. A task
|
|
615
|
+
* in a step now is left alone, so no step's run is overtaken; the reason is returned for the writing run to record.
|
|
616
|
+
*/
|
|
617
|
+
export const writeOther = function* (input: {
|
|
618
|
+
readonly task: Id<"tasks">
|
|
619
|
+
readonly fields: Option.Option<Record<string, unknown>>
|
|
620
|
+
readonly files: Option.Option<ReadonlyArray<TaskFile>>
|
|
621
|
+
readonly note: string
|
|
622
|
+
/** The run that wrote it, in words: its step, its workflow and its task. */
|
|
623
|
+
readonly by: string
|
|
624
|
+
}): Run<Option.Option<string>> {
|
|
625
|
+
const store = yield* WorkflowStore
|
|
626
|
+
const task = yield* taskWithId(input.task)
|
|
627
|
+
const workflow = yield* workflowNamed(task.workflow)
|
|
628
|
+
const inStep = (yield* store.flowsOfTask(task._id)).find((flow) => Option.isSome(stepOfPlace(flow.place)))
|
|
629
|
+
if (inStep !== undefined) return Option.some(`it was in step ${Option.getOrElse(stepOfPlace(inStep.place), () => "")} when the run ended`)
|
|
630
|
+
yield* store.insertTaskNote({ task: task._id, note: `${input.note} (written by ${input.by})` })
|
|
631
|
+
if (Option.isSome(input.fields) || Option.isSome(input.files)) {
|
|
632
|
+
yield* changeTask({
|
|
633
|
+
workflow,
|
|
634
|
+
task,
|
|
635
|
+
fields: Option.getOrElse(input.fields, () => task.fields),
|
|
636
|
+
files: Option.getOrElse(input.files, () => task.files),
|
|
637
|
+
})
|
|
638
|
+
}
|
|
639
|
+
yield* advance(workflow.name)
|
|
640
|
+
return Option.none()
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
/**
|
|
644
|
+
* Keeps a list event's tasks in step with the list a sync step read: an item with no task gets one, arriving on the
|
|
645
|
+
* event's line; a task whose item left the list before it ended ends in the event's `leftAs`, with a note saying so.
|
|
646
|
+
* An ended task whose item left the list and comes back is requeued onto the event's line, with a note: a list holds
|
|
647
|
+
* what needs work, so an item back on it needs work again. A task that ended and stayed listed stays as it ended. A task in a step now is left to its step, and the next sync ends it if its item is still gone.
|
|
648
|
+
* Returns what changed, in words, for the sync step's run.
|
|
649
|
+
*/
|
|
650
|
+
const syncList = function* (input: { readonly workflow: WorkflowRow; readonly event: string; readonly step: string; readonly task: Id<"tasks">; readonly listed: ReadonlyArray<unknown> }): Run<string> {
|
|
651
|
+
const store = yield* WorkflowStore
|
|
652
|
+
const event = input.workflow.graph.events.find((candidate) => candidate.id === input.event)
|
|
653
|
+
if (event === undefined || event.kind !== "list") return yield* Effect.fail(new UnknownEvent({ workflow: input.workflow.name, event: input.event }))
|
|
654
|
+
const listed = new Map<string, unknown>()
|
|
655
|
+
for (const fields of input.listed) {
|
|
656
|
+
const key: unknown = typeof fields === "object" && fields !== null ? (fields as Record<string, unknown>)[event.key] : undefined
|
|
657
|
+
if (typeof key !== "string") {
|
|
658
|
+
return yield* Effect.fail(new InvalidTaskFields({ task: input.task, problem: ` listed an item of list ${event.id} has no string field ${event.key}` }))
|
|
659
|
+
}
|
|
660
|
+
listed.set(key, fields)
|
|
661
|
+
}
|
|
662
|
+
const existing = new Map((yield* store.listedTasksOf({ workflow: input.workflow.name, event: event.id })).map((task) => [task.listedAs?.key ?? "", task]))
|
|
663
|
+
let made = 0
|
|
664
|
+
let left = 0
|
|
665
|
+
let back = 0
|
|
666
|
+
let stillInAStep = 0
|
|
667
|
+
for (const [key, fields] of listed) {
|
|
668
|
+
if (existing.has(key)) continue
|
|
669
|
+
const task = yield* store.insertTask({ workflow: input.workflow.name, fields, files: [], parent: Option.none(), listedAs: Option.some({ event: event.id, key }) })
|
|
670
|
+
yield* startFlow({ workflow: input.workflow, task, event: event.id })
|
|
671
|
+
made += 1
|
|
672
|
+
}
|
|
673
|
+
for (const [key, task] of existing) {
|
|
674
|
+
const arrivals = (yield* store.flowsOfTask(task._id)).filter((flow) => flow.startedBy === event.id)
|
|
675
|
+
const leftWhileEnded = task.listedAs?.leftWhileEnded === true
|
|
676
|
+
if (listed.has(key)) {
|
|
677
|
+
if (task.endedAs === undefined || (task.endedAs !== event.leftAs && !leftWhileEnded)) continue
|
|
678
|
+
// Back on a list of work to do: it needs work again (a function that regressed), however it ended.
|
|
679
|
+
if (leftWhileEnded) yield* store.setLeftWhileEnded({ task: task._id, left: false })
|
|
680
|
+
yield* requeue({ task: task._id, event: event.id, fields: Option.none(), note: `${input.step} found ${key} on list ${event.id} again, so it needs work again` })
|
|
681
|
+
back += 1
|
|
682
|
+
continue
|
|
683
|
+
}
|
|
684
|
+
if (task.endedAs !== undefined) {
|
|
685
|
+
if (task.endedAs !== event.leftAs && !leftWhileEnded) yield* store.setLeftWhileEnded({ task: task._id, left: true })
|
|
686
|
+
continue
|
|
687
|
+
}
|
|
688
|
+
if (arrivals.some((flow) => Option.isSome(stepOfPlace(flow.place)))) {
|
|
689
|
+
stillInAStep += 1
|
|
690
|
+
continue
|
|
691
|
+
}
|
|
692
|
+
yield* store.insertTaskNote({ task: task._id, note: `${input.step} no longer found ${key} on list ${event.id}` })
|
|
693
|
+
for (const flow of arrivals) {
|
|
694
|
+
const moved = yield* store.moveFlow({ flow: flow._id, place: `end:${event.leftAs}`, enteredAt: store.now })
|
|
695
|
+
yield* afterArriving({ workflow: input.workflow, flow: moved })
|
|
696
|
+
}
|
|
697
|
+
left += 1
|
|
698
|
+
}
|
|
699
|
+
const inAStep = stillInAStep === 0 ? "" : `; ${stillInAStep} gone from it are in a step, so a later sync ends them`
|
|
700
|
+
return `${listed.size} listed: ${made} new, ${left} left, ${back} back${inAStep}`
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
/**
|
|
704
|
+
* Records the failure and puts the task back at the front of the queue it was taken from, to be taken again: at once,
|
|
705
|
+
* or after the step's `retries.delayMs`. At the step's `retries.limit` of failed runs in a row it leaves through
|
|
706
|
+
* `retries.giveUp` instead.
|
|
707
|
+
*/
|
|
708
|
+
export const fail = function* (input: { readonly run: Id<"stepRuns">; readonly error: string; readonly measurements: Option.Option<StepMeasurements> }): Run<void> {
|
|
709
|
+
const store = yield* WorkflowStore
|
|
710
|
+
const run = yield* runningRun(input.run)
|
|
711
|
+
yield* store.finishStepRun({ run: run._id, status: "failed", endState: Option.none(), error: Option.some(input.error), measurements: input.measurements, note: Option.none() })
|
|
712
|
+
const workflow = yield* workflowNamed(run.workflow)
|
|
713
|
+
const step = yield* stepNamed({ workflow, step: run.step })
|
|
714
|
+
const retries = step.retries
|
|
715
|
+
if (retries === undefined) {
|
|
716
|
+
yield* store.moveFlow({ flow: run.flow, place: run.takenFrom.place, enteredAt: run.takenFrom.enteredAt })
|
|
717
|
+
return yield* advance(run.workflow)
|
|
718
|
+
}
|
|
719
|
+
// The failed runs in a row of this flow in this step, this one included.
|
|
720
|
+
const runs = (yield* store.stepRunsOfTask(run.task)).filter((candidate) => candidate.flow === run.flow && candidate.step === run.step)
|
|
721
|
+
const inARow = [...runs].sort((a, b) => b.startedAt - a.startedAt || b._creationTime - a._creationTime).findIndex((candidate) => candidate.status !== "failed")
|
|
722
|
+
const failures = inARow === -1 ? runs.length : inARow
|
|
723
|
+
if (failures >= retries.limit) {
|
|
724
|
+
yield* store.insertTaskNote({ task: run.task, note: `${step.id} gave up after ${failures} failed runs in a row; the last: ${input.error.slice(0, 500)}` })
|
|
725
|
+
yield* leaveStep({ workflow, flow: yield* flowWithId(run.flow), step, endState: retries.giveUp, measurements: Option.none(), note: Option.none() })
|
|
726
|
+
return yield* advance(run.workflow)
|
|
727
|
+
}
|
|
728
|
+
yield* store.moveFlow({ flow: run.flow, place: run.takenFrom.place, enteredAt: run.takenFrom.enteredAt, notBefore: store.now + retries.delayMs })
|
|
729
|
+
yield* advance(run.workflow)
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
export const heartbeat = function* (input: { readonly run: Id<"stepRuns">; readonly leaseMs: number }): Run<void> {
|
|
733
|
+
const store = yield* WorkflowStore
|
|
734
|
+
const run = yield* runningRun(input.run)
|
|
735
|
+
yield* store.extendLease({ run: run._id, leaseMs: input.leaseMs })
|
|
736
|
+
}
|
|
737
|
+
|
|
738
|
+
/** A worker that stops heartbeating loses its task: the run fails and the task goes back to the front of its queue. */
|
|
739
|
+
export const expireLease = function* (input: { readonly run: Id<"stepRuns"> }): Run<void> {
|
|
740
|
+
const store = yield* WorkflowStore
|
|
741
|
+
const maybeRun = yield* store.getStepRun(input.run)
|
|
742
|
+
if (Option.isNone(maybeRun) || maybeRun.value.status !== "running") return
|
|
743
|
+
const run = maybeRun.value
|
|
744
|
+
const maybeExpiry = yield* store.leaseExpiryOf(run._id)
|
|
745
|
+
if (Option.isNone(maybeExpiry)) return
|
|
746
|
+
if (maybeExpiry.value > store.now) return yield* store.scheduleLeaseCheck({ run: run._id, at: maybeExpiry.value })
|
|
747
|
+
yield* fail({ run: run._id, error: `lease expired: worker ${run.worker ?? "unknown"} stopped reporting`, measurements: Option.none() })
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
/** Retires a workflow: it and everything in it are deleted. */
|
|
751
|
+
export const remove = function* (input: { readonly workflow: string }): Run<void> {
|
|
752
|
+
const store = yield* WorkflowStore
|
|
753
|
+
const maybeWorkflow = yield* store.getWorkflow(input.workflow)
|
|
754
|
+
if (Option.isSome(maybeWorkflow)) yield* store.deleteWorkflow(maybeWorkflow.value)
|
|
755
|
+
}
|