You are reading GraphMaquina 2.0.4. The latest version is 2.0.6.

Handle transition outcomes

How an operation selects its edge and its result, and where an eligibility check stops An operation names a transition identifier. The engine resolves the single edge keyed by the current state and that identifier. With no such edge the node's policy rejects the request as NO_TRANSITION. Otherwise guards run, and a rejecting guard rejects as GUARD. Before the edge is resolved, a machine bound as a sub-machine rejects as DETACHED an entity whose parent does not hold it; once it is resolved, a machine whose current state holds a sub-machine rejects as RESERVED_EXIT an identifier that this binding maps as an exit. When a step ends a sub-machine in a terminal state, and the parent that held it when the step began is not in flight, and the step neither moved it out of the bound state nor entered it again, the parent's exit runs and commits with that step, and the outcome is still the step's. A move or successful action commits the resolved edge as Applied; a returned business failure resolves, from the same origin, the identifier of the recovery rule that declares its failure kind, or else the onFailure identifier, and commits it as Failed. Reevaluation is a separate entry point. With no watch it returns Ignored with NO_WATCH; with no matching rule it returns Ignored with NO_RULE_MATCHED. With a matching rule it executes the selected edge and returns that execution's outcome. Technical errors throw instead of producing an outcome. An eligibility check runs the same admission in the same order: the binding check, the edge lookup, the refusal of a reserved exit and the guards, up to the first that rejects. At a refusal it answers Ineligible with the kind, reason and guard that execute would reject with; once every guard passed it answers Eligible. It stops before the action: it writes no state and runs no action, commit, exit, hook or watch. GRAPHMAQUINA / OPERATION FLOW One identifier. One edge. One answer. Simplified root operation; hooks and watches follow a successful commit. Request an edge execute(entity, APPROVE) Never a target state Resolve (from, id) Exactly one edge, or none Resolved once, never retried No edge: the node answers Rejected · NO_TRANSITION The policy supplies the reason nothing keyed reevaluate(entity) A separate entry point Selects an edge, or does not Run the resolved edge Guards in declaration order MOVE: none · ACTION: await A guard rejects Rejected · GUARD, guard named No staged state commit one edge found reject Outcome.Ignored NO_WATCH NO_RULE_MATCHED no rule held Commit that same edge Outcome.Applied A self-loop commits too guards pass, action ok Commit the recovery edge Its id, resolved from the origin Outcome.Failed · movedTo() action failed() SUB-MACHINES Before resolving, a child its parent does not hold: Rejected · DETACHED. After resolving, an exit of the sub-machine bound to the origin: Rejected · RESERVED_EXIT. A step that ends a held sub-machine also commits its parent's exit, unless the parent is in flight or the step moved it. ELIGIBILITY CHECK eligibility(entity, APPROVE) It runs the admission of execute in the same order. A refusal answers Ineligible with its kind. Binding check DETACHED Edge lookup NO_TRANSITION Reserved exit RESERVED_EXIT Guards, in order GUARD Action onward a call only an eligibility check runs up to here, then answers Eligible A check writes no state and runs no action, commit, exit, hook or watch. TECHNICAL EXCEPTION A timeout aborts before commit. A hook failure may happen after commit. Neither becomes an Outcome. No second edge is ever tried: another edge reaching the same state is a different transition, and it is not a substitute.

Outcome<E, S, T> is a sealed interface with four variants. Every outcome classifies itself, so a caller that only needs to know what happened and why reads it without narrowing:

Variant status() code() explanation() State written?
Applied APPLIED APPLIED empty Yes, the resolved edge committed
Rejected REJECTED NO_TRANSITION, GUARD_REJECTED, DETACHED or RESERVED_EXIT the policy's reason, the guard's, or the library's fixed text for the last two No
Failed FAILED FAILURE_ROUTED the reason the action returned; empty when failsOn or a recovery rule routed a throwable Yes, the failure route committed
Ignored IGNORED NO_WATCH or NO_RULE_MATCHED for reevaluate, NO_AUTOMATIC_TRANSITION or NO_CANDIDATE_ADMITTED for advance and the attempts of an automatic chain empty, except for NO_CANDIDATE_ADMITTED, which names each candidate's rejection No

What each variant adds to the accessors every outcome has:

status APPLIED

status REJECTED

status FAILED

status IGNORED

«sealed interface»

Outcome<E,S,T>

+entity() : E

+from() : S

+recordedState() : S

+requestedTransition() : Optional<T>

+status() : OutcomeStatus

+code() : OutcomeCode

+explanation() : Optional<String>

+records() : List<TransitionRecord>

+reactions() : List<Reaction>

+automaticSteps() : List<AutomaticStep>

+automaticFailure() : Optional<Failed>

+automaticAbort() : Optional<Aborted>

+automaticBlock() : Optional<Ignored>

+starts() : List<SubmachineStart>

+flow() : FlowView

+asApplied() : Optional<Applied>

+asRejected() : Optional<Rejected>

+asFailed() : Optional<Failed>

+asIgnored() : Optional<Ignored>

Applied

+transition() : T

+to() : S

Rejected

+transition() : T

+reason() : String

+kind() : RejectionKind

+guard() : Optional<String>

Failed

+transition() : T

+to() : S

+failureTransition() : T

+movedTo() : S

+reason() : String

+cause() : Optional<Throwable>

+failureKind() : Optional<Class>

Ignored

+reason() : IgnoreReason

+rejections() : List<Ineligible>

status APPLIED

status REJECTED

status FAILED

status IGNORED

«sealed interface»

Outcome<E,S,T>

+entity() : E

+from() : S

+recordedState() : S

+requestedTransition() : Optional<T>

+status() : OutcomeStatus

+code() : OutcomeCode

+explanation() : Optional<String>

+records() : List<TransitionRecord>

+reactions() : List<Reaction>

+automaticSteps() : List<AutomaticStep>

+automaticFailure() : Optional<Failed>

+automaticAbort() : Optional<Aborted>

+automaticBlock() : Optional<Ignored>

+starts() : List<SubmachineStart>

+flow() : FlowView

+asApplied() : Optional<Applied>

+asRejected() : Optional<Rejected>

+asFailed() : Optional<Failed>

+asIgnored() : Optional<Ignored>

Applied

+transition() : T

+to() : S

Rejected

+transition() : T

+reason() : String

+kind() : RejectionKind

+guard() : Optional<String>

Failed

+transition() : T

+to() : S

+failureTransition() : T

+movedTo() : S

+reason() : String

+cause() : Optional<Throwable>

+failureKind() : Optional<Class>

Ignored

+reason() : IgnoreReason

+rejections() : List<Ineligible>

A cascade returns Applied or Failed to the action that called cascade(...); a rejection inside it aborts the root instead. Both are provisional there: their hops are written only if the root commits.

Every outcome also has entity(), from(), recordedState(), requestedTransition(), records(), reactions(), automaticSteps(), starts() and flow(), and the three searches of its automatic steps, automaticFailure(), automaticAbort() and automaticBlock(). recordedState() is to for Applied, movedTo for Failed and from for the other two. requestedTransition() is the identifier the caller asked for, the one a reevaluation's watch selected, or the automatic edge an advance ran; it is empty only for Ignored, which ran no edge at all. Records, journals and reactions describes what records(), reactions(), automaticSteps(), starts() and flow() return, and find what the automatic steps did what the three searches return.

Read the classification with its limits in mind:

This method can be added to the quickstart's App:

static String describe(Outcome<Ticket, TicketState, TicketTransition> outcome) {
    return outcome.code() + " at " + outcome.recordedState()
            + outcome.explanation().map((String text) -> ": " + text).orElse("");
}

Contents

Map an outcome to a response

A web layer copies the classification into a type it owns, so its contract does not change when the library does. The HTTP mapping below is one application's policy, not the library's; another application may just as well answer 409 for every rejection and every handled failure:

record TransitionResponse(
        String id,
        OutcomeStatus status,
        OutcomeCode code,
        TicketState from,
        TicketState state,
        TicketTransition transition,
        String explanation) {

    static TransitionResponse of(
            String id,
            Outcome<Ticket, TicketState, TicketTransition> outcome) {
        return new TransitionResponse(
            id,
            outcome.status(),
            outcome.code(),
            outcome.from(),
            outcome.recordedState(),
            outcome.requestedTransition().orElse(null),
            outcome.explanation().orElse(null));
    }
}

static int httpStatus(OutcomeCode code) {
    return switch (code) {
        case APPLIED, FAILURE_ROUTED, NO_WATCH, NO_RULE_MATCHED,
                NO_AUTOMATIC_TRANSITION -> 200;
        case NO_TRANSITION, DETACHED, RESERVED_EXIT -> 409;
        case GUARD_REJECTED, NO_CANDIDATE_ADMITTED -> 422;
    };
}

The switch has no default: it is exhaustive, so a code added by a future release fails the build instead of falling through. Do not serialize the Outcome itself: it holds the entity, a Throwable, reactions with their own entities, and the call's flow, whose values are whatever the steps and hooks put. A call failure cannot be serialized at all: every CallFailedException, whatever its subtype, holds its MachineCall, which is not Serializable, so writing one to an ObjectOutputStream throws NotSerializableException.

Read what only one variant carries

The sealed variants remain available when a caller needs what only one of them carries: the rejecting guard, the recovery identifier, the requested destination of a failure or its cause. asApplied(), asRejected(), asFailed() and asIgnored() return the outcome as that variant, with the outcome's type arguments, or empty:

Optional<String> guard = outcome.asRejected().flatMap(Outcome.Rejected::guard);
Optional<TicketTransition> recovery = outcome.asFailed().map(Outcome.Failed::failureTransition);

Ignored.rejections() lists why an advance with the reason NO_CANDIDATE_ADMITTED ran no automatic edge: one Eligibility.Ineligible per edge it tried, in the order it tried them, each with the identifier, the state, the RejectionKind, the guard of a GUARD rejection and the reason. It is empty for every other Ignored.

A switch over the variants reads all of them at once:

static String detail(Outcome<Ticket, TicketState, TicketTransition> outcome) {
    return switch (outcome) {
        case Outcome.Applied<Ticket, TicketState, TicketTransition> applied ->
                applied.transition() + " moved to " + applied.to();
        case Outcome.Rejected<Ticket, TicketState, TicketTransition> rejected ->
                "Refused " + rejected.transition() + " by "
                        + rejected.guard().orElse("the state's policy");
        case Outcome.Failed<Ticket, TicketState, TicketTransition> failed ->
                failed.failureTransition() + " moved to " + failed.movedTo() + ": "
                        + failed.reason();
        case Outcome.Ignored<Ticket, TicketState, TicketTransition> ignored ->
                "Unchanged at " + ignored.recordedState() + " (" + ignored.reason() + ")"
                        + ignored.explanation().map((String text) -> ": " + text).orElse("");
    };
}

Technical failures throw instead of becoming a fifth outcome. An abort (TransitionAbortedException), a commit failure (CommitFailedException) and a failing hook (AfterCommitException) share the supertype CallFailedException. It says as values which call failed (call()), where it was (phase()), how far it got in writing states (statesWritten()) and which actions ran (journal()), and it hands out the call's flow (flow()). A hook fails after state was already written. Handle a failed call shows how to read them.

Records, journals and reactions

Find what the automatic steps did

A call's automatic attempts can fail, abort or stop at a guard after the call itself committed, in its own chains or in chains nested in its reactions and in other attempts. Three methods of every outcome search all of them and return the first one that matches:

Method Returns Present when
automaticFailure() Optional<Outcome.Failed<?, ?, ?>> an attempt ended in Failed, whether its route stopped the chain or let it go on
automaticAbort() Optional<AutomaticStep.Aborted> an attempt aborted, on a domain failure that no route takes, a technical failure, any other exception or maxAutomaticChain, or the reads a chain makes around its attempts threw
automaticBlock() Optional<Outcome.Ignored<?, ?, ?>> an attempt admitted none of its candidates, NO_CANDIDATE_ADMITTED; its rejections() say why

They search in the order the attempts ran. First come the reactions(), each Reaction.Done searched the same way through its outcome; then the automaticSteps(), in order, each step looked at itself and then searched through its outcome, its reactions and its steps. So an attempt nested in a reaction comes before the call's own steps. Only AutomaticStep entries count: a Reaction.Done whose outcome is Failed, or a Reaction.Aborted, is the result of a watch, which reactions() holds. The types carry wildcards because the attempts can be of other machines: peers, children and parents. A failure and a block can happen in one call: with a route that continues, the chain goes on from the recovery state, and automaticFailure() still returns the failure. Rejected and Ignored have neither steps nor reactions, so the three are empty; the outcome of an advance is its own first attempt, which you read directly.

advance(entity) goes on from where the entity stands: after a Failed, from the recovery state; after an abort before any write, from the state the attempt started in. An aborted attempt's cause is its CallFailedException, whose statesWritten() says whether it wrote: after a setter or a hook threw, the entity may have moved, and advance goes on from whatever state it has.

Handle a failed call

A call that does not return an outcome throws an Error or one of three CallFailedExceptions, always one of that very call. A request refused before the call starts is not a call failure: a null argument throws NullPointerException, an identifier of another catalogue IllegalArgumentException, and a call made where no call may start ReentrantTransitionException. Read what happened from its values, not from its message:

Type phase() statesWritten()
TransitionAbortedException and its subclasses RESOLVE, GUARD or ACTION NONE
CommitFailedException COMMIT NONE, or PARTIAL when a setter threw
AfterCommitException HOOK ALL

The phases follow the call: RESOLVE reads the identity and the state, checks the binding of a sub-machine and selects the edge; GUARD runs the root edge's guards, and is entered only when it has any; ACTION lasts from the passed guards until the step ends, its cascades, failure route, sub-machine starts and exits included, which never change the phase; COMMIT checks the original states and calls the setters; HOOK runs the after-commit hooks; REACTIONS dispatches the watch reactions; and AUTOMATIC_STEPS runs the automatic chains of the entities the commit moved, which a call of a registry without automatic edges never enters. Only an Error leaves either of the last two as a failure. The names of CallPhase and StatesWritten are stable identifiers, safe to log or to use as a metric tag.

call() is the call that failed, the same MachineCall an observer received, and journal() lists the actions that ran. Any other exception involved is the cause, a failure of another call included, which keeps the flow of its own call.

flow() is the call's flow, frozen when the call failed and attached before the observers hear of the failure. It reads like an outcome's, as read the flow after the call shows, and holds what the call wrote up to the failure:

With import io.github.graphmaquina.error.CallFailedException;, this method can be added to the quickstart's App:

static String describe(CallFailedException failure) {
    String written = switch (failure.statesWritten()) {
        case NONE -> "no state was written";
        case PARTIAL -> "some states were written";
        case ALL -> "every state was written";
    };
    // actions may have run even when no state was written
    String actions = failure.journal().isEmpty()
            ? "no action ran"
            : failure.journal().size() + " action(s) ran";
    return failure.call() + " failed in " + failure.phase() + ": " + written + ", " + actions;
}

statesWritten() describes the setters only: a JPA or other transaction around the call commits or rolls back later, on its own. Neither the phase nor statesWritten() decides a retry by itself. NONE with an action in the journal that called a payment service means the payment may have happened although no state moved. Retry only what your actions make idempotent, and reconcile the rest.


Next: Check an operation before you call it. Back to the documentation index.