@protobase/workflows 0.100.10 → 0.100.11

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.
@@ -17,6 +17,7 @@ import { depthProblems } from "./depth-problems.js";
17
17
  import { pinProblems } from "./pins/check-pins.js";
18
18
  import { dataflowProblems, dataflowVisible } from "./dataflow/check-dataflow.js";
19
19
  import { orderOf } from "./types.js";
20
+ import { customStepOf } from "../plugin/custom-step-id.js";
20
21
  //#region src/definition/check-definition.ts
21
22
  const missingArguments = (state, options) => {
22
23
  const needed = options.required?.[taskResource(state.Resource).type] ?? [];
@@ -25,21 +26,26 @@ const missingArguments = (state, options) => {
25
26
  return needed.filter((name) => given[name] === void 0 || given[name] === "");
26
27
  };
27
28
  const waitProblems = (state) => {
28
- const { waits } = taskResource(state.Resource);
29
- if (!waits) return [...state.TimeoutSeconds !== void 0 && state.TimeoutSeconds > limits.taskTimeoutSeconds ? [{
29
+ const { type, waits } = taskResource(state.Resource);
30
+ const custom = customStepOf(type) !== void 0;
31
+ if (custom && waits) return [{
32
+ field: "Resource",
33
+ message: `ends in .waitForTaskToken, but ${type} is a custom step, which waits for the runner that runs it already: write ${type}`
34
+ }];
35
+ if (!waits && !custom) return [...state.TimeoutSeconds !== void 0 && state.TimeoutSeconds > limits.taskTimeoutSeconds ? [{
30
36
  field: "TimeoutSeconds",
31
37
  message: `is ${state.TimeoutSeconds}, more than the ${limits.taskTimeoutSeconds} seconds a step type runs; only a Task whose Resource ends in .waitForTaskToken waits longer`
32
38
  }] : [], ...state.HeartbeatSeconds !== void 0 ? [{
33
39
  field: "HeartbeatSeconds",
34
40
  message: "is for a Task whose Resource ends in .waitForTaskToken, whose outside executor sends heartbeats; this step type ends or fails within its TimeoutSeconds"
35
41
  }] : []];
36
- const timeout = state.TimeoutSeconds ?? limits.waitingTaskTimeoutSeconds;
42
+ const timeout = state.TimeoutSeconds ?? (custom ? limits.taskTimeoutSeconds : limits.waitingTaskTimeoutSeconds);
37
43
  return [...state.HeartbeatSeconds !== void 0 && state.HeartbeatSeconds >= timeout ? [{
38
44
  field: "HeartbeatSeconds",
39
45
  message: `is ${state.HeartbeatSeconds}, which must be less than the Task's TimeoutSeconds (${timeout})`
40
46
  }] : [], ...state.Cache === true ? [{
41
47
  field: "Cache",
42
- message: "is true, but a Task that waits for an outside result hands its work off on every try and caches nothing"
48
+ message: custom ? "is true, but a custom step runs on a runner on every try and caches nothing" : "is true, but a Task that waits for an outside result hands its work off on every try and caches nothing"
43
49
  }] : []];
44
50
  };
45
51
  const machineProblems = (machine, scope, options) => {
package/dist/index.d.ts CHANGED
@@ -23,7 +23,7 @@ import { ErrorOutput, StepError } from "./run/errors.js";
23
23
  import { Redactor, redacted, secretRedactor, shortestSecret } from "./run/redact.js";
24
24
  import { KeyShape } from "./run/cache/cache-key.js";
25
25
  import { CacheCall, CacheEntry, CacheIdentity, StepCacheStore } from "./run/cache/cache-port.js";
26
- import { BlockRun, BlockRunStore, BlockShare, Checkpoint, KeptAnswer, LoadedRun, ReplayedStep, RunChange, RunStatus, RunStore, SegmentQueue, StepLog, StepRecord, StepStatus, TaskAnswer, TaskContext, TaskHandler, TaskHandlers, TaskTokenStore, TraceMode, TraceSink, WaitingTask } from "./run/port.js";
26
+ import { BlockRun, BlockRunStore, BlockShare, Checkpoint, CustomStepJob, CustomStepJobs, KeptAnswer, LoadedRun, ReplayedStep, RunChange, RunStatus, RunStore, SegmentQueue, StepLog, StepRecord, StepStatus, TaskAnswer, TaskContext, TaskHandler, TaskHandlers, TaskTokenStore, TraceMode, TraceSink, WaitingTask } from "./run/port.js";
27
27
  import { EarlierCheckpoint, keptAssigned, rerunCheckpoint, rerunProblem, resultRead } from "./run/rerun.js";
28
28
  import { RerunFrom, rerunFrom } from "./run/rerun-from.js";
29
29
  import { heldBackLog } from "./run/replay.js";
@@ -36,5 +36,8 @@ import { triggerChecks } from "./plugin/trigger-checks.js";
36
36
  import { TypeEntry, Unavailable, typeList } from "./plugin/type-list.js";
37
37
  import { ConnectionSupport, connectionUnavailable } from "./plugin/connection-availability.js";
38
38
  import { CatalogEntry, TypeCatalog, typeCatalog } from "./plugin/type-catalog.js";
39
- import { CustomStepManifest, CustomStepVersion, ManifestProblem, customPlugin, customStepEntry, customStepOf, latestCustomSteps, manifestProblems, withCustomSteps } from "./plugin/custom-steps.js";
40
- export { type AnswerRefusal, type BlockCache, type BlockRun, type BlockRunStore, type BlockShare, type BlockState, type CacheCall, type CacheEntry, type CacheIdentity, type CatalogEntry, type Catcher, type CheckOptions, type Checkpoint, type ChoiceRule, type ChoiceState, type ConnectionHeader, type ConnectionHeaders, type ConnectionSupport, type CustomStepManifest, type CustomStepVersion, type Definition, type DefinitionParts, type Dependencies, type EarlierCheckpoint, type ErrorOutput, type KeptAnswer, type KeyShape, type LoadedPlugin, type LoadedRun, type Machine, type ManifestProblem, type MapState, type Order, type PinKind, type PinSchemas, type PinType, type Problem, type ReadBase, type RecordSchemas, type RecordUse, type Redactor, type Reference, type ReplayedStep, type RerunFrom, type Retrier, type RunChange, type RunStatus, type RunStore, type Runner, type RunnerPort, type SegmentInput, type SegmentQueue, type State, type StateMachine, type StepCacheStore, StepError, type StepLog, type StepRecord, type StepStatus, type StepWiring, type TaskAnswer, type TaskContext, type TaskHandler, type TaskHandlers, type TaskState, type TaskTokenStore, type TraceMode, type TraceSink, type Trigger, type TriggerCheck, type TypeCatalog, type TypeEntry, type Unavailable, type WaitingTask, allStates, assignedNames, blockDefinition, checkDefinition, connectionUnavailable, createRunner, customPlugin, customStepEntry, customStepOf, dataflowDefinitionSchema, definitionFromParts, definitionSchema, definitionWarnings, dependsOn, expressionReferences, expressionSource, findBlock, fits, heldBackLog, importStateMachine, innerMachine, inputSchema, keptAssigned, latestCustomSteps, limits, loadPlugins, machineDependencies, manifestProblems, nestingDepth, orderOf, parseReference, partOfProblem, partsOfDefinition, pinType, pinTypeText, problemText, readText, redacted, referenceSchema, referenceValue, rerunCheckpoint, rerunFrom, rerunProblem, resolveSchema, resultRead, resultSchema, resultState, runSegment, schemaAt, secretRedactor, shortestSecret, stepHandlers, stepStatusSchema, taskResource, taskTokenHash, tokenPattern, triggerChecks, triggerSchema, typeCatalog, typeList, usedConnections, waitSuffix, waitsForToken, withCustomSteps };
39
+ import { KnownRunner, MatchSettings, Placement, PollingRunner, QueuedJob, RunnerState, Tier, jobKind, matchJobs, tierOf } from "./runners/match-jobs.js";
40
+ import { CompletedVersion, JobCompletion, jobAnswer, jobErrors } from "./runners/job-answer.js";
41
+ import { customPlugin, customStepOf } from "./plugin/custom-step-id.js";
42
+ import { CustomStepManifest, CustomStepVersion, ManifestProblem, customStepEntry, latestCustomSteps, manifestProblems, withCustomSteps } from "./plugin/custom-steps.js";
43
+ export { type AnswerRefusal, type BlockCache, type BlockRun, type BlockRunStore, type BlockShare, type BlockState, type CacheCall, type CacheEntry, type CacheIdentity, type CatalogEntry, type Catcher, type CheckOptions, type Checkpoint, type ChoiceRule, type ChoiceState, type CompletedVersion, type ConnectionHeader, type ConnectionHeaders, type ConnectionSupport, type CustomStepJob, type CustomStepJobs, type CustomStepManifest, type CustomStepVersion, type Definition, type DefinitionParts, type Dependencies, type EarlierCheckpoint, type ErrorOutput, type JobCompletion, type KeptAnswer, type KeyShape, type KnownRunner, type LoadedPlugin, type LoadedRun, type Machine, type ManifestProblem, type MapState, type MatchSettings, type Order, type PinKind, type PinSchemas, type PinType, type Placement, type PollingRunner, type Problem, type QueuedJob, type ReadBase, type RecordSchemas, type RecordUse, type Redactor, type Reference, type ReplayedStep, type RerunFrom, type Retrier, type RunChange, type RunStatus, type RunStore, type Runner, type RunnerPort, type RunnerState, type SegmentInput, type SegmentQueue, type State, type StateMachine, type StepCacheStore, StepError, type StepLog, type StepRecord, type StepStatus, type StepWiring, type TaskAnswer, type TaskContext, type TaskHandler, type TaskHandlers, type TaskState, type TaskTokenStore, type Tier, type TraceMode, type TraceSink, type Trigger, type TriggerCheck, type TypeCatalog, type TypeEntry, type Unavailable, type WaitingTask, allStates, assignedNames, blockDefinition, checkDefinition, connectionUnavailable, createRunner, customPlugin, customStepEntry, customStepOf, dataflowDefinitionSchema, definitionFromParts, definitionSchema, definitionWarnings, dependsOn, expressionReferences, expressionSource, findBlock, fits, heldBackLog, importStateMachine, innerMachine, inputSchema, jobAnswer, jobErrors, jobKind, keptAssigned, latestCustomSteps, limits, loadPlugins, machineDependencies, manifestProblems, matchJobs, nestingDepth, orderOf, parseReference, partOfProblem, partsOfDefinition, pinType, pinTypeText, problemText, readText, redacted, referenceSchema, referenceValue, rerunCheckpoint, rerunFrom, rerunProblem, resolveSchema, resultRead, resultSchema, resultState, runSegment, schemaAt, secretRedactor, shortestSecret, stepHandlers, stepStatusSchema, taskResource, taskTokenHash, tierOf, tokenPattern, triggerChecks, triggerSchema, typeCatalog, typeList, usedConnections, waitSuffix, waitsForToken, withCustomSteps };
package/dist/index.js CHANGED
@@ -13,6 +13,7 @@ import { inputSchema, referenceSchema, resultSchema, resultState, stepStatusSche
13
13
  import { expressionReferences, parseReference, readText, referenceValue } from "./definition/pins/references.js";
14
14
  import { dependsOn, machineDependencies } from "./definition/dataflow/dependencies.js";
15
15
  import { orderOf } from "./definition/types.js";
16
+ import { customPlugin, customStepOf } from "./plugin/custom-step-id.js";
16
17
  import { checkDefinition } from "./definition/check-definition.js";
17
18
  import { definitionFromParts, partOfProblem, partsOfDefinition } from "./definition/parts.js";
18
19
  import { definitionWarnings } from "./definition/check-warnings.js";
@@ -21,15 +22,17 @@ import { StepError } from "./run/errors.js";
21
22
  import { redacted, secretRedactor, shortestSecret } from "./run/redact.js";
22
23
  import { keptAssigned, rerunCheckpoint, rerunProblem, resultRead } from "./run/rerun.js";
23
24
  import { heldBackLog } from "./run/replay.js";
24
- import { customPlugin, customStepEntry, customStepOf, latestCustomSteps, manifestProblems, withCustomSteps } from "./plugin/custom-steps.js";
25
25
  import { taskTokenHash, tokenPattern } from "./run/task-token.js";
26
26
  import { rerunFrom } from "./run/rerun-from.js";
27
27
  import { runSegment } from "./run/segment.js";
28
28
  import { createRunner } from "./run/runner.js";
29
+ import { customStepEntry, latestCustomSteps, manifestProblems, withCustomSteps } from "./plugin/custom-steps.js";
29
30
  import { loadPlugins } from "./plugin/load-plugins.js";
30
31
  import { stepHandlers } from "./plugin/step-handlers.js";
31
32
  import { triggerChecks } from "./plugin/trigger-checks.js";
32
33
  import { typeList } from "./plugin/type-list.js";
33
34
  import { connectionUnavailable } from "./plugin/connection-availability.js";
34
35
  import { typeCatalog } from "./plugin/type-catalog.js";
35
- export { StepError, allStates, assignedNames, blockDefinition, checkDefinition, connectionUnavailable, createRunner, customPlugin, customStepEntry, customStepOf, dataflowDefinitionSchema, definitionFromParts, definitionSchema, definitionWarnings, dependsOn, expressionReferences, expressionSource, findBlock, fits, heldBackLog, importStateMachine, innerMachine, inputSchema, keptAssigned, latestCustomSteps, limits, loadPlugins, machineDependencies, manifestProblems, nestingDepth, orderOf, parseReference, partOfProblem, partsOfDefinition, pinType, pinTypeText, problemText, readText, redacted, referenceSchema, referenceValue, rerunCheckpoint, rerunFrom, rerunProblem, resolveSchema, resultRead, resultSchema, resultState, runSegment, schemaAt, secretRedactor, shortestSecret, stepHandlers, stepStatusSchema, taskResource, taskTokenHash, tokenPattern, triggerChecks, triggerSchema, typeCatalog, typeList, usedConnections, waitSuffix, waitsForToken, withCustomSteps };
36
+ import { jobKind, matchJobs, tierOf } from "./runners/match-jobs.js";
37
+ import { jobAnswer, jobErrors } from "./runners/job-answer.js";
38
+ export { StepError, allStates, assignedNames, blockDefinition, checkDefinition, connectionUnavailable, createRunner, customPlugin, customStepEntry, customStepOf, dataflowDefinitionSchema, definitionFromParts, definitionSchema, definitionWarnings, dependsOn, expressionReferences, expressionSource, findBlock, fits, heldBackLog, importStateMachine, innerMachine, inputSchema, jobAnswer, jobErrors, jobKind, keptAssigned, latestCustomSteps, limits, loadPlugins, machineDependencies, manifestProblems, matchJobs, nestingDepth, orderOf, parseReference, partOfProblem, partsOfDefinition, pinType, pinTypeText, problemText, readText, redacted, referenceSchema, referenceValue, rerunCheckpoint, rerunFrom, rerunProblem, resolveSchema, resultRead, resultSchema, resultState, runSegment, schemaAt, secretRedactor, shortestSecret, stepHandlers, stepStatusSchema, taskResource, taskTokenHash, tierOf, tokenPattern, triggerChecks, triggerSchema, typeCatalog, typeList, usedConnections, waitSuffix, waitsForToken, withCustomSteps };
@@ -0,0 +1,9 @@
1
+ //#region src/plugin/custom-step-id.d.ts
2
+ /** The plugin name the app's custom steps take, as `custom:<name>:<version>`; no plugin may take it. */
3
+ export declare const customPlugin = "custom";
4
+ /** The custom step and version a step type's id names, `custom:<name>:<version>`; undefined for any other id. */
5
+ export declare const customStepOf: (id: string) => {
6
+ name: string;
7
+ version: number;
8
+ } | undefined;
9
+ //#endregion
@@ -0,0 +1,14 @@
1
+ //#region src/plugin/custom-step-id.ts
2
+ /** The plugin name the app's custom steps take, as `custom:<name>:<version>`; no plugin may take it. */
3
+ const customPlugin = "custom";
4
+ const customId = /^custom:([a-z][a-z0-9_]*):([1-9][0-9]*)$/;
5
+ /** The custom step and version a step type's id names, `custom:<name>:<version>`; undefined for any other id. */
6
+ const customStepOf = (id) => {
7
+ const found = customId.exec(id);
8
+ return found ? {
9
+ name: found[1],
10
+ version: Number(found[2])
11
+ } : void 0;
12
+ };
13
+ //#endregion
14
+ export { customPlugin, customStepOf };
@@ -1,9 +1,8 @@
1
1
  import { CheckOptions } from "../definition/check-definition.js";
2
2
  import { JsonSchema } from "./context.js";
3
3
  import { TypeEntry } from "./type-list.js";
4
+ import { customPlugin, customStepOf } from "./custom-step-id.js";
4
5
  //#region src/plugin/custom-steps.d.ts
5
- /** The plugin name the app's custom steps take, as `custom:<name>:<version>`; no plugin may take it. */
6
- export declare const customPlugin = "custom";
7
6
  /** One saved version of a custom step, as its type is made from it. */
8
7
  export type CustomStepVersion = {
9
8
  name: string;
@@ -34,11 +33,6 @@ export declare const manifestProblems: (manifest: CustomStepManifest) => Manifes
34
33
  * it requires when its output gives a stored file, its output, and its errors as `<error_prefix>.<Name>`.
35
34
  */
36
35
  export declare const customStepEntry: (step: CustomStepVersion) => TypeEntry;
37
- /** The custom step and version a step type's id names, `custom:<name>:<version>`; undefined for any other id. */
38
- export declare const customStepOf: (id: string) => {
39
- name: string;
40
- version: number;
41
- } | undefined;
42
36
  /** The latest version of each custom step among `ids`, by the step's unversioned id, `custom:<name>`. */
43
37
  export declare const latestCustomSteps: (ids: readonly string[]) => Record<string, string>;
44
38
  /**
@@ -50,4 +44,5 @@ export declare const withCustomSteps: (custom: readonly TypeEntry[]) => {
50
44
  types: (types: readonly TypeEntry[]) => TypeEntry[];
51
45
  check: (check: CheckOptions) => CheckOptions;
52
46
  };
53
- //#endregion
47
+ //#endregion
48
+ export { customPlugin, customStepOf };
@@ -1,7 +1,6 @@
1
+ import { customPlugin, customStepOf } from "./custom-step-id.js";
1
2
  import { Ajv } from "ajv";
2
3
  //#region src/plugin/custom-steps.ts
3
- /** The plugin name the app's custom steps take, as `custom:<name>:<version>`; no plugin may take it. */
4
- const customPlugin = "custom";
5
4
  const stepName = /^[a-z][a-z0-9_]*$/;
6
5
  const errorName = /^[A-Z][A-Za-z0-9]*$/;
7
6
  const dockerfileBytes = 65536;
@@ -197,15 +196,6 @@ const customStepEntry = (step) => {
197
196
  };
198
197
  };
199
198
  const requiredInputs = (input) => Array.isArray(input.required) ? input.required : [];
200
- const customId = /^custom:([a-z][a-z0-9_]*):([1-9][0-9]*)$/;
201
- /** The custom step and version a step type's id names, `custom:<name>:<version>`; undefined for any other id. */
202
- const customStepOf = (id) => {
203
- const found = customId.exec(id);
204
- return found ? {
205
- name: found[1],
206
- version: Number(found[2])
207
- } : void 0;
208
- };
209
199
  /** The latest version of each custom step among `ids`, by the step's unversioned id, `custom:<name>`. */
210
200
  const latestCustomSteps = (ids) => {
211
201
  const latest = /* @__PURE__ */ new Map();
@@ -1,4 +1,4 @@
1
- import { customPlugin } from "./custom-steps.js";
1
+ import { customPlugin } from "./custom-step-id.js";
2
2
  import { checkPlugin } from "./define-plugin.js";
3
3
  //#region src/plugin/load-plugins.ts
4
4
  const record = (value) => value === void 0 || typeof value === "object" && value !== null;
@@ -1,4 +1,4 @@
1
- import { BlockRun, BlockShare, TaskTokenStore, WaitingTask } from "./port.js";
1
+ import { BlockRun, BlockShare, CustomStepJob, TaskTokenStore, WaitingTask } from "./port.js";
2
2
  //#region src/run/context.d.ts
3
3
  /** A scope that cannot go on in this segment: it waits until a time, or the segment's time is up. */
4
4
  export type Paused = {
@@ -29,6 +29,10 @@ export type SegmentTokens = {
29
29
  heartbeatAt: Date | null;
30
30
  }) => Promise<boolean>;
31
31
  };
32
+ /** Where a run's custom steps wait for a runner, as its segment queues them. */
33
+ export type SegmentCustomSteps = {
34
+ queue: (job: Omit<CustomStepJob, 'run'>) => Promise<void>;
35
+ };
32
36
  /** A run's blocks' runs, as its segment reaches them. */
33
37
  export type SegmentBlocks = {
34
38
  find: (visit: string) => Promise<BlockRun | undefined>;
@@ -298,6 +298,28 @@ export type TaskTokenStore<Db> = {
298
298
  /** Takes an answer for a try still waiting: a heartbeat marks its time, a success or failure settles it; false when it no longer waits. */
299
299
  answer(db: Db, hash: string, answer: KeptAnswer, at: Date): Promise<boolean>;
300
300
  };
301
+ /**
302
+ * A try of a custom step (`custom:<name>:<version>`) as it is handed to a runner: its arguments as given (`arguments`)
303
+ * and as the step records them, its secrets blanked out (`input`), and the hash of its try's token, by which the app
304
+ * answers it once the runner completes it. The token itself goes nowhere: the runner proves itself otherwise.
305
+ */
306
+ export type CustomStepJob = {
307
+ run: string;
308
+ visit: string;
309
+ state: string;
310
+ step: string;
311
+ input: unknown;
312
+ arguments: unknown;
313
+ hash: string;
314
+ };
315
+ /** Where custom steps' tries wait for a runner. */
316
+ export type CustomStepJobs<Db> = {
317
+ /**
318
+ * Queues a try for a runner, replacing a job of the same try that a segment queued before it stopped; throws a
319
+ * `StepError` when the run's tenant has no such custom step.
320
+ */
321
+ queue(db: Db, job: CustomStepJob): Promise<void>;
322
+ };
301
323
  /** Which runs keep a trace: every run, only those that fail, or none. */
302
324
  export type TraceMode = NonNullable<Definition['trace']>;
303
325
  /**
@@ -1,5 +1,6 @@
1
1
  import { limits } from "../limits.js";
2
2
  import { taskResource } from "../definition/task-resource.js";
3
+ import { customStepOf } from "../plugin/custom-step-id.js";
3
4
  import { StepError, errorOutput } from "./errors.js";
4
5
  import { redacted } from "./redact.js";
5
6
  import { evaluateAssign, evaluateKept, evaluateTemplate, recordedArguments } from "./evaluate.js";
@@ -14,7 +15,7 @@ import { runTask } from "./task.js";
14
15
  import { runWaitingTask } from "./waiting-task.js";
15
16
  //#region src/run/result-states.ts
16
17
  const task = async (state, call) => {
17
- if (taskResource(state.Resource).waits) return runWaitingTask(state, call);
18
+ if (taskResource(state.Resource).waits || customStepOf(state.Resource)) return runWaitingTask(state, call);
18
19
  const args = await evaluateTemplate(state.Arguments ?? {}, call.bindings, "Arguments");
19
20
  const key = `${call.context.runId}/${call.scope}/${call.position.seq - call.position.attempt + 1}`;
20
21
  const input = redacted(recordedArguments(state.Arguments ?? {}, args));
@@ -1,5 +1,5 @@
1
1
  import { StepCacheStore } from "./cache/cache-port.js";
2
- import { BlockRunStore, LoadedRun, RunStore, SegmentQueue, StepRecord, TaskAnswer, TaskHandlers, TaskTokenStore, TraceMode, TraceSink } from "./port.js";
2
+ import { BlockRunStore, CustomStepJobs, LoadedRun, RunStore, SegmentQueue, StepRecord, TaskAnswer, TaskHandlers, TaskTokenStore, TraceMode, TraceSink } from "./port.js";
3
3
  //#region src/run/runner.d.ts
4
4
  /**
5
5
  * The runner's port: where runs are kept, the queue that runs their segments, the step types, the secrets expressions
@@ -16,6 +16,8 @@ export type RunnerPort<Db> = {
16
16
  blocks?: BlockRunStore<Db>;
17
17
  /** Where waiting Tasks' tokens are kept; without it a Task that waits for an outside result fails. */
18
18
  tokens?: TaskTokenStore<Db>;
19
+ /** Where custom steps wait for a runner; without it a Task of a custom step fails. */
20
+ customSteps?: CustomStepJobs<Db>;
19
21
  secrets?: Readonly<Record<string, string>>;
20
22
  trace?: TraceSink;
21
23
  traceMode?: TraceMode;
@@ -36,7 +38,7 @@ export type AnswerRefusal = {
36
38
  * The workflow runner over a port. `start` queues a run's first segment in `db`, which may be the caller's
37
39
  * transaction, so the run starts when it commits; `segment` is what the queue's job runs.
38
40
  */
39
- export declare const createRunner: <Db>({ store, queue, tasks, cache, blocks, tokens, secrets, trace, traceMode, now, budgetMs, maxSteps }: RunnerPort<Db>) => {
41
+ export declare const createRunner: <Db>({ store, queue, tasks, cache, blocks, tokens, customSteps, secrets, trace, traceMode, now, budgetMs, maxSteps }: RunnerPort<Db>) => {
40
42
  start: (db: Db, runId: string) => Promise<void>;
41
43
  /** The steps an ended run's trace holds, which a re-run from one of them starts from: undefined when it kept none. */
42
44
  readTrace: (runId: string) => Promise<readonly StepRecord[] | undefined>;
@@ -48,6 +50,13 @@ export declare const createRunner: <Db>({ store, queue, tasks, cache, blocks, to
48
50
  answerTask: (db: Db, token: string, answer: TaskAnswer) => Promise<{
49
51
  run: string;
50
52
  } | AnswerRefusal>;
53
+ /**
54
+ * Takes an answer as `answerTask` does, to the try whose token has this hash, from the app's own executor, which
55
+ * proves otherwise that it may answer and never holds the token: a custom step's runner.
56
+ */
57
+ answerTaskByHash: (db: Db, hash: string, answer: TaskAnswer) => Promise<AnswerRefusal | {
58
+ run: string;
59
+ }>;
51
60
  /** Puts the steps a re-run from a step keeps of an earlier run at the start of `run`'s trace, as the run keeps one. */
52
61
  keepSteps: (run: Pick<LoadedRun, "id" | "definition" | "trace">, steps: readonly StepRecord[]) => Promise<void> | undefined;
53
62
  /**
@@ -37,8 +37,39 @@ const blankedOut = (output) => (JSON.stringify(output) ?? "").includes(blankedMa
37
37
  * The workflow runner over a port. `start` queues a run's first segment in `db`, which may be the caller's
38
38
  * transaction, so the run starts when it commits; `segment` is what the queue's job runs.
39
39
  */
40
- const createRunner = ({ store, queue, tasks, cache, blocks, tokens, secrets = {}, trace, traceMode = "all", now = () => /* @__PURE__ */ new Date(), budgetMs = limits.segmentMs, maxSteps = limits.runSteps }) => {
40
+ const createRunner = ({ store, queue, tasks, cache, blocks, tokens, customSteps, secrets = {}, trace, traceMode = "all", now = () => /* @__PURE__ */ new Date(), budgetMs = limits.segmentMs, maxSteps = limits.runSteps }) => {
41
41
  secretRedactor(Object.values(secrets));
42
+ const answerByHash = async (db, hash, answer) => {
43
+ const kept = keptAnswer(answer);
44
+ if (!("kind" in kept)) return kept;
45
+ const found = tokens && await tokens.byHash(db, hash);
46
+ if (!found) return {
47
+ error: "TaskDoesNotExist",
48
+ message: "No waiting Task was given this token"
49
+ };
50
+ const closed = {
51
+ error: "TaskTimedOut",
52
+ message: "The Task this token was given to has ended"
53
+ };
54
+ if (found.status !== "waiting") return closed;
55
+ const run = await store.load(db, found.run);
56
+ if (!run || ended.has(run.status)) return {
57
+ error: "TaskTimedOut",
58
+ message: "The run of the Task this token was given to has ended"
59
+ };
60
+ const at = now();
61
+ const late = overdue(found, at);
62
+ if (late) {
63
+ await queue.wake(db, found.run);
64
+ return {
65
+ error: "TaskTimedOut",
66
+ message: `The Task this token was given to has ended: ${late.cause}`
67
+ };
68
+ }
69
+ if (!await tokens.answer(db, hash, kept, at)) return closed;
70
+ if (answer.kind !== "heartbeat") await queue.wake(db, found.run);
71
+ return { run: found.run };
72
+ };
42
73
  return {
43
74
  start: (db, runId) => queue.schedule(db, runId),
44
75
  /** The steps an ended run's trace holds, which a re-run from one of them starts from: undefined when it kept none. */
@@ -53,37 +84,13 @@ const createRunner = ({ store, queue, tasks, cache, blocks, tokens, secrets = {}
53
84
  error: "InvalidToken",
54
85
  message: "This is not a task token"
55
86
  };
56
- const kept = keptAnswer(answer);
57
- if (!("kind" in kept)) return kept;
58
- const hash = await taskTokenHash(token);
59
- const found = tokens && await tokens.byHash(db, hash);
60
- if (!found) return {
61
- error: "TaskDoesNotExist",
62
- message: "No waiting Task was given this token"
63
- };
64
- const closed = {
65
- error: "TaskTimedOut",
66
- message: "The Task this token was given to has ended"
67
- };
68
- if (found.status !== "waiting") return closed;
69
- const run = await store.load(db, found.run);
70
- if (!run || ended.has(run.status)) return {
71
- error: "TaskTimedOut",
72
- message: "The run of the Task this token was given to has ended"
73
- };
74
- const at = now();
75
- const late = overdue(found, at);
76
- if (late) {
77
- await queue.wake(db, found.run);
78
- return {
79
- error: "TaskTimedOut",
80
- message: `The Task this token was given to has ended: ${late.cause}`
81
- };
82
- }
83
- if (!await tokens.answer(db, hash, kept, at)) return closed;
84
- if (answer.kind !== "heartbeat") await queue.wake(db, found.run);
85
- return { run: found.run };
87
+ return answerByHash(db, await taskTokenHash(token), answer);
86
88
  },
89
+ /**
90
+ * Takes an answer as `answerTask` does, to the try whose token has this hash, from the app's own executor, which
91
+ * proves otherwise that it may answer and never holds the token: a custom step's runner.
92
+ */
93
+ answerTaskByHash: (db, hash, answer) => answerByHash(db, hash, answer),
87
94
  /** Puts the steps a re-run from a step keeps of an earlier run at the start of `run`'s trace, as the run keeps one. */
88
95
  keepSteps: (run, steps) => trace?.write(run.id, steps, { mode: run.trace ?? run.definition.trace ?? traceMode }),
89
96
  /**
@@ -127,6 +134,10 @@ const createRunner = ({ store, queue, tasks, cache, blocks, tokens, secrets = {}
127
134
  handedOff: (visit, done) => tokens.handedOff(db, runId, visit, done),
128
135
  close: (visit, failure, seen) => tokens.close(db, runId, visit, failure, seen)
129
136
  };
137
+ const jobs = customSteps && { queue: (job) => customSteps.queue(db, {
138
+ ...job,
139
+ run: runId
140
+ }) };
130
141
  const segment = {
131
142
  runId,
132
143
  definition,
@@ -138,6 +149,7 @@ const createRunner = ({ store, queue, tasks, cache, blocks, tokens, secrets = {}
138
149
  ...cache && { cache },
139
150
  ...blockRuns && { blocks: blockRuns },
140
151
  ...taskTokens && { tokens: taskTokens },
152
+ ...jobs && { customSteps: jobs },
141
153
  signal,
142
154
  now,
143
155
  budgetMs,
@@ -3,7 +3,7 @@ import { Redactor } from "./redact.js";
3
3
  import { StepCacheStore } from "./cache/cache-port.js";
4
4
  import { Checkpoint, StepRecord, TaskHandlers } from "./port.js";
5
5
  import { Replayed } from "./replay-of.js";
6
- import { ScopeOutcome, SegmentBlocks, SegmentTokens } from "./context.js";
6
+ import { ScopeOutcome, SegmentBlocks, SegmentCustomSteps, SegmentTokens } from "./context.js";
7
7
  //#region src/run/segment.d.ts
8
8
  export type SegmentInput = {
9
9
  runId: string;
@@ -30,6 +30,8 @@ export type SegmentInput = {
30
30
  blocks?: SegmentBlocks;
31
31
  /** The run's waiting Tasks' tokens; without them a Task that waits for an outside result fails. */
32
32
  tokens?: SegmentTokens;
33
+ /** Where the run's custom steps wait for a runner; without it a custom step fails. */
34
+ customSteps?: SegmentCustomSteps;
33
35
  signal: AbortSignal;
34
36
  now?: () => Date;
35
37
  /** How long the segment takes new steps. Default `limits.segmentMs`. */
@@ -48,5 +50,5 @@ export type SegmentOutcome = (ScopeOutcome | {
48
50
  * (a Wait, a retry's delay), or yields once its time is up, saving its checkpoints on the way and as it pauses.
49
51
  * `superseded` when another segment saved a newer checkpoint first.
50
52
  */
51
- export declare const runSegment: ({ runId, definition, input, startedAt, secrets, redactor, saved, save, keep, tasks, cache, replayed, blocks, tokens, signal, now, budgetMs, maxSteps }: SegmentInput) => Promise<SegmentOutcome>;
53
+ export declare const runSegment: ({ runId, definition, input, startedAt, secrets, redactor, saved, save, keep, tasks, cache, replayed, blocks, tokens, customSteps, signal, now, budgetMs, maxSteps }: SegmentInput) => Promise<SegmentOutcome>;
52
54
  //#endregion
@@ -11,7 +11,7 @@ import { replayOf } from "./replay-of.js";
11
11
  * (a Wait, a retry's delay), or yields once its time is up, saving its checkpoints on the way and as it pauses.
12
12
  * `superseded` when another segment saved a newer checkpoint first.
13
13
  */
14
- const runSegment = async ({ runId, definition, input, startedAt, secrets, redactor, saved, save, keep, tasks, cache, replayed, blocks, tokens, signal, now = () => /* @__PURE__ */ new Date(), budgetMs = limits.segmentMs, maxSteps = limits.runSteps }) => {
14
+ const runSegment = async ({ runId, definition, input, startedAt, secrets, redactor, saved, save, keep, tasks, cache, replayed, blocks, tokens, customSteps, signal, now = () => /* @__PURE__ */ new Date(), budgetMs = limits.segmentMs, maxSteps = limits.runSteps }) => {
15
15
  const latest = new Map(saved.map((checkpoint) => [checkpoint.scope, checkpoint]));
16
16
  const after = new Map(saved.map((checkpoint) => [checkpoint.scope, checkpoint.seq]));
17
17
  const steps = [];
@@ -56,6 +56,7 @@ const runSegment = async ({ runId, definition, input, startedAt, secrets, redact
56
56
  ...replayed && { replay: replayOf(replayed) },
57
57
  ...blocks && { blocks },
58
58
  ...tokens && { tokens },
59
+ ...customSteps && { customSteps },
59
60
  signal,
60
61
  now,
61
62
  deadline: Date.now() + budgetMs,
package/dist/run/task.js CHANGED
@@ -1,6 +1,5 @@
1
1
  import { limits } from "../limits.js";
2
2
  import { StepError, SupersededError } from "./errors.js";
3
- import "../plugin/custom-steps.js";
4
3
  //#region src/run/task.ts
5
4
  const aborted = (signal) => new Promise((_, reject) => {
6
5
  if (signal.aborted) return reject(signal.reason);
@@ -9,12 +8,10 @@ const aborted = (signal) => new Promise((_, reject) => {
9
8
  /**
10
9
  * Runs a Task's step type with its arguments, within its `TimeoutSeconds`: its result, or a `StepError` naming why it
11
10
  * failed (`States.Timeout` when the time ran out, `States.TaskFailed` for an error of no name of its own). When the
12
- * worker stops, the abort is thrown as it is, so the step is not saved and runs again in the next segment. A custom
13
- * step, which the save takes, fails as one that does not run yet.
11
+ * worker stops, the abort is thrown as it is, so the step is not saved and runs again in the next segment.
14
12
  */
15
13
  const runTask = async (context, state, args, idempotencyKey, logs) => {
16
14
  const handler = context.tasks[state.Resource];
17
- if (!handler && state.Resource.startsWith(`custom:`)) throw new StepError("States.Runtime", "Custom steps do not run yet");
18
15
  if (!handler) throw new StepError("States.Runtime", `"${state.Resource}" is not a step type of this app`);
19
16
  const timeout = AbortSignal.timeout((state.TimeoutSeconds ?? limits.defaultTaskTimeoutSeconds) * 1e3);
20
17
  const signal = AbortSignal.any([context.signal, timeout]);
@@ -1,5 +1,6 @@
1
1
  import { limits } from "../limits.js";
2
2
  import { taskResource } from "../definition/task-resource.js";
3
+ import { customStepOf } from "../plugin/custom-step-id.js";
3
4
  import { StepError, errorOutput } from "./errors.js";
4
5
  import { redacted } from "./redact.js";
5
6
  import { evaluateTemplate, recordedArguments } from "./evaluate.js";
@@ -44,9 +45,14 @@ const overdue = (task, at, timeoutSeconds = Math.round((task.deadline.getTime()
44
45
  * no segment, until an answer wakes it, its `TimeoutSeconds` pass (`States.Timeout`, from the try's start) or a
45
46
  * heartbeat is overdue (`States.HeartbeatTimeout`). The answer is the Task's result, which `Output` and `Assign` read as
46
47
  * `$states.result`, or its failure, under the error the answer names. The token is blanked out of all the run keeps.
48
+ *
49
+ * A custom step's Task (`custom:<name>:<version>`) waits the same way, its hand-off a job queued for a runner with the
50
+ * hash of the try's token, by which the app answers it as the runner completes the job; its `TimeoutSeconds` is a step type's by default, the queue
51
+ * included.
47
52
  */
48
53
  const runWaitingTask = async (state, call) => {
49
54
  const { type } = taskResource(state.Resource);
55
+ const custom = customStepOf(type) !== void 0;
50
56
  const template = state.Arguments ?? {};
51
57
  if (call.context.replay) return {
52
58
  held: true,
@@ -54,13 +60,14 @@ const runWaitingTask = async (state, call) => {
54
60
  };
55
61
  const tokens = call.context.tokens;
56
62
  if (!tokens) throw new StepError("States.Runtime", "This app keeps no waiting Tasks");
63
+ if (custom && !call.context.customSteps) throw new StepError("States.Runtime", "This app runs no custom steps");
57
64
  const visit = `${call.scope}|${call.position.seq}`;
58
65
  const found = await tokens.find(visit);
59
66
  if (found && (found.handedOffAt || found.status !== "waiting")) return settle(found, visit, call);
60
67
  const token = newTaskToken();
61
68
  call.context.redactor.add(token);
62
69
  const startedAt = call.context.now();
63
- const timeout = state.TimeoutSeconds ?? limits.waitingTaskTimeoutSeconds;
70
+ const timeout = state.TimeoutSeconds ?? (custom ? limits.taskTimeoutSeconds : limits.waitingTaskTimeoutSeconds);
64
71
  const hash = await taskTokenHash(token);
65
72
  await tokens.begin({
66
73
  visit,
@@ -80,7 +87,15 @@ const runWaitingTask = async (state, call) => {
80
87
  Cache: false
81
88
  };
82
89
  try {
83
- await runTask(call.context, handOff, args, key, call.logs);
90
+ if (custom) await call.context.customSteps.queue({
91
+ visit,
92
+ state: call.name,
93
+ step: type,
94
+ input,
95
+ arguments: args,
96
+ hash
97
+ });
98
+ else await runTask(call.context, handOff, args, key, call.logs);
84
99
  } catch (error) {
85
100
  if (!(error instanceof StepError)) throw error;
86
101
  const failure = errorOutput(error);
@@ -94,9 +109,10 @@ const runWaitingTask = async (state, call) => {
94
109
  };
95
110
  return handedOff(visit, call, input);
96
111
  }
112
+ const until = new Date(startedAt.getTime() + timeout * 1e3).toISOString();
97
113
  call.logs.push({
98
114
  at: call.context.now().toISOString(),
99
- message: `Handed off; waits for an outside result until ${new Date(startedAt.getTime() + timeout * 1e3).toISOString()}`
115
+ message: custom ? `Queued for a runner; waits for its result until ${until}` : `Handed off; waits for an outside result until ${until}`
100
116
  });
101
117
  return handedOff(visit, call, input);
102
118
  };
@@ -0,0 +1,28 @@
1
+ import { TaskAnswer } from "../run/port.js";
2
+ import { JsonSchema } from "../plugin/context.js";
3
+ //#region src/runners/job-answer.d.ts
4
+ /** What a runner sends as it completes a custom step's job: the step's output, or the error it failed with and why. */
5
+ export type JobCompletion = {
6
+ output: unknown;
7
+ } | {
8
+ error: string;
9
+ cause?: string;
10
+ };
11
+ /** The parts of a custom step's version that its completion is checked against. */
12
+ export type CompletedVersion = {
13
+ output: JsonSchema;
14
+ error_prefix: string;
15
+ errors: Record<string, string>;
16
+ };
17
+ /** The errors a custom step fails with that its manifest does not name: an output its schema refuses, and any other failure. */
18
+ export declare const jobErrors: {
19
+ readonly invalidOutput: "Custom.InvalidOutput";
20
+ readonly failed: "Custom.Failed";
21
+ };
22
+ /**
23
+ * The answer a custom step's Task takes from its runner's completion: its output, once it fits the version's output
24
+ * schema, else `Custom.InvalidOutput` with what does not fit; a failure under `<error_prefix>.<Name>` when the runner
25
+ * names one of the version's errors, by its name or in full, else `Custom.Failed`, with the name it gave in the cause.
26
+ */
27
+ export declare const jobAnswer: (version: CompletedVersion, completion: JobCompletion) => TaskAnswer;
28
+ //#endregion
@@ -0,0 +1,45 @@
1
+ import { Ajv } from "ajv";
2
+ //#region src/runners/job-answer.ts
3
+ /** The errors a custom step fails with that its manifest does not name: an output its schema refuses, and any other failure. */
4
+ const jobErrors = {
5
+ invalidOutput: "Custom.InvalidOutput",
6
+ failed: "Custom.Failed"
7
+ };
8
+ /**
9
+ * The answer a custom step's Task takes from its runner's completion: its output, once it fits the version's output
10
+ * schema, else `Custom.InvalidOutput` with what does not fit; a failure under `<error_prefix>.<Name>` when the runner
11
+ * names one of the version's errors, by its name or in full, else `Custom.Failed`, with the name it gave in the cause.
12
+ */
13
+ const jobAnswer = (version, completion) => {
14
+ if ("output" in completion) {
15
+ const ajv = new Ajv({
16
+ strict: false,
17
+ allErrors: true
18
+ });
19
+ const valid = ajv.compile(version.output);
20
+ if (valid(completion.output)) return {
21
+ kind: "success",
22
+ output: JSON.stringify(completion.output)
23
+ };
24
+ return {
25
+ kind: "failure",
26
+ error: jobErrors.invalidOutput,
27
+ cause: `The output does not fit the step's output schema: ${ajv.errorsText(valid.errors, { dataVar: "output" })}`
28
+ };
29
+ }
30
+ const { error, cause = "" } = completion;
31
+ const prefix = `${version.error_prefix}.`;
32
+ const name = error.startsWith(prefix) ? error.slice(prefix.length) : error;
33
+ if (Object.hasOwn(version.errors, name)) return {
34
+ kind: "failure",
35
+ error: `${prefix}${name}`,
36
+ cause
37
+ };
38
+ return {
39
+ kind: "failure",
40
+ error: jobErrors.failed,
41
+ cause: error === "" ? cause : `${error}${cause === "" ? "" : `: ${cause}`}`
42
+ };
43
+ };
44
+ //#endregion
45
+ export { jobAnswer, jobErrors };
@@ -0,0 +1,83 @@
1
+ //#region src/runners/match-jobs.d.ts
2
+ /**
3
+ * What a runner says of itself with each claim: its platform, the kinds of steps it runs and its labels, its free
4
+ * slots, the steps whose images it holds (by step version, `custom:<name>:<version>`, until images have digests), each
5
+ * with whether a snapshot of it is ready, and its warm instances with their free concurrency.
6
+ */
7
+ export type RunnerState = {
8
+ platform: string;
9
+ kinds: string[];
10
+ labels: string[];
11
+ capacity: {
12
+ slots: number;
13
+ };
14
+ images: {
15
+ step: string;
16
+ snapshot?: boolean;
17
+ }[];
18
+ instances: {
19
+ step: string;
20
+ free: number;
21
+ }[];
22
+ };
23
+ /** A runner holding a claim open, of a tenant, with its labels as its record sets them and the state it sent. */
24
+ export type PollingRunner = {
25
+ id: string;
26
+ tenant: string | null;
27
+ labels: string[];
28
+ state: RunnerState;
29
+ polledAt: Date;
30
+ };
31
+ /** A job waiting for a runner: its step, since when it is queued, and since when a pass first left it for a better runner. */
32
+ export type QueuedJob = {
33
+ id: string;
34
+ tenant: string | null;
35
+ step: string;
36
+ labels?: string[];
37
+ queuedAt: Date;
38
+ passedOverAt: Date | null;
39
+ };
40
+ /**
41
+ * A runner of a tenant that holds a claim open or runs a job, free or busy, with what it said of itself last: one a job
42
+ * may wait for.
43
+ */
44
+ export type KnownRunner = {
45
+ tenant: string | null;
46
+ state: RunnerState;
47
+ };
48
+ /** How long a job waits for a runner better than the best one free: one with its image, and one with a warm instance. */
49
+ export type MatchSettings = {
50
+ coldWaitMs: number;
51
+ warmWaitMs: number;
52
+ };
53
+ /** How hot a runner is for a job: 1 a warm instance with room, 2 a snapshot, 3 the image, 4 nothing of it. */
54
+ export type Tier = 1 | 2 | 3 | 4;
55
+ export type Placement = {
56
+ job: string;
57
+ runner: string;
58
+ tier: Tier;
59
+ };
60
+ /** The kind of step a runner must run for a custom step's job: all custom steps are containers. */
61
+ export declare const jobKind = "container";
62
+ /** How hot `runner` is for a job of `step`. */
63
+ export declare const tierOf: (state: RunnerState, step: string) => Tier;
64
+ /**
65
+ * Which jobs go to which of the runners holding a claim open, each runner taking one, and which jobs a pass left for a
66
+ * better runner for the first time (`passedOver`), whose wait counts from now. Each job takes the hottest runner that
67
+ * fits it, by `tierOf`, the one that has waited longest among equals; but one whose best is a runner without its image
68
+ * waits up to `coldWaitMs` for one with it, and one whose best has its image waits up to `warmWaitMs` for a warm
69
+ * instance, each counted from when a pass first left it, before it takes the best that is free. It waits only while a
70
+ * runner of its tenant it would wait for is `known`, busy or not; with none it takes the best free at once. A job left
71
+ * waiting leaves its runner to the jobs after it.
72
+ */
73
+ export declare const matchJobs: ({ jobs, runners, known, now, settings }: {
74
+ jobs: readonly QueuedJob[];
75
+ runners: readonly PollingRunner[];
76
+ known: readonly KnownRunner[];
77
+ now: Date;
78
+ settings: MatchSettings;
79
+ }) => {
80
+ placements: Placement[];
81
+ passedOver: string[];
82
+ };
83
+ //#endregion
@@ -0,0 +1,66 @@
1
+ //#region src/runners/match-jobs.ts
2
+ /** The kind of step a runner must run for a custom step's job: all custom steps are containers. */
3
+ const jobKind = "container";
4
+ /** How hot `runner` is for a job of `step`. */
5
+ const tierOf = (state, step) => {
6
+ if (state.instances.some((instance) => instance.step === step && instance.free > 0)) return 1;
7
+ const image = state.images.find((one) => one.step === step);
8
+ if (image?.snapshot) return 2;
9
+ return image ? 3 : 4;
10
+ };
11
+ const holdsImage = (state, step) => state.images.some((image) => image.step === step) || holdsInstance(state, step);
12
+ const holdsInstance = (state, step) => state.instances.some((instance) => instance.step === step);
13
+ const fits = (runner, job) => {
14
+ if (runner.tenant !== job.tenant) return false;
15
+ if (!runner.state.kinds.includes("container") || runner.state.capacity.slots < 1) return false;
16
+ const labels = /* @__PURE__ */ new Set([...runner.labels, ...runner.state.labels]);
17
+ return (job.labels ?? []).every((label) => labels.has(label));
18
+ };
19
+ const roundRobin = (jobs) => {
20
+ const byTenant = /* @__PURE__ */ new Map();
21
+ for (const job of [...jobs].sort((a, b) => a.queuedAt.getTime() - b.queuedAt.getTime())) byTenant.set(job.tenant, [...byTenant.get(job.tenant) ?? [], job]);
22
+ const queues = [...byTenant.values()];
23
+ const ordered = [];
24
+ for (let turn = 0; ordered.length < jobs.length; turn++) for (const queue of queues) if (queue[turn]) ordered.push(queue[turn]);
25
+ return ordered;
26
+ };
27
+ /**
28
+ * Which jobs go to which of the runners holding a claim open, each runner taking one, and which jobs a pass left for a
29
+ * better runner for the first time (`passedOver`), whose wait counts from now. Each job takes the hottest runner that
30
+ * fits it, by `tierOf`, the one that has waited longest among equals; but one whose best is a runner without its image
31
+ * waits up to `coldWaitMs` for one with it, and one whose best has its image waits up to `warmWaitMs` for a warm
32
+ * instance, each counted from when a pass first left it, before it takes the best that is free. It waits only while a
33
+ * runner of its tenant it would wait for is `known`, busy or not; with none it takes the best free at once. A job left
34
+ * waiting leaves its runner to the jobs after it.
35
+ */
36
+ const matchJobs = ({ jobs, runners, known, now, settings }) => {
37
+ const free = [...runners].sort((a, b) => a.polledAt.getTime() - b.polledAt.getTime());
38
+ const placements = [];
39
+ const passedOver = [];
40
+ for (const job of roundRobin(jobs)) {
41
+ const fitting = free.filter((runner) => fits(runner, job));
42
+ if (fitting.length === 0) continue;
43
+ const best = fitting.map((runner) => ({
44
+ runner,
45
+ tier: tierOf(runner.state, job.step)
46
+ })).sort((a, b) => a.tier - b.tier)[0];
47
+ const waited = job.passedOverAt ? now.getTime() - job.passedOverAt.getTime() : 0;
48
+ const tenants = known.filter((runner) => runner.tenant === job.tenant);
49
+ if ((best.tier === 4 ? tenants.some((runner) => holdsImage(runner.state, job.step)) : best.tier !== 1 && tenants.some((runner) => holdsInstance(runner.state, job.step))) && waited < (best.tier === 4 ? settings.coldWaitMs : settings.warmWaitMs)) {
50
+ if (!job.passedOverAt) passedOver.push(job.id);
51
+ continue;
52
+ }
53
+ placements.push({
54
+ job: job.id,
55
+ runner: best.runner.id,
56
+ tier: best.tier
57
+ });
58
+ free.splice(free.indexOf(best.runner), 1);
59
+ }
60
+ return {
61
+ placements,
62
+ passedOver
63
+ };
64
+ };
65
+ //#endregion
66
+ export { jobKind, matchJobs, tierOf };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@protobase/workflows",
3
- "version": "0.100.10",
3
+ "version": "0.100.11",
4
4
  "description": "Workflows as state machines with JSONata expressions: their check, a runner that saves only what a run needs to go on and traces every step, and the plugin interface for trigger and step types.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {