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 the model's aggregates, in
internal/application/usecases. Each one loads at most one aggregate,
changes it, and saves it with its events in one transaction. The events
go into outbox_events in that transaction, and a relay publishes them
(model integration_rules). The step-by-step diagrams are on
Sequence Diagrams; the
contract is apis/last-mile-delivery/openapi.yaml.
Reads are not use cases: GET /waves?stationNodeId=&serviceDate= reads the
wave table directly.
Triggers at a glance
| Use case | Aggregate | Trigger | Inbound adapter |
|---|---|---|---|
ScheduleWave | DeliveryWave | Station planner | REST POST /waves |
InductPackage | DeliveryWave | policies InductOnArrival, RetryNextWave | Kafka consumer of LoadArrived; internal handler of own DeliveryAttempted |
CloseInduction | DeliveryWave | Station planner | REST POST /waves/{waveId}/induction-closures |
DispatchWave | DeliveryWave | Station planner | REST POST /waves/{waveId}/dispatches |
CompleteWave | DeliveryWave | policy: the last route of the wave completes, or a dispatch with no route (ADR 0002 A9) | none (internal, same transaction) |
CancelWave | DeliveryWave | Station planner | REST POST /waves/{waveId}/cancellations |
DeclareCost | DeliveryWave | Station planner | REST POST /waves/{waveId}/cost-declarations |
DeclareEmission | DeliveryWave | Station planner | REST POST /waves/{waveId}/emission-declarations |
PlanRoute | Route | Station planner | REST POST /routes |
StartRoute | Route | DSP driver app | REST POST /routes/{routeId}/starts |
RecordAttempt | Route | DSP driver app | REST POST /routes/{routeId}/attempts |
CompleteRoute | Route | policy CompleteRouteOnLastAttempt: the attempt that records the last outstanding package (ADR 0002 A16) | none (internal, same unit of work) |
ContractPartner | DeliveryServicePartner | caller not named in the model | REST POST /partners |
Error mapping
Every error is returned as application/problem+json (RFC 9457) with a
type slug. Domain errors come from the model's invariants. The shared
slugs not-found, illegal-transition, concurrent-update and
validation-failed are the same in every retail-network service; the other
slugs are one per Err... name (kebab-case, no Err). Source: last-mile-delivery
ADR 0002 (invariants table) and internal/adapters/inbound/http/errors.go.
| Error | HTTP | Problem type | Kind |
|---|---|---|---|
ErrInvalidWaveTimes | 422 | invalid-wave-times | validation |
ErrWaveFull | 409 | wave-full | capacity |
ErrInductionClosed | 409 | induction-closed | closed |
ErrRouteOverCapacity | 409 | route-over-capacity | capacity |
ErrRouteNotStarted | 409 | route-not-started | state |
ErrAlreadyDelivered | 409 | already-delivered | conflict |
ErrInvalidVanCapacity | 422 | invalid-van-capacity | validation |
ErrUnknownStation | 422 | unknown-station | validation |
ErrPackageNotOnRoute | 404 | package-not-on-route | not found |
ErrAttemptAlreadyRecorded | 409 | attempt-already-recorded | conflict |
ErrPackageNotInducted | 409 | package-not-inducted | state |
ErrPackageAlreadyRouted | 409 | package-already-routed | conflict |
ErrStopKeyMismatch | 409 | stop-key-mismatch | validation |
ErrPartnerInactive | 409 | partner-inactive | state |
ErrPartnerStationMismatch | 409 | partner-station-mismatch | conflict |
ErrRouteIncomplete | 409 | route-incomplete | state |
ErrNotFound | 404 | not-found | not found |
ErrIllegalTransition | 409 | illegal-transition | state |
ErrConcurrentUpdate | 409 | concurrent-update | stale |
ErrValidation | 422 | validation-failed | validation (malformed body, a value-object rule, an unknown field) |
Idempotency of every POST
Governed by last-mile-delivery ADR 0010 (it supersedes the per-route key and the 422 on reuse of ADR 0002 A21):
- Every
POSTtakes anIdempotency-Keyof 1 to 128 printable ASCII characters: missing is 400idempotency-key-required, malformed is 400idempotency-key-invalid. - The key is global (looked up by the key alone). The request fingerprint is
method + path + SHA-256 of the body. The same key and fingerprint replays the
stored answer with the header
Idempotency-Replayed: true; the same key with another fingerprint is 409idempotency-key-reused. - A 2xx and a 4xx answer are stored (24 hours); a 5xx, an error or a panic rolls everything back and is stored nowhere, so the retry re-executes. The key row, the aggregate change and the outbox rows commit in one transaction.
ScheduleWave
- Actor / trigger: Station planner.
- Inbound adapter: REST
POST /waveswithIdempotency-Key. - Input:
stationNodeId,serviceDate,inductCutoffAt,windowStart,windowEnd,stopCapacity. - Preconditions:
stationNodeIdis aDELIVERY_STATIONknown toStationView(ADR 0002 A1); an unknown or non-station id isErrUnknownStation. The check lives in the use case, not in the aggregate, becauseStationViewis an application read model.serviceDateis aYYYY-MM-DDdate andstopCapacityan integer from 0 up. - Main flow:
- Look up the
Idempotency-Key; if it was seen, return the stored response. - Check the station against
StationView. - Build
DeliveryWaveinOPENwithStopCapacity{stops, assigned: 0}. - Check
inductCutoffAt < windowStart < windowEnd. - In one transaction: insert the wave, write
DeliveryWaveScheduledto the outbox, store the idempotency key. Then the packages waiting at the station (AT_STATION) are inducted into the new wave, oldest arrival first, until it is full (ADR 0002 A19). - Return
201with the wave.
- Look up the
- Errors:
ErrUnknownStation→ 422unknown-station;ErrInvalidWaveTimes→ 422invalid-wave-times; 422validation-failed(malformed body, badserviceDate). - Events:
DeliveryWaveScheduled. - Idempotency:
Idempotency-Keyheader (see above).
InductPackage
- Actor / trigger: policy
InductOnArrival(onLoadArrivedat a delivery station) and policyRetryNextWave(on aFAILEDattempt). - Inbound adapter: Kafka consumer of
com.retailnetwork.logistics.linehaul-transportation.load.LoadArrived; an internal handler of this context's ownDeliveryAttemptedfor retries. - Input:
trackingNumber,stationNodeId, the arrival (or failure) instant. - Preconditions: the arrival is at a
DELIVERY_STATION: the event'snodeTypewins, andStationViewdecides only when the event carries none (ADR 0002 A8); otherwise the event is ignored. The package's destination area is notCARRIER_HANDOFF(ADR 0015, below). - Main flow:
- Claim the CloudEvents
idinprocessed_events(skip if seen). - Record the arrival in
InboundPackagesView(LoadArrivedonly). - For each tracking number, refuse it when its destination postal prefix is
a known
CARRIER_HANDOFFservice area (see below); otherwise list the station'sOPENwaves whoseinductCutoffAtis after the instant, earliest first. - Call
InductPackageon the first wave. OnErrWaveFullorErrInductionClosed, try the next wave. - On success, in one transaction: save the wave (version checked), record
the package against the wave, and write
DeliveryWaveCapacityChanged.
- Claim the CloudEvents
- Errors (no HTTP; asynchronous):
ErrWaveFull,ErrInductionClosedmove on to the next wave. If no wave accepts the package it staysAT_STATIONandPackageInductionDeferredis raised (ADR 0002 A19).ErrConcurrentUpdate(concurrent-update) retries the whole attempt once. - Events:
DeliveryWaveCapacityChanged, one per inducted package. - Idempotency: the inbox on the CloudEvents
id, plus a no-op when the tracking number is already inducted in anOPENwave. - Carrier-area exclusion (ADR 0015): a
ServiceAreaAssignedwhosedeliveryModeisCARRIER_HANDOFFis not wave territory. The consumer stores the mode in its area read model (an event withoutdeliveryModedecodes toNETWORK_ROUTE);arriveNewandretryWaitingthen refuse a package whose destination prefix is such an area: no wave, no stop capacity, no history row, no event, and the counterlast_mile_delivery.carrier_area.skippedrises. A package whose prefix has no area row, or whose label data is missing (thepkg:<trackingNumber>stop), is inducted as usual. Packages already inducted when an area flips stay on their wave. - Failure count:
PackageAttemptHistorycounts failed attempts; the third failure raisesPackageReturnInitiatedand the package is not re-inducted (ADR 0002 A18).
CloseInduction
- Actor / trigger: Station planner.
- Inbound adapter: REST
POST /waves/{waveId}/induction-closureswithIdempotency-Key. - Preconditions: the wave exists and is
OPEN. - Main flow:
- Load the wave by
waveId. CloseInduction:OPEN→INDUCTION_CLOSED.- Save (version checked). No event in the model.
- Return
200with the wave.
- Load the wave by
- Errors: 404
not-found; 409illegal-transition; 409concurrent-update. - Events: none.
- Idempotency:
Idempotency-Key; a repeated call on anINDUCTION_CLOSEDwave with the same key returns the stored response.
DispatchWave
- Actor / trigger: Station planner.
- Inbound adapter: REST
POST /waves/{waveId}/dispatcheswithIdempotency-Key. - Preconditions: the wave is
INDUCTION_CLOSED. - Main flow:
- Load the wave.
DispatchWave:INDUCTION_CLOSED→DISPATCHED.- Save (version checked). Packages inducted in the wave that no route of
the wave holds are re-inducted onto the next eligible wave in the same
transaction (ADR 0002 A11). A wave with no route completes at once
(A9), so the response may show
COMPLETED. Return200.
- Errors: 404
not-found; 409illegal-transition; 409concurrent-update. - Events: none of its own (a re-induction raises
DeliveryWaveCapacityChangedorPackageInductionDeferred). - Idempotency:
Idempotency-Key.
CompleteWave
- Actor / trigger: none from outside. The wave completes automatically
(ADR 0002 A9): in the same transaction in which its last route completes
(every route of the wave is
COMPLETED), or at once when a wave is dispatched with no route. - Inbound adapter: none; there is no REST operation.
- Preconditions: the wave is
DISPATCHED. - Main flow: inside that transaction,
CompleteWave(DISPATCHED→COMPLETED), save. - Errors: none reach a caller; any other state is
ErrIllegalTransitioninside the unit of work. - Events: none.
- Idempotency: not applicable, no caller.
CancelWave
- Actor / trigger: Station planner.
- Inbound adapter: REST
POST /waves/{waveId}/cancellationswithIdempotency-Key. - Input:
reason, 1 to 200 characters, required. - Preconditions: the wave is
OPEN. - Main flow:
- Load the wave.
CancelWave(OPEN→CANCELLED) with thereason.- In the same transaction every package inducted in the wave is
re-inducted onto the next eligible wave (ADR 0002 A10, A6, A7); a
package with no eligible wave is unplaced and raises
PackageInductionDeferred. The cancelled wave keeps its induction list as a record. - Save (version checked) with
DeliveryWaveCancelledin the outbox. - Return
200with the wave (stateCANCELLED,cancelReason).
- Errors: 404
not-found; 409illegal-transitionwhen the wave is notOPEN; 409concurrent-update; 422validation-failed(empty or too longreason). - Events:
DeliveryWaveCancelledon the integration streamretailnetwork.last-mile-delivery.events(consumed bydelivery-promiseandorder-sourcing; ADR 0002 A22), plusDeliveryWaveCapacityChanged/PackageInductionDeferredfor the re-inducted packages. - Idempotency:
Idempotency-Key(see above). A second cancel of aCANCELLEDwave under a new key is not an unchanged 200: it is 409illegal-transition, the wave staysCANCELLEDand no secondDeliveryWaveCancelledis raised.
PlanRoute
- Actor / trigger: Station planner.
- Inbound adapter: REST
POST /routeswithIdempotency-Key. - Input:
waveId,dspId,stops[]of{stopNo, trackingNumbers[]}. - Preconditions (ADR 0002 A12): the wave exists and is
INDUCTION_CLOSED(ErrIllegalTransitionotherwise); the partner exists, isACTIVE(ErrPartnerInactive) and works for the wave's station (ErrPartnerStationMismatch); stop numbers run 1..n without gaps or duplicates; a tracking number appears at most once per route; every package is inducted in the wave (ErrPackageNotInducted) and on no other route (ErrPackageAlreadyRouted); onestopKeyper stop (ErrStopKeyMismatch). - Main flow:
- Look up the
Idempotency-Key. - Load the
DeliveryServicePartner(read only) for its van capacity. - Load the wave (read only) for its state and
stationNodeId. - Build
RouteinPLANNED; check stop count<=van capacity. - In one transaction: insert the route and its stops, write
RoutePlanned, store the key. Return201.
- Look up the
- Errors: 404
not-found(wave or partner); 409illegal-transition(wave notINDUCTION_CLOSED); 409route-over-capacity,partner-inactive,partner-station-mismatch,package-not-inducted,package-already-routed,stop-key-mismatch; 422validation-failed. - Events:
RoutePlanned(analytics only). - Idempotency:
Idempotency-Key.
StartRoute
- Actor / trigger: DSP driver app.
- Inbound adapter: REST
POST /routes/{routeId}/startswithIdempotency-Key. - Preconditions: the route is
PLANNEDand its wave isDISPATCHED(ADR 0002 A14: otherwiseErrIllegalTransition; the use case reads the wave and does not change it). - Main flow:
- Load the route.
StartRoute:PLANNED→OUT_FOR_DELIVERY.- In one transaction: save (version checked) and write one
PackageOutForDeliveryper tracking number on the route. - Return
200.
- Errors: 404
not-found; 409illegal-transition; 409concurrent-update. - Events:
PackageOutForDelivery× packages. - Idempotency:
Idempotency-Key.
RecordAttempt
- Actor / trigger: DSP driver app.
- Inbound adapter: REST
POST /routes/{routeId}/attemptswithIdempotency-Key. - Input:
trackingNumber,outcome(DELIVEREDorFAILED),outcomeDetail(optional:NOT_HOME,ACCESS_PROBLEMorOTHERonFAILED,SAFE_PLACE_USEDonDELIVERED; omitted means not reported),failureReason(whenFAILED),at. - Preconditions: the route is
OUT_FOR_DELIVERYand carries the tracking number; one attempt per package per route (ADR 0002 A15). - Main flow:
- Load the route.
- Check the state (
ErrRouteNotStarted). - Check the tracking number is on the route (
ErrPackageNotOnRoute) and was not attempted before (ErrAlreadyDeliveredafter aDELIVERED,ErrAttemptAlreadyRecordedafter aFAILED). - Record the attempt and set the stop's outcome.
- In one transaction: save (version checked), write
DeliveryAttempted, and fold the attempt into theDeliveryPointProfileof the stop (ADR 0014), which may raiseDeliveryPointFlaggedfor the packages newly affected. - Return
201with the attempt. - When this was the last outstanding package, the route completes right
after the attempt (
CompleteRouteOnLastAttempt, a second save in the same unit of work), and the wave completes when its last route does (A9, A16). - After the commit, if
FAILED,RetryNextWaverunsInductPackagein its own transaction (one aggregate per transaction).
- Errors:
ErrRouteNotStarted→ 409route-not-started;ErrAlreadyDelivered→ 409already-delivered;ErrAttemptAlreadyRecorded→ 409attempt-already-recorded; 404not-found(route); 404package-not-on-route(a tracking number not on the route); 409concurrent-update; 422validation-failed(including anoutcomeDetailthat does not pair with the outcome, andCOLLECTEDon a delivery induction). - Events:
DeliveryAttempted;DeliveryPointFlaggedwhen the stop's profile crosses the two-strike threshold. - Idempotency:
Idempotency-Key. A retriedDELIVEREDwith a new key fails withErrAlreadyDelivered, which is the invariant doing its job.
CompleteRoute
- Actor / trigger: none from outside. Policy
CompleteRouteOnLastAttempt(ADR 0002 A16): the route completes right after the attempt that records its last outstanding package. - Inbound adapter: none; there is no REST operation.
- Preconditions: the route is
OUT_FOR_DELIVERYand every package has an attempt; the domain refuses it withErrRouteIncompletewhile one has none. - Main flow: a second save in the unit of work of
RecordAttempt:CompleteRoute(OUT_FOR_DELIVERY→COMPLETED), then the wave completes if this was its last route. A route whose driver never records every package staysOUT_FOR_DELIVERY. - Errors: none reach a caller.
- Events: none.
- Idempotency: not applicable, no caller.
ContractPartner
- Actor / trigger: not named in the model (assumed: Station planner).
- Inbound adapter: REST
POST /partnerswithIdempotency-Key. - Input:
stationNodeId,vanCapacity. - Preconditions:
stationNodeIdis aDELIVERY_STATIONknown toStationView(ADR 0002 A1). - Main flow:
- Look up the
Idempotency-Key. - Check the station against
StationView. - Build
DeliveryServicePartnerinACTIVE; check van capacity> 0. - Insert it and store the key in one transaction. Return
201.
- Look up the
- Errors:
ErrUnknownStation→ 422unknown-station;ErrInvalidVanCapacity→ 422invalid-van-capacity; 422validation-failed. - Events: none (
events: []). - Idempotency:
Idempotency-Key.