Skip to main content

Use Cases

As built

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 caseTriggerInbound adapter (proposed)
QueueAssignmentCustomerOrderPlacedinternal/adapters/inbound/kafka, topic retailnetwork.customer-ordering.events
ReoptimiseAssignmentre-optimisation sweep; network-ops plannerscheduler in cmd/order-sourcing; internal/adapters/inbound/http POST /assignments/{assignmentId}/reoptimisations
ReleaseToNodereleaseAt reached; SAME_DAY right after queueingscheduler in cmd/order-sourcing (release timer); the same use case calls ReleaseConsolidated and ReleaseAsFollower when a merge applies
HandleNodeRefusalPurchaseOrderRejected, PurchaseOrderExpiredKafka, topic retailnetwork.vendor-connectivity.events
LockAssignmentPurchaseOrderAcceptedKafka, topic retailnetwork.vendor-connectivity.events
MarkShippedVendorShipmentConfirmedKafka, topic retailnetwork.vendor-connectivity.events
MarkDeliveredPackageDeliveredKafka, topic retailnetwork.shipping-and-tracking.events
CancelAssignmentCustomerOrderCancelledKafka, topic retailnetwork.customer-ordering.events
ApplyRevisedPromisePromiseRevisedKafka, topic retailnetwork.delivery-promise.events (a revision of a RELEASED merged member runs Requeue)
PublishSourcingPolicynetwork-ops plannerPUT /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.

ErrorHTTP statusProblem typeKind
ErrCandidateBreaksPromise422candidate-breaks-promisevalidation of a candidate against deliverByLatest
ErrAssignmentLocked409assignment-lockedstate
ErrNodeExcluded409node-excludedconflict
ErrReleaseInFlight409release-in-flightstate
ErrStaleAssignmentVersion409stale-assignment-versionstale
ErrCancelAfterLock409cancel-after-lockstate
unknown assignmentId (ErrNotFound, a port error)404not-foundnot 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-ordering publishes CustomerOrderPlaced.
  • Inbound adapter: Kafka consumer of com.retailnetwork.commerce.customer-ordering.customerorder.CustomerOrderPlaced.
  • Preconditions: no assignment exists for (orderId, groupNo).
  • Main flow:
    1. Check the inbox for the CloudEvents id; stop if processed.
    2. For each entry of groups: build the PromiseConstraint (promiseId, tier, deliverByLatest, witnessNodeId) and the lines.
    3. Search candidates in the read models and rank them (AssignmentCost); the best one sets releaseAt (VirtualQueue).
    4. Create the assignment in QUEUED, assignmentVersion 1.
    5. Save, outbox FulfillmentQueued, inbox row, one transaction.
    6. For a SAME_DAY group, run ReleaseToNode at once.
  • Errors: none of the model's invariants applies at creation. A group with no feasible candidate at all is still queued; ReleaseToNode will declare it unsourceable (see the open question on releaseAt without 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 QUEUED assignments; the network-ops planner.

  • Inbound adapter: scheduler; REST POST /assignments/{assignmentId}/reoptimisations with Idempotency-Key.

  • Preconditions: state QUEUED.

  • Main flow:

    1. Load the assignment (404 if unknown).
    2. Re-run the candidate search on the current read models, skipping excluded nodes and candidates with eta > deliverByLatest.
    3. Rank by AssignmentCost; ties go to the witness node.
    4. If the best node differs, replace the candidate, move releaseAt, bump assignmentVersion and raise FulfillmentReassigned. If it is the same node with a better path, update the candidate and releaseAt silently.
    5. Save with the version check and the outbox row.
  • Errors:

    ErrorWhenHTTPProblem type
    ErrAssignmentLockedstate LOCKED (or later)409assignment-locked
    ErrReleaseInFlightstate RELEASED, a release is pending409release-in-flight
    ErrNodeExcludedthe chosen candidate is an excluded node (guard)409node-excluded
    ErrCandidateBreaksPromisethe chosen candidate's eta is past deliverByLatest (guard)422candidate-breaks-promise
    ErrStaleAssignmentVersionthe row changed since the load409stale-assignment-version
    ErrIllegalTransitionstate UNSOURCEABLE or CANCELLED (ADR 0002 A5)409illegal-transition
    ErrAssignmentLockedstate SHIPPED or DELIVERED (as LOCKED)409assignment-locked
    not found (ErrNotFound)unknown assignmentId404not-found
  • Events: FulfillmentReassigned when 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 for SAME_DAY.

  • Inbound adapter: scheduler (QUEUED assignments with releaseAt <= now).

  • Preconditions: state QUEUED; no release PENDING.

  • Main flow:

    1. Load the assignment.
    2. Re-check the candidate against fresh read models: not excluded, eta <= deliverByLatest, node still ACTIVE, every line available.
    3. If it holds: append a Release (releaseNo = last + 1, nodeId, releasedAt, requiredShipBy = pickup cutoff, outcome PENDING), resolve each line's listingId for the node, state RELEASED, raise FulfillmentReleasedToNode.
    4. If no candidate meets deliverByLatest: state UNSOURCEABLE, raise FulfillmentUnsourceable with excludedNodes.
    5. Consolidation (only when the current SourcingPolicy has consolidationMaxAssignments of 2 or more and the due carrier has a key and is CONSOLIDATED): read the queued groups of the same key, run the pure sourcing.Merge; with at least one follower the carrier calls ReleaseConsolidated and each follower ReleaseAsFollower in the same unit of work (FulfillmentReleasedToNode with members, AssignmentsConsolidated). Otherwise the carrier releases alone, as before.
    6. Save with the version check and the outbox row.
  • Errors:

    ErrorWhenHTTPProblem type
    ErrReleaseInFlighta release is already PENDING409release-in-flight
    ErrCandidateBreaksPromisethe candidate no longer meets deliverByLatest (guard; the flow picks another or goes UNSOURCEABLE)422candidate-breaks-promise
    ErrNodeExcludedthe candidate is an excluded node (guard)409node-excluded
    ErrStaleAssignmentVersionconcurrent change409stale-assignment-version
  • Events: FulfillmentReleasedToNode or FulfillmentUnsourceable.

  • Idempotency: the timer selects only QUEUED rows; a second firing finds RELEASED and stops. vendor-connectivity derives poNumber from assignmentId + releaseNo, so a re-delivered event issues no second PO.

HandleNodeRefusal​

  • Actor / trigger: vendor-connectivity publishes PurchaseOrderRejected or PurchaseOrderExpired.

  • Inbound adapter: Kafka consumer of com.retailnetwork.partner.vendor-connectivity.purchaseorder.PurchaseOrderRejected and ...purchaseorder.PurchaseOrderExpired.

  • Preconditions: state RELEASED; the event's releaseNo is the PENDING release.

  • Main flow:

    1. Inbox check.
    2. Load; if releaseNo is not the pending release, record the inbox row and stop (a late outcome of an old release).
    3. Set that release's outcome (REJECTED with reasonCode, or EXPIRED) and add ExcludedNode{nodeId, reason}.
    4. Search and rank candidates without the excluded nodes.
    5. A candidate meets deliverByLatest: state QUEUED, new releaseAt (immediately if already past), raise FulfillmentReassigned (fromNodeId = refusing node). None: state UNSOURCEABLE, raise FulfillmentUnsourceable.
    6. Save with version check, outbox and inbox rows.
  • Errors:

    ErrorWhenHTTPProblem type
    ErrAssignmentLockedthe assignment is already LOCKED409assignment-locked
    ErrStaleAssignmentVersionconcurrent change409stale-assignment-version (retry)
  • Events: FulfillmentReassigned or FulfillmentUnsourceable.

  • Idempotency: inbox; the releaseNo match makes a repeat a no-op.

LockAssignment​

  • Actor / trigger: vendor-connectivity publishes PurchaseOrderAccepted (LockOnCommit).

  • Inbound adapter: Kafka consumer of com.retailnetwork.partner.vendor-connectivity.purchaseorder.PurchaseOrderAccepted.

  • Preconditions: state RELEASED; releaseNo is the pending release.

  • Main flow:

    1. Inbox check; load.
    2. Set the release outcome to ACCEPTED, lockedAt = acceptedAt, state LOCKED.
    3. Save with version check, outbox FulfillmentLocked, inbox row.
  • Errors:

    ErrorWhenHTTPProblem type
    ErrAssignmentLockedalready LOCKED by a different release (should not happen)409assignment-locked
    ErrStaleAssignmentVersionconcurrent change409stale-assignment-version (retry)

    An acceptance for a CANCELLED assignment has no modelled outcome (open question): the proposal is to log it and record the inbox row.

  • Events: FulfillmentLocked.

  • Idempotency: inbox; a repeat on LOCKED with the same releaseNo is a no-op.

MarkShipped​

  • Actor / trigger: vendor-connectivity publishes VendorShipmentConfirmed.
  • Inbound adapter: Kafka consumer of com.retailnetwork.partner.vendor-connectivity.purchaseorder.VendorShipmentConfirmed.
  • Preconditions: state LOCKED.
  • Main flow: inbox check; load; record trackingNumbers, shippedAt; state SHIPPED; save with outbox FulfillmentShipped.
  • Errors: ErrStaleAssignmentVersion → 409 stale-assignment-version (retry). A shipment for an assignment that is not LOCKED has no Err... in the model; it is logged.
  • Events: FulfillmentShipped.
  • Idempotency: inbox; a repeat on SHIPPED is a no-op.

MarkDelivered​

  • Actor / trigger: shipping-and-tracking publishes PackageDelivered.
  • Inbound adapter: Kafka consumer of com.retailnetwork.logistics.shipping-and-tracking.journey.PackageDelivered.
  • Preconditions: state SHIPPED.
  • Main flow: inbox check; load by assignmentId; record deliveredAt; state DELIVERED; save with outbox FulfillmentDelivered.
  • Errors: ErrStaleAssignmentVersion → 409 stale-assignment-version (retry).
  • Events: FulfillmentDelivered.
  • Idempotency: inbox; a repeat on DELIVERED is a no-op. Whether a multi-package group waits for every trackingNumber is an open question.

CancelAssignment​

  • Actor / trigger: customer-ordering publishes CustomerOrderCancelled.

  • Inbound adapter: Kafka consumer of com.retailnetwork.commerce.customer-ordering.customerorder.CustomerOrderCancelled.

  • Preconditions: state QUEUED, an unmerged RELEASED or UNSOURCEABLE; from LOCKED, SHIPPED or DELIVERED, and from a RELEASED member of a live merge, the request is refused (below).

  • Main flow:

    1. Inbox check.
    2. For each groupNo in groupNos, load the assignment of (orderId, groupNo).
    3. Cancel: state CANCELLED; a PENDING release stays as it is (the PO is cancelled by vendor-connectivity on the event).
    4. Save with outbox FulfillmentCancelled (reason from the event).
  • Errors:

    ErrorWhenHTTPProblem type
    ErrCancelAfterLockstate LOCKED, SHIPPED or DELIVEREDno HTTP (consumer): RefuseCancel keeps the state and publishes FulfillmentCancelRefused (CANCEL_AFTER_LOCK)cancel-after-lock
    ErrCancelWhileMergeda RELEASED carrier or follower of a live mergeno HTTP (consumer): RefuseCancel keeps the state, withdraws nothing and publishes FulfillmentCancelRefused (CANCEL_WHILE_MERGED); the order side keeps the group and may retrynot an HTTP error
    ErrStaleAssignmentVersionconcurrent change409stale-assignment-version (retry)
  • Events: FulfillmentCancelled, or FulfillmentCancelRefused for a refused request.

  • Idempotency: inbox; an already CANCELLED assignment is a no-op.

ApplyRevisedPromise​

  • Actor / trigger: delivery-promise publishes PromiseRevised (its answer to FulfillmentUnsourceable).
  • Inbound adapter: Kafka consumer of com.retailnetwork.commerce.delivery-promise.promise.PromiseRevised.
  • Preconditions: the assignment of promiseId is in any non-terminal state (QUEUED, RELEASED, LOCKED, SHIPPED, UNSOURCEABLE) and the event's revisionNo is higher than the applied one; otherwise the event is ignored (order-sourcing ADR 0002 A9, gap G13).
  • Main flow:
    1. Inbox check; load the assignment by promiseId.
    2. Replace PromiseConstraint.deliverByLatest (a revision never moves it earlier, delivery-promise's ErrRevisionMovesEarlier) and witnessNodeId from the event's nodeId when present; reset the node exclusions (they are scoped to the revision).
    3. In UNSOURCEABLE: search and rank candidates under the new constraint; if one exists set releaseAt and state QUEUED, otherwise stay UNSOURCEABLE silently (no second FulfillmentUnsourceable; delivery-promise answers with PromiseUnkeepable). In QUEUED: re-search; a changed node raises FulfillmentReassigned (reason PROMISE_REVISED), an empty set is UNSOURCEABLE (FulfillmentUnsourceable, reason NO_CANDIDATE). In RELEASED, LOCKED and SHIPPED only the constraint changes: the node is already committed.
    4. Save with version check and inbox row.
  • Errors: ErrStaleAssignmentVersion → 409 stale-assignment-version (retry). A revision not above the applied revisionNo (ErrStaleRevision) is ignored; the inbox row is still written. A terminal assignment (DELIVERED, CANCELLED) is ErrIllegalTransition.
  • Events: FulfillmentConstraintRevised (assignmentId, revisionNo, deliverByLatest, analytics only) is ALWAYS raised when a revision applies, in every state (ADR 0002 A9); FulfillmentReassigned follows when a QUEUED assignment changes node, and FulfillmentUnsourceable when a QUEUED assignment loses its last candidate.
  • Idempotency: inbox; applied from UNSOURCEABLE, and for a merged RELEASED member through Requeue: when the revised window (after the new latest, or before the new earliest when known) excludes the merged eta, the release is withdrawn (FulfillmentReleaseWithdrawn), every member's pending release gets outcome WITHDRAWN, every member returns to QUEUED and is re-searched with no node exclusion (FulfillmentReassigned with CONSOLIDATION_WITHDRAWN if its node changed), and AssignmentsDeconsolidated is raised. A stale revision stays ignored.

PublishSourcingPolicy​

  • Actor / trigger: the network-ops planner, PUT /sourcing-policy with the whole document (crossRegionSurchargeCents, maxCostDeviationPercent, consolidationMaxAssignments).
  • Main flow: validate the ranges; publish version current + 1; raise the analytics-only SourcingPolicyPublished in 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 409 concurrent-update.
  • Idempotency: the route sits behind the Idempotency-Key middleware like a POST, so a retried publish replays instead of publishing twice. Because the body is the whole document, a PUT that omits consolidationMaxAssignments switches consolidation off again.