Use cases
One application service per command or policy, in internal/application/usecases. Every writing use case runs inside one UnitOfWork (transact): it loads at most one aggregate to change, saves it, and writes its events to outbox_events in the same Postgres transaction; a relay publishes them afterwards (Architecture). Three read use cases (ListWaves, GetWaveStops, GetRoute) are shared by REST, MCP and A2A. Step-by-step diagrams are on Sequence diagrams; the wire contract is apis/openapi.yaml. Decision ids (A…, G…) refer to ADR 0002 and the gap register.
Source: internal/application/usecases/{waves,routes,partners,induct,consumers,queries}.go, internal/adapters/inbound/http/{server,errors}.go, internal/adapters/inbound/kafka/consumers.go.
Triggers at a glance
| Use case | Aggregate | Trigger | Inbound adapter |
|---|---|---|---|
ScheduleWave | DeliveryWave (+ waiting PackageAttemptHistory) | station planner | REST POST /waves |
CloseInduction | DeliveryWave | station planner | REST POST /waves/{waveId}/induction-closures |
DispatchWave | DeliveryWave (+ leftovers, completion) | station planner | REST POST /waves/{waveId}/dispatches |
CancelWave | DeliveryWave (+ re-induction) | station planner | REST POST /waves/{waveId}/cancellations |
PlanRoute | Route (reads wave, partner) | station planner | REST POST /routes |
StartRoute | Route (reads wave) | DSP driver app | REST POST /routes/{routeId}/starts |
RecordAttempt | Route + PackageAttemptHistory (+ wave, completion) | DSP driver app | REST POST /routes/{routeId}/attempts |
ContractPartner | DeliveryServicePartner | station planner | REST POST /partners |
DeactivatePartner | DeliveryServicePartner | station planner | REST POST /partners/{dspId}/deactivations |
InductOnArrival (policy) | PackageAttemptHistory, DeliveryWave | LoadArrived | Kafka consumer linehaul |
ApplyNodeRegistered, ApplyServiceAreaAssigned | read models rm_stations, rm_station_service_areas | NodeRegistered, ServiceAreaAssigned | Kafka consumer node-topology |
ApplyLabelIssued | read model rm_package_stops | LabelIssued | Kafka consumer shipping |
ListWaves, GetWaveStops, GetRoute | none (reads) | any client | REST GET, MCP tools, A2A skills |
Policies that run inside other use cases: InductDeferredOnSchedule (inside ScheduleWave), RetryNextWave (inside RecordAttempt), CompleteWaveOnLastRoute (inside DispatchWave and RecordAttempt), re-induction of leftovers (inside DispatchWave and CancelWave).
Error mapping
REST errors are RFC 9457 application/problem+json; the type is the slug (internal/adapters/inbound/http/errors.go).
| Error | HTTP | Problem type |
|---|---|---|
malformed body, shared.ErrValidation | 422 | validation-failed |
wave.ErrInvalidWaveTimes | 422 | invalid-wave-times |
partner.ErrInvalidVanCapacity | 422 | invalid-van-capacity |
usecases.ErrUnknownStation | 422 | unknown-station |
missing Idempotency-Key | 400 | idempotency-key-required |
Idempotency-Key not 1 to 128 printable ASCII characters | 400 | idempotency-key-invalid |
| key reused with another method, path or body | 409 | idempotency-key-reused |
bad limit, bad cursor, undeclared query parameter | 400 | invalid-limit, invalid-cursor, unknown-query-parameter |
ports.ErrNotFound | 404 | not-found |
route.ErrPackageNotOnRoute | 404 | package-not-on-route |
wave.ErrWaveFull | 409 | wave-full |
wave.ErrInductionClosed | 409 | induction-closed |
wave.ErrAlreadyInducted | 409 | already-inducted |
route.ErrRouteOverCapacity | 409 | route-over-capacity |
route.ErrRouteNotStarted | 409 | route-not-started |
shared.ErrAlreadyDelivered | 409 | already-delivered |
route.ErrAttemptAlreadyRecorded | 409 | attempt-already-recorded |
route.ErrPackageNotInducted | 409 | package-not-inducted |
route.ErrPackageAlreadyRouted | 409 | package-already-routed |
route.ErrStopKeyMismatch | 409 | stop-key-mismatch |
route.ErrPartnerInactive | 409 | partner-inactive |
route.ErrPartnerStationMismatch | 409 | partner-station-mismatch |
route.ErrRouteIncomplete | 409 | route-incomplete |
shared.ErrIllegalTransition | 409 | illegal-transition |
ports.ErrConcurrentUpdate | 409 | concurrent-update |
| anything else | 500 | internal-error |
Every problem type declares a replay class (ADR 0019): a FINAL refusal is stored under the key and replayed, a RETRYABLE one is not stored and its key is released (the class table is in the ADR and is held equal to problemCatalogue by test).
ScheduleWave
- Trigger: station planner,
POST /waveswithIdempotency-Key. - Input:
stationNodeId,serviceDate(YYYY-MM-DD),inductCutoffAt,windowStart,windowEnd,stopCapacity. - Invariants: the station is a known
DELIVERY_STATIONinrm_stations(ErrUnknownStation);inductCutoffAt < windowStart < windowEnd(ErrInvalidWaveTimes); valid ids and capacity. - Flow: require the station,
wave.Schedulebuilds anOPENwave at version 1, save, then policyInductDeferredOnSchedule: sweep the station's packages in statusAT_STATION(oldest first, at mostSweepLimit= 1000) and induct each into the first eligible wave. Publish; return the wave as saved (the sweep may already have filled stops). - Events:
DeliveryWaveScheduled, plus oneDeliveryWaveCapacityChangedper new stop the sweep inducted.
CloseInduction
- Trigger: station planner,
POST /waves/{waveId}/induction-closures. - Invariant: the wave is
OPEN(OPENtoINDUCTION_CLOSED, elseillegal-transition). - Events: none.
DispatchWave
- Trigger: station planner,
POST /waves/{waveId}/dispatches. - Invariant: the wave is
INDUCTION_CLOSED(toDISPATCHED). - Flow: dispatch; re-induct leftovers (A11): every package inducted in the wave that no route of it holds is placed on the next eligible
OPENwave, or becomesAT_STATIONagain; thenCompleteWaveOnLastRoute(A9): complete the wave at once when no route is left uncompleted. - Events:
DeliveryWaveCapacityChangedon the receiving waves,PackageInductionDeferredfor a package no wave takes.
CancelWave
- Trigger: station planner,
POST /waves/{waveId}/cancellationswithreason(1 toMaxReasoncharacters, trimmed). - Invariant: the wave is
OPEN(toCANCELLED); in any other state, a second cancel of aCANCELLEDwave included, the answer is409 illegal-transitionand nothing is published again (DeliveryWave.Cancelviamove(StateOpen, StateCancelled),internal/domain/wave/wave.go:271-277). - Flow: cancel, then re-induct every package it held onto the next eligible wave (G17); a package no wave takes is deferred.
- Events:
DeliveryWaveCancelled(an integration event, G5),DeliveryWaveCapacityChanged,PackageInductionDeferred.
PlanRoute
- Trigger: station planner,
POST /routes. - Input:
waveId,dspId,stops[]of{stopNo, trackingNumbers[]}. - Invariants (
route.Plan, A12): at least one stop, numbered1..nin order, each with valid and distinct tracking numbers; the wave isINDUCTION_CLOSED; the partner is active and belongs to the wave's station; stops<=the partner'svanCapacity; every package is inducted in the wave, not on another route of it, and all packages of a stop share onestopKey. - Events:
RoutePlanned(analytics topic only).
StartRoute
- Trigger: DSP driver app,
POST /routes/{routeId}/starts. - Invariants: the route is
PLANNEDand its wave isDISPATCHED(elseillegal-transition). - Events: one
PackageOutForDeliveryper tracking number, in stop order (A14), then oneStopEtaWindowAssignedper stop, in stop order, in the same transaction (ADR 0013): a window of at most two hours per stop, spread over what is left of the wave's delivery window from the start instant. When less than 30 minutes are left no ETA event is raised and the route starts normally (counterlast_mile_delivery.stop_eta.skipped). Nothing about the ETA is stored on the route.
RecordAttempt
- Trigger: DSP driver app,
POST /routes/{routeId}/attempts. - Input:
trackingNumber,outcome(DELIVEREDorFAILED),failureReason(required exactly whenFAILED), optionaloutcomeDetail(the category the driver client reports, validated against the outcome; ADR 0014),at. - Invariants: the route is
OUT_FOR_DELIVERY(route-not-started); the package is on the route (package-not-on-route); one attempt per package per route (attempt-already-recorded); a delivered package cannot be delivered again, on any route (already-delivered, also enforced by a partial unique index). - Flow: record the attempt on the route; update the package's
PackageAttemptHistory:DELIVEREDmarks it delivered;FAILEDcounts a failure, and unless this would be the third,RetryNextWaveplaces the package on the next eligible wave (A18, A19). Save, publish, then complete the route when every package has an attempt (A16) and the wave when its last route completes (A9). - Events:
DeliveryAttempted; on a failure that finds a waveDeliveryWaveCapacityChanged, with nonePackageInductionDeferred; on the third failurePackageReturnInitiated. - Metric: the business counter
last_mile_delivery.package.attemptedcounts the outcome (delivered,failed, orrejectedwith the error slug asreason).
ContractPartner and DeactivatePartner
ContractPartner(POST /partners): the station must be known (unknown-station),vanCapacity > 0(invalid-van-capacity); saves anACTIVEpartner. No event.DeactivatePartner(POST /partners/{dspId}/deactivations, G34):ACTIVEtoINACTIVE; an inactive partner cannot be given a new route (partner-inactive). No event.
InductOnArrival (policy, consumer linehaul)
- Trigger:
com.retailnetwork.logistics.linehaul-transportation.load.LoadArrived. - Flow: claim the CloudEvents id in
processed_events(a repeat is a no-op); ignore a load that did not reach a delivery station (A8: the event'snodeTypewhen present, elserm_stations); for every valid tracking number record it inrm_inbound_packagesandarriveit: a new package gets its stop key fromrm_package_stops(orpkg:<trackingNumber>), is placed on the firstOPENwave whose cutoff is after the arrival (earliest first, skipping full or closed waves), and gets aPackageAttemptHistory(INDUCTED, orAT_STATIONwhen no wave takes it); a package already waiting is retried; one already inducted, delivered or returned is ignored (A18). A package whosedestinationPostalPrefixis assignedCARRIER_HANDOFFis refused first: nothing is raised, no history row is kept, the counterlast_mile_delivery.carrier_area.skippedis recorded, and the package never enters a wave (ADR 0015; the same refusal guards the waiting-package sweep). - Events:
DeliveryWaveCapacityChangedper new stop,PackageInductionDeferredper unplaced package.
Read-model consumers
ApplyNodeRegistered: claims the event and keeps the node inrm_stationsonly whennodeTypeisDELIVERY_STATION; the first write wins (ON CONFLICT (node_id) DO NOTHING).ApplyServiceAreaAssigned: keeps the assignment inrm_station_service_areaswhen itsassignmentVersionis higher than the stored one; the declareddeliveryModeis kept with it (absent or unknown reads asNETWORK_ROUTE, ADR 0015).ApplyLabelIssued: keepsstopKey,destinationPostalPrefixandassignmentIdinrm_package_stops, first write per tracking number wins (ON CONFLICT (tracking_number) DO NOTHING); a label without a usablestopKeyis ignored (A4).
None of them raises events. Deterministic problems (undecodable payload, invalid values) are dead-lettered, transient ones retried (Runbook).
Queries
ListWaves(stationNodeId, serviceDate): the station's waves for the date ordered byinductCutoffAtthenwaveId; an invalid station id or a date that is notYYYY-MM-DDisvalidation-failed; none is an empty list.GetWaveStops(waveId): the wave's packages grouped bystopKeyin order of first induction (G11), withdestinationPostalPrefixwhen the label data has it;not-foundfor an unknown wave.GetRoute(routeId): the route with its stops (derivedoutcome) and attempts;not-foundfor an unknown route.
Not here
Completing a wave or a route has no REST command: both are policies (CompleteWaveOnLastRoute, and route completion inside RecordAttempt). Packages are inducted only by the linehaul consumer and the policies above, never by a REST call.