Use Cases
Derived from network/model/model.yaml. This context's service is built; the model carries its as-built contracts, and identifiers (Err... names, routes, CloudEvents types) are the names the service uses.
One application service per command of FulfillmentAssignment, in the
proposed package internal/application/usecases. The runtime sequences are
on Sequence Diagrams; event
payloads on Domain Events. The
network-level walk-through with times is the
order assignment model.
Triggers at a glance
| Use case | Trigger | Inbound adapter (proposed) |
|---|---|---|
QueueAssignment | CustomerOrderPlaced | internal/adapters/inbound/kafka, topic retailnetwork.customer-ordering.events |
ReoptimiseAssignment | re-optimisation sweep; network-ops planner | scheduler in cmd/order-sourcing; internal/adapters/inbound/http POST /assignments/{assignmentId}/reoptimisations |
ReleaseToNode | releaseAt reached; SAME_DAY right after queueing | scheduler in cmd/order-sourcing (release timer); the same use case calls ReleaseConsolidated and ReleaseAsFollower when a merge applies |
HandleNodeRefusal | PurchaseOrderRejected, PurchaseOrderExpired | Kafka, topic retailnetwork.vendor-connectivity.events |
LockAssignment | PurchaseOrderAccepted | Kafka, topic retailnetwork.vendor-connectivity.events |
MarkShipped | VendorShipmentConfirmed | Kafka, topic retailnetwork.vendor-connectivity.events |
MarkDelivered | PackageDelivered | Kafka, topic retailnetwork.shipping-and-tracking.events |
CancelAssignment | CustomerOrderCancelled | Kafka, topic retailnetwork.customer-ordering.events |
ApplyRevisedPromise | PromiseRevised | Kafka, topic retailnetwork.delivery-promise.events (a revision of a RELEASED merged member runs Requeue) |
PublishSourcingPolicy | network-ops planner | PUT /sourcing-policy, behind the Idempotency-Key middleware |
Queries are not use cases here. GET /assignments?state=&nodeId=&orderId=
(ListAssignments) and GET /assignments/{assignmentId} (GetAssignment)
read the repository directly. So does GET /sourcing-policy. The read-model projectors (34 consumed event
types into the event-fed views) are not use cases either: they apply no domain rule.
How a change commits
Every use case loads the assignment, calls one aggregate method, and saves it
with an optimistic-concurrency check on assignmentVersion, writing the
outbox row (and, for a Kafka trigger, the processed_events inbox row) in the
same Postgres transaction. A relay later drains the outbox to
retailnetwork.order-sourcing.events. No use case calls another context
synchronously (sync_calls: []).
Error mapping
The problem type is the slug below; responses are
application/problem+json (RFC 9457). For Kafka-driven use cases the
status is the canonical mapping of the error (it is not sent anywhere); the
consumer action is what the adapter does.
| Error | HTTP status | Problem type | Kind |
|---|---|---|---|
ErrCandidateBreaksPromise | 422 | candidate-breaks-promise | validation of a candidate against deliverByLatest |
ErrAssignmentLocked | 409 | assignment-locked | state |
ErrNodeExcluded | 409 | node-excluded | conflict |
ErrReleaseInFlight | 409 | release-in-flight | state |
ErrStaleAssignmentVersion | 409 | stale-assignment-version | stale |
ErrCancelAfterLock | 409 | cancel-after-lock | state |
unknown assignmentId (ErrNotFound, a port error) | 404 | not-found | not found |
Kafka consumers retry ErrStaleAssignmentVersion from a fresh load. A domain
error that a retry cannot fix (for example ErrCancelAfterLock) is logged,
the inbox row is written, and the message is acknowledged; it is never
retried forever.
QueueAssignment
- Actor / trigger:
customer-orderingpublishesCustomerOrderPlaced. - Inbound adapter: Kafka consumer of
com.retailnetwork.commerce.customer-ordering.customerorder.CustomerOrderPlaced. - Preconditions: no assignment exists for (
orderId,groupNo). - Main flow:
- Check the inbox for the CloudEvents
id; stop if processed. - For each entry of
groups: build thePromiseConstraint(promiseId,tier,deliverByLatest,witnessNodeId) and the lines. - Search candidates in the read models and rank them (
AssignmentCost); the best one setsreleaseAt(VirtualQueue). - Create the assignment in
QUEUED,assignmentVersion1. - Save, outbox
FulfillmentQueued, inbox row, one transaction. - For a
SAME_DAYgroup, runReleaseToNodeat once.
- Check the inbox for the CloudEvents
- Errors: none of the model's invariants applies at creation. A group
with no feasible candidate at all is still queued;
ReleaseToNodewill declare it unsourceable (see the open question onreleaseAtwithout a candidate). - Events:
FulfillmentQueued. - Idempotency: inbox on the CloudEvents
id; a unique key on (orderId,groupNo) makes a repeated event a no-op.
ReoptimiseAssignment
-
Actor / trigger: the re-optimisation sweep over
QUEUEDassignments; the network-ops planner. -
Inbound adapter: scheduler; REST
POST /assignments/{assignmentId}/reoptimisationswithIdempotency-Key. -
Preconditions: state
QUEUED. -
Main flow:
- Load the assignment (404 if unknown).
- Re-run the candidate search on the current read models, skipping
excluded nodes and candidates with
eta > deliverByLatest. - Rank by
AssignmentCost; ties go to the witness node. - If the best node differs, replace the candidate, move
releaseAt, bumpassignmentVersionand raiseFulfillmentReassigned. If it is the same node with a better path, update the candidate andreleaseAtsilently. - Save with the version check and the outbox row.
-
Errors:
Error When HTTP Problem typeErrAssignmentLockedstate LOCKED(or later)409 assignment-lockedErrReleaseInFlightstate RELEASED, a release is pending409 release-in-flightErrNodeExcludedthe chosen candidate is an excluded node (guard) 409 node-excludedErrCandidateBreaksPromisethe chosen candidate's etais pastdeliverByLatest(guard)422 candidate-breaks-promiseErrStaleAssignmentVersionthe row changed since the load 409 stale-assignment-versionErrIllegalTransitionstate UNSOURCEABLEorCANCELLED(ADR 0002 A5)409 illegal-transitionErrAssignmentLockedstate SHIPPEDorDELIVERED(asLOCKED)409 assignment-lockednot found ( ErrNotFound)unknown assignmentId404 not-found -
Events:
FulfillmentReassignedwhen the node changes; none otherwise. -
Idempotency: a re-run on unchanged read models picks the same candidate and changes nothing. The REST route stores the response per
Idempotency-Key.
ReleaseToNode
-
Actor / trigger: the release timer at
releaseAt; immediately forSAME_DAY. -
Inbound adapter: scheduler (
QUEUEDassignments withreleaseAt <= now). -
Preconditions: state
QUEUED; no releasePENDING. -
Main flow:
- Load the assignment.
- Re-check the candidate against fresh read models: not excluded,
eta <= deliverByLatest, node stillACTIVE, every line available. - If it holds: append a
Release(releaseNo= last + 1,nodeId,releasedAt,requiredShipBy= pickup cutoff,outcomePENDING), resolve each line'slistingIdfor the node, stateRELEASED, raiseFulfillmentReleasedToNode. - If no candidate meets
deliverByLatest: stateUNSOURCEABLE, raiseFulfillmentUnsourceablewithexcludedNodes. - Consolidation (only when the current
SourcingPolicyhasconsolidationMaxAssignmentsof 2 or more and the due carrier has a key and isCONSOLIDATED): read the queued groups of the same key, run the puresourcing.Merge; with at least one follower the carrier callsReleaseConsolidatedand each followerReleaseAsFollowerin the same unit of work (FulfillmentReleasedToNodewithmembers,AssignmentsConsolidated). Otherwise the carrier releases alone, as before. - Save with the version check and the outbox row.
-
Errors:
Error When HTTP Problem typeErrReleaseInFlighta release is already PENDING409 release-in-flightErrCandidateBreaksPromisethe candidate no longer meets deliverByLatest(guard; the flow picks another or goesUNSOURCEABLE)422 candidate-breaks-promiseErrNodeExcludedthe candidate is an excluded node (guard) 409 node-excludedErrStaleAssignmentVersionconcurrent change 409 stale-assignment-version -
Events:
FulfillmentReleasedToNodeorFulfillmentUnsourceable. -
Idempotency: the timer selects only
QUEUEDrows; a second firing findsRELEASEDand stops.vendor-connectivityderivespoNumberfromassignmentId + releaseNo, so a re-delivered event issues no second PO.
HandleNodeRefusal
-
Actor / trigger:
vendor-connectivitypublishesPurchaseOrderRejectedorPurchaseOrderExpired. -
Inbound adapter: Kafka consumer of
com.retailnetwork.partner.vendor-connectivity.purchaseorder.PurchaseOrderRejectedand...purchaseorder.PurchaseOrderExpired. -
Preconditions: state
RELEASED; the event'sreleaseNois thePENDINGrelease. -
Main flow:
- Inbox check.
- Load; if
releaseNois not the pending release, record the inbox row and stop (a late outcome of an old release). - Set that release's
outcome(REJECTEDwithreasonCode, orEXPIRED) and addExcludedNode{nodeId, reason}. - Search and rank candidates without the excluded nodes.
- A candidate meets
deliverByLatest: stateQUEUED, newreleaseAt(immediately if already past), raiseFulfillmentReassigned(fromNodeId= refusing node). None: stateUNSOURCEABLE, raiseFulfillmentUnsourceable. - Save with version check, outbox and inbox rows.
-
Errors:
Error When HTTP Problem typeErrAssignmentLockedthe assignment is already LOCKED409 assignment-lockedErrStaleAssignmentVersionconcurrent change 409 stale-assignment-version(retry) -
Events:
FulfillmentReassignedorFulfillmentUnsourceable. -
Idempotency: inbox; the
releaseNomatch makes a repeat a no-op.
LockAssignment
-
Actor / trigger:
vendor-connectivitypublishesPurchaseOrderAccepted(LockOnCommit). -
Inbound adapter: Kafka consumer of
com.retailnetwork.partner.vendor-connectivity.purchaseorder.PurchaseOrderAccepted. -
Preconditions: state
RELEASED;releaseNois the pending release. -
Main flow:
- Inbox check; load.
- Set the release
outcometoACCEPTED,lockedAt = acceptedAt, stateLOCKED. - Save with version check, outbox
FulfillmentLocked, inbox row.
-
Errors:
Error When HTTP Problem typeErrAssignmentLockedalready LOCKEDby a different release (should not happen)409 assignment-lockedErrStaleAssignmentVersionconcurrent change 409 stale-assignment-version(retry)An acceptance for a
CANCELLEDassignment has no modelled outcome (open question): the proposal is to log it and record the inbox row. -
Events:
FulfillmentLocked. -
Idempotency: inbox; a repeat on
LOCKEDwith the samereleaseNois a no-op.
MarkShipped
- Actor / trigger:
vendor-connectivitypublishesVendorShipmentConfirmed. - Inbound adapter: Kafka consumer of
com.retailnetwork.partner.vendor-connectivity.purchaseorder.VendorShipmentConfirmed. - Preconditions: state
LOCKED. - Main flow: inbox check; load; record
trackingNumbers,shippedAt; stateSHIPPED; save with outboxFulfillmentShipped. - Errors:
ErrStaleAssignmentVersion→ 409stale-assignment-version(retry). A shipment for an assignment that is notLOCKEDhas noErr...in the model; it is logged. - Events:
FulfillmentShipped. - Idempotency: inbox; a repeat on
SHIPPEDis a no-op.
MarkDelivered
- Actor / trigger:
shipping-and-trackingpublishesPackageDelivered. - Inbound adapter: Kafka consumer of
com.retailnetwork.logistics.shipping-and-tracking.journey.PackageDelivered. - Preconditions: state
SHIPPED. - Main flow: inbox check; load by
assignmentId; recorddeliveredAt; stateDELIVERED; save with outboxFulfillmentDelivered. - Errors:
ErrStaleAssignmentVersion→ 409stale-assignment-version(retry). - Events:
FulfillmentDelivered. - Idempotency: inbox; a repeat on
DELIVEREDis a no-op. Whether a multi-package group waits for everytrackingNumberis an open question.
CancelAssignment
-
Actor / trigger:
customer-orderingpublishesCustomerOrderCancelled. -
Inbound adapter: Kafka consumer of
com.retailnetwork.commerce.customer-ordering.customerorder.CustomerOrderCancelled. -
Preconditions: state
QUEUED, an unmergedRELEASEDorUNSOURCEABLE; fromLOCKED,SHIPPEDorDELIVERED, and from aRELEASEDmember of a live merge, the request is refused (below). -
Main flow:
- Inbox check.
- For each
groupNoingroupNos, load the assignment of (orderId,groupNo). - Cancel: state
CANCELLED; aPENDINGrelease stays as it is (the PO is cancelled byvendor-connectivityon the event). - Save with outbox
FulfillmentCancelled(reasonfrom the event).
-
Errors:
Error When HTTP Problem typeErrCancelAfterLockstate LOCKED,SHIPPEDorDELIVEREDno HTTP (consumer): RefuseCancelkeeps the state and publishesFulfillmentCancelRefused(CANCEL_AFTER_LOCK)cancel-after-lockErrCancelWhileMergeda RELEASEDcarrier or follower of a live mergeno HTTP (consumer): RefuseCancelkeeps the state, withdraws nothing and publishesFulfillmentCancelRefused(CANCEL_WHILE_MERGED); the order side keeps the group and may retrynot an HTTP error ErrStaleAssignmentVersionconcurrent change 409 stale-assignment-version(retry) -
Events:
FulfillmentCancelled, orFulfillmentCancelRefusedfor a refused request. -
Idempotency: inbox; an already
CANCELLEDassignment is a no-op.
ApplyRevisedPromise
- Actor / trigger:
delivery-promisepublishesPromiseRevised(its answer toFulfillmentUnsourceable). - Inbound adapter: Kafka consumer of
com.retailnetwork.commerce.delivery-promise.promise.PromiseRevised. - Preconditions: the assignment of
promiseIdis in any non-terminal state (QUEUED,RELEASED,LOCKED,SHIPPED,UNSOURCEABLE) and the event'srevisionNois higher than the applied one; otherwise the event is ignored (order-sourcing ADR 0002 A9, gap G13). - Main flow:
- Inbox check; load the assignment by
promiseId. - Replace
PromiseConstraint.deliverByLatest(a revision never moves it earlier,delivery-promise'sErrRevisionMovesEarlier) andwitnessNodeIdfrom the event'snodeIdwhen present; reset the node exclusions (they are scoped to the revision). - In
UNSOURCEABLE: search and rank candidates under the new constraint; if one exists setreleaseAtand stateQUEUED, otherwise stayUNSOURCEABLEsilently (no secondFulfillmentUnsourceable;delivery-promiseanswers withPromiseUnkeepable). InQUEUED: re-search; a changed node raisesFulfillmentReassigned(reasonPROMISE_REVISED), an empty set isUNSOURCEABLE(FulfillmentUnsourceable, reasonNO_CANDIDATE). InRELEASED,LOCKEDandSHIPPEDonly the constraint changes: the node is already committed. - Save with version check and inbox row.
- Inbox check; load the assignment by
- Errors:
ErrStaleAssignmentVersion→ 409stale-assignment-version(retry). A revision not above the appliedrevisionNo(ErrStaleRevision) is ignored; the inbox row is still written. A terminal assignment (DELIVERED,CANCELLED) isErrIllegalTransition. - Events:
FulfillmentConstraintRevised(assignmentId,revisionNo,deliverByLatest, analytics only) is ALWAYS raised when a revision applies, in every state (ADR 0002 A9);FulfillmentReassignedfollows when aQUEUEDassignment changes node, andFulfillmentUnsourceablewhen aQUEUEDassignment loses its last candidate. - Idempotency: inbox; applied from
UNSOURCEABLE, and for a mergedRELEASEDmember throughRequeue: when the revised window (after the new latest, or before the new earliest when known) excludes the mergedeta, the release is withdrawn (FulfillmentReleaseWithdrawn), every member's pending release gets outcomeWITHDRAWN, every member returns toQUEUEDand is re-searched with no node exclusion (FulfillmentReassignedwithCONSOLIDATION_WITHDRAWNif its node changed), andAssignmentsDeconsolidatedis raised. A stale revision stays ignored.
PublishSourcingPolicy
- Actor / trigger: the network-ops planner,
PUT /sourcing-policywith the whole document (crossRegionSurchargeCents,maxCostDeviationPercent,consolidationMaxAssignments). - Main flow: validate the ranges; publish version current + 1; raise the analytics-only
SourcingPolicyPublishedin the same transaction. - Errors: an out-of-range field is 422
validation-failed; an empty body is 400; a publish that loses a race for the same version is retried once, then 409concurrent-update. - Idempotency: the route sits behind the
Idempotency-Keymiddleware like a POST, so a retried publish replays instead of publishing twice. Because the body is the whole document, a PUT that omitsconsolidationMaxAssignmentsswitches consolidation off again.