Class WorkflowAbstract

The base class of every workflow. A class extending it is the workflow's own code: its fields are what the workflow needs, given to its constructor, and its methods are what its decorators mark, such as its ID generator.

The static build() makes the workflow object an application runs, never new, or builder() when it adds to what the decorators declared or puts the workflow together without them, and the object's instance() makes one instance of the workflow per journey. A workflow inherits nothing the executor calls: the executor reads the workflow's WorkflowDescriptor, which build() gives the object.

import assert from "node:assert/strict";
import type { Event } from "itinera/event";
import type { Reporter } from "itinera/report";
import { type Outcome, Step, step } from "itinera/step";
import { withStep, Workflow, workflow } from "itinera/workflow";

@step()
class Charge extends Step {
override run(): Outcome {
return this.succeed();
}
}

@step()
class Ship extends Step {
override run(): Outcome {
return this.succeed();
}
}

class Audit implements Reporter {
readonly kinds: string[] = [];

report(event: Event): void {
this.kinds.push(event.kind);
}
}

@workflow({ name: "orders", reporters: [Audit] })
@withStep(Charge, { name: "charge", retryBudget: 1 })
@withStep(Ship, { name: "ship" })
class Orders extends Workflow {
constructor(readonly shop: string) {
super();
}
}

const orders = Orders.build("corner");
const instance = orders.instance({
order: "1",
price: 40,
discount: undefined,
});

assert.equal(instance.workflow.shop, "corner");
assert.equal(instance.descriptor.name, "orders");
assert.deepEqual(
instance.descriptor.steps().map((described) => described.name),
["charge", "ship"],
);
assert.deepEqual(
[...instance.initialData],
[
["order", "1"],
["price", 40],
],
);

Index

  • What an input adapter returns to supply nothing, so that the input it is asked for is read from the data bag under its key.

    import assert from "node:assert/strict";
    import { LocalExecutor } from "itinera/executor";
    import {
    type Contributor,
    contributor,
    type DataBag,
    dataBag,
    type JourneyId,
    journeyId,
    } from "itinera/journey";
    import {
    input,
    type Outcome,
    type StepName,
    stepName,
    Step,
    step,
    } from "itinera/step";
    import {
    type FromDataBag,
    fromWorkflow,
    inputAdapter,
    type InputAdapterOptions,
    key,
    type Supplied,
    type SuppliedValue,
    withStep,
    Workflow,
    workflow,
    } from "itinera/workflow";
    import { integer, string } from "itinera/value";

    @step()
    class Charge extends Step {
    constructor(@input("amount", integer) readonly amount: number) {
    super();
    }

    override run(@contributor() contributor: Contributor): Outcome {
    contributor.contribute("charged", this.amount);
    return this.succeed();
    }
    }

    const adapting: InputAdapterOptions = { steps: ["charge"], name: "prices" };

    @workflow({ name: "orders" })
    @withStep(Charge, { name: "charge" })
    class Orders extends Workflow {
    readonly asked: string[] = [];

    constructor(readonly prices: ReadonlyMap<string, number>) {
    super();
    }

    @inputAdapter(adapting)
    price(
    @stepName() step: StepName,
    @key() key: string,
    @fromWorkflow("order", string) order: string,
    @journeyId() id: JourneyId,
    @dataBag() bag: DataBag,
    ): Supplied {
    this.asked.push(`${id}: ${step} ${key}`);
    const price = this.prices.get(order);
    return price === undefined || bag.read(key, integer).kind === "present"
    ? this.fromDataBag()
    : this.supply(price);
    }
    }

    export default (async () => {
    const orders = Orders.build(new Map([["A-1", 40]]));
    const supplying = orders.instance(new Map([["order", "A-1"]]));
    const reading = orders.instance(
    new Map<string, string | number>([
    ["order", "A-1"],
    ["amount", 25],
    ]),
    );

    const supplied = await new LocalExecutor().run(supplying);
    const read = await new LocalExecutor().run(reading);

    assert.ok(supplied.isSucceeded() && read.isSucceeded());
    assert.equal(charged(supplied.status.dataBag), 40);
    assert.equal(charged(read.status.dataBag), 25);
    assert.deepEqual(orders.asked, [
    `${supplying.journeyId}: charge amount`,
    `${reading.journeyId}: charge amount`,
    ]);
    const charge = "charge" as StepName;
    assert.deepEqual(
    orders.price(
    charge,
    "amount",
    "A-1",
    supplying.journeyId,
    supplied.status.dataBag,
    ),
    { kind: "supplied", value: 40 } satisfies SuppliedValue,
    );
    assert.deepEqual(
    orders.price(
    charge,
    "amount",
    "A-1",
    reading.journeyId,
    read.status.dataBag,
    ),
    { kind: "fromDataBag" } satisfies FromDataBag,
    );
    })();

    function charged(bag: DataBag): number {
    return bag.read("charged", integer).option().unwrap();
    }

    Returns Supplied

  • Makes one instance of the workflow, for one journey: its initial data, then its journey ID, made by the workflow's ID generator or as a random UUID, then its reporters, after those the workflow lists.

    Parameters

    • this: Built<Workflow>
    • OptionalinitialData: ValuesByKey

      The initial content of the data bag, checked when the instance is run.

    • Optionaloptions: InstanceOptions

      The instance's own reporters and initial global metadata.

    Returns WorkflowInstance<Workflow>

    Error if the object was not made by build().

    TypeError if the ID generator returns what is not a string, or an empty string.

    Whatever the ID generator, or a function making a reporter, throws.

  • What a service provider returns to lend instance to the step, with data for reporters, which compiles only when it is a value.

    import assert from "node:assert/strict";
    import { type JourneyId, journeyId } from "itinera/journey";
    import {
    type Provided,
    provider,
    type ProviderDecorator,
    type ProviderOptions,
    providerReporter,
    type ProviderReporter,
    service,
    serviceType,
    } from "itinera/service";
    import {
    Attempt,
    attempt,
    type Outcome,
    Step,
    step,
    type StepName,
    stepName,
    } from "itinera/step";
    import { withStep, Workflow, workflow } from "itinera/workflow";

    interface PaymentGateway {
    take(amount: number): string;
    }

    const PAYMENT_GATEWAY = serviceType<PaymentGateway>("PaymentGateway");

    @step()
    class Charge extends Step {
    override run(
    @service("payments", PAYMENT_GATEWAY) payments: PaymentGateway,
    ): Outcome {
    payments.take(40);
    return this.succeed();
    }
    }

    const perAttempt: ProviderOptions = {
    key: "payments",
    perAttempt: true,
    steps: ["charge"],
    name: "fresh gateway",
    };
    const journeyLong: ProviderDecorator<PaymentGateway> =
    provider(PAYMENT_GATEWAY);

    @workflow({ name: "orders" })
    @withStep(Charge, { name: "charge" })
    class Orders extends Workflow {
    @journeyLong
    async payments(
    @journeyId() id: JourneyId,
    @providerReporter() reporter: ProviderReporter,
    ): Promise<Provided<PaymentGateway>> {
    await reporter.info("gateway opened");
    return this.provide(
    { take: (amount) => `${id}: ${String(amount)}` },
    { region: "eu" },
    );
    }

    @provider(PAYMENT_GATEWAY, perAttempt)
    fresh(
    @stepName() step: StepName,
    @attempt() attempt: Attempt,
    ): Provided<PaymentGateway> {
    return this.provide({
    take: (amount) => `${step} ${String(attempt.number)}: ${String(amount)}`,
    });
    }
    }

    class Reported implements ProviderReporter {
    readonly lines: string[] = [];

    info(message: string): Promise<void> {
    return this.record(`info: ${message}`);
    }

    warning(message: string): Promise<void> {
    return this.record(`warning: ${message}`);
    }

    error(message: string): Promise<void> {
    return this.record(`error: ${message}`);
    }

    setGlobalMetadata(key: string): Promise<void> {
    return this.record(`metadata: ${key}`);
    }

    private record(line: string): Promise<void> {
    this.lines.push(line);
    return Promise.resolve();
    }
    }

    export default (async () => {
    const orders = Orders.build();
    const reporter = new Reported();

    const lent = await orders.payments("R-1" as JourneyId, reporter);
    const fresh = orders.fresh("charge" as StepName, Attempt.first);

    assert.equal(lent.instance.take(40), "R-1: 40");
    assert.deepEqual(lent.data, { region: "eu" });
    assert.deepEqual(reporter.lines, ["info: gateway opened"]);
    assert.equal(fresh.instance.take(40), "charge 1: 40");
    assert.equal(fresh.data, undefined);
    })();

    Type Parameters

    • T
    • D = undefined

    Parameters

    Returns Provided<T>

  • What an input adapter returns to supply value to the input it is asked for, which compiles only when value is a value.

    import assert from "node:assert/strict";
    import { LocalExecutor } from "itinera/executor";
    import {
    type Contributor,
    contributor,
    type DataBag,
    dataBag,
    type JourneyId,
    journeyId,
    } from "itinera/journey";
    import {
    input,
    type Outcome,
    type StepName,
    stepName,
    Step,
    step,
    } from "itinera/step";
    import {
    type FromDataBag,
    fromWorkflow,
    inputAdapter,
    type InputAdapterOptions,
    key,
    type Supplied,
    type SuppliedValue,
    withStep,
    Workflow,
    workflow,
    } from "itinera/workflow";
    import { integer, string } from "itinera/value";

    @step()
    class Charge extends Step {
    constructor(@input("amount", integer) readonly amount: number) {
    super();
    }

    override run(@contributor() contributor: Contributor): Outcome {
    contributor.contribute("charged", this.amount);
    return this.succeed();
    }
    }

    const adapting: InputAdapterOptions = { steps: ["charge"], name: "prices" };

    @workflow({ name: "orders" })
    @withStep(Charge, { name: "charge" })
    class Orders extends Workflow {
    readonly asked: string[] = [];

    constructor(readonly prices: ReadonlyMap<string, number>) {
    super();
    }

    @inputAdapter(adapting)
    price(
    @stepName() step: StepName,
    @key() key: string,
    @fromWorkflow("order", string) order: string,
    @journeyId() id: JourneyId,
    @dataBag() bag: DataBag,
    ): Supplied {
    this.asked.push(`${id}: ${step} ${key}`);
    const price = this.prices.get(order);
    return price === undefined || bag.read(key, integer).kind === "present"
    ? this.fromDataBag()
    : this.supply(price);
    }
    }

    export default (async () => {
    const orders = Orders.build(new Map([["A-1", 40]]));
    const supplying = orders.instance(new Map([["order", "A-1"]]));
    const reading = orders.instance(
    new Map<string, string | number>([
    ["order", "A-1"],
    ["amount", 25],
    ]),
    );

    const supplied = await new LocalExecutor().run(supplying);
    const read = await new LocalExecutor().run(reading);

    assert.ok(supplied.isSucceeded() && read.isSucceeded());
    assert.equal(charged(supplied.status.dataBag), 40);
    assert.equal(charged(read.status.dataBag), 25);
    assert.deepEqual(orders.asked, [
    `${supplying.journeyId}: charge amount`,
    `${reading.journeyId}: charge amount`,
    ]);
    const charge = "charge" as StepName;
    assert.deepEqual(
    orders.price(
    charge,
    "amount",
    "A-1",
    supplying.journeyId,
    supplied.status.dataBag,
    ),
    { kind: "supplied", value: 40 } satisfies SuppliedValue,
    );
    assert.deepEqual(
    orders.price(
    charge,
    "amount",
    "A-1",
    reading.journeyId,
    read.status.dataBag,
    ),
    { kind: "fromDataBag" } satisfies FromDataBag,
    );
    })();

    function charged(bag: DataBag): number {
    return bag.read("charged", integer).option().unwrap();
    }

    Type Parameters

    • T

    Parameters

    Returns Supplied

  • Makes the workflow object of a class declared with @workflow, calling its constructor with the arguments given, and gives it the workflow descriptor made when the class was defined.

    Type Parameters

    • C extends new (...args: never[]) => Workflow

    Parameters

    • this: C
    • ...args: ConstructorParameters<C>

    Returns Built<InstanceType<C>>

    Error if the class is not declared with @workflow.

  • Starts putting the workflow together from what the decorators of the class declared, if anything, adding to it what the decorators cannot say, or everything, for a class declared without them.

    import assert from "node:assert/strict";
    import type { Event } from "itinera/event";
    import { type DataBag, dataBag } from "itinera/journey";
    import type { Reporter } from "itinera/report";
    import { type Outcome, Step } from "itinera/step";
    import { Workflow } from "itinera/workflow";
    import { integer } from "itinera/value";

    class Charge extends Step {
    override run(): Outcome {
    return this.succeed();
    }
    }

    class Ship extends Step {
    override run(): Outcome {
    return this.succeed();
    }
    }

    class Audit implements Reporter {
    readonly kinds: string[] = [];

    report(event: Event): void {
    this.kinds.push(event.kind);
    }
    }

    class Orders extends Workflow {
    constructor(readonly shop: string) {
    super();
    }

    orderId(data: DataBag): string {
    const number = data.read("number", integer).option();
    return `${this.shop}-${number.map(String).unwrapOr("unnumbered")}`;
    }
    }

    const orders = Orders.builder()
    .name("orders")
    .step(Charge.builder("charge").retryBudget(1).noRetryOnAbnormalTermination())
    .step(Ship.builder("ship"))
    .reporter(Audit)
    .idGenerator("orderId", dataBag())
    .constructWith("corner")
    .build();

    const instance = orders.instance({ number: 7 });
    assert.equal(instance.descriptor.name, "orders");
    assert.equal(instance.journeyId, "corner-7");
    assert.deepEqual(
    instance.descriptor.steps().map((described) => described.name),
    ["charge", "ship"],
    );
    assert.equal(instance.descriptor.steps()[0]?.retryBudget, 1);
    assert.equal(instance.descriptor.steps()[0]?.retryOnAbnormalTermination, false);

    Type Parameters

    • C extends new (...args: never[]) => Workflow

    Parameters

    • this: C

    Returns WorkflowBuilder<C>

    Error if the class does not extend Workflow itself.

  • Lists the steps the decorators of the class declared, in order, without running anything and without a workflow object, as its workflow descriptor's listing() does.

    import assert from "node:assert/strict";
    import {
    type OnSuccess,
    onStepSuccess,
    StepPolicy,
    stepPolicy,
    } from "itinera/policy";
    import { type Provided, provider, service, serviceType } from "itinera/service";
    import {
    type Outcome,
    RescueStep,
    rescueStep,
    type RescueOutcome,
    Step,
    step,
    } from "itinera/step";
    import {
    inputAdapter,
    key,
    type ListedStep,
    type Supplied,
    withStep,
    Workflow,
    workflow,
    } from "itinera/workflow";

    interface PaymentGateway {
    take(amount: number): string;
    }

    const PAYMENT_GATEWAY = serviceType<PaymentGateway>("PaymentGateway");

    @step()
    class Charge extends Step {
    override run(
    @service("payments", PAYMENT_GATEWAY) payments: PaymentGateway,
    ): Outcome {
    payments.take(40);
    return this.succeed();
    }
    }

    @step()
    class Ship extends Step {
    override run(): Outcome {
    return this.succeed();
    }
    }

    @rescueStep()
    class Refund extends RescueStep {
    override run(): RescueOutcome {
    return this.succeed();
    }
    }

    @stepPolicy({ name: "audit" })
    class Audit extends StepPolicy {
    @onStepSuccess()
    audited(): OnSuccess {
    return this.keepDefault();
    }
    }

    @workflow({ name: "orders" })
    @withStep(Charge, { name: "charge", policies: [Audit], rescue: Refund })
    @withStep(Ship, { name: "ship" })
    class Orders extends Workflow {
    @inputAdapter({ steps: ["charge"] })
    pricing(@key() inputKey: string): Supplied {
    return this.supply(inputKey.length);
    }

    @provider(PAYMENT_GATEWAY, { name: "gateway" })
    payments(): Provided<PaymentGateway> {
    return this.provide({ take: (amount) => `${String(amount)} paid` });
    }
    }

    const listing: readonly ListedStep[] = Orders.listing();

    assert.deepEqual(listing, [
    {
    step: "charge",
    position: 1,
    policies: ["audit"],
    adapter: "pricing",
    services: [{ key: "payments", provider: "gateway" }],
    rescue: { step: "charge_rescue", services: [] },
    },
    { step: "ship", position: 2, policies: [], services: [] },
    ]);
    assert.deepEqual(
    Orders.builder()
    .step(Ship.builder("return"))
    .listing()
    .map((listed) => listed.step),
    ["charge", "ship", "return"],
    );

    Parameters

    • this: new (...args: never[]) => Workflow

    Returns readonly ListedStep[]

    Error if the class is not declared with @workflow.