Skip to main content

Use cases

Source: internal/application/usecases (schedules.go, departures.go, loads.go, generate.go, booking.go, consumers.go), the aggregates in internal/domain/{departure,schedule,load,volume,network} and the problem table in internal/adapters/inbound/http/errors.go. Every use case runs through Service.write (or consume for Kafka-driven ones): one Postgres transaction commits the aggregate change, its outbox rows and, for a consumed event, the processed_events claim. Reads (ListDepartures, GetDeparture) are also use cases because REST, MCP and A2A all call them.

Conventions​

  • Idempotency. Every REST POST needs an Idempotency-Key and replays the first stored answer for 24 h (a 2xx or a refusal that is final for the request); a refusal that depends on state another request can change (concurrent-update, not-found, illegal-transition, package-already-loaded and the others of ADR 0015) and a 5xx are not stored, so a retry under the same key runs again. Every consumer claims (consumer, event_id) in processed_events, so a redelivered CloudEvent changes nothing.
  • Optimistic concurrency. Aggregates carry a version; a lost race is concurrent-update (409). Departure and ExpectedVolume writes inside a transaction share one working set (bookingSet) so a departure keeps one version line.
  • Idempotent commands. A command whose target is already in the target state returns it unchanged and raises nothing /closures, a DEPARTED one on /dispatches, an ARRIVED one on /receipts, a CANCELLED departure on /cancellations, a RETIRED schedule on /retirements).
  • Errors become RFC 9457 problems; the slugs are in Troubleshooting.

Commands (REST)​

Use caseTriggerInputsInvariants and rulesEvents raised
DefineLaneSchedulePOST /lane-scheduleslaneId, 1 to 100 slots (dayOfWeek, cutoffLocalTime, departsLocalTime, arrivesLocalTime, capacityPackages >= 1)The lane must be known in lane_views (else 404). Slots must not overlap on a weekday (overlapping-slots); departs not before cutoff (invalid-departure-times). Creates an ACTIVE schedule (201) or replaces the slots of an ACTIVE one (200, effective from the next horizon roll, departures already generated stay). A RETIRED schedule cannot be redefined (illegal-transition).none
RetireLaneSchedulePOST /lane-schedules/{laneId}/retirementslaneIdACTIVE to RETIRED; the horizon roll skips it from now on; generated departures stay.none
CancelDeparturePOST /departures/{departureId}/cancellationsdepartureId, reasonOnly a SCHEDULED departure can be cancelled (illegal-transition otherwise; an already CANCELLED one is returned unchanged). In the same transaction every assignment booked on it is rebooked on the next SCHEDULED PICKUP departure from the same origin with room and a later cutoff, or fails (ADR 0002 A15).DepartureCancelled; per moved booking BookingMoved plus DepartureCapacityChanged of the new departure; per failed booking BookingFailed
ChangeDepartureCapacityPUT /departures/{departureId}/capacitydepartureId, capacityPackages (0..2147483647)Only SCHEDULED; never below the booked count (departure-full); the same value changes nothing.DepartureCapacityChanged
OpenLoadPOST /loadsdepartureIdThe departure must be SCHEDULED; at most one load per departure (load-already-exists, unique loads.departure_id). Copies kind, nodes, node types and capacity from the departure.none
AddPackagePOST /loads/{loadId}/packagesloadId, trackingNumber (1 to 64 characters)Load OPEN and its departure SCHEDULED; a tracking number is on at most one OPEN or CLOSED load (package-already-loaded, partial unique index); package count at most the departure capacity (load-over-capacity); a number already on this load is a no-op. On LINEHAUL and AIR departures the package is also booked on the departure (ADR 0002 A20); on a PICKUP departure the capacity was booked by the assignment.DepartureCapacityChanged (LINEHAUL, AIR)
CloseLoadPOST /loads/{loadId}/closuresloadIdOPEN to CLOSED while the departure is SCHEDULED; closes the departure (SCHEDULED to CLOSED).LoadClosed (analytics topic)
DispatchLoadPOST /loads/{loadId}/dispatchesloadIdCLOSED to DEPARTED; records the departure of the trip (departure CLOSED to DEPARTED, departedAt). Counted in linehaul.loads.dispatched by outcome.LoadDeparted, DepartureDeparted (analytics topic)
ReceiveLoadPOST /loads/{loadId}/receiptsloadIdDEPARTED to ARRIVED; records the arrival of the trip (departure to ARRIVED, arrivedAt).LoadArrived, DepartureArrived (analytics topic)

Queries (REST, MCP, A2A)​

Use caseTriggerInputsNotes
ListDeparturesGET /departures, MCP list_departures, A2A skill list_departuresorigin, destination, from, to (cutoff window, from inclusive, to exclusive, RFC 3339), limit (1..1000, default 500)Ordered by cutoffAt then departureId. limit out of range or from after to is validation-failed.
GetDepartureGET /departures/{departureId}, MCP get_departure, A2A skill get_departuredepartureIdUnknown id is not-found.

Workers​

Use caseTriggerRulesEvents raised
GenerateDepartures (policy HorizonRoll)Once at boot of cmd/api, then every GENERATE_INTERVALFor every ACTIVE lane schedule with a known, OPEN lane and known origin and destination nodes, plans the departures of the next 14 days (schedule.PlanLane; GROUND lanes produce LINEHAUL, AIR lanes AIR); for every pickup-eligible node, plans PICKUP departures from its declared cutoffs (schedule.PlanPickups). Departure ids are deterministic (lane, kind, cutoff, generation), so a rerun schedules nothing new. One failing schedule or node is counted in failed and logged; the rest still run.DepartureScheduled per new departure
Outbox relayEvery OUTBOX_RELAY_INTERVALPublishes outbox_events rows in id order; skips rows past OUTBOX_MAX_ATTEMPTSnone (transport)

Consumed events (Kafka)​

Each handler runs as consume(consumer, eventId, ...): claim, apply, enqueue events, commit together.

Use caseConsumed eventEffectEvents raised
HandleNodeRegisterednode-topology NodeRegisteredStores the node view (type, operator, time zone); re-plans pickups of the node and of origins of lanes that end at itDepartureScheduled for new pickups
HandleProfileDeclaredNodeOperationalProfileDeclaredStores the profile when its revision is higher (ADR 0002 A11); re-plans pickups; cancels future unbooked pickups the cutoffs no longer produce (reason PROFILE_REVISED)DepartureScheduled, DepartureCancelled
HandleNodeActivatedNodeActivatedMarks the node ACTIVE and generates its pickups (A10)DepartureScheduled
HandleNodeSuspended, HandleNodeRetiredNodeSuspended, NodeRetiredCancels every future SCHEDULED pickup of the node (reason NODE_SUSPENDED or NODE_RETIRED), rebooking its assignmentsDepartureCancelled, BookingMoved, BookingFailed
HandleLaneOpenedLaneOpenedStores or refreshes the lane view (mode GROUND or AIR, transit minutes >= 1) and re-plans pickups at its originDepartureScheduled
HandleLaneClosedLaneClosedMarks the lane closed: no new departure is scheduled on it (A12); unknown lane is ignorednone
HandleReleasedorder-sourcing FulfillmentReleasedToNodeRecords the assignment's expected volume (RELEASED) with its planned pickup departurenone
HandleReassignedFulfillmentReassignedUpdates the node of the expected volume only (A16)none
HandleLocked (policy BookOnLock)FulfillmentLockedBooks one package on the pickup departure (a follower lock, consolidatedInto set, only claims the event: the carrier's lock books the merged package, ADR 0014); if it is unknown, cancelled, closed or full, rebooks on the next PICKUP departure from the same origin or records the failure (A13, A14)DepartureCapacityChanged, BookingMoved, BookingFailed
HandleCancelledFulfillmentCancelledMarks the expected volume CANCELLED; the booking is not released (A16)none
HandleLabelIssuedshipping-and-tracking LabelIssuedAdds the tracking number to the assignment's expected volume (A18)none
HandleLabelVoidedLabelVoidedRemoves the tracking number from the projection; the booking stays (A18)none

BookingFailed carries one of the reasons DEPARTURE_CANCELLED, DEPARTURE_CLOSED, DEPARTURE_FULL, DEPARTURE_UNKNOWN.

Not use cases​

CloseDeparture, RecordDeparture and RecordArrival exist on the aggregate but have no entry point of their own: they run inside CloseLoad, DispatchLoad and ReceiveLoad. BookCapacity and ReleaseCapacity are the aggregate methods Book and Release used by HandleLocked, AddPackage and the cancel path.