Skip to main content

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 caseTriggerInbound adapterEvents raised
IssueLabel (includes StartJourney)vendor-connectivityREST POST /labelsLabelIssued
IssueReturnLabelcustomer-returnsREST POST /return-labelsLabelIssued (with purpose: RETURN)
VoidLabeloperations toolingREST POST /labels/{labelRef}/voidsLabelVoided
RecordScanany REST callerREST POST /journeys/{trackingNumber}/scansPackageScanned, plus PackageHandedOver or PackageDelivered on those transitions
ApplyScansconsumed VendorShipmentConfirmed, LoadDeparted, LoadArrived, PackageOutForDelivery, DeliveryAttemptedthe four Kafka consumerssame as RecordScan, per tracking number
ReturnToSenderconsumed PackageReturnInitiatedlast-mile consumerPackageReturned
ApplyEtaWindows (AssignEta)consumed StopEtaWindowAssignedlast-mile consumerPackageEtaWindowAssigned, per tracking number
RelayDeliveryPointFlag (FlagDeliveryPoint)consumed DeliveryPointFlaggedlast-mile consumerPackageDeliveryPointFlagged, per tracking number
SweepSilence (RaiseException, DeclareLost)timer, SILENCE_SWEEP_INTERVAL (5 m), also at startscheduler job silence-sweepPackageExceptionRaised, PackageLost
PurgeShipTotimer, HOUSEKEEPING_INTERVAL (1 h), also at startscheduler job ship-to-purgenone
Housekeeping of the technical tablestimer, HOUSEKEEPING_INTERVAL, also at startscheduler job housekeeping (postgres.Housekeeping)none
RecordCatalogItemconsumed CatalogItemCreatedcatalog consumernone
NoteNodeDestinationconsumed NodeRegistered, every node typenode-topology consumernone
GetJourney (query)shoppers, customer-ordering, console, agentsREST GET /journeys/{trackingNumber}, MCP and A2A get_journeynone

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).

ErrorHTTPSlug
shared.ErrValidation and malformed bodies422validation-failed
shipto.ErrAddressSuspect422address-suspect
shipto.ErrPickupPointUnavailable422pickup-point-unavailable
missing Idempotency-Key400idempotency-key-required
ports.ErrNotFound404not-found
label.ErrLabelAlreadyIssued409label-already-issued
shipto.ErrDestinationPrefixUnavailable409destination-prefix-unavailable
label.ErrTrackingNumberTaken409tracking-number-taken
journey.ErrVoidAfterHandover409void-after-handover
journey.ErrDuplicateScan409duplicate-scan
journey.ErrScanOutOfOrder409scan-out-of-order
journey.ErrJourneyClosed409journey-closed
shared.ErrIllegalTransition409illegal-transition
ports.ErrConcurrentUpdate409concurrent-update
ports.ErrShipToUnavailable503ship-to-unavailable
anything else500internal-error

IssueLabel​

Source: internal/application/usecases/labels.go, internal/domain/label/label.go.

  • Trigger: vendor-connectivity while handling a vendor's label request. REST POST /labels, Idempotency-Key required.
  • 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-EXPRESS for SAME_DAY and NEXT_DAY, RN-GROUND otherwise); the stopKey is 64 lower-case hex characters.
  • Flow:
    1. Validate the command with placeholder values; reject with validation-failed.
    2. Look up a label for (poNumber, packageNo); a hit is label-already-issued.
    3. Call GetShipTo on customer-ordering. A 404 becomes validation-failed ("orderId ... is unknown to customer-ordering"); any other failure is ship-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 but ACTIVE (PROPOSED, SUSPENDED, RETIRED), refuses the issuance with ErrPickupPointUnavailable, answered 422 pickup-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.
    4. Validate the address, then run the deterministic deliverability check on it (Address.Quality, ADR 0011). A SUSPECT verdict refuses the issuance with ErrAddressSuspect, answered 422 address-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), derive stopKey (HMAC-SHA-256 of the normalised address) and the five-character postal prefix.
    5. In one transaction: mint labelRef (lbl-<uuid>) and a tracking number (RN plus 16 base-32 characters), save the label, save the sealed snapshot, start the journey (StartJourney, state LABELLED, version 1, no event of its own) and enqueue LabelIssued.
  • Result: 201 with the label metadata, never the address. The attempt is counted once in shipping.labels.issued as issued or rejected with the reason.
  • Idempotency: the Idempotency-Key replays the first stored response; a new key for the same package hits label-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-taken and concurrent-update are RETRYABLE: nothing is stored, the key is free and the same request under the same key is executed again, and the 201 it gets then is what the key replays (ADR 0016, ADR 0020).

IssueReturnLabel​

  • Trigger: customer-returns, for one package of a return authorization. REST POST /return-labels, Idempotency-Key required (ADR 0017, ADR 0018).
  • Invariants: one label per (returnAuthorizationId, packageNo); the return destination is named by exactly one of destinationNodeId and the deprecated destinationPostalPrefix.
  • Flow:
    1. Validate the command; both destination forms, or neither, is validation-failed.
    2. Look up a label for (returnAuthorizationId, packageNo); a hit is label-already-issued.
    3. Resolve the destination prefix. For destinationNodeId, read the node's row of the local NodeDestinationView (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, is destination-prefix-unavailable: nothing is stored and customer-ordering is not called. For destinationPostalPrefix the 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.
    4. Read the ship-to of orderId from customer-ordering, before the transaction, and derive the stopKey exactly as the outbound label of that order did.
    5. In one transaction: save the label (purpose: RETURN, tier STANDARD, carrier RN-GROUND) and enqueue LabelIssued. No journey is started and no snapshot is sealed.
  • Result: 201 with the ReturnLabel. The attempt is counted once in shipping.labels.issued.
  • Idempotency: the Idempotency-Key replays the first stored response for 24 hours. destination-prefix-unavailable is RETRYABLE (like concurrent-update, validation-failed and tracking-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 that 201 is then what the key replays (ADR 0018).

VoidLabel​

  • Trigger: operations tooling. REST POST /labels/{labelRef}/voids, body reason (1 to 500 characters), Idempotency-Key required.
  • Invariants: a label can be voided only while its journey is still LABELLED (ErrVoidAfterHandover once handed over and still open; a journey already DELIVERED, RETURNED, LOST or VOIDED answers ErrJourneyClosed, checked first in Journey.Void, journey_close.go:82-87); a VOIDED label 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 label ISSUED to VOIDED with the reason, save both, enqueue LabelVoided. 200 with 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), path trackingNumber. Input (events): one Fact per 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 (unknown when none).
  • Edge table (journey.next): SHIPMENT_CONFIRMED keeps LABELLED; PICKUP_DEPARTURE takes LABELLED to HANDED_OVER; DEPARTURE and TRANSIT_ARRIVAL take HANDED_OVER or IN_TRANSIT to IN_TRANSIT; STATION_ARRIVAL takes HANDED_OVER or IN_TRANSIT to AT_STATION; OUT_FOR_DELIVERY takes AT_STATION to OUT_FOR_DELIVERY; DELIVERED takes OUT_FOR_DELIVERY to DELIVERED; DELIVERY_FAILED takes OUT_FOR_DELIVERY back to AT_STATION.
  • Order of checks in Journey.RecordScan: validation, ErrJourneyClosed, ErrDuplicateScan (nothing stored), ErrScanOutOfOrder (stored with applied=false), the edge table (ErrIllegalTransition, stored with applied=false).
  • Events: every applied scan raises PackageScanned; LABELLED to HANDED_OVER also raises PackageHandedOver (HandoverOnFirstScan); a move to DELIVERED also raises PackageDelivered and closes the journey.
  • REST outcome: 200 with the journey, or the 409 above; a scan stored unapplied is committed and the caller still gets the error. scan-out-of-order and illegal-transition are OUTCOME refusals (ADR 0020): the 409 is stored under the Idempotency-Key together with the scan, so a retry under the same key replays it and never answers duplicate-scan; duplicate-scan and journey-closed are FINAL, concurrent-update RETRYABLE. Consumer outcome: ApplyScans claims the event id in the inbox first (a replay is skipped), 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_STATION journey can be returned. A closed journey and an unknown tracking number are acknowledged; a journey not yet AT_STATION returns ErrIllegalTransition, which the consumer retries because the failed-attempt scan may still be on its way.
  • Flow: claim the event, move AT_STATION to RETURNED, enqueue PackageReturned (returnedAt from 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, enqueue PackageEtaWindowAssigned. The window is not a scan: the state does not change.
  • Invariants: a terminal journey refuses it (ErrJourneyClosed), an assignedAt not 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.EtaCurrent is true while the state is OUT_FOR_DELIVERY and the window was assigned at or after the last applied scan; only then do REST, MCP and A2A get_journey carry etaStart and etaEnd.

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 reasons NOT_HOME and ACCESS_PROBLEM and drops stopKey.
  • Flow: claim the event id, then for each tracking number of the stop: load the journey, FlagDeliveryPoint(reason, flaggedAt), save, enqueue PackageDeliveryPointFlagged (with the journey's assignmentId and orderId, 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 a flaggedAt not 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-sweep job. Candidate journeys come from ListStale in pages of 200 (SweepPageSize), each decided in its own unit.
  • Silence windows while HANDED_OVER, IN_TRANSIT or AT_STATION: 6 h SAME_DAY, 24 h NEXT_DAY, 48 h TWO_DAY, 72 h STANDARD; 12 h while OUT_FOR_DELIVERY; LABELLED and terminal states are not watched.
  • RaiseException: a watched journey past its window with no unanswered exception gets PackageExceptionRaised (reason NO_SCAN, the only reason); the state does not change; one exception per silence, a new applied scan re-arms it.
  • DeclareLost: an IN_TRANSIT journey whose exception stayed unanswered for 48 h moves to LOST and enqueues PackageLost.
  • 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​

  • PurgeShipTo deletes ship_to_snapshots whose journey closed more than 30 days ago (ShipToRetention; ADR 0002 A9) and logs snapshots_deleted=<n>.
  • Housekeeping (cmd/api/main.go housekeep) deletes idempotency_keys older than 24 h, already-relayed outbox_events older than 7 days and processed_events older 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.