@mark1russell7/workflow-runner 0.0.0-bootstrap.0 → 0.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.
- package/LICENSE +21 -0
- package/README.md +36 -1
- package/build/engine-B_0OOo1N.d.ts +229 -0
- package/build/engine-B_0OOo1N.d.ts.map +1 -0
- package/build/index.d.ts +14 -0
- package/build/index.d.ts.map +1 -0
- package/build/index.js +984 -0
- package/build/index.js.map +1 -0
- package/build/service.d.ts +31 -0
- package/build/service.d.ts.map +1 -0
- package/build/service.js +56 -0
- package/build/service.js.map +1 -0
- package/package.json +51 -8
- package/src/engine.ts +662 -0
- package/src/index.ts +14 -0
- package/src/machines.ts +98 -0
- package/src/record.ts +89 -0
- package/src/service.ts +54 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/machines.ts","../src/engine.ts","../src/record.ts"],"sourcesContent":["import type { Machine } from \"@mark1russell7/algebra\";\n\nconst SOURCES: Machine[\"sources\"] = [{ ref: \"docs/WORKFLOW.md#the-runner-w4\", rung: \"implemented\", note: \"D225\" }];\n\n/**\n * The state machine of a run. A run is queued, then it runs. It ends with one status. The runner records each\n * transition, and a test checks the record against this machine.\n */\nexport const RUN_MACHINE: Machine = {\n format: \"mark1russell7.machine/1\",\n id: \"workflow.run\",\n title: \"The run of a workflow\",\n layer: \"self\",\n version: \"1.0.0\",\n sources: SOURCES,\n states: {\n queued: { initial: true },\n running: {},\n succeeded: { final: true },\n failed: { final: true },\n refused: { final: true, note: \"A grant, an owner or a check refused the run. No later effect happened.\" },\n invalid: { final: true, note: \"The document has an error. No effect happened.\" },\n \"in-doubt\": { final: true, note: \"An effect started and has no outcome, and its procedure does not remove a second call.\" },\n cancelled: { final: true },\n },\n events: {\n start: { kind: \"app\" },\n succeed: { kind: \"local\" },\n fail: { kind: \"local\" },\n refuse: { kind: \"local\" },\n reject: { kind: \"local\" },\n doubt: { kind: \"local\" },\n cancel: { kind: \"app\" },\n },\n knobs: {},\n timers: {},\n transitions: [\n { id: \"start\", from: \"queued\", to: \"running\", on: \"start\" },\n { id: \"reject\", from: \"queued\", to: \"invalid\", on: \"reject\" },\n { id: \"refuse-early\", from: \"queued\", to: \"refused\", on: \"refuse\" },\n { id: \"succeed\", from: \"running\", to: \"succeeded\", on: \"succeed\" },\n { id: \"fail\", from: \"running\", to: \"failed\", on: \"fail\" },\n { id: \"refuse\", from: \"running\", to: \"refused\", on: \"refuse\" },\n { id: \"doubt\", from: \"running\", to: \"in-doubt\", on: \"doubt\" },\n { id: \"cancel\", from: [\"queued\", \"running\"], to: \"cancelled\", on: \"cancel\" },\n ],\n};\n\n/**\n * The state machine of one step of one job instance. A failed try waits for its retry. A refusal and a doubt end the\n * step at once: no retry and no `continue` changes them.\n */\nexport const STEP_MACHINE: Machine = {\n format: \"mark1russell7.machine/1\",\n id: \"workflow.step\",\n title: \"The step of a job\",\n layer: \"self\",\n version: \"1.0.0\",\n sources: SOURCES,\n states: {\n pending: { initial: true },\n running: {},\n waiting: { note: \"A try failed. The next try starts at the due time of the record.\" },\n succeeded: { final: true },\n skipped: { final: true },\n failed: { final: true },\n \"timed-out\": { final: true },\n refused: { final: true },\n \"in-doubt\": { final: true },\n cancelled: { final: true },\n },\n events: {\n run: { kind: \"local\" },\n skip: { kind: \"local\" },\n succeed: { kind: \"local\" },\n fail: { kind: \"local\" },\n retry: { kind: \"local\" },\n due: { kind: \"timer\" },\n expire: { kind: \"timer\" },\n refuse: { kind: \"local\" },\n doubt: { kind: \"local\" },\n cancel: { kind: \"app\" },\n },\n knobs: {},\n timers: {},\n transitions: [\n { id: \"run\", from: \"pending\", to: \"running\", on: \"run\" },\n { id: \"skip\", from: \"pending\", to: \"skipped\", on: \"skip\" },\n { id: \"succeed\", from: \"running\", to: \"succeeded\", on: \"succeed\" },\n { id: \"fail\", from: \"running\", to: \"failed\", on: \"fail\" },\n { id: \"retry\", from: \"running\", to: \"waiting\", on: \"retry\" },\n { id: \"due\", from: \"waiting\", to: \"running\", on: \"due\" },\n { id: \"expire\", from: \"running\", to: \"timed-out\", on: \"expire\" },\n { id: \"refuse\", from: [\"pending\", \"running\"], to: \"refused\", on: \"refuse\" },\n { id: \"doubt\", from: [\"pending\", \"running\"], to: \"in-doubt\", on: \"doubt\" },\n { id: \"cancel\", from: [\"pending\", \"running\", \"waiting\"], to: \"cancelled\", on: \"cancel\" },\n ],\n};\n","import { transitionOn } from \"@mark1russell7/algebra\";\nimport type { Clock } from \"@mark1russell7/algebra/clock\";\nimport { readRecord } from \"@mark1russell7/optional/read\";\nimport { type Cap, type Effect, type Machine, Failure, context, isEnvelope, isRecord, run } from \"@mark1russell7/coeval\";\nimport { canonicalHash } from \"@mark1russell7/rigor-generators\";\nimport { backoffDelay } from \"@mark1russell7/service/backoff\";\nimport { type ProcedureInfo, checkWorkflow, workflowMachine } from \"@mark1russell7/workflow\";\nimport { RUN_MACHINE, STEP_MACHINE } from \"./machines.ts\";\nimport type { Outcome, RunEntry, RunStatus, RunStore, StepStatus, TriggerEvent } from \"./record.ts\";\n\n/** The facts of one procedure for the runner: the facts of the check, and the removal of a second call. */\nexport interface RunnerProcedure extends ProcedureInfo {\n /**\n * `true` when the procedure removes a second call with the same key. Then the runner calls again after a crash or a\n * time limit. Without it, an effect with no outcome ends the step as `in-doubt`.\n */\n readonly idempotent?: boolean;\n}\n\n/** One call of a procedure, for the host. */\nexport interface ProcedureCall {\n /** The path of the procedure, for example `[\"git\", \"clone\"]`. */\n readonly procedure: readonly string[];\n /** The inputs. A secret stays a reference: the host reads its value. */\n readonly inputs: Readonly<Record<string, unknown>>;\n /** The idempotency key: the same for each try and each resume of one effect. */\n readonly key: string;\n /** The number of the try, from 1. */\n readonly try: number;\n /** The workspace that runs the workflow. */\n readonly workspace: string;\n /** The signal of the time limit of the step. */\n readonly signal: AbortSignal;\n}\n\n/** One question to the grant check. */\nexport interface AccessRequest {\n readonly from: string;\n readonly access: \"read\" | \"write\";\n readonly target: string;\n}\n\n/** The answer of the grant check. */\nexport interface AccessAnswer {\n readonly ok: boolean;\n readonly why: string;\n}\n\n/** The limits of the runner. A document over a limit is `invalid`, and an outcome over its limit fails its step. */\nexport interface RunnerLimits {\n /** The most rows of one matrix. The default is 256. */\n readonly matrix?: number;\n /** The most tries of one step. The default is 10. */\n readonly tries?: number;\n /** The most bytes of one outcome as JSON. The default is 1000000. */\n readonly outcomeBytes?: number;\n /** The most job instances that run at the same time. The default is 8. */\n readonly jobs?: number;\n}\n\n/** The ports of the runner. The runner names no host: the host gives each port. */\nexport interface RunnerOptions {\n /** The facts of each procedure, by its path with dots. A call of a procedure that is not here is refused. */\n readonly procedures: Readonly<Record<string, RunnerProcedure>>;\n /** The host does one call. A throw is the failure of the call. */\n readonly call: (call: ProcedureCall) => Promise<unknown>;\n /** The grant check. A throw is a refusal. */\n readonly access: (request: AccessRequest) => AccessAnswer | Promise<AccessAnswer>;\n /**\n * The redaction of the host: it removes the value of each secret from a value. The runner gives it each outcome, each\n * error text, each payload and the trigger event, before the record and before a later step reads them.\n */\n readonly redact: (value: unknown) => unknown;\n /** The store of the records. */\n readonly store: RunStore;\n /** The clock of the time limits and the retry waits. */\n readonly clock: Clock;\n /** The wall time of the record, in milliseconds. The default is `Date.now`. A due time of a retry uses it. */\n readonly wall?: () => number;\n /** The machine of the documents. The default is `workflowMachine()`. */\n readonly machine?: Machine;\n /** The namespaces of calls, besides `procedure`. */\n readonly callNamespaces?: readonly string[];\n /** The limits. */\n readonly limits?: RunnerLimits;\n}\n\n/** A request to start a run. */\nexport interface StartRequest {\n /** The workflow document. */\n readonly doc: unknown;\n /** The workspace that holds the document, from the store of the host. The field `workspace` of the document must be the same. */\n readonly owner: string;\n /** The event that starts the run. */\n readonly trigger: TriggerEvent;\n /** The inputs of the run. */\n readonly inputs?: Readonly<Record<string, unknown>>;\n}\n\n/** The end of a run. */\nexport interface RunResult {\n readonly run: string;\n readonly status: RunStatus;\n readonly why: string;\n readonly entries: readonly RunEntry[];\n}\n\n/** The runner of a workflow. */\nexport interface WorkflowRunner {\n /** This function gives the run id of a request: the same document, owner and event give the same id. */\n readonly runIdOf: (request: StartRequest) => string;\n /** This function starts a run. A request with a run id that has a record resumes that run. */\n readonly start: (request: StartRequest) => Promise<RunResult>;\n /** This function resumes a run from its record. The record holds the document, thus a changed document makes no change. */\n readonly resume: (run: string) => Promise<RunResult>;\n}\n\ntype Rec = Readonly<Record<string, unknown>>;\n\nconst fieldsOrEmpty = (value: unknown): Rec => readRecord(value) ?? {};\nconst listOf = (value: unknown): readonly unknown[] => (Array.isArray(value) ? value : []);\nconst valueOf = (doc: unknown): Rec => (isEnvelope(doc) ? fieldsOrEmpty(doc.value) : {});\n\n/** The error of a step that ends it at once: a refusal or a doubt. No retry and no `continue` changes it. */\nclass Halt extends Error {\n readonly status: \"refused\" | \"in-doubt\";\n\n constructor(status: \"refused\" | \"in-doubt\", why: string) {\n super(why);\n this.status = status;\n }\n}\n\n/** The error of a document part that the runner cannot evaluate. */\nclass PartError extends Error {}\n\n/** The prior record of a run, as maps for a resume. */\ninterface Prior {\n readonly ends: ReadonlyMap<string, Outcome>;\n readonly starts: ReadonlyMap<string, RunEntry & { readonly type: \"effect-start\" }>;\n readonly steps: ReadonlyMap<string, RunEntry & { readonly type: \"step-end\" }>;\n readonly jobs: ReadonlyMap<string, RunEntry & { readonly type: \"job-end\" }>;\n readonly rows: ReadonlyMap<string, readonly unknown[]>;\n readonly states: ReadonlyMap<string, { readonly state: string; readonly runs: number; readonly due?: number }>;\n readonly end?: RunEntry & { readonly type: \"end\" };\n}\n\nfunction priorOf(entries: readonly RunEntry[]): Prior {\n const ends = new Map<string, Outcome>();\n const starts = new Map<string, RunEntry & { readonly type: \"effect-start\" }>();\n const steps = new Map<string, RunEntry & { readonly type: \"step-end\" }>();\n const jobs = new Map<string, RunEntry & { readonly type: \"job-end\" }>();\n const rows = new Map<string, readonly unknown[]>();\n const states = new Map<string, { state: string; runs: number; due?: number }>();\n let end: (RunEntry & { readonly type: \"end\" }) | undefined;\n for (const entry of entries) {\n if (entry.type === \"effect-start\") starts.set(entry.at, entry);\n else if (entry.type === \"effect-end\") ends.set(entry.at, entry.outcome);\n else if (entry.type === \"step-end\") steps.set(entry.instance, entry);\n else if (entry.type === \"job-end\") jobs.set(entry.instance, entry);\n else if (entry.type === \"rows\") rows.set(entry.job, entry.rows);\n else if (entry.type === \"transition\" && entry.machine === \"workflow.step\") {\n const was = states.get(entry.instance) ?? { state: \"pending\", runs: 0 };\n states.set(entry.instance, { state: entry.to, runs: was.runs + (entry.to === \"running\" ? 1 : 0), ...(entry.due === undefined ? {} : { due: entry.due }) });\n } else if (entry.type === \"end\") end = entry;\n }\n return { ends, starts, steps, jobs, rows, states, ...(end === undefined ? {} : { end }) };\n}\n\n/** The short hash of a matrix row. The address of a row does not change when the order of the rows changes. */\nfunction rowKey(row: unknown): string {\n return canonicalHash(row).slice(0, 12);\n}\n\n/** The order of the jobs: each job after its needs. A cycle or a missing need gives `undefined`. */\nfunction jobOrder(jobs: Rec): readonly string[] | undefined {\n const order: string[] = [];\n const state = new Map<string, \"open\" | \"done\">();\n const visit = (id: string): boolean => {\n if (state.get(id) === \"done\") return true;\n if (state.get(id) === \"open\" || !(id in jobs)) return false;\n state.set(id, \"open\");\n for (const need of listOf(valueOf(jobs[id])[\"needs\"])) if (typeof need !== \"string\" || !visit(need)) return false;\n state.set(id, \"done\");\n order.push(id);\n return true;\n };\n for (const id of Object.keys(jobs)) if (!visit(id)) return undefined;\n return order;\n}\n\n/** The problems that make a document `invalid` for the runner, besides the errors of `checkWorkflow`. */\nfunction runnerProblems(doc: unknown, limits: Required<RunnerLimits>): readonly string[] {\n const problems: string[] = [];\n const jobs = fieldsOrEmpty(valueOf(doc)[\"jobs\"]);\n if (jobOrder(jobs) === undefined) problems.push(\"The needs of the jobs have a cycle or name no job.\");\n for (const [id, job] of Object.entries(jobs)) {\n listOf(valueOf(job)[\"steps\"]).forEach((step, index) => {\n const s = valueOf(step);\n if (typeof s[\"id\"] !== \"string\") problems.push(`The step ${String(index + 1)} of the job ${id} has no id. The runner addresses each effect by the step id.`);\n const retry = s[\"retry\"];\n if (retry !== undefined) {\n const r = fieldsOrEmpty(retry);\n const tries = r[\"tries\"];\n if (typeof tries !== \"number\" || !Number.isInteger(tries) || tries < 1 || tries > limits.tries) problems.push(`The retry of the step ${String(s[\"id\"])} of the job ${id} needs tries: a whole number from 1 to ${String(limits.tries)}.`);\n for (const key of [\"delay\", \"factor\", \"cap\"]) if (r[key] !== undefined && (typeof r[key] !== \"number\" || (r[key] as number) < 0)) problems.push(`The retry ${key} of the step ${String(s[\"id\"])} of the job ${id} must be a number of 0 or more.`);\n }\n });\n }\n return problems;\n}\n\n/** The default value of each input of a document that has one. */\nfunction defaultsOf(doc: unknown): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const [name, input] of Object.entries(fieldsOrEmpty(valueOf(doc)[\"inputs\"]))) if (isRecord(input) && \"default\" in input) out[name] = input[\"default\"];\n return out;\n}\n\nconst DEFAULT_LIMITS: Required<RunnerLimits> = { matrix: 256, tries: 10, outcomeBytes: 1_000_000, jobs: 8 };\n\n/**\n * This function makes a runner of workflows. The runner records each run in the store, and each record is the log of\n * a resume. It refuses an effect that the grant check does not permit, and it records each answer.\n *\n * @param options - The ports and the limits.\n * @returns The runner.\n */\nexport function workflowRunner(options: RunnerOptions): WorkflowRunner {\n const machine = options.machine ?? workflowMachine();\n const limits: Required<RunnerLimits> = { ...DEFAULT_LIMITS, ...options.limits };\n const wall = options.wall ?? Date.now;\n const namespaces = [\"procedure\", ...(options.callNamespaces ?? [])];\n const callCaps: readonly Cap[] = namespaces.map((namespace) => [namespace]);\n\n const runIdOf = (request: StartRequest): string =>\n canonicalHash({ doc: canonicalHash(request.doc), owner: request.owner, trigger: { kind: request.trigger.kind, id: request.trigger.id } });\n\n async function start(request: StartRequest): Promise<RunResult> {\n const id = runIdOf(request);\n const entries = await options.store.read(id);\n if (entries.length > 0) return resume(id);\n const start: RunEntry = {\n type: \"start\",\n run: id,\n docHash: canonicalHash(request.doc),\n doc: request.doc,\n owner: request.owner,\n workspace: valueOf(request.doc)[\"workspace\"],\n trigger: options.redact(request.trigger) as TriggerEvent,\n inputs: options.redact({ ...defaultsOf(request.doc), ...request.inputs }),\n time: wall(),\n };\n await options.store.append(id, 0, start);\n return resume(id);\n }\n\n async function resume(id: string): Promise<RunResult> {\n const entries = [...(await options.store.read(id))];\n const first = entries[0];\n if (first?.type !== \"start\") throw new Error(`The run ${id} has no record.`);\n const prior = priorOf(entries);\n if (prior.end !== undefined) return { run: id, status: prior.end.status, why: prior.end.why, entries };\n return new Run(id, first, entries, prior).go();\n }\n\n /** One run: its writer, its state and its jobs. */\n class Run {\n private tail: Promise<void> = Promise.resolve();\n private runState: string;\n private halt: { readonly status: \"refused\" | \"in-doubt\"; readonly why: string } | undefined;\n private failed = false;\n private readonly event: unknown;\n private readonly doc: unknown;\n\n private readonly id: string;\n private readonly first: RunEntry & { readonly type: \"start\" };\n private readonly entries: RunEntry[];\n private readonly prior: Prior;\n\n constructor(id: string, first: RunEntry & { readonly type: \"start\" }, entries: RunEntry[], prior: Prior) {\n this.id = id;\n this.first = first;\n this.entries = entries;\n this.prior = prior;\n this.doc = first.doc;\n let state = \"queued\";\n for (const entry of entries) if (entry.type === \"transition\" && entry.machine === \"workflow.run\") state = entry.to;\n this.runState = state;\n this.event = { name: first.trigger.kind, id: first.trigger.id, data: first.trigger.data ?? null };\n }\n\n /** This function appends one entry. The appends of one run go in one order, and a conflict stops the run. */\n private write(entry: RunEntry): Promise<void> {\n const next = this.tail.then(async () => {\n await options.store.append(this.id, this.entries.length, entry);\n this.entries.push(entry);\n });\n this.tail = next.catch(() => undefined);\n return next;\n }\n\n private async move(event: string): Promise<void> {\n const t = transitionOn(RUN_MACHINE, this.runState, event);\n if (t === undefined) throw new Error(`The run machine has no transition on ${event} from ${this.runState}.`);\n await this.write({ type: \"transition\", machine: \"workflow.run\", instance: this.id, from: this.runState, on: event, to: t.to, time: wall() });\n this.runState = t.to;\n }\n\n private async finish(event: string, status: RunStatus, why: string): Promise<RunResult> {\n await this.move(event);\n await this.write({ type: \"end\", status, why, time: wall() });\n return { run: this.id, status, why, entries: this.entries };\n }\n\n private async ask(at: string, access: \"read\" | \"write\", target: unknown, from = this.first.owner): Promise<AccessAnswer> {\n let answer: AccessAnswer;\n if (typeof target !== \"string\" || target === \"\") answer = { ok: false, why: \"The target workspace is not a text.\" };\n else {\n try {\n const given = await options.access({ from, access, target });\n answer = isRecord(given) && given[\"ok\"] === true ? { ok: true, why: String(given[\"why\"] ?? \"\") } : { ok: false, why: String(fieldsOrEmpty(given)[\"why\"] ?? \"The grant check gave no grant.\") };\n } catch (error) {\n answer = { ok: false, why: `The grant check failed: ${error instanceof Error ? error.message : String(error)}` };\n }\n }\n await this.write({ type: \"grant\", at, from, access, target: typeof target === \"string\" ? target : JSON.stringify(target ?? null), ok: answer.ok, why: answer.why, time: wall() });\n return answer;\n }\n\n async go(): Promise<RunResult> {\n if (this.runState !== \"queued\" && this.runState !== \"running\") {\n // A crash after the last transition of the run and before its end: the end follows the transition.\n const status = this.runState as RunStatus;\n await this.write({ type: \"end\", status, why: \"The record ended after the last transition of the run.\", time: wall() });\n return { run: this.id, status, why: \"The record ended after the last transition of the run.\", entries: this.entries };\n }\n if (this.runState === \"queued\") {\n const reject = await this.precheck();\n if (reject !== undefined) return reject;\n await this.move(\"start\");\n }\n const jobs = fieldsOrEmpty(valueOf(this.doc)[\"jobs\"]);\n const order = jobOrder(jobs) ?? [];\n const done = new Map<string, { status: StepStatus; outputs: unknown }>();\n const running = new Map<string, Promise<void>>();\n const waiting = [...order];\n while (waiting.length > 0 || running.size > 0) {\n for (const id of [...waiting]) {\n if (running.size >= limits.jobs) break;\n const needs = listOf(valueOf(jobs[id])[\"needs\"]) as readonly string[];\n if (!needs.every((need) => done.has(need))) continue;\n waiting.splice(waiting.indexOf(id), 1);\n const task = this.job(id, jobs[id], needs, done).then((end) => {\n done.set(id, end);\n running.delete(id);\n });\n running.set(id, task);\n }\n if (running.size > 0) await Promise.race(running.values());\n }\n if (this.halt !== undefined) return this.finish(this.halt.status === \"refused\" ? \"refuse\" : \"doubt\", this.halt.status, this.halt.why);\n if (this.failed) return this.finish(\"fail\", \"failed\", \"A job failed.\");\n return this.finish(\"succeed\", \"succeeded\", \"Each job succeeded or was skipped.\");\n }\n\n /** The checks before the first effect: the document, the owner and the trigger. */\n private async precheck(): Promise<RunResult | undefined> {\n const problems = [\n ...checkWorkflow(this.doc, { machine, procedures: options.procedures, callNamespaces: options.callNamespaces ?? [] })\n .filter((issue) => issue.level === \"error\")\n .map((issue) => `${issue.code}: ${issue.message}`),\n ...runnerProblems(this.doc, limits),\n ];\n if (problems.length > 0) return this.finish(\"reject\", \"invalid\", problems.join(\" \"));\n if (this.first.workspace !== this.first.owner) {\n return this.finish(\"refuse\", \"refused\", `The document names the workspace ${JSON.stringify(this.first.workspace)}, and the workspace ${this.first.owner} holds it.`);\n }\n const trigger = this.first.trigger;\n if (trigger.kind === \"feed\") {\n const answer = await this.ask(\"trigger\", \"read\", trigger.from);\n if (!answer.ok) return this.finish(\"refuse\", \"refused\", `The feed cannot read ${String(trigger.from)}: ${answer.why}`);\n }\n if (trigger.kind === \"call\") {\n const answer = await this.ask(\"trigger\", \"write\", this.first.owner, typeof trigger.caller === \"string\" ? trigger.caller : \"\");\n if (!answer.ok) return this.finish(\"refuse\", \"refused\", `The caller ${String(trigger.caller)} cannot start a workflow of ${this.first.owner}: ${answer.why}`);\n }\n return undefined;\n }\n\n /** This function evaluates one part with no capability: a call in it gives `#CAP!`. */\n private async part(doc: unknown, names: Rec): Promise<unknown> {\n if (!isEnvelope(doc)) return doc;\n const ran = await run(machine, doc, context({ names, event: this.event }), { perform: () => {\n throw new Failure({ code: \"#CAP!\", reason: \"Only the field do of a step can call a procedure.\" });\n } });\n if (!ran.result.ok) throw new PartError(`${ran.result.error.code} ${ran.result.error.reason}`);\n return ran.result.value;\n }\n\n private async terms(record: unknown, names: Rec): Promise<Record<string, unknown>> {\n const out: Record<string, unknown> = {};\n for (const [key, doc] of Object.entries(fieldsOrEmpty(isEnvelope(record) && record.type === \"record\" ? record.value : record))) out[key] = await this.part(doc, names);\n return out;\n }\n\n private async job(id: string, job: unknown, needs: readonly string[], done: ReadonlyMap<string, { status: StepStatus; outputs: unknown }>): Promise<{ status: StepStatus; outputs: unknown }> {\n const recorded = this.prior.jobs.get(id);\n if (recorded !== undefined) return { status: recorded.status, outputs: recorded.outputs ?? {} };\n const end = async (status: StepStatus, outputs: unknown = {}): Promise<{ status: StepStatus; outputs: unknown }> => {\n await this.write({ type: \"job-end\", instance: id, status, ...(outputs === undefined ? {} : { outputs }), time: wall() });\n return { status, outputs };\n };\n const j = valueOf(job);\n if (this.halt !== undefined) return end(\"cancelled\");\n const needNames: Record<string, unknown> = {};\n for (const need of needs) needNames[need] = { result: done.get(need)?.status, outputs: done.get(need)?.outputs ?? {} };\n if (needs.some((need) => done.get(need)?.status !== \"succeeded\")) return end(\"skipped\");\n const inputs = this.first.inputs;\n try {\n const workflowEnv = await this.terms(valueOf(this.doc)[\"env\"], { inputs });\n const base = { inputs, needs: needNames };\n if (j[\"if\"] !== undefined && (await this.part(j[\"if\"], { ...base, env: workflowEnv })) !== true) return end(\"skipped\");\n let rows = this.prior.rows.get(id);\n if (rows === undefined && j[\"matrix\"] !== undefined) {\n const value = await this.part(j[\"matrix\"], base);\n if (!Array.isArray(value)) throw new PartError(\"The matrix gives no list of rows.\");\n if (value.length > limits.matrix) {\n this.failed = true;\n throw new PartError(`The matrix has ${String(value.length)} rows. The limit is ${String(limits.matrix)}.`);\n }\n rows = value;\n await this.write({ type: \"rows\", job: id, rows: value, time: wall() });\n }\n const seen = new Map<string, number>();\n const instances = rows === undefined ? [{ key: id, row: undefined }] : rows.map((row) => {\n const hash = rowKey(row);\n const count = (seen.get(hash) ?? 0) + 1;\n seen.set(hash, count);\n return { key: `${id}[${hash}${count > 1 ? `~${String(count)}` : \"\"}]`, row };\n });\n let status: StepStatus = \"succeeded\";\n let outputs: unknown = {};\n // The time limit of the job counts from its start in this process. Each step of the job ends by it.\n const deadline = typeof j[\"timeout\"] === \"number\" ? options.clock.now() + j[\"timeout\"] * 1000 : undefined;\n for (const instance of instances) {\n const ended = await this.instance(instance.key, j, { ...base, ...(instance.row === undefined ? {} : { matrix: instance.row }) }, workflowEnv, deadline);\n if (ended.status !== \"succeeded\") status = ended.status;\n outputs = ended.outputs;\n }\n if (status !== \"succeeded\") this.failed = true;\n return end(status, outputs);\n } catch (error) {\n if (!(error instanceof PartError)) throw error;\n this.failed = true;\n return end(\"failed\", { error: error.message });\n }\n }\n\n /** One job instance: its steps in order. */\n private async instance(key: string, j: Rec, base: Rec, workflowEnv: Rec, deadline: number | undefined): Promise<{ status: StepStatus; outputs: unknown }> {\n const jobEnv = { ...workflowEnv, ...(await this.terms(j[\"env\"], { ...base, env: workflowEnv })) };\n const steps: Record<string, unknown> = {};\n let failedBefore = false;\n for (const step of listOf(j[\"steps\"])) {\n const s = valueOf(step);\n const instance = `${key}/${String(s[\"id\"])}`;\n const status = await this.step(instance, s, { ...base, env: jobEnv, job: { status: failedBefore ? \"failure\" : \"success\" }, steps }, failedBefore, (value) => {\n steps[String(s[\"id\"])] = value;\n }, deadline);\n if (status === \"failed\" && s[\"continue\"] !== true) failedBefore = true;\n if (status === \"timed-out\" || status === \"cancelled\") failedBefore = true;\n if (status === \"refused\" || status === \"in-doubt\") return { status, outputs: {} };\n }\n if (failedBefore) return { status: \"failed\", outputs: {} };\n const outputs = await this.terms(j[\"outputs\"], { ...base, env: jobEnv, steps });\n return { status: \"succeeded\", outputs: options.redact(outputs) };\n }\n\n private async stepMove(instance: string, state: { value: string }, event: string, due?: number): Promise<void> {\n const t = transitionOn(STEP_MACHINE, state.value, event);\n if (t === undefined) throw new Error(`The step machine has no transition on ${event} from ${state.value}.`);\n await this.write({ type: \"transition\", machine: \"workflow.step\", instance, from: state.value, on: event, to: t.to, time: wall(), ...(due === undefined ? {} : { due }) });\n state.value = t.to;\n }\n\n private async stepEnd(instance: string, status: StepStatus, value?: unknown): Promise<StepStatus> {\n await this.write({ type: \"step-end\", instance, status, ...(value === undefined ? {} : { value }), time: wall() });\n return status;\n }\n\n /** One step: its condition, its tries, its time limit, and the grant check at each effect. */\n private async step(instance: string, s: Rec, names: Rec, failedBefore: boolean, keep: (value: unknown) => void, deadline?: number): Promise<StepStatus> {\n const recorded = this.prior.steps.get(instance);\n if (recorded !== undefined) {\n if (recorded.status === \"succeeded\") keep(recorded.value);\n return recorded.status;\n }\n const was = this.prior.states.get(instance);\n const state = { value: was?.state ?? \"pending\" };\n const env = { ...fieldsOrEmpty(names[\"env\"]), ...(await this.terms(s[\"env\"], names)) };\n const scope = { ...names, env };\n if (this.halt !== undefined || (state.value === \"pending\" && deadline !== undefined && options.clock.now() >= deadline)) {\n await this.stepMove(instance, state, \"cancel\");\n return this.stepEnd(instance, \"cancelled\");\n }\n if (state.value !== \"pending\" && state.value !== \"running\" && state.value !== \"waiting\") {\n // A crash after the last transition of the step and before its end: the end follows the transition.\n if (state.value !== \"succeeded\") return this.stepEnd(instance, state.value as StepStatus, { why: \"The record ended after the last transition of the step.\" });\n const outcome = await this.attempt(instance, s, scope, Math.max(was?.runs ?? 1, 1));\n if (outcome.kind !== \"ok\") throw new Error(`The step ${instance} succeeded in its record, and its replay gives no value.`);\n const value = options.redact(outcome.value);\n keep(value);\n return this.stepEnd(instance, \"succeeded\", value);\n }\n if (state.value === \"pending\") {\n const go = s[\"if\"] === undefined ? !failedBefore : (await this.part(s[\"if\"], scope)) === true;\n if (!go) {\n await this.stepMove(instance, state, \"skip\");\n return this.stepEnd(instance, \"skipped\");\n }\n }\n const retry = fieldsOrEmpty(s[\"retry\"]);\n const tries = typeof retry[\"tries\"] === \"number\" ? retry[\"tries\"] : 1;\n let attempt = was?.runs ?? 0;\n if (state.value === \"waiting\") {\n await this.wait((was?.due ?? wall()) - wall());\n await this.stepMove(instance, state, \"due\");\n } else if (state.value === \"pending\") {\n await this.stepMove(instance, state, \"run\");\n attempt += 1;\n }\n // A resume in the state running continues the same try: its effects replay, and an open effect is in doubt.\n if (attempt === 0) attempt = 1;\n for (;;) {\n const outcome = await this.attempt(instance, s, scope, attempt, deadline);\n if (outcome.kind === \"ok\") {\n await this.stepMove(instance, state, \"succeed\");\n const value = options.redact(outcome.value);\n keep(value);\n return this.stepEnd(instance, \"succeeded\", value);\n }\n if (outcome.kind === \"halt\") {\n this.halt ??= { status: outcome.status, why: outcome.why };\n await this.stepMove(instance, state, outcome.status === \"refused\" ? \"refuse\" : \"doubt\");\n return this.stepEnd(instance, outcome.status, { why: outcome.why });\n }\n if (attempt >= tries || this.halt !== undefined) {\n await this.stepMove(instance, state, outcome.kind === \"expired\" ? \"expire\" : \"fail\");\n return this.stepEnd(instance, outcome.kind === \"expired\" ? \"timed-out\" : \"failed\", { why: outcome.why });\n }\n const delay = backoffDelay({ base: 1000 * Number(retry[\"delay\"] ?? 1), factor: Number(retry[\"factor\"] ?? 2), ...(retry[\"cap\"] === undefined ? {} : { cap: 1000 * Number(retry[\"cap\"]) }) }, attempt);\n await this.stepMove(instance, state, \"retry\", wall() + delay);\n await this.wait(delay);\n await this.stepMove(instance, state, \"due\");\n attempt += 1;\n }\n }\n\n private wait(ms: number): Promise<void> {\n if (ms <= 0) return Promise.resolve();\n return new Promise((resolve) => options.clock.after(ms, resolve));\n }\n\n /** One try of a step. */\n private async attempt(instance: string, s: Rec, scope: Rec, attempt: number, deadline?: number): Promise<{ kind: \"ok\"; value: unknown } | { kind: \"fail\" | \"expired\"; why: string } | { kind: \"halt\"; status: \"refused\" | \"in-doubt\"; why: string }> {\n const controller = new AbortController();\n const own = typeof s[\"timeout\"] === \"number\" ? s[\"timeout\"] * 1000 : Infinity;\n const left = deadline === undefined ? Infinity : Math.max(0, deadline - options.clock.now());\n const timeout = Math.min(own, left) === Infinity ? undefined : Math.min(own, left);\n let expired = false;\n const cancel = timeout === undefined ? undefined : options.clock.after(timeout, () => {\n expired = true;\n controller.abort(new Error(\"The time limit of the step ended.\"));\n });\n const open = new Set<string>();\n let halt: Halt | undefined;\n const perform = async (effect: Effect): Promise<unknown> => {\n try {\n return await this.effect(instance, attempt, effect, controller.signal, open);\n } catch (error) {\n if (error instanceof Halt) halt ??= error;\n throw error;\n }\n };\n try {\n const ran = await run(machine, s[\"do\"], context({ names: scope, event: this.event, caps: callCaps }), { perform, signal: controller.signal });\n if (halt !== undefined) return { kind: \"halt\", status: halt.status, why: halt.message };\n if (expired) {\n const doubt = [...open].find((at) => !this.idempotent(at));\n if (doubt !== undefined) return { kind: \"halt\", status: \"in-doubt\", why: `The time limit ended while the effect ${doubt} ran. Its procedure does not remove a second call.` };\n return { kind: \"expired\", why: \"The time limit of the step ended.\" };\n }\n if (!ran.result.ok) return { kind: \"fail\", why: `${ran.result.error.code} ${String(options.redact(ran.result.error.reason))}` };\n return { kind: \"ok\", value: ran.result.value };\n } finally {\n cancel?.();\n }\n }\n\n private readonly procedureAt = new Map<string, string>();\n\n private idempotent(at: string): boolean {\n const name = this.procedureAt.get(at);\n return name !== undefined && options.procedures[name]?.idempotent === true;\n }\n\n /** One effect: the replay of its record, or the grant check and the live call. */\n private async effect(instance: string, attempt: number, effect: Effect, signal: AbortSignal, open: Set<string>): Promise<unknown> {\n const address = effect.address ?? `#${String(effect.index)}`;\n const at = `${instance}@${String(attempt)}/${address}`;\n const key = `${this.id}/${instance}/${address}`;\n const ended = this.prior.ends.get(at);\n if (ended !== undefined) {\n if (ended.ok) return ended.value;\n throw new Failure({ code: ended.code as `#${string}`, reason: ended.why });\n }\n const refuse = async (why: string): Promise<never> => {\n await this.write({ type: \"effect-end\", at, outcome: { ok: false, code: \"#GRANT!\", why }, time: wall() });\n throw new Halt(\"refused\", why);\n };\n const namespace = String(effect.path[0]);\n if (!namespaces.includes(namespace)) return refuse(`The effect ${effect.kind} is not a call.`);\n const name = (namespace === \"procedure\" ? effect.path.slice(1) : effect.path).map(String).join(\".\");\n this.procedureAt.set(at, name);\n const info = options.procedures[name];\n if (info === undefined) return refuse(`No procedure ${name} is known, thus no grant covers it.`);\n if (!isRecord(effect.payload)) return refuse(`The inputs of ${name} are not a record.`);\n const payload = effect.payload;\n for (const access of [\"read\", \"write\"] as const) {\n for (const input of info.workspaces?.[access] ?? []) {\n const answer = await this.ask(at, access, payload[input]);\n if (!answer.ok) return refuse(`The workspace ${this.first.owner} cannot ${access} ${JSON.stringify(payload[input] ?? null)} (the input ${input} of ${name}): ${answer.why}`);\n }\n }\n if (this.prior.starts.has(at) && info.idempotent !== true) {\n throw new Halt(\"in-doubt\", `The effect ${at} started before and has no outcome. The procedure ${name} does not remove a second call.`);\n }\n if (!this.prior.starts.has(at)) {\n await this.write({ type: \"effect-start\", at, key, try: attempt, procedure: name, payload: options.redact(payload), time: wall() });\n }\n open.add(at);\n let outcome: Outcome;\n try {\n const value = options.redact(await options.call({ procedure: name.split(\".\"), inputs: payload, key, try: attempt, workspace: this.first.owner, signal }));\n const bytes = JSON.stringify(value ?? null).length;\n outcome = bytes > limits.outcomeBytes ? { ok: false, code: \"#SIZE!\", why: `The outcome has ${String(bytes)} bytes. The limit is ${String(limits.outcomeBytes)}.` } : { ok: true, value: value ?? null };\n } catch (error) {\n if (signal.aborted) throw error;\n const code = error instanceof Failure ? error.error.code : \"#CALL!\";\n const why = error instanceof Failure ? error.error.reason : error instanceof Error ? error.message : String(error);\n outcome = { ok: false, code, why: String(options.redact(why)) };\n }\n await this.write({ type: \"effect-end\", at, outcome, time: wall() });\n open.delete(at);\n if (outcome.ok) return outcome.value;\n throw new Failure({ code: outcome.code as `#${string}`, reason: outcome.why });\n }\n }\n\n return { runIdOf, start, resume };\n}\n","/** The final status of a run. */\nexport type RunStatus = \"succeeded\" | \"failed\" | \"refused\" | \"invalid\" | \"in-doubt\" | \"cancelled\";\n\n/** The final status of a step. */\nexport type StepStatus = \"succeeded\" | \"skipped\" | \"failed\" | \"timed-out\" | \"refused\" | \"in-doubt\" | \"cancelled\";\n\n/** The event that started a run. `id` makes the run id: the same event gives the same run. */\nexport interface TriggerEvent {\n /** The kind of the trigger: `manual`, `schedule`, `event`, `feed` or `call`. */\n readonly kind: string;\n /** The id of the event, for example the id of a delivery or the time of a schedule boundary. */\n readonly id: string;\n /** The data of the event. A reference reads it as `event`. */\n readonly data?: unknown;\n /** For a feed: the workspace that the feed reads. */\n readonly from?: string;\n /** For a call: the workspace of the caller. */\n readonly caller?: string;\n}\n\n/** The outcome of one effect, after the redaction of the host. */\nexport type Outcome = { readonly ok: true; readonly value: unknown } | { readonly ok: false; readonly code: string; readonly why: string };\n\n/** One entry of the record of a run. The record is append-only, and it is also the log of a resume. */\nexport type RunEntry =\n | {\n readonly type: \"start\";\n readonly run: string;\n readonly docHash: string;\n readonly doc: unknown;\n readonly owner: string;\n readonly workspace: unknown;\n readonly trigger: TriggerEvent;\n readonly inputs: unknown;\n readonly time: number;\n }\n | { readonly type: \"grant\"; readonly at: string; readonly from: string; readonly access: \"read\" | \"write\"; readonly target: string; readonly ok: boolean; readonly why: string; readonly time: number }\n | { readonly type: \"transition\"; readonly machine: \"workflow.run\" | \"workflow.step\"; readonly instance: string; readonly from: string; readonly on: string; readonly to: string; readonly time: number; readonly due?: number }\n | { readonly type: \"rows\"; readonly job: string; readonly rows: readonly unknown[]; readonly time: number }\n | { readonly type: \"effect-start\"; readonly at: string; readonly key: string; readonly try: number; readonly procedure: string; readonly payload: unknown; readonly time: number }\n | { readonly type: \"effect-end\"; readonly at: string; readonly outcome: Outcome; readonly time: number }\n | { readonly type: \"step-end\"; readonly instance: string; readonly status: StepStatus; readonly value?: unknown; readonly time: number }\n | { readonly type: \"job-end\"; readonly instance: string; readonly status: StepStatus; readonly outputs?: unknown; readonly time: number }\n | { readonly type: \"end\"; readonly status: RunStatus; readonly why: string; readonly time: number };\n\n/** The answer of a store to an append that another writer took first. */\nexport class RecordConflict extends Error {\n /** The count of the entries that the store holds. */\n readonly length: number;\n\n /**\n * This constructor makes the error.\n *\n * @param run - The run id.\n * @param seq - The place that the writer asked for.\n * @param length - The count of the entries that the store holds.\n */\n constructor(run: string, seq: number, length: number) {\n super(`The record of the run ${run} has ${String(length)} entries, not ${String(seq)}. Another runner writes it.`);\n this.name = \"RecordConflict\";\n this.length = length;\n }\n}\n\n/**\n * The store of the records of the runs. An append gives the place of the entry. When the record has another length,\n * the store refuses with `RecordConflict`. Thus two runners cannot write one run (a fenced append).\n */\nexport interface RunStore {\n /** This function appends one entry at the place `seq`, or it refuses with `RecordConflict`. */\n readonly append: (run: string, seq: number, entry: RunEntry) => Promise<void> | void;\n /** This function gives the entries of a run in their order. A run with no record gives an empty list. */\n readonly read: (run: string) => Promise<readonly RunEntry[]> | readonly RunEntry[];\n}\n\n/** A store in memory, for tests and for a host with no durable store. Each entry is a copy as JSON. */\nexport function memoryStore(): RunStore & { readonly runs: () => readonly string[] } {\n const records = new Map<string, RunEntry[]>();\n return {\n append(run, seq, entry) {\n const list = records.get(run) ?? [];\n if (seq !== list.length) throw new RecordConflict(run, seq, list.length);\n list.push(JSON.parse(JSON.stringify(entry)) as RunEntry);\n records.set(run, list);\n },\n read: (run) => [...(records.get(run) ?? [])],\n runs: () => [...records.keys()],\n };\n}\n"],"mappings":";;;;;;;AAEA,MAAM,UAA8B,CAAC;CAAE,KAAK;CAAkC,MAAM;CAAe,MAAM;AAAO,CAAC;;;;;AAMjH,MAAa,cAAuB;CAClC,QAAQ;CACR,IAAI;CACJ,OAAO;CACP,OAAO;CACP,SAAS;CACT,SAAS;CACT,QAAQ;EACN,QAAQ,EAAE,SAAS,KAAK;EACxB,SAAS,CAAC;EACV,WAAW,EAAE,OAAO,KAAK;EACzB,QAAQ,EAAE,OAAO,KAAK;EACtB,SAAS;GAAE,OAAO;GAAM,MAAM;EAA0E;EACxG,SAAS;GAAE,OAAO;GAAM,MAAM;EAAiD;EAC/E,YAAY;GAAE,OAAO;GAAM,MAAM;EA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O,EAAE;GACd,IAAI,QAAQ,IAAI,OAAO,QAAQ;GAC/B,MAAM,IAAI,QAAQ;IAAE,MAAM,QAAQ;IAAsB,QAAQ,QAAQ;GAAI,CAAC;EAC/E;CACF;CAEA,OAAO;EAAE;EAAS;EAAO;CAAO;AAClC;;;ACvmBA,IAAa,iBAAb,cAAoC,MAAM;;CAE/B;;;;;;;;CAST,YAAY,KAAa,KAAa,QAAgB;EACpD,MAAM,yBAAyB,IAAI,OAAO,OAAO,MAAM,EAAE,gBAAgB,OAAO,GAAG,EAAE,4BAA4B;EACjH,KAAK,OAAO;EACZ,KAAK,SAAS;CAChB;AACF;;AAcA,SAAgB,cAAqE;CACnF,MAAM,0BAAU,IAAI,IAAwB;CAC5C,OAAO;EACL,OAAO,KAAK,KAAK,OAAO;GACtB,MAAM,OAAO,QAAQ,IAAI,GAAG,KAAK,CAAC;GAClC,IAAI,QAAQ,KAAK,QAAQ,MAAM,IAAI,eAAe,KAAK,KAAK,KAAK,MAAM;GACvE,KAAK,KAAK,KAAK,MAAM,KAAK,UAAU,KAAK,CAAC,CAAa;GACvD,QAAQ,IAAI,KAAK,IAAI;EACvB;EACA,OAAO,QAAQ,CAAC,GAAI,QAAQ,IAAI,GAAG,KAAK,CAAC,CAAE;EAC3C,YAAY,CAAC,GAAG,QAAQ,KAAK,CAAC;CAChC;AACF"}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { c as StartRequest, i as RunResult, l as WorkflowRunner } from "./engine-B_0OOo1N.js";
|
|
2
|
+
/** The answer of a queue to an offer. */
|
|
3
|
+
export type OfferAnswer = {
|
|
4
|
+
readonly accepted: true;
|
|
5
|
+
readonly run: string;
|
|
6
|
+
} | {
|
|
7
|
+
readonly accepted: false;
|
|
8
|
+
readonly run: string;
|
|
9
|
+
readonly why: "duplicate" | "full" | "closed";
|
|
10
|
+
};
|
|
11
|
+
/** A queue of runs. The host gives `next` to the `iteration` of a worker loop of `@mark1russell7/service`. */
|
|
12
|
+
export interface RunQueue {
|
|
13
|
+
/** This function offers a request. A full queue refuses it at once: the caller keeps the event and offers it again later. */
|
|
14
|
+
readonly offer: (request: StartRequest) => OfferAnswer;
|
|
15
|
+
/** This function waits for one request, and runs it. It rejects when the queue is closed and empty. */
|
|
16
|
+
readonly next: () => Promise<RunResult>;
|
|
17
|
+
/** This function closes the queue. The requests in it stay, and `next` takes them. */
|
|
18
|
+
readonly close: () => void;
|
|
19
|
+
/** The count of the requests that wait. */
|
|
20
|
+
readonly size: () => number;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* This function makes a queue of runs with a bound. The same event gives the same run id, thus a second offer of a run
|
|
24
|
+
* that waits or runs is a duplicate. The store removes a duplicate after the end: `start` gives the recorded end.
|
|
25
|
+
*
|
|
26
|
+
* @param runner - The runner.
|
|
27
|
+
* @param capacity - The most requests that wait.
|
|
28
|
+
* @returns The queue.
|
|
29
|
+
*/
|
|
30
|
+
export declare function runQueue(runner: WorkflowRunner, capacity: number): RunQueue;
|
|
31
|
+
//# sourceMappingURL=service.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"service.d.ts","names":[],"sources":["../src/service.ts"],"mappings":";;YAIY;WAAyB;WAAyB;;WAA2B;WAA0B;WAAsB;;;iBAGxH;;WAEN,QAAQ,SAAS,iBAAiB;;WAElC,YAAY,QAAQ;;WAEpB;;WAEA;;;;;;;;;;wBAWK,SAAS,QAAQ,gBAAgB,mBAAmB"}
|
package/build/service.js
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { Channel } from "@mark1russell7/service/channel";
|
|
2
|
+
// src/service.ts
|
|
3
|
+
/**
|
|
4
|
+
* This function makes a queue of runs with a bound. The same event gives the same run id, thus a second offer of a run
|
|
5
|
+
* that waits or runs is a duplicate. The store removes a duplicate after the end: `start` gives the recorded end.
|
|
6
|
+
*
|
|
7
|
+
* @param runner - The runner.
|
|
8
|
+
* @param capacity - The most requests that wait.
|
|
9
|
+
* @returns The queue.
|
|
10
|
+
*/
|
|
11
|
+
function runQueue(runner, capacity) {
|
|
12
|
+
if (!Number.isInteger(capacity) || capacity < 1) throw new RangeError("The capacity of a run queue must be a whole number of 1 or more.");
|
|
13
|
+
const channel = new Channel(capacity);
|
|
14
|
+
const live = /* @__PURE__ */ new Set();
|
|
15
|
+
return {
|
|
16
|
+
offer(request) {
|
|
17
|
+
const run = runner.runIdOf(request);
|
|
18
|
+
if (channel.isClosed) return {
|
|
19
|
+
accepted: false,
|
|
20
|
+
run,
|
|
21
|
+
why: "closed"
|
|
22
|
+
};
|
|
23
|
+
if (live.has(run)) return {
|
|
24
|
+
accepted: false,
|
|
25
|
+
run,
|
|
26
|
+
why: "duplicate"
|
|
27
|
+
};
|
|
28
|
+
if (!channel.trySend(request)) return {
|
|
29
|
+
accepted: false,
|
|
30
|
+
run,
|
|
31
|
+
why: "full"
|
|
32
|
+
};
|
|
33
|
+
live.add(run);
|
|
34
|
+
return {
|
|
35
|
+
accepted: true,
|
|
36
|
+
run
|
|
37
|
+
};
|
|
38
|
+
},
|
|
39
|
+
async next() {
|
|
40
|
+
const request = await channel.receive();
|
|
41
|
+
const run = runner.runIdOf(request);
|
|
42
|
+
try {
|
|
43
|
+
return await runner.start(request);
|
|
44
|
+
} finally {
|
|
45
|
+
live.delete(run);
|
|
46
|
+
}
|
|
47
|
+
},
|
|
48
|
+
close: () => {
|
|
49
|
+
channel.close();
|
|
50
|
+
},
|
|
51
|
+
size: () => channel.size
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
export { runQueue };
|
|
55
|
+
|
|
56
|
+
//# sourceMappingURL=service.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"service.js","names":[],"sources":["../src/service.ts"],"sourcesContent":["import { Channel } from \"@mark1russell7/service/channel\";\nimport type { RunResult, StartRequest, WorkflowRunner } from \"./engine.ts\";\n\n/** The answer of a queue to an offer. */\nexport type OfferAnswer = { readonly accepted: true; readonly run: string } | { readonly accepted: false; readonly run: string; readonly why: \"duplicate\" | \"full\" | \"closed\" };\n\n/** A queue of runs. The host gives `next` to the `iteration` of a worker loop of `@mark1russell7/service`. */\nexport interface RunQueue {\n /** This function offers a request. A full queue refuses it at once: the caller keeps the event and offers it again later. */\n readonly offer: (request: StartRequest) => OfferAnswer;\n /** This function waits for one request, and runs it. It rejects when the queue is closed and empty. */\n readonly next: () => Promise<RunResult>;\n /** This function closes the queue. The requests in it stay, and `next` takes them. */\n readonly close: () => void;\n /** The count of the requests that wait. */\n readonly size: () => number;\n}\n\n/**\n * This function makes a queue of runs with a bound. The same event gives the same run id, thus a second offer of a run\n * that waits or runs is a duplicate. The store removes a duplicate after the end: `start` gives the recorded end.\n *\n * @param runner - The runner.\n * @param capacity - The most requests that wait.\n * @returns The queue.\n */\nexport function runQueue(runner: WorkflowRunner, capacity: number): RunQueue {\n if (!Number.isInteger(capacity) || capacity < 1) throw new RangeError(\"The capacity of a run queue must be a whole number of 1 or more.\");\n const channel = new Channel<StartRequest>(capacity);\n const live = new Set<string>();\n return {\n offer(request) {\n const run = runner.runIdOf(request);\n if (channel.isClosed) return { accepted: false, run, why: \"closed\" };\n if (live.has(run)) return { accepted: false, run, why: \"duplicate\" };\n if (!channel.trySend(request)) return { accepted: false, run, why: \"full\" };\n live.add(run);\n return { accepted: true, run };\n },\n async next() {\n const request = await channel.receive();\n const run = runner.runIdOf(request);\n try {\n return await runner.start(request);\n } finally {\n live.delete(run);\n }\n },\n close: () => {\n channel.close();\n },\n size: () => channel.size,\n };\n}\n"],"mappings":";;;;;;;;;;AA0BA,SAAgB,SAAS,QAAwB,UAA4B;CAC3E,IAAI,CAAC,OAAO,UAAU,QAAQ,KAAK,WAAW,GAAG,MAAM,IAAI,WAAW,kEAAkE;CACxI,MAAM,UAAU,IAAI,QAAsB,QAAQ;CAClD,MAAM,uBAAO,IAAI,IAAY;CAC7B,OAAO;EACL,MAAM,SAAS;GACb,MAAM,MAAM,OAAO,QAAQ,OAAO;GAClC,IAAI,QAAQ,UAAU,OAAO;IAAE,UAAU;IAAO;IAAK,KAAK;GAAS;GACnE,IAAI,KAAK,IAAI,GAAG,GAAG,OAAO;IAAE,UAAU;IAAO;IAAK,KAAK;GAAY;GACnE,IAAI,CAAC,QAAQ,QAAQ,OAAO,GAAG,OAAO;IAAE,UAAU;IAAO;IAAK,KAAK;GAAO;GAC1E,KAAK,IAAI,GAAG;GACZ,OAAO;IAAE,UAAU;IAAM;GAAI;EAC/B;EACA,MAAM,OAAO;GACX,MAAM,UAAU,MAAM,QAAQ,QAAQ;GACtC,MAAM,MAAM,OAAO,QAAQ,OAAO;GAClC,IAAI;IACF,OAAO,MAAM,OAAO,MAAM,OAAO;GACnC,UAAU;IACR,KAAK,OAAO,GAAG;GACjB;EACF;EACA,aAAa;GACX,QAAQ,MAAM;EAChB;EACA,YAAY,QAAQ;CACtB;AACF"}
|
package/package.json
CHANGED
|
@@ -1,13 +1,56 @@
|
|
|
1
1
|
{
|
|
2
|
+
"$schema": "https://json.schemastore.org/package",
|
|
2
3
|
"name": "@mark1russell7/workflow-runner",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
7
|
-
"
|
|
4
|
+
"version": "0.1.0",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./build/index.js",
|
|
7
|
+
"devDependencies": {
|
|
8
|
+
"@mark1russell7/cue": "^2.1.1",
|
|
9
|
+
"@types/node": "^26.6.4",
|
|
10
|
+
"@vitest/coverage-v8": "^5.0.3",
|
|
11
|
+
"typescript": "^7.0.2",
|
|
12
|
+
"vitest": "^5.0.3"
|
|
8
13
|
},
|
|
9
|
-
"
|
|
14
|
+
"exports": {
|
|
15
|
+
".": {
|
|
16
|
+
"types": "./build/index.d.ts",
|
|
17
|
+
"default": "./build/index.js"
|
|
18
|
+
},
|
|
19
|
+
"./service": {
|
|
20
|
+
"types": "./build/service.d.ts",
|
|
21
|
+
"default": "./build/service.js"
|
|
22
|
+
},
|
|
23
|
+
"./package.json": "./package.json"
|
|
24
|
+
},
|
|
25
|
+
"files": [
|
|
26
|
+
"build",
|
|
27
|
+
"src",
|
|
28
|
+
"!src/**/*.test.ts"
|
|
29
|
+
],
|
|
10
30
|
"publishConfig": {
|
|
11
31
|
"access": "public"
|
|
12
|
-
}
|
|
13
|
-
|
|
32
|
+
},
|
|
33
|
+
"sideEffects": false,
|
|
34
|
+
"description": "The runner of a workflow document: the order of the jobs, a grant check at each effect, a record of each run, and a resume that replays its record.",
|
|
35
|
+
"dependencies": {
|
|
36
|
+
"@mark1russell7/algebra": "^0.9.18",
|
|
37
|
+
"@mark1russell7/coeval": "0.39.1",
|
|
38
|
+
"@mark1russell7/optional": "^1.6.0",
|
|
39
|
+
"@mark1russell7/rigor-generators": "^0.2.10",
|
|
40
|
+
"@mark1russell7/service": "^0.13.7",
|
|
41
|
+
"@mark1russell7/workflow": "0.1.0"
|
|
42
|
+
},
|
|
43
|
+
"license": "MIT",
|
|
44
|
+
"repository": {
|
|
45
|
+
"type": "git",
|
|
46
|
+
"url": "git+https://github.com/mark1russell7/coeval.git",
|
|
47
|
+
"directory": "packages/workflow-runner"
|
|
48
|
+
},
|
|
49
|
+
"scripts": {
|
|
50
|
+
"build": "tsdown",
|
|
51
|
+
"test": "vitest run",
|
|
52
|
+
"test:watch": "vitest",
|
|
53
|
+
"typecheck": "tsc -p tsconfig.json && tsc -p tsconfig.test.json"
|
|
54
|
+
},
|
|
55
|
+
"types": "./build/index.d.ts"
|
|
56
|
+
}
|