Class StepPolicy<R>Abstract

The base class of every step policy: hooks called around the attempts of the steps it is attached to, each a method marked with the decorator of the hook it implements, such as @onStepSuccess(). itinera builds a new instance for every attempt, with a constructor that takes nothing.

A hook fails by throwing, which aborts the journey. Only a class extending StepPolicy is a step policy, whether it is declared with @stepPolicy or given to a workflow's builder.

import assert from "node:assert/strict";
import {
type Contributor,
contributor,
type JourneyId,
journeyId,
} from "itinera/journey";
import { None, type Option, Some } from "itinera/option";
import {
failureCause,
fromStep,
type HookDecorator,
type KeepDefault,
type OnFailure,
onStepFailure,
onStepRetry,
onStepSuccess,
type OnSuccess,
onWorkflowSuccess,
type PolicyOptions,
RetryCause,
retryCause,
role,
type RolesOf,
type RolesOfOne,
type StepFailureCause,
StepPolicy,
stepPolicy,
type StepPolicyClass,
WorkflowPolicy,
workflowPolicy,
type WorkflowPolicyClass,
} from "itinera/policy";
import {
attempt,
Attempt,
failureReason,
type FromFailure,
type FromFailureOptions,
type Outcome,
type Reason,
Step,
step,
type StepName,
stepName,
} from "itinera/step";
import {
fromWorkflow,
withStep,
Workflow,
workflow,
type WorkflowClass,
} from "itinera/workflow";
import { integer, optional } from "itinera/value";

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

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

@stepPolicy({ name: "audit" })
class Audit extends StepPolicy {
@onStepSuccess()
audited(
@fromStep("charged", integer) charged: number,
@contributor() contributor: Contributor,
): OnSuccess {
contributor.contribute("audit", `charged ${String(charged)}`);
return charged > 1000 ? this.failWorkflow("too much") : this.keepDefault();
}

@onStepRetry()
retried(
@stepName() step: StepName,
@attempt() attempt: Attempt,
@retryCause() cause: RetryCause,
): OnFailure {
return attempt.number > 2 && cause === RetryCause.AbnormalTermination
? this.failWorkflow({
code: "unstable",
message: `${step} keeps failing`,
})
: this.keepDefault();
}

@onStepFailure()
failed(
@failureCause() cause: StepFailureCause,
@failureReason({ optional: true }) reason: Option<Reason>,
): OnFailure {
return reason.isSome() && reason.value.code === "fraud"
? this.failWorkflow(reason.value)
: this.failWorkflow(cause);
}
}

@workflowPolicy({ name: "notify" })
class Notify extends WorkflowPolicy<Messages> {
@onWorkflowSuccess()
paid(
@journeyId() id: JourneyId,
@fromWorkflow("payment", optional(integer)) payment: Option<number>,
@role<Messages>() messages: Messages,
): void {
messages.tell(`order ${id}: paid ${String(payment.unwrapOr(0))}`);
}
}

@workflow({ name: "orders", policies: [Notify] })
@withStep(Charge, { name: "charge", retryBudget: 2, policies: [Audit] })
class Orders extends Workflow implements Messages {
readonly told: string[] = [];

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

const contributed = new Map<string, unknown>();
const recording: Contributor = {
contribute: (key, value) => {
contributed.set(key, value);
},
};
const audit = new Audit();
const kept: KeepDefault = { kind: "KeepDefault" };
const notQuite: FromFailure<Reason, false> = { code: "late" };
const asOptional: FromFailureOptions<true> = { optional: true };
const named: PolicyOptions = { name: "audit" };
const policies: readonly StepPolicyClass[] = [Audit];
const workflowPolicies: readonly WorkflowPolicyClass<Messages>[] = [Notify];
const shop = Orders.build();
const messages: RolesOfOne<typeof Notify> = shop;
const roles: RolesOf<[typeof Audit, typeof Notify]> = messages;
const orders: WorkflowClass<Messages> = Orders;
const onSuccess: HookDecorator<OnSuccess, StepPolicy> = onStepSuccess();

assert.deepEqual(audit.audited(40, recording), kept);
assert.deepEqual([...contributed], [["audit", "charged 40"]]);
assert.deepEqual(audit.audited(2000, recording), {
kind: "FailWorkflow",
reason: { code: "too much" },
});
assert.deepEqual(audit.failed("retries exhausted", None), {
kind: "FailWorkflow",
reason: { code: "retries exhausted" },
});
new Notify().paid("R-1" as JourneyId, Some(40), roles);
assert.deepEqual(shop.told, ["order R-1: paid 40"]);
assert.equal(notQuite.code, "late");
assert.ok(asOptional.optional);
assert.equal(named.name, "audit");
assert.deepEqual(policies, [Audit]);
assert.deepEqual(workflowPolicies, [Notify]);
assert.equal(orders, Orders);
assert.equal(typeof onSuccess, "function");

Type Parameters

  • R = unknown

    The roles its hooks request, which every workflow it is attached to must provide: an interface, or several joined with &.

Hierarchy (View Summary)

Index

  • Type Parameters

    • R = unknown

      The roles its hooks request, which every workflow it is attached to must provide: an interface, or several joined with &.

    Returns StepPolicy<R>

"[roles]": R

The roles the policy requests. It exists only in the types, where a workflow it is attached to must provide them.

  • Starts putting a step policy of this class together, for a class declared without decorators, named name, or else after the class, as Audit.builder("audit").

    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);

    A step policy keeps no static data, which every attempt of every journey would share, refused as WithoutStaticData says: at compile time, or else when the builder starts.

    Type Parameters

    Parameters

    Returns StepPolicyBuilder<C>

    Error if the class keeps static data, if the name is empty, or if the class is declared with a policy's decorator.