Skip to main content

Use cases

The application layer is internal/application/usecases. Every command runs in one ports.UnitOfWork and has one shape (writer.go): claim the CloudEvents id in the inbox (Kafka triggers only), load the aggregate, call exactly one domain method, save with the optimistic-concurrency check and append the raised events to the outbox. The aggregate, its events and the inbox row commit or roll back together. A ports.ErrConcurrentUpdate re-runs the whole attempt once on fresh state before the conflict is reported (transact). Nothing here calls a sibling context synchronously: reads use the event-fed local read models (ports.ReadModels, ports.WorldReader).

The aggregate is FulfillmentAssignment (package internal/domain/assignment, one per (orderId, groupNo)), with the states QUEUED, RELEASED, LOCKED, SHIPPED, DELIVERED, UNSOURCEABLE and CANCELLED. There are 15 use cases: 10 commands on the aggregate, 1 inbox-only recorder, the queue sweep, the read-model projector and 2 queries.

Source: internal/application/usecases/*.go, internal/domain/assignment/commands.go, internal/adapters/inbound/kafka/handlers.go.

Triggers at a glance​

Kafka types below are the CloudEvents type suffix; the full type is com.retailnetwork.<tier>.<producer>.<entity>.<Name> (see Integration).

#Use case (file)TriggerInbound adapter
1QueueAssignment (queue.go)CustomerOrderPlacedKafka, retailnetwork.customer-ordering.events
2ReoptimiseAssignment (commands.go)POST /assignments/{id}/reoptimisations; the queue sweepREST; sweep worker in cmd/api
3ReleaseToNode (commands.go)releaseAt reached (the sweep)sweep worker in cmd/api
4HandleNodeRefusal (commands.go)PurchaseOrderRejected, PurchaseOrderExpiredKafka, retailnetwork.vendor-connectivity.events
5LockAssignment (commands.go)PurchaseOrderAcceptedKafka, retailnetwork.vendor-connectivity.events
6MarkShipped (commands.go)VendorShipmentConfirmedKafka, retailnetwork.vendor-connectivity.events
7MarkDelivered (commands.go)PackageDeliveredKafka, retailnetwork.shipping-and-tracking.events
8RecordPickupMoved (commands.go)BookingMovedKafka, retailnetwork.linehaul-transportation.events
9CancelAssignment (cancel_revise.go)CustomerOrderCancelledKafka, retailnetwork.customer-ordering.events
10ApplyRevisedPromise (cancel_revise.go)PromiseRevisedKafka, retailnetwork.delivery-promise.events
11RecordProcessed (commands.go)BookingFailedKafka, retailnetwork.linehaul-transportation.events
12SweepQueue (sweep.go)timer, SWEEP_INTERVAL (default 15 s)startSweep in cmd/api/main.go
13Projector (projector.go)24 sibling event types, see belowKafka, six topics
14Queries.ListAssignments (queries.go)GET /assignments; MCP list_assignments; A2A find_assignmentsREST, MCP, A2A
15Queries.GetAssignment (queries.go)GET /assignments/{id}; MCP get_assignment; A2A assignment_detailREST, MCP, A2A
16SourcingPolicies.Current (policy.go)GET /sourcing-policyREST
17SourcingPolicies.Publish (policy.go)PUT /sourcing-policy (with Idempotency-Key)REST

Use cases in detail​

#InputsInvariants checkedEvents raised
1orderId, destinationPostalPrefix, groups[] (groupNo, promiseId, tier, witnessNodeId, deliverByLatest, lines[])Per group, in one transaction: a group already queued for (orderId, groupNo) is skipped, so a repeated order is a no-op. Ids, tier, line bounds (at most 200 lines) are validated by assignment.Queue (shared.ErrValidation). The best candidate comes from the pure search over a fresh World snapshot; its eta must not be after deliverByLatest (ErrCandidateBreaksPromise). No candidate at all creates the assignment directly in UNSOURCEABLE. A SAME_DAY group with a candidate is released at once, in the same transaction.FulfillmentQueued (analytics topic only); FulfillmentUnsourceable when no candidate; for SAME_DAY, FulfillmentReleasedToNode. Adds one count to sourcing.groups.sourced per created group (outcome = the lower-case state), or one count with outcome=failed and a reason when the command fails.
2assignment id; optional assignmentVersion in the REST body (0 or absent skips the check); Idempotency-Key header over RESTState must be QUEUED: RELEASED is ErrReleaseInFlight, LOCKED/SHIPPED/DELIVERED is ErrAssignmentLocked, the others shared.ErrIllegalTransition. A non-zero assignmentVersion must equal the current one (ErrStaleAssignmentVersion). The candidate must not be an excluded node and not break the promise. An empty candidate set moves the assignment to UNSOURCEABLE. If the search returns the same candidate and the same release point, nothing is written and no event is raised (the version does not move).FulfillmentReassigned when the node changes (reason REOPTIMISED); FulfillmentUnsourceable (NO_CANDIDATE); none when unchanged
3assignment idA no-op unless the assignment is QUEUED (a second timer firing finds RELEASED and stops). The candidate is re-searched against fresh read models; the lines are resolved to the node's listingIds and must match the group's lines exactly. No candidate left: UNSOURCEABLE. Otherwise a Release is appended (releaseNo = previous + 1, requiredShipBy = the pickup cutoff, outcome PENDING) and the state is RELEASED.FulfillmentReleasedToNode; FulfillmentReassigned if the re-check picked another node (RELEASE_RECHECK); FulfillmentUnsourceable
4assignmentId, releaseNo, outcome (REJECTED or EXPIRED), reasonCode (trimmed, at most 200 printable characters)Refused with ErrAssignmentLocked once LOCKED or later. The release must be the pending last one (ErrReleaseNotPending otherwise: a late outcome of an old release). The refusing node is added to the exclusion list (REJECTED:<reasonCode> or EXPIRED) and the search is re-run without excluded nodes. A candidate that meets deliverByLatest: state back to QUEUED with a new releaseAt. None: UNSOURCEABLE.FulfillmentReassigned (PURCHASE_ORDER_REJECTED or PURCHASE_ORDER_EXPIRED); FulfillmentUnsourceable (NODE_REFUSED)
5assignmentId, releaseNo, acceptedAtThe release must be the pending one. A repeat for the release that already locked the assignment returns no events. A different release on a committed assignment is ErrAssignmentLocked; a CANCELLED one is ErrIllegalTransition. Sets LOCKED, lockedAt (falls back to now) and the pickup departure.FulfillmentLocked (lockReason PURCHASE_ORDER_ACCEPTED)
6assignmentId, trackingNumbers (1 to 100, each at most 64 printable characters), shippedAtState must be LOCKED (ErrIllegalTransition otherwise); a repeat on SHIPPED/DELIVERED is a no-op.FulfillmentShipped
7assignmentId, trackingNumber, deliveredAtState must be SHIPPED; the tracking number must be on the shipment (shared.ErrValidation); a repeat is a no-op. The group becomes DELIVERED only when its last package is delivered; earlier packages only save progress.FulfillmentDelivered (analytics topic only), on the last package
8assignmentId, fromDepartureId, toDepartureIdState must be LOCKED. A move to the current departure, or from a departure that is not the current one, changes nothing. The node never changes.none (the version moves)
9orderId, groupNos[], optional reason (default UNSPECIFIED)Per group, in one transaction: a group this service never queued is skipped. QUEUED, RELEASED and UNSOURCEABLE cancel; a pending release stays as it is (vendor-connectivity cancels the purchase order). LOCKED and later is ErrCancelAfterLock, which the use case turns into a refusal: the state stays, the version moves. A repeat on CANCELLED is a no-op.FulfillmentCancelled; FulfillmentCancelRefused (CANCEL_AFTER_LOCK)
10promiseId, revisionNo, deliverByLatest, nodeId (becomes the witness when not empty)Looked up by promiseId (FindByPromise). deliverByLatest is required. A revision not above the applied revisionNo is ErrStaleRevision and is ignored. DELIVERED and CANCELLED are ErrIllegalTransition. In every other state the revision is applied and the exclusion list is reset; only in QUEUED and UNSOURCEABLE is the search re-run under the new constraint (an UNSOURCEABLE group with a candidate goes back to QUEUED; a QUEUED one with none becomes UNSOURCEABLE).FulfillmentConstraintRevised; then FulfillmentReassigned (PROMISE_REVISED) or FulfillmentUnsourceable where the search changes the outcome
11CloudEvents id and typeOnly claims the inbox row: BookingFailed needs no state change because the departure's own cancellation or capacity events drive re-optimisation.none
12after cursor, limit (page of 100 in cmd/api)One pass: up to limit due releases (QUEUED with releaseAt <= now), then up to limit re-optimisations after the cursor. Rows another writer changed (ErrConcurrentUpdate), rows gone (ErrNotFound), and rows that moved on (ErrAssignmentLocked, ErrReleaseInFlight) count as skipped; other errors are collected, logged and the tick continues.those of use cases 2 and 3
13one of the 24 projected event typesEach method is one unit of work: inbox claim plus one row change. Newer revision wins (profileRevision, assignmentVersion), older instants are ignored (asOf, computedAt), any arrival order converges. No domain rule beyond that, so no event is raised.none
14optional state, nodeId, orderId, limit, after (the REST cursor decodes to it)state must be one of the seven states; limit 1 to 500 (default 100; REST fetches one extra row to learn whether a next page exists), ordered by id ascending, strictly after after; anything else is shared.ErrValidation (422 over REST; a bad limit, cursor or query parameter is answered 400 by the REST adapter before the use case runs).none
15assignment idUnknown id is ports.ErrNotFound (404 over REST).none

Which events go to which topic is on Domain events and the event catalogue. Nine of the fifteen events are on retailnetwork.order-sourcing.events; FulfillmentQueued, FulfillmentSourcingDecided, FulfillmentDelivered, AssignmentsConsolidated, AssignmentsDeconsolidated and SourcingPolicyPublished are analytics-only (Stream() in internal/domain/assignment/events.go, events_consolidation.go and internal/domain/policy/events.go).

The projected events (use case 13)​

TopicEvent types projected
retailnetwork.node-topology.eventsNodeRegistered, NodeOperationalProfileDeclared, NodeActivated, NodeSuspended, NodeRetired, LaneOpened, LaneClosed, LaneCostDeclared, ServiceAreaAssigned, RegionDefined
retailnetwork.linehaul-transportation.eventsDepartureScheduled, DepartureCapacityChanged, DepartureCancelled
retailnetwork.last-mile-delivery.eventsDeliveryWaveScheduled, DeliveryWaveCapacityChanged, DeliveryWaveCancelled, WaveCostDeclared
retailnetwork.offer-availability.eventsListingCreated, ListingAvailabilityChanged, ListingSuppressed, ListingRestored, CatalogItemDiscontinued
retailnetwork.node-performance.eventsNodeScorecardUpdated
retailnetwork.delivery-promise.eventsPromiseBookExhausted

Nine consumed topics carry 34 handled event types: 10 reach a command use case (rows 1, 4 to 11 above) and 24 are projected.

How a candidate is chosen​

internal/domain/sourcing.Search is a pure function of the World snapshot and the request:

  • A node qualifies when it is eligible (an ACTIVE vendor-operated fulfilment centre with a declared profile), not excluded, ships every line in full (listing present and not suppressed, item not discontinued, quantity available) and, for the SAME_DAY tier, is a SUB_SAME_DAY or MICRO node.
  • A path starts at a usable departure of the node whose pickup cutoff is not before now + handlingMinutes, follows at most five departures (none for SAME_DAY), respects the sort dwell at intermediate nodes, and ends at a delivery wave of the destination's service-area station whose induct cutoff is not before the last arrival and whose window ends no later than deliverByLatest. The candidate eta is that window end.
  • Cost: estimatedCostCents (the declared per-unit lane costs of every departure plus the final wave's per-stop cost, ADR 0011) plus the sourcing policy's cross-region surcharge, effectiveCostCents. The legacy points (100 per onward leg, 10 per hour between departure and wave start, 1000 for a node outside the destination's region, a scorecard penalty on the 30-day window (A 0, B 50, C 200, D 500; no scorecard or PROVISIONAL adds nothing), and 500 when the promise book is under pressure for that node and pickup departure) are the tie-break score.
  • Carbon: estimatedCo2eGrams (the declared per-unit lane emissions of every departure plus the final wave's per-stop emission, ADR 0017) is recorded beside the cost and NEVER ranks: the ordering is exactly the money ordering.
  • Order: with a published policy whose maxCostDeviationPercent is above 0, candidates within cheapest + floor(cheapest * percent / 100) come first, in-region before cross-region, then the ones over the budget; inside each group, lowest effective cents, then the lowest tie-break score, then the witness node, then the lower node id, then the lower pickup departure id. With the default policy (version 0, or every lever 0) the order is exactly that of ADR 0011: no budget tier.
  • A CONSOLIDATED promise (ADR 0016) bounds the search with its window start (deliverByEarliest: a delivery wave that ends before it is skipped, so the group lands on the wave of the chosen day; unknown = no bound) and, after the money and before the legacy score, prefers the LATER pickup cutoff, which holds the release until the latest pickup that still reaches that day. Other tiers are untouched.
  • The policy is an input: the use case reads the current version once per search (writer.currentPolicy) and passes it in sourcing.Request.Policy; the version is stamped on every candidate and on the release (policyVersion). The budget counter ordersourcing_budget_preferred_total{kind="region"} counts a release the budget rule decided. Order-level split planning does not exist (customer-ordering decides the groups), so there is no split surcharge (ADR 0014).
  • releaseAt: now for SAME_DAY; otherwise the pickup cutoff minus the node's handling time minus a 30 minute acknowledgement budget, never before now.

Source: internal/domain/sourcing/sourcing.go (Search), rank.go (Rank, the comparator and the budget tiers) and paths.go (option, penalties, explore, finish).

Errors and the problem types they become​

The REST adapter maps each error in internal/adapters/inbound/http/errors.go (first match wins); full symptoms and remedies are in Troubleshooting. Problem type URIs are https://errors.order-sourcing.retail-network.example/<slug>.

ErrorStatusProblem slug
assignment.ErrAssignmentLocked409assignment-locked
assignment.ErrReleaseInFlight409release-in-flight
assignment.ErrNodeExcluded409node-excluded
assignment.ErrStaleAssignmentVersion409stale-assignment-version
assignment.ErrCandidateBreaksPromise422candidate-breaks-promise
ports.ErrNotFound404not-found
ports.ErrConcurrentUpdate409concurrent-update
policy.ErrVersionNotNext409policy-version-not-next
shared.ErrIllegalTransition409illegal-transition
shared.ErrValidation422validation-failed
malformed body or query400malformed-request
missing Idempotency-Key on the reoptimise route400idempotency-key-required
Idempotency-Key not 1 to 128 printable ASCII characters400idempotency-key-invalid
Idempotency-Key reused with another request409idempotency-key-reused
bad limit, bad cursor, undeclared query parameter on GET /assignments400invalid-limit, invalid-cursor, unknown-query-parameter
anything else500internal-error

Each catalogue entry also declares the replay class of its problem (ADR 0019): malformed-request and assignment-locked are FINAL (stored and replayed under the same Idempotency-Key); every other entry is RETRYABLE (nothing is stored, the key is released and a retry executes again); no entry is OUTCOME, because no refusal commits state first.

assignment.ErrCancelAfterLock, ErrReleaseNotPending and ErrStaleRevision have no REST route that can raise them; they only occur on the Kafka path.

What the consumers do with a failure​

Consumer.HandleMessage (internal/adapters/inbound/kafka/consumer.go):

  • Not a valid CloudEvent, or a type with no handler: logged or skipped, acknowledged.
  • errBadPayload or shared.ErrValidation: the event can never be applied. With a DLQ configured it is dead-lettered at once to <topic>.dlq; otherwise it is skipped.
  • ports.ErrNotFound, ErrIllegalTransition, ErrAssignmentLocked, ErrReleaseNotPending, ErrStaleRevision, ErrStaleAssignmentVersion: the aggregate has moved on, a retry cannot help. Logged at WARN and acknowledged; the unit of work rolled back, so no inbox row is written for that event id. (ApplyRevisedPromise swallows ErrStaleRevision itself and commits the inbox row.)
  • Anything else (database down): returned, so the loop retries with backoff and eventually dead-letters.

Where the code differs from the earlier design text​

The aggregator's design pack (warehouse-docs, network/contexts/order-sourcing) was written before the build. The code differs in these places, and the code is the reference:

  • A group with no candidate is created UNSOURCEABLE at once (assignment.Queue, line 69), not queued.
  • A promise revision is applied in every non-terminal state, not only from UNSOURCEABLE, and it raises FulfillmentConstraintRevised (assignment.ApplyRevisedPromise).
  • MarkDelivered is per tracking number; the group delivers when the last package does.
  • BookingMoved and BookingFailed are consumed (use cases 8 and 11).
  • Reoptimisation of a non-QUEUED assignment reports the state's own error (409), not a single "not queued" error.
  • ADR 0002 A18 says the sweep interval defaults to 30 s; the code default is 15 s (defaultSweepInterval in cmd/api/main.go).
  • NodeOperationalProfileDeclared is projected with a sort dwell of 0 minutes: the handler passes a literal 0 (internal/adapters/inbound/kafka/handlers.go, NodeTopology), so rm_nodes.sort_dwell_minutes stays 0 and onward legs wait for no dwell.