Interface StepBuilder<C, R>
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
Methods
needs
-
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(),
);Returns this
no Retry On Abnormal Termination
-
Never retries an attempt that ends in an abnormal termination, whatever the retry budget.
Returns this
policy
-
policy<P extends StepPolicyClass<unknown>>(
policy: P | StepPolicyBuilder<P>,
): StepBuilder<C, R & RolesOfOne<P>>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
- P extends StepPolicyClass<unknown>
Parameters
- policy: P | StepPolicyBuilder<P>
Returns StepBuilder<C, R & RolesOfOne<P>>
rescue
-
Gives the step a rescue step, which runs as
<step name>_rescuebefore 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
- Q extends RescueStepClass
Parameters
- rescue: Q | RescueStepBuilder<Q>
Returns this
retry Budget
run
-
run(
...requests: Tokens<
Parameters<InstanceType<C>["run"]>,
Place<InstanceType<C>, "run">,
>,
): thisThe requests of the step's
run, one per parameter in order, such asservice("payments", PAYMENTS)orcontributor(), 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(),
);Returns this
Puts one step of the class
Ctogether for a workflow's builder: what@withStepsays about a step, one method at a time, started by the step class's staticbuilder(name). Each method checks what it is given at once and returns the builder, which the workflow's builder takes in itsstep.A step class declared without decorators is given its requests by position, with
needsandrun.