Declaring by hand
What you want to do
The annotations have declared the shop's workflow, and the checker has checked it as the program was built. You want to see what the annotations stand for, and to write part of the shop that way yourself: for a declaration put together when the program starts, from the shop's configuration, or for a mistake you'd rather read as a value than as an error of the build.
The code
The shop by hand
The shop is the one chapter 36 runs, declared in the long form: without the annotations, for its pricing step, its audit and its workflow. Each request is made once, by Requests from org.itineradev.itinera.request, such as Requests.input("price", TypeToken.of(Long.class)). Its type names the kind of part that may make it, such as BuildKind for what builds a step, and the type of its answer. The discount's, made by JavaRequests from org.itineradev.itinera.request.java, answers with an Optional<Long>. The pricing is a plain class implementing SyncStepRun, and its static pricing() declares it: StepDescriptor.builder("price", ...) takes what builds it afresh for each attempt, as in chapter 12, from got, the typed answers to the requests request lists:
/**
* Works out what an order costs, for one attempt: its price, less its discount if it has one, given
* back as the amount to charge.
*/
final class Price implements SyncStepRun {
static final Request<BuildKind, Long> PRICE = Requests.input("price", TypeToken.of(Long.class));
static final Request<BuildKind, Optional<Long>> DISCOUNT =
JavaRequests.optionalInput("discount", TypeToken.of(Long.class));
static final Request<ContributorKind, Contributor> CONTRIBUTOR = Requests.contributor();
private final long price;
private final Optional<Long> discount;
private final Contributor contributor;
Price(long price, Optional<Long> discount, Contributor contributor) {
this.price = price;
this.discount = discount;
this.contributor = contributor;
}
@Override
public Outcome run() {
contributor.contribute("amount", price - discount.orElse(0L));
return Outcome.success();
}
/** Declares the pricing, built for each attempt from what it requests. */
static StepDescriptor<Sync> pricing() {
return StepDescriptor.builder(
"price", got -> new Price(got.get(PRICE), got.get(DISCOUNT), got.get(CONTRIBUTOR)))
.request(PRICE)
.request(DISCOUNT)
.request(CONTRIBUTOR)
.build();
}
}
The audit is a plain class too. StepPolicyDescriptor.builder names it and makes it with Audit::new, and onStepSuccess takes its hook's requests, in order, and calls charged with their answers:
/**
* Writes an audit line for every step it is attached to that succeeds: the journey, the attempt
* that took the money, the amount the order was charged, and the receipt the step gave back.
*/
final class Audit {
static final Request<JourneyIdKind, JourneyId> JOURNEY = Requests.journeyId();
static final Request<StepNameKind, StepName> STEP = Requests.stepName();
static final Request<AttemptKind, Attempt> ATTEMPT = Requests.attempt();
static final Request<WorkflowDataKind, Long> AMOUNT =
Requests.fromWorkflow("amount", TypeToken.of(Long.class));
static final Request<FromStepKind, String> RECEIPT =
Requests.fromStep("receipt", TypeToken.of(String.class));
static final Request<ContributorKind, Contributor> CONTRIBUTOR = Requests.contributor();
OnSuccess charged(
JourneyId journey,
StepName step,
Attempt attempt,
long amount,
String receipt,
Contributor contributor) {
contributor.contribute(
"audit",
journey
+ ": "
+ step
+ " took "
+ amount
+ " on attempt "
+ attempt
+ ", receipt "
+ receipt);
return OnSuccess.keepDefault();
}
/** Declares the audit, its hook {@code charged} called with what it requests, in order. */
static StepPolicyDescriptor<Audit, Sync> audit() {
return StepPolicyDescriptor.builder("audit", Audit::new)
.onStepSuccess(
List.of(JOURNEY, STEP, ATTEMPT, AMOUNT, RECEIPT, CONTRIBUTOR),
(audit, got) ->
audit.charged(
got.get(JOURNEY),
got.get(STEP),
got.get(ATTEMPT),
got.get(AMOUNT),
got.get(RECEIPT),
got.get(CONTRIBUTOR)))
.build();
}
}
Orders implements both roles but no longer ItineraWorkflow, so its ID generator, input adapter and providers are plain methods now, and build the Supplied.Value, Supplied.FromDataBag.INSTANCE and Provided.Instance that supply, fromDataBag and provide made before:
/**
* The shop: it tells its customers through the channel it configures, and the bank gives refunds.
* Its plain methods name each journey, describe each parcel and give the services.
*/
final class Orders implements Messages, Refunds {
private final String channel;
Orders(String channel) {
this.channel = channel;
}
@Override
public void tell(String customer, String message) {
System.out.println(channel + " to " + customer + ": " + message);
}
@Override
public void refund(String receipt, long amount) {
System.out.println("the bank gives " + amount + " back on receipt " + receipt);
}
/** Names each journey after its order. */
String orderNumber(DataBag data) {
String order = data.read("order", TypeToken.of(String.class)).orNull();
if (order == null) throw new IllegalStateException("an order without a number");
return order;
}
/**
* Gives the shipping the weight of the order's parcel, as the warehouse describes it. Every other
* input of the shipping is read from the data bag.
*/
Supplied parcels(String key, Parcel parcel) {
return key.equals("weight")
? new Supplied.Value(parcel.weight())
: Supplied.FromDataBag.INSTANCE;
}
/** The order book, which has the orders completed before today. */
Provided<OrderBook> ledger() {
return new Provided.Instance<>(new Ledger(List.of("A-13")));
}
/** The bank, as the payment client of the journey. */
Provided<Payments> bank() {
return new Provided.Instance<>(new Bank(2026));
}
/** The bank's card registry in Europe. */
Provided<Cards> cards() {
return new Provided.Instance<>(BankLibrary.cardRegistry("eu"), "eu");
}
/** A carrier for every attempt of a step: the main carrier first, the backup carrier after. */
Provided<Carrier> carriers(Attempt attempt) {
if (attempt.isFirst()) return new Provided.Instance<>(new MainCarrier());
return new Provided.Instance<>(new BackupCarrier());
}
}
Parcel is chapter 21's, OrderBook is chapter 22's, Carrier is chapter 12's, Messages chapter 19's, Refunds chapter 23's, and Payments, Cards and cardRegistry are chapter 35's.
And WorkflowDescriptor.builder, in Main's static orders(), puts the workflow together, part by part. The adapter's and providers' builders name the workflow's class, as in ProviderDescriptor.<Orders, OrderBook>builder. The other steps and policies keep their annotations, and go in through StepDescriptor.builder("lookup", Lookup.class), StepPolicyDescriptor.of, RescueStepDescriptor.of and WorkflowPolicyDescriptor.of, which read each class alone:
static final Request<KeyKind, String> KEY = Requests.key();
static final Request<WorkflowDataKind, Parcel> PARCEL =
Requests.fromWorkflow("parcel", TypeToken.of(Parcel.class));
static final Request<AttemptKind, Attempt> ATTEMPT = Requests.attempt();
/**
* Declares the shop's workflow, part by part, and checks it. It looks the order up, and finishes
* an order already completed. Otherwise it works out what the order costs, then charges it,
* repairing a charge that fails and auditing one that succeeds, then ships, and shipping may be
* tried once more, its charge refunded if it is given up. Once a journey has ended, the customer
* is told.
*/
static WorkflowDescriptor<Orders, Sync> orders() {
var parcels =
InputAdapterDescriptor.<Orders>builder(
"parcels", "ship", (orders, got) -> orders.parcels(got.get(KEY), got.get(PARCEL)))
.request(KEY)
.request(PARCEL)
.build();
var ledger =
ProviderDescriptor.<Orders, OrderBook>builder(
"ledger", "orderBook", OrderBook.class, (orders, got) -> orders.ledger())
.build();
var bank =
ProviderDescriptor.<Orders, Payments>builder(
"bank", "payments", Payments.class, (orders, got) -> orders.bank())
.build();
var cards =
ProviderDescriptor.<Orders, Cards>builder(
"cards", "cards", Cards.class, (orders, got) -> orders.cards())
.step("charge_rescue")
.build();
var carriers =
ProviderDescriptor.<Orders, Carrier>perAttempt(
"carriers",
"carrier",
Carrier.class,
(orders, got) -> orders.carriers(got.get(ATTEMPT)))
.request(ATTEMPT)
.build();
return WorkflowDescriptor.builder(Orders.class, "orders")
.step(
StepDescriptor.builder("lookup", Lookup.class)
.policy(StepPolicyDescriptor.of(AlreadyCompleted.class))
.build())
.step(Price.pricing())
.step(
StepDescriptor.builder("charge", Charge.class)
.rescue(RescueStepDescriptor.of(RenewCard.class))
.policy(Audit.audit())
.policy(StepPolicyDescriptor.of(Outage.class))
.build())
.step(
StepDescriptor.builder("ship", Ship.class)
.retryBudget(1)
.policy(StepPolicyDescriptor.of(FailedShipping.class))
.build())
.role(Messages.class)
.role(Refunds.class)
.policy(WorkflowPolicyDescriptor.of(Notify.class))
.reporter(journey -> new Log())
.reporter(journey -> new Desk())
.idGenerator((orders, data) -> orders.orderNumber(data))
.inputAdapter(parcels)
.provider(ledger)
.provider(bank)
.provider(cards)
.provider(carriers)
.build();
}
The rest is as earlier chapters show it: the lookup and AlreadyCompleted in chapter 22, the charge in chapter 33, RenewCard in chapter 35, the shipping in chapter 17, Outage in chapter 34, FailedShipping in chapter 23, Notify in chapter 19, the log in chapter 33, chapter 35 and chapter 36, and the desk in chapter 11.
main calls orders() once, and makes each order's instance with InstanceBuilder.of, from org.itineradev.itinera.instance:
var instance =
InstanceBuilder.of(orders, new Orders("email"))
.reportersGlobalMetadata("customer", order.customer())
.initialData(order)
.create();followUp is chapter 34's, and NewOrder chapter 36's. main runs Ann's order and Jo's, and prints:
Ann's order A-1:
log orders A-1 for Ann #1 journey_started order, customer, price, discount, parcel, card, giftCard
log orders A-1 for Ann #2 attempt_started lookup, attempt 1
log orders A-1 for Ann #3 service_provided lookup gets orderBook from ledger, a ch38_declaring_by_hand.Ledger
the order book has no order A-1 yet
log orders A-1 for Ann #4 step_succeeded lookup
log orders A-1 for Ann #5 contribution_committed completed
log orders A-1 for Ann #6 hook_called alreadyCompleted: on step success of lookup
log orders A-1 for Ann #7 attempt_started price, attempt 1
log orders A-1 for Ann #8 step_succeeded price
log orders A-1 for Ann #9 contribution_committed amount
log orders A-1 for Ann #10 attempt_started charge, attempt 1
log orders A-1 for Ann #11 service_provided charge gets payments from bank, a ch38_declaring_by_hand.Bank
the bank charges 30 for order A-1
log orders A-1 for Ann, receipt R-A-1 #12 global_metadata_set receipt
log orders A-1 for Ann, receipt R-A-1 #13 step_succeeded charge
log orders A-1 for Ann, receipt R-A-1 #14 contribution_committed receipt
log orders A-1 for Ann, receipt R-A-1 #15 hook_called audit: on step success of charge
log orders A-1 for Ann, receipt R-A-1 #16 contribution_committed audit
log orders A-1 for Ann, receipt R-A-1 #17 attempt_started ship, attempt 1
log orders A-1 for Ann, receipt R-A-1 #18 input_adapter_supplied ship gets weight from parcels
log orders A-1 for Ann, receipt R-A-1 #19 service_provided ship gets carrier from carriers, a ch38_declaring_by_hand.MainCarrier
the main carrier books order A-1
log orders A-1 for Ann, receipt R-A-1 #20 step_info ship: the parcel leaves with receipt R-A-1
log orders A-1 for Ann, receipt R-A-1 #21 step_succeeded ship
log orders A-1 for Ann, receipt R-A-1 #22 contribution_committed tracking
log orders A-1 for Ann, receipt R-A-1 #23 optional_input_absent code
email to Ann: Order A-1 is on its way, tracking T-A-1.
log orders A-1 for Ann, receipt R-A-1 #24 hook_called notify: on workflow success
log orders A-1 for Ann, receipt R-A-1 #25 journey_succeeded
the journey succeeded, with receipt R-A-1 and tracking T-A-1
audit: A-1: charge took 30 on attempt 1, receipt R-A-1
Jo's order A-8:
log orders A-8 for Jo #1 journey_started order, customer, price, parcel, card, giftCard
log orders A-8 for Jo #2 attempt_started lookup, attempt 1
log orders A-8 for Jo #3 service_provided lookup gets orderBook from ledger, a ch38_declaring_by_hand.Ledger
the order book has no order A-8 yet
log orders A-8 for Jo #4 step_succeeded lookup
log orders A-8 for Jo #5 contribution_committed completed
log orders A-8 for Jo #6 hook_called alreadyCompleted: on step success of lookup
log orders A-8 for Jo #7 attempt_started price, attempt 1
log orders A-8 for Jo #8 optional_input_absent discount
log orders A-8 for Jo #9 step_succeeded price
log orders A-8 for Jo #10 contribution_committed amount
log orders A-8 for Jo #11 attempt_started charge, attempt 1
log orders A-8 for Jo #12 service_provided charge gets payments from bank, a ch38_declaring_by_hand.Bank
the bank declines card jo-2024: it has expired
log orders A-8 for Jo #13 step_failed charge: card-expired
log orders A-8 for Jo #14 step_rescuing charge: failure, rescued by charge_rescue
log orders A-8 for Jo #15 attempt_started charge_rescue, attempt 1
log orders A-8 for Jo #16 service_provided charge_rescue gets cards from cards, a ch38_declaring_by_hand.Registry, with eu
the card registry in eu says card jo-2024 was replaced by jo-2029
log orders A-8 for Jo #17 step_succeeded charge_rescue
log orders A-8 for Jo #18 contribution_committed card
log orders A-8 for Jo #19 data_overwritten card
log orders A-8 for Jo #20 step_rescued charge by charge_rescue
log orders A-8 for Jo #21 attempt_started charge, attempt 2
the bank charges 30 for order A-8
log orders A-8 for Jo, receipt R-A-8 #22 global_metadata_set receipt
log orders A-8 for Jo, receipt R-A-8 #23 step_succeeded charge
log orders A-8 for Jo, receipt R-A-8 #24 contribution_committed receipt
log orders A-8 for Jo, receipt R-A-8 #25 hook_called audit: on step success of charge
log orders A-8 for Jo, receipt R-A-8 #26 contribution_committed audit
log orders A-8 for Jo, receipt R-A-8 #27 attempt_started ship, attempt 1
log orders A-8 for Jo, receipt R-A-8 #28 input_adapter_supplied ship gets weight from parcels
log orders A-8 for Jo, receipt R-A-8 #29 service_provided ship gets carrier from carriers, a ch38_declaring_by_hand.MainCarrier
the main carrier books order A-8
log orders A-8 for Jo, receipt R-A-8 #30 step_info ship: the parcel leaves with receipt R-A-8
log orders A-8 for Jo, receipt R-A-8 #31 step_succeeded ship
log orders A-8 for Jo, receipt R-A-8 #32 contribution_committed tracking
log orders A-8 for Jo, receipt R-A-8 #33 optional_input_absent code
email to Jo: Order A-8 is on its way, tracking T-A-8.
log orders A-8 for Jo, receipt R-A-8 #34 hook_called notify: on workflow success
log orders A-8 for Jo, receipt R-A-8 #35 journey_succeeded
the journey succeeded, with receipt R-A-8 and tracking T-A-8
audit: A-8: charge took 30 on attempt 2, receipt R-A-8A workflow put together wrongly
This small shop has steps and policies of its own:
/** Charges an order. */
@Step
final class Charge implements ItineraStep {
public Outcome run() {
return succeed();
}
}
/** Ships an order of the weight it is given. */
@Step
final class Ship implements ItineraStep {
Ship(@Input long weight) {}
public Outcome run() {
return succeed();
}
}
/** Audits a charge that succeeds. */
@StepPolicy(name = "audit")
final class Audit implements ItineraStepPolicy {
@OnStepSuccess
public OnSuccess charged() {
return keepDefault();
}
}
/** Keeps the receipt of a charge that succeeds. */
@StepPolicy(name = "receipts")
final class Receipts implements ItineraStepPolicy {
@OnStepSuccess
public OnSuccess charged() {
return keepDefault();
}
}
/** The shop whose orders the workflow takes. */
final class Shop {}
Main's static methods declare its parts, parcelsFor its adapter, and detail says what a violation is:
static final Request<WorkflowDataKind, Long> PARCEL =
Requests.fromWorkflow("parcel", TypeToken.of(Long.class));
/** The parcels adapter, which gives the step it is attached to the parcel's weight. */
static InputAdapterDescriptor<Shop, Sync> parcelsFor(String step) {
return InputAdapterDescriptor.<Shop>builder(
"parcels", step, (shop, got) -> new Supplied.Value(got.get(PARCEL)))
.request(PARCEL)
.build();
}
/** The charge, with the policies given. */
static StepDescriptor<Sync> charge(List<StepPolicyDescriptor<?, Sync>> policies) {
var charge = StepDescriptor.builder("charge", Charge.class);
for (var policy : policies) charge.policy(policy);
return charge.build();
}
/** The shipping. */
static StepDescriptor<Sync> ship() {
return StepDescriptor.builder("ship", Ship.class).build();
}
/** Starts the shop's workflow. */
static WorkflowBuilder<Shop, Sync> shop() {
return WorkflowDescriptor.builder(Shop.class, "shop");
}
/** Says what one violation is, by the name the specification gives it, and what it concerns. */
static String detail(Violation violation) {
if (violation instanceof Violation.DuplicateStepName duplicate) {
return violation.getNamed() + ": " + duplicate.step();
}
if (violation instanceof Violation.StepHookDefinedTwice twice) {
return violation.getNamed() + ": " + twice.hook() + " on step " + twice.step();
}
if (violation instanceof Violation.InputAdapterForUnknownStep unknown) {
return violation.getNamed() + ": " + unknown.adapter() + " on " + unknown.step();
}
return violation.getNamed();
}
It is declared by hand with three mistakes: ship listed twice, two policies of the charge that both define on step success, and the parcels adapter attached to shipping, a step the workflow doesn't have:
var audit = StepPolicyDescriptor.of(Audit.class);
var receipts = StepPolicyDescriptor.of(Receipts.class);
shop()
.step(charge(List.of(audit, receipts)))
.step(ship())
.step(ship())
.inputAdapter(parcelsFor("shipping"))
.build();The program builds: the checker reads a workflow only in a class that implements ItineraWorkflow, which Shop doesn't, and reads each step and policy alone, and each is right on its own. build() throws a Violations, from org.itineradev.itinera.workflow, and main reads it:
} catch (Violations refused) {
System.out.println("the workflow was refused:");
for (var violation : refused.getViolations()) {
System.out.println(" " + detail(violation));
}
}Fixed, it builds, and main prints its listing:
var fixed =
shop()
.step(charge(List.of(StepPolicyDescriptor.of(Audit.class))))
.step(ship())
.inputAdapter(parcelsFor("ship"))
.build();
System.out.println("the fixed workflow was built:");
for (var step : fixed.listing()) {
System.out.println(" " + step.position() + ". " + step.step());
}It prints:
the workflow was refused:
duplicate step name: ship
hook defined twice: on step success on step charge
input adapter for unknown step: parcels on shipping
the fixed workflow was built:
1. charge
2. shipHow it works
- Both forms make the same descriptors, and they mix. A workflow is a workflow descriptor: its name, a step descriptor for each step in order, its policies, roles, reporters, ID generator, input adapters and providers. The annotations declare them, the long form writes them, and the executor runs either the same way.
- Each annotation stands for a builder's call.
@WithStepstands forStepDescriptor.builderand itsretryBudget,rescueandpolicy, and each@Inputof a step for arequest.@StepPolicyand a hook's annotation stand forStepPolicyDescriptor.builderand itsonStepSuccess, or another hook's method.@Workflowstands forWorkflowDescriptor.builder,reporterandpolicy, a role the workflow implements forrole, and@IdGenerator,@InputAdapterand@Providerfor the methods of their names.journey -> new Log(), aReporterFactory, makes each journey's log, andAudit::new, aPolicyFactory, the audit for each attempt. build()checks the declaration, as admission. It throws aViolationslisting every violation, each aViolationnamed as the specification names it. The checker finds them in an annotated workflow as the program is built, as chapter 37 showed; how the parts are put together is left tobuild().- When you need the long form. Beside the two needs this chapter started from, the long form also suits a class you can't annotate, such as one from a library. No option of itinera turns the annotations off: a program uses whichever form it needs.
What the book hasn't said is how to decide, for a new rule of the shop, which part it belongs in.
Outcomes
We have shown what the annotations stand for, how to write it by hand, and how a workflow declared by hand reports its mistakes.
| The usual way | With Itinera |
|---|---|
| Wiring declared by a framework's annotations is often read by code nobody sees. | The annotations stand for public builders, which you can call yourself, part by part. |
| A wiring mistake found at start-up often stops at the first one. | build() throws every violation at once, each a value. |