@jive-sh/workflow-platform 0.7.0 → 1.1.0

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