Interface StepBuilder<C, R>

Puts one step of the class C together for a workflow's builder: what @withStep says about a step, one method at a time, started by the step class's static builder(name). Each method checks what it is given at once and returns the builder, which the workflow's builder takes in its step.

A step class declared without decorators is given its requests by position, with needs and run.

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);
interface StepBuilder<C extends StepClass, R = unknown> {
    needs(
        ...requests: Tokens<ConstructorParameters<C>, Place<C, undefined>>,
    ): this;
    noRetryOnAbnormalTermination(): this;
    policy<P extends StepPolicyClass<unknown>>(
        policy: P | StepPolicyBuilder<P>,
    ): StepBuilder<C, R & RolesOfOne<P>>;
    rescue<Q extends RescueStepClass>(rescue: Q | RescueStepBuilder<Q>): this;
    retryBudget(retries: number): this;
    run(
        ...requests: Tokens<
            Parameters<InstanceType<C>["run"]>,
            Place<InstanceType<C>, "run">,
        >,
    ): this;
}

Type Parameters

  • C extends StepClass

    The class of the step.

  • R = unknown

    The roles its step policies request, which the workflow must implement.

Index

  • The requests of the step's constructor, one per parameter in order, such as input("amount", integer), each with its type written, for a step class declared without decorators.

    import assert from "node:assert/strict";
    import { type Contributor, contributor } from "itinera/journey";
    import { type Provided, service, serviceType } from "itinera/service";
    import {
    type Attempt,
    attempt,
    input,
    type Outcome,
    Step,
    type StepName,
    stepName,
    } from "itinera/step";
    import { key, type Supplied, Workflow } from "itinera/workflow";
    import { integer, string } from "itinera/value";

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

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

    class Charge extends Step {
    constructor(readonly amount: number) {
    super();
    }

    override run(payments: PaymentGateway, contributing: Contributor): Outcome {
    contributing.contribute("payment", payments.take(this.amount));
    return this.succeed();
    }
    }

    class Orders extends Workflow {
    pricing(step: StepName, inputKey: string): Supplied {
    return this.supply(step === "charge" && inputKey === "amount" ? 40 : 0);
    }

    payments(attempted: Attempt): Provided<PaymentGateway> {
    return this.provide({
    take: (amount) => `${String(amount)} paid, attempt ${String(attempted)}`,
    });
    }
    }

    const orders = Orders.builder()
    .name("orders")
    .step(
    Charge.builder("charge")
    .needs(input("amount", integer))
    .run(service("payments", PAYMENT_GATEWAY), contributor()),
    )
    .inputAdapter("pricing", { steps: ["charge"] }, stepName(), key())
    .provider("payments", PAYMENT_GATEWAY, { perAttempt: true }, attempt())
    .build();

    assert.deepEqual(
    orders
    .instance()
    .descriptor.steps()
    .map((described) => described.name),
    ["charge"],
    );

    // @ts-expect-error the amount is a number, so it cannot be read as a string
    Charge.builder("charge").needs(input("amount", string));

    assert.throws(
    // @ts-expect-error run takes two parameters, and each needs its request
    () => Charge.builder("charge").run(service("payments", PAYMENT_GATEWAY)),
    /Charge.run: parameter 2 carries no request/,
    );

    Orders.builder().inputAdapter(
    // @ts-expect-error payments provides a service, it does not supply an input
    "payments",
    { steps: ["charge"] },
    stepName(),
    key(),
    );

    Parameters

    • ...requests: Tokens<ConstructorParameters<C>, Place<C, undefined>>

    Returns this

    Error if the class declares its requests with decorators, or if a parameter is left without a request.

  • Never retries an attempt that ends in an abnormal termination, whatever the retry budget.

    Returns this

  • Attaches a step policy, after those attached so far: a class declared with @stepPolicy, or a policy's builder. The workflow must implement the roles it requests.

    It returns a new builder, which carries the roles the policy requests, and leaves this one as it was, so that no builder can reach the workflow's builder without the roles of its policies.

    import assert from "node:assert/strict";
    import { type Contributor, contributor } from "itinera/journey";
    import {
    failureCause,
    fromStep,
    type OnFailure,
    type OnSuccess,
    type PolicyDescriptor,
    role,
    type StepFailureCause,
    StepPolicy,
    type StepPolicyBuilder,
    WorkflowPolicy,
    type WorkflowPolicyBuilder,
    } from "itinera/policy";
    import { Step, type Outcome } from "itinera/step";
    import { Workflow } from "itinera/workflow";
    import { integer } from "itinera/value";

    /** A role the shop provides: telling a customer something. */
    interface Messages {
    tell(message: string): void;
    }

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

    class Audit extends StepPolicy {
    audited(charged: number, contributing: Contributor): OnSuccess {
    contributing.contribute("audit", `charged ${String(charged)}`);
    return this.keepDefault();
    }

    failed(cause: StepFailureCause): OnFailure {
    return this.failWorkflow(cause);
    }
    }

    class Notify extends WorkflowPolicy<Messages> {
    paid(messages: Messages): void {
    messages.tell("paid");
    }
    }

    class Orders extends Workflow implements Messages {
    readonly told: string[] = [];

    tell(message: string): void {
    this.told.push(message);
    }
    }

    const audit: StepPolicyBuilder<typeof Audit> = Audit.builder("audit")
    .onStepSuccess("audited", fromStep("charged", integer), contributor())
    .onStepFailure("failed", failureCause());
    const notify: WorkflowPolicyBuilder<typeof Notify> = Notify.builder(
    "notify",
    ).onWorkflowSuccess("paid", role<Messages>());

    const orders = Orders.builder()
    .name("orders")
    .step(Charge.builder("charge").policy(audit))
    .policy(notify)
    .build();

    const descriptor = orders.instance().descriptor;
    const attached: readonly PolicyDescriptor[] =
    descriptor.steps()[0]?.policies() ?? [];

    assert.deepEqual(
    attached.map((policy) => policy.name),
    ["audit"],
    );
    assert.deepEqual(attached[0]?.hooks(), ["on step success", "on step failure"]);
    const built = attached[0].build();
    assert.ok(built instanceof Audit);
    assert.deepEqual(attached[0].call(built, "on step failure", ["failure"]), {
    kind: "FailWorkflow",
    reason: { code: "failure" },
    });
    assert.deepEqual(
    descriptor.policies().map((policy) => policy.name),
    ["notify"],
    );

    class Counter extends Workflow {}

    // @ts-expect-error Counter does not implement Messages, which notify requests
    Counter.builder().policy(notify);

    Type Parameters

    Parameters

    Returns StepBuilder<C, R & RolesOfOne<P>>

    Error if the class is not declared with @stepPolicy, or if the policy's builder was given no hook.

  • Gives the step a rescue step, which runs as <step name>_rescue before the step runs again after an attempt that failed: a class declared with @rescueStep, or a rescue step's builder.

    import assert from "node:assert/strict";
    import { type Contributor, contributor } from "itinera/journey";
    import { None, type Option, Some } from "itinera/option";
    import {
    failureReason,
    fromRescuedStep,
    input,
    type Outcome,
    type Reason,
    RescueStep,
    rescueStep,
    type RescueOutcome,
    type RescueStepBuilder,
    type RescueStepClass,
    Step,
    step,
    } from "itinera/step";
    import { Contributions } from "itinera/testing";
    import { withStep, Workflow, workflow } from "itinera/workflow";
    import { integer, optional, string } from "itinera/value";

    @rescueStep()
    class Refund extends RescueStep {
    constructor(
    @input("order", string) readonly order: string,
    @fromRescuedStep("charged", optional(integer))
    readonly charged: Option<number>,
    @failureReason({ optional: true }) readonly reason: Option<Reason>,
    ) {
    super();
    }

    override run(@contributor() contributor: Contributor): RescueOutcome {
    const why = this.reason.isSome() ? this.reason.value.code : "a throw";
    contributor.contribute(
    "refunded",
    `${this.order}: ${String(this.charged.unwrapOr(0))} after ${why}`,
    );
    return this.succeed();
    }
    }

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

    class Weigh extends RescueStep {
    constructor(readonly grams: number) {
    super();
    }

    override run(): RescueOutcome {
    return this.grams > 0 ? this.succeed() : this.fail("nothing to weigh");
    }
    }

    const rescue: RescueStepClass = Refund;

    @workflow({ name: "orders" })
    @withStep(Charge, { name: "charge", rescue })
    class Orders extends Workflow {}

    const weighing: RescueStepBuilder<typeof Weigh> = Weigh.builder().needs(
    fromRescuedStep("grams", integer),
    );
    const shipping = Orders.builder()
    .step(Charge.builder("ship").rescue(weighing))
    .build();

    const refund = new Refund("A-1", Some(40), Some({ code: "declined" }));
    const unknown = new Refund("B-2", None, None);

    const refunding = new Contributions();
    const guessing = new Contributions();

    assert.deepEqual(refund.run(refunding.contributor), { kind: "success" });
    assert.equal(refunded(refunding), "A-1: 40 after declined");
    unknown.run(guessing.contributor);
    assert.equal(refunded(guessing), "B-2: 0 after a throw");
    assert.deepEqual(new Weigh(0).run(), {
    kind: "failure",
    reason: { code: "nothing to weigh" },
    });
    assert.ok(Orders.build() instanceof Orders);
    assert.deepEqual(
    shipping
    .instance()
    .descriptor.steps()
    .map((described) => described.name),
    ["charge", "ship"],
    );

    function refunded(contributions: Contributions): string {
    return contributions.read("refunded", string).option().unwrap();
    }

    Type Parameters

    Parameters

    Returns this

    Error if the class is not declared with @rescueStep.

  • How many times the step may be retried after its first attempt, a whole number from 0: 0 unless this says otherwise.

    Parameters

    • retries: number

    Returns this

    Error if retries is not a whole number from 0.

  • The requests of the step's run, one per parameter in order, such as service("payments", PAYMENTS) or contributor(), for a step class declared without decorators.

    import assert from "node:assert/strict";
    import { type Contributor, contributor } from "itinera/journey";
    import { type Provided, service, serviceType } from "itinera/service";
    import {
    type Attempt,
    attempt,
    input,
    type Outcome,
    Step,
    type StepName,
    stepName,
    } from "itinera/step";
    import { key, type Supplied, Workflow } from "itinera/workflow";
    import { integer, string } from "itinera/value";

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

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

    class Charge extends Step {
    constructor(readonly amount: number) {
    super();
    }

    override run(payments: PaymentGateway, contributing: Contributor): Outcome {
    contributing.contribute("payment", payments.take(this.amount));
    return this.succeed();
    }
    }

    class Orders extends Workflow {
    pricing(step: StepName, inputKey: string): Supplied {
    return this.supply(step === "charge" && inputKey === "amount" ? 40 : 0);
    }

    payments(attempted: Attempt): Provided<PaymentGateway> {
    return this.provide({
    take: (amount) => `${String(amount)} paid, attempt ${String(attempted)}`,
    });
    }
    }

    const orders = Orders.builder()
    .name("orders")
    .step(
    Charge.builder("charge")
    .needs(input("amount", integer))
    .run(service("payments", PAYMENT_GATEWAY), contributor()),
    )
    .inputAdapter("pricing", { steps: ["charge"] }, stepName(), key())
    .provider("payments", PAYMENT_GATEWAY, { perAttempt: true }, attempt())
    .build();

    assert.deepEqual(
    orders
    .instance()
    .descriptor.steps()
    .map((described) => described.name),
    ["charge"],
    );

    // @ts-expect-error the amount is a number, so it cannot be read as a string
    Charge.builder("charge").needs(input("amount", string));

    assert.throws(
    // @ts-expect-error run takes two parameters, and each needs its request
    () => Charge.builder("charge").run(service("payments", PAYMENT_GATEWAY)),
    /Charge.run: parameter 2 carries no request/,
    );

    Orders.builder().inputAdapter(
    // @ts-expect-error payments provides a service, it does not supply an input
    "payments",
    { steps: ["charge"] },
    stepName(),
    key(),
    );

    Parameters

    • ...requests: Tokens<Parameters<InstanceType<C>["run"]>, Place<InstanceType<C>, "run">>

    Returns this

    Error if the class declares its requests with decorators, or if a parameter is left without a request.