Use cases
The use cases live in internal/application/usecases. Every use case that changes an aggregate saves it and hands its events to the outbox inside one Postgres unit of work (writer.transact in writer.go); the relay publishes the outbox rows to retailnetwork.shipping-and-tracking.events. Consumed events add their CloudEvents id to processed_events in the same transaction as the effect. The one synchronous call, GetShipTo, is made before the transaction opens, so no lock is held across the network.
Triggers at a glance
| Use case | Trigger | Inbound adapter | Events raised |
|---|---|---|---|
IssueLabel (includes StartJourney) | vendor-connectivity | REST POST /labels | LabelIssued |
IssueReturnLabel | customer-returns | REST POST /return-labels | LabelIssued (with purpose: RETURN) |
VoidLabel | operations tooling | REST POST /labels/{labelRef}/voids | LabelVoided |
RecordScan | any REST caller | REST POST /journeys/{trackingNumber}/scans | PackageScanned, plus PackageHandedOver or PackageDelivered on those transitions |
ApplyScans | consumed VendorShipmentConfirmed, LoadDeparted, LoadArrived, PackageOutForDelivery, DeliveryAttempted | the four Kafka consumers | same as RecordScan, per tracking number |
ReturnToSender | consumed PackageReturnInitiated | last-mile consumer | PackageReturned |
ApplyEtaWindows (AssignEta) | consumed StopEtaWindowAssigned | last-mile consumer | PackageEtaWindowAssigned, per tracking number |
RelayDeliveryPointFlag (FlagDeliveryPoint) | consumed DeliveryPointFlagged | last-mile consumer | PackageDeliveryPointFlagged, per tracking number |
SweepSilence (RaiseException, DeclareLost) | timer, SILENCE_SWEEP_INTERVAL (5 m), also at start | scheduler job silence-sweep | PackageExceptionRaised, PackageLost |
PurgeShipTo | timer, HOUSEKEEPING_INTERVAL (1 h), also at start | scheduler job ship-to-purge | none |
Housekeeping of the technical tables | timer, HOUSEKEEPING_INTERVAL, also at start | scheduler job housekeeping (postgres.Housekeeping) | none |
RecordCatalogItem | consumed CatalogItemCreated | catalog consumer | none |
NoteNodeDestination | consumed NodeRegistered, every node type | node-topology consumer | none |
GetJourney (query) | shoppers, customer-ordering, console, agents | REST GET /journeys/{trackingNumber}, MCP and A2A get_journey | none |
Errors and the problem types they become
REST errors are RFC 9457 application/problem+json; type is the slug (internal/adapters/inbound/http/errors.go).
| Error | HTTP | Slug |
|---|---|---|
shared.ErrValidation and malformed bodies | 422 | validation-failed |
shipto.ErrAddressSuspect | 422 | address-suspect |
shipto.ErrPickupPointUnavailable | 422 | pickup-point-unavailable |
missing Idempotency-Key | 400 | idempotency-key-required |
ports.ErrNotFound | 404 | not-found |
label.ErrLabelAlreadyIssued | 409 | label-already-issued |
shipto.ErrDestinationPrefixUnavailable | 409 | destination-prefix-unavailable |
label.ErrTrackingNumberTaken | 409 | tracking-number-taken |
journey.ErrVoidAfterHandover | 409 | void-after-handover |
journey.ErrDuplicateScan | 409 | duplicate-scan |
journey.ErrScanOutOfOrder | 409 | scan-out-of-order |
journey.ErrJourneyClosed | 409 | journey-closed |
shared.ErrIllegalTransition | 409 | illegal-transition |
ports.ErrConcurrentUpdate | 409 | concurrent-update |
ports.ErrShipToUnavailable | 503 | ship-to-unavailable |
| anything else | 500 | internal-error |
IssueLabel
Source: internal/application/usecases/labels.go, internal/domain/label/label.go.
- Trigger:
vendor-connectivitywhile handling a vendor's label request. RESTPOST /labels,Idempotency-Keyrequired. - Input:
poNumber,packageNo(1 to 2147483647),assignmentId,orderId,tier(SAME_DAY,NEXT_DAY,TWO_DAY,STANDARD); ids are 1 to 64 characters. - Invariants: one label per
(poNumber, packageNo)(ErrLabelAlreadyIssued); a tracking number is unique network-wide (ErrTrackingNumberTaken, one retry with a fresh number before the error surfaces); the carrier follows the tier (RN-EXPRESSforSAME_DAYandNEXT_DAY,RN-GROUNDotherwise); thestopKeyis 64 lower-case hex characters. - Flow:
- Validate the command with placeholder values; reject with
validation-failed. - Look up a label for
(poNumber, packageNo); a hit islabel-already-issued. - Call
GetShipToon customer-ordering. A 404 becomesvalidation-failed("orderId ... is unknown to customer-ordering"); any other failure isship-to-unavailable. An answer{destinationKind: PICKUP_POINT, pickupPointId}takes the pickup branch instead of steps 4 and 5 (issuePickup, ADR 0016): the point is read from the local PickupPointView; a point the view does not hold, or holds in any state butACTIVE(PROPOSED,SUSPENDED,RETIRED), refuses the issuance withErrPickupPointUnavailable, answered 422pickup-point-unavailable, and nothing is written. Otherwise the label takes the point's own prefix and a stop key of the point id, no address is read or sealed, and the journey starts with the point and its hold deadline. - Validate the address, then run the deterministic deliverability check on it (
Address.Quality, ADR 0011). ASUSPECTverdict refuses the issuance withErrAddressSuspect, answered 422address-suspect; the detail carries reason tokens only (RECIPIENT_PLACEHOLDER,STREET_PLACEHOLDER,STREET_MISSING_NUMBER,CITY_PLACEHOLDER,POSTAL_CODE_TOO_SHORT), and no label, journey, snapshot or event is written. Otherwise seal the address (AES-256-GCM, fresh nonce), derivestopKey(HMAC-SHA-256 of the normalised address) and the five-character postal prefix. - In one transaction: mint
labelRef(lbl-<uuid>) and a tracking number (RNplus 16 base-32 characters), save the label, save the sealed snapshot, start the journey (StartJourney, stateLABELLED, version 1, no event of its own) and enqueueLabelIssued.
- Validate the command with placeholder values; reject with
- Result:
201with the label metadata, never the address. The attempt is counted once inshipping.labels.issuedasissuedorrejectedwith the reason. - Idempotency: the
Idempotency-Keyreplays the first stored response; a new key for the same package hitslabel-already-issued(FINAL, stored). A refusal is stored only when the replay class of its problem type says so (ADR 0020);pickup-point-unavailable,validation-failed(an order customer-ordering does not know yet),address-suspect(the address is read from customer-ordering, so the shopper can correct it),tracking-number-takenandconcurrent-updateare RETRYABLE: nothing is stored, the key is free and the same request under the same key is executed again, and the201it gets then is what the key replays (ADR 0016, ADR 0020).
IssueReturnLabel
- Trigger:
customer-returns, for one package of a return authorization. RESTPOST /return-labels,Idempotency-Keyrequired (ADR 0017, ADR 0018). - Invariants: one label per
(returnAuthorizationId, packageNo); the return destination is named by exactly one ofdestinationNodeIdand the deprecateddestinationPostalPrefix. - Flow:
- Validate the command; both destination forms, or neither, is
validation-failed. - Look up a label for
(returnAuthorizationId, packageNo); a hit islabel-already-issued. - Resolve the destination prefix. For
destinationNodeId, read the node's row of the localNodeDestinationView(node_destinations), which holds the prefix this context derived from the node's registered postal code (shipto.NodePrefix). No row, or a row with an empty prefix, isdestination-prefix-unavailable: nothing is stored and customer-ordering is not called. FordestinationPostalPrefixthe value is taken as sent and the view is not read. The use case does not judge whether the node is the right one or whether it is active. - Read the ship-to of
orderIdfrom customer-ordering, before the transaction, and derive thestopKeyexactly as the outbound label of that order did. - In one transaction: save the label (
purpose: RETURN, tierSTANDARD, carrierRN-GROUND) and enqueueLabelIssued. No journey is started and no snapshot is sealed.
- Validate the command; both destination forms, or neither, is
- Result:
201with theReturnLabel. The attempt is counted once inshipping.labels.issued. - Idempotency: the
Idempotency-Keyreplays the first stored response for 24 hours.destination-prefix-unavailableis RETRYABLE (likeconcurrent-update,validation-failedandtracking-number-taken; the replay class on its catalogue entry, ADR 0020): nothing is stored and the same request under the same key is executed again and is served once the node fact has arrived, and that201is then what the key replays (ADR 0018).
VoidLabel
- Trigger: operations tooling. REST
POST /labels/{labelRef}/voids, bodyreason(1 to 500 characters),Idempotency-Keyrequired. - Invariants: a label can be voided only while its journey is still
LABELLED(ErrVoidAfterHandoveronce handed over and still open; a journey alreadyDELIVERED,RETURNED,LOSTorVOIDEDanswersErrJourneyClosed, checked first inJourney.Void,journey_close.go:82-87); aVOIDEDlabel is returned unchanged and nothing is published. - Flow: load the label, load the journey of the same tracking number, close the journey as
VOIDED(no journey event), move the labelISSUEDtoVOIDEDwith the reason, save both, enqueueLabelVoided.200with the label. - Errors:
not-found,void-after-handover,journey-closed,validation-failed.
RecordScan (REST) and ApplyScans (events)
Sources: usecases/scans.go, internal/domain/journey/journey.go, internal/adapters/inbound/kafka/handlers.go.
- Input (REST):
scanId(1 to 256),nodeId(1 to 64),scanType,at(RFC 3339), pathtrackingNumber. Input (events): oneFactper tracking number of the event; the scan id is<CloudEvents id>:<trackingNumber>and a missing node takes the node of the journey's last applied scan (unknownwhen none). - Edge table (
journey.next):SHIPMENT_CONFIRMEDkeepsLABELLED;PICKUP_DEPARTUREtakesLABELLEDtoHANDED_OVER;DEPARTUREandTRANSIT_ARRIVALtakeHANDED_OVERorIN_TRANSITtoIN_TRANSIT;STATION_ARRIVALtakesHANDED_OVERorIN_TRANSITtoAT_STATION;OUT_FOR_DELIVERYtakesAT_STATIONtoOUT_FOR_DELIVERY;DELIVEREDtakesOUT_FOR_DELIVERYtoDELIVERED;DELIVERY_FAILEDtakesOUT_FOR_DELIVERYback toAT_STATION. - Order of checks in
Journey.RecordScan: validation,ErrJourneyClosed,ErrDuplicateScan(nothing stored),ErrScanOutOfOrder(stored withapplied=false), the edge table (ErrIllegalTransition, stored withapplied=false). - Events: every applied scan raises
PackageScanned;LABELLEDtoHANDED_OVERalso raisesPackageHandedOver(HandoverOnFirstScan); a move toDELIVEREDalso raisesPackageDeliveredand closes the journey. - REST outcome:
200with the journey, or the 409 above; a scan stored unapplied is committed and the caller still gets the error.scan-out-of-orderandillegal-transitionare OUTCOME refusals (ADR 0020): the 409 is stored under theIdempotency-Keytogether with the scan, so a retry under the same key replays it and never answersduplicate-scan;duplicate-scanandjourney-closedare FINAL,concurrent-updateRETRYABLE. Consumer outcome:ApplyScansclaims the event id in the inbox first (a replay isskipped), then folds every fact; duplicate, out-of-order, no-edge and closed outcomes are counted and acknowledged, an unknown tracking number is counted and acknowledged, anything else is returned and retried.
ReturnToSender
- Trigger: consumed
PackageReturnInitiated(last-mile-delivery, third failed attempt). - Invariant: only an
AT_STATIONjourney can be returned. A closed journey and an unknown tracking number are acknowledged; a journey not yetAT_STATIONreturnsErrIllegalTransition, which the consumer retries because the failed-attempt scan may still be on its way. - Flow: claim the event, move
AT_STATIONtoRETURNED, enqueuePackageReturned(returnedAtfrom the event).
ApplyEtaWindows: AssignEta
Source: usecases/eta.go, internal/domain/journey/journey_eta.go (ADR 0013).
- Trigger: consumed
StopEtaWindowAssigned(last-mile-delivery, when a route starts; one event per stop). - Flow: claim the event id, then for each tracking number of the stop: load the journey,
AssignEta(etaStart, etaEnd, assignedAt), save, enqueuePackageEtaWindowAssigned. The window is not a scan: the state does not change. - Invariants: a terminal journey refuses it (
ErrJourneyClosed), anassignedAtnot strictly newer than the stored one is stale (ErrEtaStale). Both, and an unknown tracking number, are counted and acknowledged; a replay of the event is skipped by the inbox. - Reading it:
Journey.EtaCurrentis true while the state isOUT_FOR_DELIVERYand the window was assigned at or after the last applied scan; only then do REST, MCP and A2Aget_journeycarryetaStartandetaEnd.
RelayDeliveryPointFlag: FlagDeliveryPoint
Source: usecases/point_flag.go, internal/domain/journey/journey_point_flag.go (ADR 0014).
- Trigger: consumed
DeliveryPointFlagged(last-mile-delivery, the delivery point behind a stop failed twice; one event per stop). The consumer accepts only the reasonsNOT_HOMEandACCESS_PROBLEMand dropsstopKey. - Flow: claim the event id, then for each tracking number of the stop: load the journey,
FlagDeliveryPoint(reason, flaggedAt), save, enqueuePackageDeliveryPointFlagged(with the journey'sassignmentIdandorderId, so customer-ordering can warn the shopper by order). The flag is not a scan: the state does not change. - Invariants: a terminal journey refuses it (
ErrJourneyClosed) and aflaggedAtnot strictly newer than the stored one is stale (ErrPointFlagStale). Both, and an unknown tracking number, are counted and acknowledged; a replay of the event is skipped by the inbox.
SweepSilence: RaiseException and DeclareLost
Source: usecases/sweep.go, internal/domain/journey/types.go.
- Trigger: the
silence-sweepjob. Candidate journeys come fromListStalein pages of 200 (SweepPageSize), each decided in its own unit. - Silence windows while
HANDED_OVER,IN_TRANSITorAT_STATION: 6 hSAME_DAY, 24 hNEXT_DAY, 48 hTWO_DAY, 72 hSTANDARD; 12 h whileOUT_FOR_DELIVERY;LABELLEDand terminal states are not watched. - RaiseException: a watched journey past its window with no unanswered exception gets
PackageExceptionRaised(reasonNO_SCAN, the only reason); the state does not change; one exception per silence, a new applied scan re-arms it. - DeclareLost: an
IN_TRANSITjourney whose exception stayed unanswered for 48 h moves toLOSTand enqueuesPackageLost. - Result: the job logs
raised=<n> lost=<n> conflicts=<n>; a concurrent update is counted as a conflict and seen again on the next tick.
PurgeShipTo and housekeeping
PurgeShipTodeletesship_to_snapshotswhose journey closed more than 30 days ago (ShipToRetention; ADR 0002 A9) and logssnapshots_deleted=<n>.- Housekeeping (
cmd/api/main.gohousekeep) deletesidempotency_keysolder than 24 h, already-relayedoutbox_eventsolder than 7 days andprocessed_eventsolder than 30 days.
RecordCatalogItem
On a consumed CatalogItemCreated, validate the catalogItemId, claim the event id and upsert catalog_dimensions (title, dimensions, weight, hazmat, fragile). Nothing is published.
GetJourney (query)
Loads the PackageJourney through the repository and returns the view: state, label identity (poNumber, assignmentId, orderId, tier), handedOverAt, deliveredAt and every stored scan in recorded order. Unknown tracking number: ErrNotFound. REST, MCP and A2A all call this one use case.