Skip to main content

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 caseAggregateTriggerInbound adapter
ScheduleWaveDeliveryWave (+ waiting PackageAttemptHistory)station plannerREST POST /waves
CloseInductionDeliveryWavestation plannerREST POST /waves/{waveId}/induction-closures
DispatchWaveDeliveryWave (+ leftovers, completion)station plannerREST POST /waves/{waveId}/dispatches
CancelWaveDeliveryWave (+ re-induction)station plannerREST POST /waves/{waveId}/cancellations
PlanRouteRoute (reads wave, partner)station plannerREST POST /routes
StartRouteRoute (reads wave)DSP driver appREST POST /routes/{routeId}/starts
RecordAttemptRoute + PackageAttemptHistory (+ wave, completion)DSP driver appREST POST /routes/{routeId}/attempts
ContractPartnerDeliveryServicePartnerstation plannerREST POST /partners
DeactivatePartnerDeliveryServicePartnerstation plannerREST POST /partners/{dspId}/deactivations
InductOnArrival (policy)PackageAttemptHistory, DeliveryWaveLoadArrivedKafka consumer linehaul
ApplyNodeRegistered, ApplyServiceAreaAssignedread models rm_stations, rm_station_service_areasNodeRegistered, ServiceAreaAssignedKafka consumer node-topology
ApplyLabelIssuedread model rm_package_stopsLabelIssuedKafka consumer shipping
ListWaves, GetWaveStops, GetRoutenone (reads)any clientREST 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).

ErrorHTTPProblem type
malformed body, shared.ErrValidation422validation-failed
wave.ErrInvalidWaveTimes422invalid-wave-times
partner.ErrInvalidVanCapacity422invalid-van-capacity
usecases.ErrUnknownStation422unknown-station
missing Idempotency-Key400idempotency-key-required
Idempotency-Key not 1 to 128 printable ASCII characters400idempotency-key-invalid
key reused with another method, path or body409idempotency-key-reused
bad limit, bad cursor, undeclared query parameter400invalid-limit, invalid-cursor, unknown-query-parameter
ports.ErrNotFound404not-found
route.ErrPackageNotOnRoute404package-not-on-route
wave.ErrWaveFull409wave-full
wave.ErrInductionClosed409induction-closed
wave.ErrAlreadyInducted409already-inducted
route.ErrRouteOverCapacity409route-over-capacity
route.ErrRouteNotStarted409route-not-started
shared.ErrAlreadyDelivered409already-delivered
route.ErrAttemptAlreadyRecorded409attempt-already-recorded
route.ErrPackageNotInducted409package-not-inducted
route.ErrPackageAlreadyRouted409package-already-routed
route.ErrStopKeyMismatch409stop-key-mismatch
route.ErrPartnerInactive409partner-inactive
route.ErrPartnerStationMismatch409partner-station-mismatch
route.ErrRouteIncomplete409route-incomplete
shared.ErrIllegalTransition409illegal-transition
ports.ErrConcurrentUpdate409concurrent-update
anything else500internal-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 /waves with Idempotency-Key.
  • Input: stationNodeId, serviceDate (YYYY-MM-DD), inductCutoffAt, windowStart, windowEnd, stopCapacity.
  • Invariants: the station is a known DELIVERY_STATION in rm_stations (ErrUnknownStation); inductCutoffAt < windowStart < windowEnd (ErrInvalidWaveTimes); valid ids and capacity.
  • Flow: require the station, wave.Schedule builds an OPEN wave at version 1, save, then policy InductDeferredOnSchedule: sweep the station's packages in status AT_STATION (oldest first, at most SweepLimit = 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 one DeliveryWaveCapacityChanged per new stop the sweep inducted.

CloseInduction​

  • Trigger: station planner, POST /waves/{waveId}/induction-closures.
  • Invariant: the wave is OPEN (OPEN to INDUCTION_CLOSED, else illegal-transition).
  • Events: none.

DispatchWave​

  • Trigger: station planner, POST /waves/{waveId}/dispatches.
  • Invariant: the wave is INDUCTION_CLOSED (to DISPATCHED).
  • Flow: dispatch; re-induct leftovers (A11): every package inducted in the wave that no route of it holds is placed on the next eligible OPEN wave, or becomes AT_STATION again; then CompleteWaveOnLastRoute (A9): complete the wave at once when no route is left uncompleted.
  • Events: DeliveryWaveCapacityChanged on the receiving waves, PackageInductionDeferred for a package no wave takes.

CancelWave​

  • Trigger: station planner, POST /waves/{waveId}/cancellations with reason (1 to MaxReason characters, trimmed).
  • Invariant: the wave is OPEN (to CANCELLED); in any other state, a second cancel of a CANCELLED wave included, the answer is 409 illegal-transition and nothing is published again (DeliveryWave.Cancel via move(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, numbered 1..n in order, each with valid and distinct tracking numbers; the wave is INDUCTION_CLOSED; the partner is active and belongs to the wave's station; stops <= the partner's vanCapacity; every package is inducted in the wave, not on another route of it, and all packages of a stop share one stopKey.
  • Events: RoutePlanned (analytics topic only).

StartRoute​

  • Trigger: DSP driver app, POST /routes/{routeId}/starts.
  • Invariants: the route is PLANNED and its wave is DISPATCHED (else illegal-transition).
  • Events: one PackageOutForDelivery per tracking number, in stop order (A14), then one StopEtaWindowAssigned per 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 (counter last_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 (DELIVERED or FAILED), failureReason (required exactly when FAILED), optional outcomeDetail (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: DELIVERED marks it delivered; FAILED counts a failure, and unless this would be the third, RetryNextWave places 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 wave DeliveryWaveCapacityChanged, with none PackageInductionDeferred; on the third failure PackageReturnInitiated.
  • Metric: the business counter last_mile_delivery.package.attempted counts the outcome (delivered, failed, or rejected with the error slug as reason).

ContractPartner and DeactivatePartner​

  • ContractPartner (POST /partners): the station must be known (unknown-station), vanCapacity > 0 (invalid-van-capacity); saves an ACTIVE partner. No event.
  • DeactivatePartner (POST /partners/{dspId}/deactivations, G34): ACTIVE to INACTIVE; 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's nodeType when present, else rm_stations); for every valid tracking number record it in rm_inbound_packages and arrive it: a new package gets its stop key from rm_package_stops (or pkg:<trackingNumber>), is placed on the first OPEN wave whose cutoff is after the arrival (earliest first, skipping full or closed waves), and gets a PackageAttemptHistory (INDUCTED, or AT_STATION when no wave takes it); a package already waiting is retried; one already inducted, delivered or returned is ignored (A18). A package whose destinationPostalPrefix is assigned CARRIER_HANDOFF is refused first: nothing is raised, no history row is kept, the counter last_mile_delivery.carrier_area.skipped is recorded, and the package never enters a wave (ADR 0015; the same refusal guards the waiting-package sweep).
  • Events: DeliveryWaveCapacityChanged per new stop, PackageInductionDeferred per unplaced package.

Read-model consumers​

  • ApplyNodeRegistered: claims the event and keeps the node in rm_stations only when nodeType is DELIVERY_STATION; the first write wins (ON CONFLICT (node_id) DO NOTHING).
  • ApplyServiceAreaAssigned: keeps the assignment in rm_station_service_areas when its assignmentVersion is higher than the stored one; the declared deliveryMode is kept with it (absent or unknown reads as NETWORK_ROUTE, ADR 0015).
  • ApplyLabelIssued: keeps stopKey, destinationPostalPrefix and assignmentId in rm_package_stops, first write per tracking number wins (ON CONFLICT (tracking_number) DO NOTHING); a label without a usable stopKey is 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 by inductCutoffAt then waveId; an invalid station id or a date that is not YYYY-MM-DD is validation-failed; none is an empty list.
  • GetWaveStops(waveId): the wave's packages grouped by stopKey in order of first induction (G11), with destinationPostalPrefix when the label data has it; not-found for an unknown wave.
  • GetRoute(routeId): the route with its stops (derived outcome) and attempts; not-found for 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.