@jive-sh/workflow-platform 0.1.0 → 0.3.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 +41 -15
- package/dist/cpu-limit/limiter.js +54 -11
- package/dist/cpu-limit/limiter.js.map +1 -1
- package/dist/index.js +44 -39
- package/dist/index.js.map +1 -1
- package/dist/keep-running.js +5 -5
- package/dist/keep-running.js.map +1 -1
- package/dist/pick-wakes.js +7 -1
- package/dist/pick-wakes.js.map +1 -1
- package/dist/queue-counts.js +47 -0
- package/dist/queue-counts.js.map +1 -0
- package/dist/steps.js +75 -18
- package/dist/steps.js.map +1 -1
- package/dist/storage/budgets.js +14 -0
- package/dist/storage/budgets.js.map +1 -1
- package/dist/storage/sqlite-store.js +68 -15
- package/dist/storage/sqlite-store.js.map +1 -1
- package/dist/views/workflow-flows.js +53 -0
- package/dist/views/workflow-flows.js.map +1 -0
- package/dist/views/workflows-view.js +81 -55
- package/dist/views/workflows-view.js.map +1 -1
- package/package.json +1 -1
- package/src/cpu-limit/limiter.ts +61 -11
- package/src/dashboard/dashboard.css +78 -0
- package/src/dashboard/index.tsx +3 -0
- package/src/dashboard/queue-chart.tsx +137 -0
- package/src/dashboard/step-graph.tsx +98 -0
- package/src/dashboard/workflow-dag.tsx +256 -0
- package/src/dashboard/workflows-dashboard.tsx +313 -0
- package/src/index.ts +46 -39
- package/src/keep-running.ts +5 -7
- package/src/pick-wakes.ts +9 -2
- package/src/queue-counts.ts +61 -0
- package/src/steps.ts +83 -26
- package/src/storage/budgets.ts +13 -0
- package/src/storage/sqlite-store.ts +82 -18
- package/src/storage/step-records.ts +6 -5
- package/src/storage/task-store.ts +32 -0
- package/src/views/workflow-flows.ts +97 -0
- package/src/views/workflows-view.ts +148 -82
package/src/index.ts
CHANGED
|
@@ -13,10 +13,11 @@ import type { WorkflowProject } from './project';
|
|
|
13
13
|
import { makePickWakes } from './pick-wakes';
|
|
14
14
|
import { makeStepFiles } from './step-files';
|
|
15
15
|
import { makeStepUsage } from './step-usage';
|
|
16
|
-
import { keptRunningByItsBudget, makeSteps } from './steps';
|
|
16
|
+
import { keptRunningByItsBudget, makeSteps, runLimitOf } from './steps';
|
|
17
17
|
import { makeTasks, type TaskRules } from './tasks';
|
|
18
|
-
import { buildWorkflowsView, type WorkflowsView, type WorkflowView } from './views/workflows-view';
|
|
19
|
-
import {
|
|
18
|
+
import { buildWorkflowFigures, buildWorkflowsView, type WorkflowFigures, type WorkflowsView, type WorkflowView } from './views/workflows-view';
|
|
19
|
+
import { makeQueueCounts } from './queue-counts';
|
|
20
|
+
import { sqliteBudgets, type LimitStore } from './storage/budgets';
|
|
20
21
|
import { sqliteEngineRecords, type EngineRecords } from './storage/engine-records';
|
|
21
22
|
import { sqliteStore } from './storage/sqlite-store';
|
|
22
23
|
import type { StepRecords } from './storage/step-records';
|
|
@@ -28,6 +29,7 @@ export * from './project';
|
|
|
28
29
|
export * from './budget-states';
|
|
29
30
|
export * from './keep-running';
|
|
30
31
|
export * from './pick-wakes';
|
|
32
|
+
export * from './queue-counts';
|
|
31
33
|
export * from './step-files';
|
|
32
34
|
export * from './step-meter';
|
|
33
35
|
export * from './steps';
|
|
@@ -48,6 +50,7 @@ export * from './views/runs-now';
|
|
|
48
50
|
export * from './views/step-funnel';
|
|
49
51
|
export * from './views/step-graph';
|
|
50
52
|
export * from './views/workflows-view';
|
|
53
|
+
export * from './views/workflow-flows';
|
|
51
54
|
export type { NewNote, TaskStore, TextChange } from './storage/task-store';
|
|
52
55
|
|
|
53
56
|
/** Where a project's records live: each store an interface, so another database can stand behind any of them. */
|
|
@@ -101,49 +104,53 @@ export const createWorkflowPlatform = <Phase extends string, R>(input: {
|
|
|
101
104
|
const steps = makeSteps<Phase, R>({
|
|
102
105
|
sourceRoot: project.sourceRoot, stepRecords: storage.stepRecords, engine: storage.engine, tasks, wakes, budgets: storage.budgets, stepFiles,
|
|
103
106
|
CurrentStepUsage: stepUsage.CurrentStepUsage, isTransientFailure: project.isTransientFailure, thisProcess: project.processes.thisProcess, inputs: storage.inputs,
|
|
107
|
+
queueChanged: (workflow) => queueCounts.changed(workflow),
|
|
108
|
+
});
|
|
109
|
+
const queueCounts = makeQueueCounts<R>({
|
|
110
|
+
store: storage.tasks, tasks, wakes, readTaskInputs: steps.readTaskInputs,
|
|
111
|
+
withQueues: () => steps.declaredWorkflows().filter((d) => d.item !== null).map((d) => d.name),
|
|
104
112
|
});
|
|
105
113
|
/**
|
|
106
|
-
* Every workflow
|
|
107
|
-
*
|
|
114
|
+
* Every workflow's limits now, by name, in one read: what a page's controls show. Every workflow has a run limit
|
|
115
|
+
* (`steps.ts` `runLimitOf`), none meaning no limit; only one its budget keeps going has an agents' limit. Empty where no
|
|
116
|
+
* store is read (a test).
|
|
108
117
|
*/
|
|
109
|
-
/** A workflow's two limits now, as stored: none for one no limit rules (no agent step, or no list of work). */
|
|
110
|
-
const limitsOf = (name: string): Effect.Effect<WorkflowView['limits'], StorageError> => {
|
|
111
|
-
const d = steps.declaredWorkflows().find((w) => w.name === name);
|
|
112
|
-
if (d === undefined || !keptRunningByItsBudget(d)) return Effect.succeed(null);
|
|
113
|
-
return Effect.map(storage.budgets.limitsOf(name), (limits) => (limits === null ? null : { agents: limits.agents, runs: runLimit(limits), runsSet: limits.runs !== null }));
|
|
114
|
-
};
|
|
115
|
-
|
|
116
|
-
/** Every limited workflow's two limits now, by name: what a page's controls show, read at each request. */
|
|
117
118
|
const limitsNow = (): Effect.Effect<Readonly<Record<string, NonNullable<WorkflowView['limits']>>>, StorageError> =>
|
|
118
|
-
Effect.map(
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
);
|
|
119
|
+
Effect.map(storage.budgets.storedLimits(), (stored) => (stored === null ? {} : Object.fromEntries(steps.declaredWorkflows().map((d) => {
|
|
120
|
+
const limits = stored.get(d.name) ?? { agents: 0, runs: null };
|
|
121
|
+
return [d.name, { agents: keptRunningByItsBudget(d) ? limits.agents : null, runs: runLimitOf(d, limits), runsSet: limits.runs !== null }] as const;
|
|
122
|
+
}))));
|
|
123
|
+
|
|
124
|
+
/** Each source file's text, read again only when the file changed: a page's links name the line a definition is on now. */
|
|
125
|
+
const texts = new Map<string, { readonly changed: number; readonly text: string } | null>();
|
|
126
|
+
const locate = (s: { readonly path: string; readonly anchor: string }): number | null => {
|
|
127
|
+
const file = path.join(project.sourceRoot, s.path);
|
|
128
|
+
try {
|
|
129
|
+
const changed = fs.statSync(file).mtimeMs;
|
|
130
|
+
if (texts.get(s.path)?.changed !== changed) texts.set(s.path, { changed, text: fs.readFileSync(file, 'utf8') });
|
|
131
|
+
} catch {
|
|
132
|
+
texts.set(s.path, null);
|
|
133
|
+
}
|
|
134
|
+
const text = texts.get(s.path)?.text;
|
|
135
|
+
const at = text === undefined ? -1 : text.indexOf(s.anchor);
|
|
136
|
+
return text === undefined || at < 0 ? null : text.slice(0, at).split('\n').length;
|
|
137
|
+
};
|
|
122
138
|
|
|
123
|
-
|
|
139
|
+
/**
|
|
140
|
+
* Every workflow as a dashboard shows it before one is opened, read now (`views/workflows-view.ts` `buildWorkflowsView`).
|
|
141
|
+
* `phases` is the order the project's page shows them in.
|
|
142
|
+
*/
|
|
143
|
+
const view = (r: { readonly now: number; readonly phases: ReadonlyArray<string> }): Effect.Effect<WorkflowsView, StorageError> => Effect.gen(function* () {
|
|
124
144
|
const limits = yield* limitsNow();
|
|
125
|
-
|
|
126
|
-
// Each file read once for the whole view.
|
|
127
|
-
const texts = new Map<string, string | null>();
|
|
128
|
-
const textOf = (file: string): string | null => {
|
|
129
|
-
if (!texts.has(file)) {
|
|
130
|
-
try { texts.set(file, fs.readFileSync(path.join(project.sourceRoot, file), 'utf8')); } catch { texts.set(file, null); }
|
|
131
|
-
}
|
|
132
|
-
return texts.get(file) ?? null;
|
|
133
|
-
};
|
|
134
|
-
return yield* buildWorkflowsView({
|
|
135
|
-
declared, phases: r.phases, now: r.now, hours: r.hours,
|
|
136
|
-
records: storage.stepRecords, engine: storage.engine, tasks,
|
|
137
|
-
locate: (s) => {
|
|
138
|
-
const text = textOf(s.path);
|
|
139
|
-
const at = text === null ? -1 : text.indexOf(s.anchor);
|
|
140
|
-
return text === null || at < 0 ? null : text.slice(0, at).split('\n').length;
|
|
141
|
-
},
|
|
142
|
-
limitsOf: (name) => limits[name] ?? null,
|
|
143
|
-
pausedOf: r.pausedOf,
|
|
144
|
-
});
|
|
145
|
+
return yield* buildWorkflowsView({ declared: steps.declaredWorkflows(), phases: r.phases, now: r.now, taskStore: storage.tasks, locate, limitsOf: (name) => limits[name] ?? null });
|
|
145
146
|
});
|
|
146
|
-
|
|
147
|
+
|
|
148
|
+
/** One workflow's figures over the `hours` before `now`, read from its own records (`buildWorkflowFigures`); none for one not declared. */
|
|
149
|
+
const figures = (r: { readonly workflow: string; readonly now: number; readonly hours: number }): Effect.Effect<WorkflowFigures | null, StorageError> => {
|
|
150
|
+
const declaration = steps.declaredWorkflows().find((d) => d.name === r.workflow);
|
|
151
|
+
return declaration === undefined ? Effect.succeed(null) : buildWorkflowFigures({ declaration, now: r.now, hours: r.hours, records: storage.stepRecords, engine: storage.engine, locate });
|
|
152
|
+
};
|
|
153
|
+
return { project, storage, wakes, stepFiles, stepUsage, tasks, steps, view, figures, limitsNow, queueCounts };
|
|
147
154
|
};
|
|
148
155
|
|
|
149
156
|
export type WorkflowPlatform<Phase extends string, R> = ReturnType<typeof createWorkflowPlatform<Phase, R>>;
|
package/src/keep-running.ts
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
* one trigger, with no code of its own: each turn it starts as many runs as the workflow's run limit keeps (`runLimit`) above
|
|
8
8
|
* the runs going, as soon as a run ends and otherwise on a fallback timer. There is no sharing between workflows, no order,
|
|
9
9
|
* no cap per item and no check of usage: a run with nothing to pick waits for an item (`steps.ts` `untilPicked`), and the
|
|
10
|
-
* stuck bucket and the queue's order keep a run off what it cannot finish. A
|
|
10
|
+
* stuck bucket and the queue's order keep a run off what it cannot finish. A run limit of 0 holds one workflow.
|
|
11
11
|
*/
|
|
12
12
|
import { keptRunningByItsBudget, type WorkflowDeclaration } from './steps';
|
|
13
13
|
import { runLimit, type WorkflowLimits } from './storage/budgets';
|
|
@@ -24,22 +24,20 @@ export const budgetedWorkflows = <D extends Pick<WorkflowDeclaration<string, unk
|
|
|
24
24
|
declared.filter(keptRunningByItsBudget);
|
|
25
25
|
|
|
26
26
|
/**
|
|
27
|
-
* How many runs of one workflow to start now: the runs its run limit keeps above the runs going
|
|
28
|
-
*
|
|
27
|
+
* How many runs of one workflow to start now: the runs its run limit keeps above the runs going. Its agents' limit plays
|
|
28
|
+
* no part: at 0 agents its runs wait at their first agent step. Pure.
|
|
29
29
|
*/
|
|
30
|
-
export const runsToStart = (w: { readonly kept: number; readonly running: number
|
|
31
|
-
w.paused ? 0 : Math.max(w.kept - w.running, 0);
|
|
30
|
+
export const runsToStart = (w: { readonly kept: number; readonly running: number }): number => Math.max(w.kept - w.running, 0);
|
|
32
31
|
|
|
33
32
|
/** One turn's plan: for each budgeted workflow, the runs going and how many to start. Pure but for the reads it is given. */
|
|
34
33
|
export const planRunStarts = <D extends Pick<WorkflowDeclaration<string, unknown>, 'name' | 'pending' | 'steps'>>(input: {
|
|
35
34
|
readonly declared: ReadonlyArray<D>;
|
|
36
35
|
readonly limitsOf: (workflow: string) => WorkflowLimits;
|
|
37
|
-
readonly paused: (workflow: string) => boolean;
|
|
38
36
|
readonly runningRuns: (workflow: string) => number;
|
|
39
37
|
}): ReadonlyArray<{ readonly declaration: D; readonly running: number; readonly start: number }> =>
|
|
40
38
|
budgetedWorkflows(input.declared).map((d) => {
|
|
41
39
|
const running = input.runningRuns(d.name);
|
|
42
|
-
return { declaration: d, running, start: runsToStart({ kept: runLimit(input.limitsOf(d.name)), running
|
|
40
|
+
return { declaration: d, running, start: runsToStart({ kept: runLimit(input.limitsOf(d.name)), running }) };
|
|
43
41
|
});
|
|
44
42
|
|
|
45
43
|
/**
|
package/src/pick-wakes.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* WHAT WAKES A PICK THAT FOUND NOTHING IT CAN CLAIM (`steps.ts` `untilPicked`), never a timer. A wake is any event that can
|
|
3
3
|
* change what a Pick can claim: a note on one of its workflow's tasks (new input, a reopen, a release, a hold, an outcome:
|
|
4
|
-
* `tasks.ts`), an item new to its list (`recordListing`), its limits
|
|
4
|
+
* `tasks.ts`), an item new to its list (`recordListing`), its limits set (which also has the run planner plan
|
|
5
5
|
* again: `runPlanChanged`), or one of its runs ending, which lets that run's
|
|
6
6
|
* claim go. A claim held outside its workflow's runs ending, or a lease running out, wakes nothing: the next of these events
|
|
7
7
|
* re-checks it. Before 2026-11-11 a Pick with nothing picked again each minute, and at budget 0 it ended its run at once:
|
|
@@ -37,12 +37,14 @@ export interface PickWakes {
|
|
|
37
37
|
/** Something every workflow's Picks can claim may have changed (every budget was set). */
|
|
38
38
|
readonly wakeEveryPick: (source: string) => void;
|
|
39
39
|
/**
|
|
40
|
-
* A workflow's limits
|
|
40
|
+
* A workflow's limits were set (every workflow's, when `workflow` is none): its Picks are woken, and the run
|
|
41
41
|
* planner (`keep-running.ts`), told through `onRunPlanChanged` in the process it runs in, plans its runs again at once.
|
|
42
42
|
*/
|
|
43
43
|
readonly runPlanChanged: (r: { readonly workflow: string | null; readonly source: string }) => void;
|
|
44
44
|
/** Calls `listener` on each `runPlanChanged` that reaches this process, raised here or relayed. */
|
|
45
45
|
readonly onRunPlanChanged: (listener: (workflow: string | null) => void) => void;
|
|
46
|
+
/** Calls `listener` on each wake that reaches this process, raised here or relayed: what else follows a queue's changes (`queue-counts.ts`). */
|
|
47
|
+
readonly onWake: (listener: (wake: Wake) => void) => void;
|
|
46
48
|
/** Waits until a wake reaches this workflow after `after` wakes; at once when one already has. */
|
|
47
49
|
readonly untilPickWoken: (r: { readonly workflow: string; readonly after: number }) => Effect.Effect<void>;
|
|
48
50
|
/** A waiting Pick picked again after a wake: `ms` is how long that pick took. */
|
|
@@ -102,9 +104,11 @@ export const makePickWakes = (): PickWakes => {
|
|
|
102
104
|
|
|
103
105
|
let relay: ((wake: Wake) => void) | null = null;
|
|
104
106
|
const runPlanListeners = new Set<(workflow: string | null) => void>();
|
|
107
|
+
const wakeListeners = new Set<(wake: Wake) => void>();
|
|
105
108
|
let released = false;
|
|
106
109
|
|
|
107
110
|
const wakeHere = (w: Wake): void => {
|
|
111
|
+
for (const listener of wakeListeners) queueMicrotask(() => listener(w));
|
|
108
112
|
if (w.runPlan === true) for (const listener of runPlanListeners) queueMicrotask(() => listener(w.workflow));
|
|
109
113
|
if (w.workflow === null) {
|
|
110
114
|
wakesOfEvery += 1;
|
|
@@ -131,6 +135,9 @@ export const makePickWakes = (): PickWakes => {
|
|
|
131
135
|
onRunPlanChanged: (listener) => {
|
|
132
136
|
runPlanListeners.add(listener);
|
|
133
137
|
},
|
|
138
|
+
onWake: (listener) => {
|
|
139
|
+
wakeListeners.add(listener);
|
|
140
|
+
},
|
|
134
141
|
relayTo: (send) => {
|
|
135
142
|
relay = send;
|
|
136
143
|
},
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* EACH QUEUE'S COUNTS, RECORDED WHEN ITS QUEUE MAY HAVE CHANGED (`queue_counts`), so a page reads the newest row and never
|
|
3
|
+
* counts. A workflow's tasks by bucket are worked out from every task's notes (`tasks.ts` `summarize`): 0.7 s for a
|
|
4
|
+
* project's 20,000 tasks on a busy machine, too long for a page load, and until 2026-11-17 a job did it every 5 minutes for
|
|
5
|
+
* a stored page. Here it is done once per change, in the one process that runs the project's workflows, which is also the
|
|
6
|
+
* one that has read each task's inputs as its Pick reads them, so the page and the Pick put a task in the same bucket.
|
|
7
|
+
*
|
|
8
|
+
* WHAT COUNTS AS A CHANGE: every wake of a workflow's Picks (`pick-wakes.ts`: a note on one of its tasks, an item new to
|
|
9
|
+
* its list, one of its runs ending, a limit set), and a Pick claiming an item (`changed`). Every change within
|
|
10
|
+
* `COUNT_AFTER_MS` of the first is one count, taken at its end, so 25 short runs ending a minute cost 12 counts and each
|
|
11
|
+
* change shows within 5 seconds. A row is written only where a count moved.
|
|
12
|
+
*/
|
|
13
|
+
import { Effect } from 'effect';
|
|
14
|
+
import type { PickWakes } from './pick-wakes';
|
|
15
|
+
import type { StorageError } from './storage/storage-error';
|
|
16
|
+
import type { TaskStore } from './storage/task-store';
|
|
17
|
+
import { bucketCounts, type Tasks } from './tasks';
|
|
18
|
+
|
|
19
|
+
/** How long after a queue's first change it is counted: every change in that time is in the one count. */
|
|
20
|
+
export const COUNT_AFTER_MS = 5_000;
|
|
21
|
+
|
|
22
|
+
export const makeQueueCounts = <R>(deps: {
|
|
23
|
+
readonly store: Pick<TaskStore, 'recordQueueCounts'>;
|
|
24
|
+
readonly tasks: Pick<Tasks, 'taskSummaries'>;
|
|
25
|
+
readonly wakes: Pick<PickWakes, 'onWake'>;
|
|
26
|
+
/** The workflows that have a queue, now. */
|
|
27
|
+
readonly withQueues: () => ReadonlyArray<string>;
|
|
28
|
+
/** Reads a workflow's tasks' inputs where it declares them (`steps.ts` `readTaskInputs`), as its Pick does before it reads its queue. */
|
|
29
|
+
readonly readTaskInputs: (workflow: string) => Effect.Effect<unknown, unknown, R>;
|
|
30
|
+
/** `COUNT_AFTER_MS` where absent; a test names a shorter one. */
|
|
31
|
+
readonly countAfterMs?: number;
|
|
32
|
+
}) => {
|
|
33
|
+
/** Counts one workflow's queue now and records it. Its inputs unread, it is counted with those last read, and that is said. */
|
|
34
|
+
const count = (workflow: string): Effect.Effect<void, StorageError, R> => Effect.gen(function* () {
|
|
35
|
+
yield* Effect.catch(deps.readTaskInputs(workflow), (e) => Effect.logError(`[queue counts] ${workflow}: its tasks' inputs could not be read, so it is counted with those last read: ${String(e)}`));
|
|
36
|
+
const counts = bucketCounts(yield* deps.tasks.taskSummaries({ workflow }));
|
|
37
|
+
yield* deps.store.recordQueueCounts({ at: Date.now() / 1000, counts: Object.entries(counts).map(([bucket, tasks]) => ({ workflow, bucket, tasks })) });
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
let countSoon: (workflow: string) => void = () => undefined;
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Starts recording: for the one process that runs the project's workflows, which gives `run`, how it runs an effect of
|
|
44
|
+
* theirs. Every queue is counted once at the start, then each on its changes.
|
|
45
|
+
*/
|
|
46
|
+
const record = (run: (count: Effect.Effect<void, StorageError, R>) => Promise<void>): void => {
|
|
47
|
+
const due = new Set<string>();
|
|
48
|
+
countSoon = (workflow) => {
|
|
49
|
+
if (due.has(workflow) || !deps.withQueues().includes(workflow)) return;
|
|
50
|
+
due.add(workflow);
|
|
51
|
+
setTimeout(() => {
|
|
52
|
+
due.delete(workflow);
|
|
53
|
+
void run(count(workflow)).catch((e: unknown) => console.error(`[queue counts] ${workflow}: not counted: ${e instanceof Error ? e.message : String(e)}`));
|
|
54
|
+
}, deps.countAfterMs ?? COUNT_AFTER_MS).unref?.();
|
|
55
|
+
};
|
|
56
|
+
deps.wakes.onWake((wake) => { for (const workflow of wake.workflow === null ? deps.withQueues() : [wake.workflow]) countSoon(workflow); });
|
|
57
|
+
for (const workflow of deps.withQueues()) countSoon(workflow);
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
return { count, record, changed: (workflow: string): void => countSoon(workflow) };
|
|
61
|
+
};
|
package/src/steps.ts
CHANGED
|
@@ -40,7 +40,7 @@
|
|
|
40
40
|
* step one record per item, and a step whose work no one item owns declares `shared` rather than dividing it up.
|
|
41
41
|
*/
|
|
42
42
|
import path from 'node:path';
|
|
43
|
-
import { Cause, Context, Effect, Exit, pipe, Result, Schedule, Schema, Semaphore } from 'effect';
|
|
43
|
+
import { Cause, Context, Data, Effect, Exit, pipe, Result, Schedule, Schema, Semaphore } from 'effect';
|
|
44
44
|
import { Activity, Workflow, WorkflowEngine } from 'effect/workflow';
|
|
45
45
|
import { describeFailure, startAndEnd } from './failure';
|
|
46
46
|
import { oneLine, standardReason } from './reasons';
|
|
@@ -180,6 +180,12 @@ export interface WorkflowDeclaration<Phase extends string = string, R = never> {
|
|
|
180
180
|
readonly pending?: () => Effect.Effect<PendingWork, unknown, R>;
|
|
181
181
|
/** Its Pick takes the first task of its queue it can claim (`tasks.ts` `queueOrder`), so a dashboard lists that queue. */
|
|
182
182
|
readonly picksQueueHead?: true;
|
|
183
|
+
/**
|
|
184
|
+
* The workflows whose results it works on: what its list of work (`pending`) is made from, or what its inputs (`inputs`)
|
|
185
|
+
* read. The dashboard draws each as an edge into it, and a workflow that gives one upstream of it new input
|
|
186
|
+
* (`giveNewInput`) is sending work back. None where it works on no other workflow's results.
|
|
187
|
+
*/
|
|
188
|
+
readonly fedBy?: ReadonlyArray<string>;
|
|
183
189
|
/** Its step graph (`StepEdge`); none until it declares one. */
|
|
184
190
|
readonly graph?: () => ReadonlyArray<StepEdge>;
|
|
185
191
|
/** What it runs on (`WorkflowInputs`); none until it declares them, and it runs whenever its trigger says. */
|
|
@@ -195,6 +201,19 @@ export interface WorkflowDeclaration<Phase extends string = string, R = never> {
|
|
|
195
201
|
readonly executionIdOf: (payload: object) => Effect.Effect<string>;
|
|
196
202
|
}
|
|
197
203
|
|
|
204
|
+
/** A run not started: its workflow's run limit was reached. What a start that waits for its result fails with. */
|
|
205
|
+
export class RunLimitReached extends Data.TaggedError('RunLimitReached')<{ readonly workflow: string; readonly limit: number }> {}
|
|
206
|
+
|
|
207
|
+
/** How often a workflow's refused starts are said, at most: a timer at 0 would say it every turn. */
|
|
208
|
+
const REFUSED_SAID_EVERY_MS = 10 * 60 * 1000;
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* A WORKFLOW'S RUN LIMIT, whatever starts it: for one its budget keeps going, its run limit or its agents' limit
|
|
212
|
+
* (`runLimit`); for any other its run limit, none meaning no limit. 0 starts nothing new. Pure.
|
|
213
|
+
*/
|
|
214
|
+
export const runLimitOf = (d: Pick<WorkflowDeclaration<string, unknown>, 'pending' | 'steps'>, limits: WorkflowLimits): number | null =>
|
|
215
|
+
keptRunningByItsBudget(d) ? runLimit(limits) : limits.runs;
|
|
216
|
+
|
|
198
217
|
/** Whether a workflow's budget rules it: an agent step and a declared list of work. Pure. */
|
|
199
218
|
export const keptRunningByItsBudget = (d: Pick<WorkflowDeclaration<string, unknown>, 'pending' | 'steps'>): boolean =>
|
|
200
219
|
d.pending !== undefined && d.steps().some((s) => s.agent);
|
|
@@ -246,6 +265,8 @@ export const makeSteps = <Phase extends string, R>(deps: {
|
|
|
246
265
|
/** This process, to tell its own records from another's. */
|
|
247
266
|
readonly thisProcess: () => ProcessIdentity;
|
|
248
267
|
readonly inputs: InputRecords;
|
|
268
|
+
/** A workflow's queue changed with no wake of its Picks: one of them claimed an item (`queue-counts.ts`). */
|
|
269
|
+
readonly queueChanged: (workflow: string) => void;
|
|
249
270
|
}) => {
|
|
250
271
|
const { stepRecords: records, stepFiles } = deps;
|
|
251
272
|
type Declaration = WorkflowDeclaration<Phase, R>;
|
|
@@ -314,12 +335,21 @@ export const makeSteps = <Phase extends string, R>(deps: {
|
|
|
314
335
|
* Whether this run should stand down before its next agent call, and whether its Pick, finding nothing it can claim, waits
|
|
315
336
|
* for work rather than ending its run. A test supplies others.
|
|
316
337
|
*/
|
|
317
|
-
/**
|
|
318
|
-
|
|
338
|
+
/**
|
|
339
|
+
* A declared workflow's limits: its run limit (`runLimitOf`, none for no limit), and its agents' limit where its budget
|
|
340
|
+
* keeps it going (none for any other). None for one not declared, or with no store to read.
|
|
341
|
+
*/
|
|
342
|
+
const limitsOf = (workflow: string): Effect.Effect<{ readonly runs: number | null; readonly agents: number | null } | null, StorageError> => {
|
|
319
343
|
const d = DECLARED.get(workflow);
|
|
320
|
-
if (d === undefined
|
|
321
|
-
return Effect.map(deps.budgets.limitsOf(workflow), (limits) => (limits === null ? null : {
|
|
344
|
+
if (d === undefined) return Effect.succeed(null);
|
|
345
|
+
return Effect.map(deps.budgets.limitsOf(workflow), (limits) => (limits === null ? null : { runs: runLimitOf(d, limits), agents: keptRunningByItsBudget(d) ? limits.agents : null }));
|
|
322
346
|
};
|
|
347
|
+
/** Whether a run is past the runs its workflow's run limit keeps, oldest first; never where it has no run limit. */
|
|
348
|
+
const pastItsRunLimit = (workflow: string, run: string): Effect.Effect<boolean, StorageError> =>
|
|
349
|
+
Effect.flatMap(limitsOf(workflow), (w) => {
|
|
350
|
+
const runs = w === null ? null : w.runs;
|
|
351
|
+
return runs === null ? Effect.succeed(false) : Effect.map(runsOldestFirst([workflow]), (going) => surplusRun(going, run, runs));
|
|
352
|
+
});
|
|
323
353
|
|
|
324
354
|
/**
|
|
325
355
|
* LIMITS THAT CANNOT BE READ HOLD THE RUN WHERE IT IS: it does not stand down, its Pick waits, and its agent step waits for a
|
|
@@ -332,27 +362,20 @@ export const makeSteps = <Phase extends string, R>(deps: {
|
|
|
332
362
|
defaultValue: () => ({
|
|
333
363
|
// Among its workflow's unfinished runs, oldest first, the run is past those its run limit keeps (`runLimit`). A run not
|
|
334
364
|
// listed is not counted.
|
|
335
|
-
standsDown: (workflow, run) => pipe(
|
|
336
|
-
|
|
337
|
-
Effect.flatMap((w) => (w === null ? Effect.succeed(false) : Effect.map(runsOldestFirst([workflow]), (going) => surplusRun(going, run, runLimit(w.limits))))),
|
|
338
|
-
Effect.catchTag('StorageError', unreadLimits(workflow, () => false)),
|
|
339
|
-
),
|
|
340
|
-
waitsForWork: (workflow, run) => pipe(
|
|
341
|
-
limitsOf(workflow),
|
|
342
|
-
Effect.flatMap((w) => (w === null ? Effect.succeed(true) : Effect.map(runsOldestFirst([workflow]), (going) => !surplusRun(going, run, runLimit(w.limits))))),
|
|
343
|
-
Effect.catchTag('StorageError', unreadLimits(workflow, () => true)),
|
|
344
|
-
),
|
|
365
|
+
standsDown: (workflow, run) => pipe(pastItsRunLimit(workflow, run), Effect.catchTag('StorageError', unreadLimits(workflow, () => false))),
|
|
366
|
+
waitsForWork: (workflow, run) => pipe(pastItsRunLimit(workflow, run), Effect.map((past) => !past), Effect.catchTag('StorageError', unreadLimits(workflow, () => true))),
|
|
345
367
|
// Its other runs in an agent step, a waiting one not counted, against its agents' limit: at 0 none is ever free, and its
|
|
346
368
|
// runs wait at their first agent step until the limit is raised.
|
|
347
369
|
agentSlot: (workflow, run) => pipe(
|
|
348
370
|
limitsOf(workflow),
|
|
349
371
|
Effect.flatMap((w): Effect.Effect<{ readonly free: true } | { readonly free: false; readonly why: string }, StorageError> => {
|
|
350
|
-
|
|
351
|
-
if (
|
|
372
|
+
const agents = w === null ? null : w.agents;
|
|
373
|
+
if (agents === null) return Effect.succeed({ free: true });
|
|
374
|
+
if (agents === 0) return Effect.succeed({ free: false, why: 'waits for an agent: its agents\x27 limit is 0' });
|
|
352
375
|
return Effect.map(Effect.all({ runs: runsOldestFirst([workflow]), inAgentStep: records.runsInAgentStep(workflow) }), ({ runs, inAgentStep }) => {
|
|
353
376
|
const going = new Set(runs);
|
|
354
377
|
const busy = inAgentStep.filter((r) => r !== run && going.has(r)).length;
|
|
355
|
-
return busy <
|
|
378
|
+
return busy < agents ? { free: true } : { free: false, why: `waits for an agent: ${busy} of its ${agents} in use` };
|
|
356
379
|
});
|
|
357
380
|
}),
|
|
358
381
|
Effect.catchTag('StorageError', unreadLimits(workflow, (why) => ({ free: false as const, why: `waits for an agent: its limits could not be read (${why})` }))),
|
|
@@ -509,13 +532,20 @@ export const makeSteps = <Phase extends string, R>(deps: {
|
|
|
509
532
|
return snapshot === null ? { restored: [], conflicts: [] } : stepFiles.undoFiles(snapshot, attributed ?? []);
|
|
510
533
|
}));
|
|
511
534
|
|
|
512
|
-
/**
|
|
513
|
-
|
|
514
|
-
|
|
535
|
+
/**
|
|
536
|
+
* A RUN PAST ITS WORKFLOW'S RUN LIMIT ENDS BEFORE IT TAKES ON MORE WORK, inside the step's activity: before a Pick, before
|
|
537
|
+
* an agent step, and before the first step this process runs of it (a run the engine resumed after a restart). It fails
|
|
538
|
+
* with `STOOD_DOWN`. A step between those goes on, so what an agent step just made is still checked and recorded. At a run
|
|
539
|
+
* limit of 0 every run is past it, so each run already going ends at the next of those.
|
|
540
|
+
*/
|
|
541
|
+
const standDownIfSurplus = (step: { readonly agent: boolean; readonly picks: boolean }) => Effect.flatMap(WorkflowEngine.WorkflowInstance, (instance) => {
|
|
542
|
+
if (!step.agent && !step.picks && lastStepRan.has(instance.executionId)) return Effect.void;
|
|
543
|
+
return Effect.flatMap(AgentBudgets, (budgets) => Effect.flatMap(budgets.standsDown(instance.workflow._tag, instance.executionId), (surplus) => {
|
|
515
544
|
if (!surplus) return Effect.void;
|
|
516
|
-
console.log(`[
|
|
545
|
+
console.log(`[run limit] ${instance.workflow._tag} run ${instance.executionId} stood down: its workflow has more runs going than its run limit`);
|
|
517
546
|
return Effect.fail(STOOD_DOWN);
|
|
518
|
-
}))
|
|
547
|
+
}));
|
|
548
|
+
});
|
|
519
549
|
|
|
520
550
|
/** One run of a workflow picks at a time: its choice is on its step record before the next reads what is taken. */
|
|
521
551
|
const pickingOneAtATime = <A, E, R2>(workflow: string, pick: Effect.Effect<A, E, R2>): Effect.Effect<A, E, R2> => {
|
|
@@ -551,6 +581,7 @@ export const makeSteps = <Phase extends string, R>(deps: {
|
|
|
551
581
|
const found = yield* pickingOneAtATime(workflow, pick);
|
|
552
582
|
if (waited) deps.wakes.countRePick(workflow, performance.now() - began);
|
|
553
583
|
if (picked(found) || !(yield* budgets.waitsForWork(workflow, instance.executionId))) {
|
|
584
|
+
if (picked(found)) deps.queueChanged(workflow);
|
|
554
585
|
if (waited && record !== null) {
|
|
555
586
|
yield* recorded('end its wait', records.setStepWaiting({ id: record, waiting: null }));
|
|
556
587
|
yield* recorded('start its record again', records.restartStepRun(record));
|
|
@@ -608,7 +639,7 @@ export const makeSteps = <Phase extends string, R>(deps: {
|
|
|
608
639
|
success: d.success,
|
|
609
640
|
error: Schema.String,
|
|
610
641
|
execute: pipe(
|
|
611
|
-
d.agent
|
|
642
|
+
standDownIfSurplus({ agent: d.agent, picks: d.picked !== undefined }),
|
|
612
643
|
Effect.andThen(measured(declaration, options?.call ?? null, options?.subject ?? null, d.subject, d.reason, d.mayWrite, d.picked === undefined ? execute : untilPicked(d.picked, execute))),
|
|
613
644
|
Effect.retry({ while: deps.isTransientFailure, times: 10, schedule: Schedule.spaced('3 seconds') }),
|
|
614
645
|
Effect.mapError(describeFailure),
|
|
@@ -682,6 +713,8 @@ export const makeSteps = <Phase extends string, R>(deps: {
|
|
|
682
713
|
readonly steps: () => ReadonlyArray<StepDeclaration>;
|
|
683
714
|
readonly pending?: () => Effect.Effect<PendingWork, unknown, R>;
|
|
684
715
|
readonly picksQueueHead?: true;
|
|
716
|
+
/** The workflows whose results it works on (`WorkflowDeclaration.fedBy`). */
|
|
717
|
+
readonly fedBy?: ReadonlyArray<string>;
|
|
685
718
|
/** Its step graph: which step can follow which, and when. */
|
|
686
719
|
readonly graph?: () => ReadonlyArray<StepEdge>;
|
|
687
720
|
/** What it runs on: its trigger starts a run only when they changed (`runIfInputsChanged`). */
|
|
@@ -692,22 +725,46 @@ export const makeSteps = <Phase extends string, R>(deps: {
|
|
|
692
725
|
((name: string, options: Parameters<typeof Workflow.make>[1]) => {
|
|
693
726
|
// The one place a workflow's own types do not matter: every workflow passes through here the same way.
|
|
694
727
|
const workflow: RunnableWorkflow = Workflow.make(name, options) as RunnableWorkflow;
|
|
728
|
+
/**
|
|
729
|
+
* EVERY START OF IT, WHATEVER CALLS IT (a timer, its inputs changing, its queue, a request), PASSES ITS RUN LIMIT: a new
|
|
730
|
+
* run starts only while fewer of its runs are going than its limit. One already going, by the same execution id, is
|
|
731
|
+
* joined as before. A start refused for the limit starts nothing: one that discards its run gets its id back, one that
|
|
732
|
+
* waits for its result fails with `RunLimitReached`. Where the limit cannot be read, the run starts, and that is said.
|
|
733
|
+
*/
|
|
734
|
+
const execute = workflow.execute.bind(workflow);
|
|
735
|
+
let refusedSaidAt = 0;
|
|
736
|
+
const startAllowed = (payload: object): Effect.Effect<{ readonly allowed: true } | { readonly allowed: false; readonly limit: number }> => Effect.gen(function* () {
|
|
737
|
+
const limits = yield* deps.budgets.limitsOf(name);
|
|
738
|
+
const limit = limits === null ? null : runLimitOf({ pending: d.pending, steps: d.steps }, limits);
|
|
739
|
+
if (limit === null) return { allowed: true } as const;
|
|
740
|
+
const going = (yield* deps.engine.unfinishedRuns()).filter((u) => u.workflow === name).map((u) => u.run);
|
|
741
|
+
if (going.length < limit) return { allowed: true } as const;
|
|
742
|
+
const id = yield* workflow.executionId(payload);
|
|
743
|
+
return going.includes(id) ? { allowed: true } as const : { allowed: false, limit } as const;
|
|
744
|
+
}).pipe(Effect.catchTag('StorageError', (e) => Effect.as(Effect.logError(`[run limit] ${name}: its limit could not be read, so the run starts: ${e.reason}`), { allowed: true } as const)));
|
|
745
|
+
const gatedExecute: RunnableWorkflow['execute'] = (payload, startOptions) => Effect.flatMap(startAllowed(payload), (gate) => {
|
|
746
|
+
if (gate.allowed) return startOptions === undefined ? execute(payload) : execute(payload, startOptions);
|
|
747
|
+
const say = Date.now() - refusedSaidAt < REFUSED_SAID_EVERY_MS ? Effect.void : Effect.sync(() => { refusedSaidAt = Date.now(); console.log(`[run limit] ${name}: not started, its run limit of ${gate.limit} is reached`); });
|
|
748
|
+
return Effect.andThen(say, startOptions?.discard === true ? workflow.executionId(payload) : Effect.fail(new RunLimitReached({ workflow: name, limit: gate.limit })));
|
|
749
|
+
});
|
|
695
750
|
DECLARED.set(name, {
|
|
696
751
|
name, phase: d.phase, description: d.description, steps: d.steps,
|
|
697
752
|
...(d.graph === undefined ? {} : { graph: d.graph }),
|
|
698
753
|
source: { path: sourcePath(d.at), anchor: `'${name}'` },
|
|
699
754
|
...(d.pending === undefined ? {} : { pending: d.pending }),
|
|
700
755
|
...(d.picksQueueHead === undefined ? {} : { picksQueueHead: d.picksQueueHead }),
|
|
756
|
+
...(d.fedBy === undefined ? {} : { fedBy: d.fedBy }),
|
|
701
757
|
...(d.inputs === undefined ? {} : { inputs: d.inputs }),
|
|
702
758
|
...(d.taskInputs === undefined ? {} : { taskInputs: d.taskInputs }),
|
|
703
759
|
item: d.item,
|
|
704
760
|
finishedWord: d.item === null ? null : d.finishedWord,
|
|
705
761
|
gate: d.item === null ? null : (d.gate ?? null),
|
|
706
|
-
start: (run) =>
|
|
707
|
-
startOn: (payload, options) => Effect.asVoid(options.wait ?
|
|
762
|
+
start: (run) => gatedExecute({ run }, { discard: true }),
|
|
763
|
+
startOn: (payload, options) => Effect.asVoid(options.wait ? gatedExecute(payload) : gatedExecute(payload, { discard: true })),
|
|
708
764
|
executionIdOf: (payload) => workflow.executionId(payload),
|
|
709
765
|
});
|
|
710
766
|
const toLayer = workflow.toLayer.bind(workflow);
|
|
767
|
+
Object.assign(workflow, { execute: gatedExecute });
|
|
711
768
|
// Every run of every workflow ends here: its items' outcomes are recorded, and the next run can start at once.
|
|
712
769
|
return Object.assign(workflow, {
|
|
713
770
|
toLayer: (execute: WorkflowBody) =>
|
package/src/storage/budgets.ts
CHANGED
|
@@ -44,6 +44,8 @@ export interface WorkflowLimits {
|
|
|
44
44
|
export interface LimitStore {
|
|
45
45
|
/** A workflow's limits: 0 agents with none stored, and none where there is no store to read (a test). */
|
|
46
46
|
readonly limitsOf: (workflow: string) => Effect.Effect<WorkflowLimits | null, StorageError>;
|
|
47
|
+
/** Every stored workflow's limits, by name, in one read: one with none stored is absent. None where there is no store. */
|
|
48
|
+
readonly storedLimits: () => Effect.Effect<ReadonlyMap<string, WorkflowLimits> | null, StorageError>;
|
|
47
49
|
}
|
|
48
50
|
|
|
49
51
|
/**
|
|
@@ -65,4 +67,15 @@ export const sqliteBudgets = (options: { readonly file: () => string }): LimitSt
|
|
|
65
67
|
db.close();
|
|
66
68
|
}
|
|
67
69
|
}),
|
|
70
|
+
storedLimits: () => storeCall('limits: storedLimits', () => {
|
|
71
|
+
const file = options.file();
|
|
72
|
+
if (!fs.existsSync(file)) return null;
|
|
73
|
+
const db = new Database(file, { readonly: true });
|
|
74
|
+
try {
|
|
75
|
+
if (db.query(`SELECT 1 FROM sqlite_master WHERE name = 'workflow_budgets'`).get() === null) return null;
|
|
76
|
+
return new Map((db.query(WORKFLOW_BUDGETS_SQL).all() as ReadonlyArray<WorkflowBudgetRow>).map((r) => [r.workflow, { agents: r.budget, runs: r.runs }]));
|
|
77
|
+
} finally {
|
|
78
|
+
db.close();
|
|
79
|
+
}
|
|
80
|
+
}),
|
|
68
81
|
});
|