Skip to main content

Aggregate Design Canvas

Synced from network-fulfillment

This page is a copy of docs/docs/ddd/aggregate-design-canvas.md on develop, derived from that repository's code. Edit it there, then re-sync.

Following the ddd-crew Aggregate Design Canvas v1.1. There are two aggregate roots in internal/domain/: NetworkOrder and CapabilityOffer. internal/domain/shared holds value objects, errors and domain events only.

NetworkOrder​

1. Name​

NetworkOrder (internal/domain/networkorder/network_order.go), identified by NetworkRef.

2. Description​

Demand that arrived from the external network, carrying a deadline we did not choose. The aggregate owns the network protocol: the single answer, its 24h deadline, and the mapping to the local order in order-management. It owns none of the fulfillment (no allocation, promise or release). It contains Line entities (networkLineRef, networkProductId, sku, quantity) that are already translated into our vocabulary.

3. State Transitions​

Source: internal/domain/networkorder/network_order.go (State constants, Submit, ConfirmAcknowledgement, Acknowledge, Reject, LinkLocalOrder, ConfirmShipment), internal/domain/networkorder/hold.go (RecordHold, SettleHold, HoldOrphaned); migrations/0003_submitted_state.up.sql (network_orders_state_check).

Omitted: Rehydrate (the repository's path back to any state, which bypasses invariants), and AcknowledgementOverdue, a query rather than a transition.

The hold (the order-management order raised for the demand) has its own small lifecycle that is orthogonal to the state above (ADR 0024): it is recorded while the order is NEW (RecordHold), and later gets one outcome, CANCELLED or ALREADY_RELEASED (SettleHold), or none while it is open. A NEW and a REJECTED order can both carry an open or a settled hold, which is why it is not a state.

4. Enforced Invariants​

InvariantEnforced by
A network order has a non-empty NetworkRefReceive, ReceiveUntranslatable → shared.ErrEmptyNetworkRef
A translated order has at least one lineReceive → shared.ErrNoLines (only ReceiveUntranslatable may be lineless)
Each line has a ref, a product id, a SKU and a positive quantityNewLine → ErrEmptyNetworkLineRef, ErrEmptyNetworkProductId, ErrUnknownProduct (empty SKU), ErrNonPositiveQuantity
Exactly one answer, in fullSubmit (only from NEW), Reject (only from NEW/SUBMITTED) → ErrAlreadyAnswered
Only a submitted answer can be confirmedConfirmAcknowledgement → ErrNotSubmitted
No local work is committed for demand we have not committed toLinkLocalOrder → ErrNotAcknowledged (state must be SUBMITTED/ACKNOWLEDGED). The database CHECK local_order_requires_answer that used to repeat this was dropped by migration 0005: the hold is now recorded earlier, on purpose
The hold is recorded only while the order is unanswered, and is never overwrittenRecordHold → ErrAlreadyAnswered unless NEW; ErrLocalOrderAlreadyLinked for a different id; the same id is a no-op (order-management replays the same order for a retried raise). LinkLocalOrder is also a no-op for the same id
A hold has at most one outcome, from a closed vocabulary, and needs a holdSettleHold → ErrNoHold, ErrUnknownHoldOutcome, ErrHoldAlreadySettled; DB CHECKs hold_outcome_vocabulary, hold_outcome_has_settled_at, hold_outcome_requires_hold
A hold is orphaned only past acknowledgeBy plus the grace, and only for NEW or REJECTEDHoldOrphaned(now, grace) (a query, the sweep's rule)
No shipment confirmation before acknowledgementConfirmShipment → ErrConfirmBeforeAcknowledge
acknowledgeBy = receivedAt + 24h, fixed at receiptReceive/ReceiveUntranslatable compute it from AcknowledgementWindow; it is persisted and never recomputed
The line set cannot be mutated from outsideLines() returns a copy
No network identifier crosses to order-managementSKUQuantities() returns only map[SKU]int
Read surfaces show the hold only for an order we committed toCommittedLocalOrderId() returns it only from SUBMITTED on; REST and MCP use it

5. Corrective Policies​

  • Deadline sweep (SweepAcknowledgementDeadlines): for every NEW order past acknowledgeBy, publish AcknowledgementDeadlineAtRisk. It never mutates the aggregate and re-fires on every pass.
  • Reject overdue (RejectOverdueOrders): cancel the order-management hold if one is recorded and still open, then Reject with ACKNOWLEDGEMENT_DEADLINE_MISSED. It never acknowledges late.
  • Orphaned-hold sweep (SweepOrphanedHolds, ADR 0024): for a NEW or REJECTED order whose hold is still open once acknowledgeBy plus ORPHAN_HOLD_GRACE has passed, cancel it, record the outcome and publish OrphanedHoldCancelled. It never changes the order's state.
  • Reconciliation (ReconcileSubmittedOrders): SUCCESS → ConfirmAcknowledgement, then release the hold. FAILURE → cancel the hold (and record its outcome), then Reject with SUBMISSION_FAILED. PENDING → retry on the next pass.
  • Idempotent receipt: ReceiveNetworkDemand returns an answered (or overdue) order for a known NetworkRef unchanged, so the poller's re-delivery is safe, and resumes an unanswered one inside its window.
  • Idempotent confirmation: ConfirmNetworkOrderShipment returns an already-CONFIRMED order unchanged.

6. Handled Commands​

CommandMethodIssued by
Receive demandReceive / ReceiveUntranslatableReceiveNetworkDemand (poller)
Record the holdRecordHoldReceiveNetworkDemand.answer, right after the raise
Submit acceptanceSubmit + LinkLocalOrderReceiveNetworkDemand.acknowledge
RejectRejectReceiveNetworkDemand.reject, RejectOverdueOrders, ReconcileSubmittedOrders.fail
Settle the holdSettleHoldfreeHold (the three reject paths, outcome CANCELLED), SweepOrphanedHolds (CANCELLED or ALREADY_RELEASED)
Confirm acknowledgementConfirmAcknowledgementReconcileSubmittedOrders.confirm
Confirm shipmentConfirmShipmentConfirmNetworkOrderShipment (REST POST .../shipment-confirmation)

7. Created Events​

The aggregate methods return only errors. The use cases raise these events from internal/domain/shared/events.go. Each is published as com.warehouse.wes.network-fulfillment.networkorder.<Event> on both topics.

EventRaised whenFull CloudEvents type
NetworkOrderReceivedafter Receive/ReceiveUntranslatable is savedcom.warehouse.wes.network-fulfillment.networkorder.NetworkOrderReceived
NetworkOrderSubmittedafter Submit + LinkLocalOrder is saved (state SUBMITTED)com.warehouse.wes.network-fulfillment.networkorder.NetworkOrderSubmitted
NetworkOrderAcknowledgedafter ConfirmAcknowledgement is saved (state ACKNOWLEDGED, the settle; ADR 0016)com.warehouse.wes.network-fulfillment.networkorder.NetworkOrderAcknowledged.v2
NetworkOrderRejectedafter every Reject (carries reason)com.warehouse.wes.network-fulfillment.networkorder.NetworkOrderRejected
NetworkOrderShipmentConfirmedafter ConfirmShipment is savedcom.warehouse.wes.network-fulfillment.networkorder.NetworkOrderShipmentConfirmed
AcknowledgementDeadlineAtRisksweep, overdue NEW order (no transition)com.warehouse.wes.network-fulfillment.networkorder.AcknowledgementDeadlineAtRisk
OrphanedHoldCancelledafter SettleHold(CANCELLED) by the orphaned-hold sweep is saved (no transition)com.warehouse.wes.network-fulfillment.networkorder.OrphanedHoldCancelled

Every state transition that answers the network raises an event: Submit raises NetworkOrderSubmitted, ConfirmAcknowledgement raises NetworkOrderAcknowledged (v2), Reject raises NetworkOrderRejected (decided 2026-10-06, ADR 0016; before it, the settle raised nothing).

8. Throughput​

Estimate, not measured. Writes per order are low and bursty: one receipt, one answer, at most one reconciliation and at most one confirmation. Concurrency on a single instance is effectively nil. Each order is touched by the poller pass, a reconcile pass and possibly an operator call, minutes apart. There is no optimistic-concurrency version column: Save is an upsert on network_ref.

9. Size​

Estimate. A handful of lines per order (one row per network line in network_order_lines). Lifetime: from receipt, it is answered within 24h, then lives until shipment confirmation (days) and stays as a terminal record. Event count per instance: 3–5 domain events (Received, then Submitted and Acknowledged (v2) on the happy path, or Rejected, possibly Rejected after a failed reconciliation, then ShipmentConfirmed), plus one AcknowledgementDeadlineAtRisk per sweep pass while the order is overdue, and at most one OrphanedHoldCancelled (once the hold has an outcome the sweep stops). The row also carries hold_outcome and hold_settled_at, both empty until the hold is settled.

CapabilityOffer​

1. Name​

CapabilityOffer (internal/domain/capabilityoffer/capability_offer.go), identified by (SKU, SiteId).

2. Description​

What this context would tell the network it can ship for one SKU at one site: the advertised quantity is the lesser of physical availability and what the eligible paths can carry before the next cutoff. It is a pure, replaceable snapshot. Each recompute supersedes it, and it has no lifecycle of its own. ADR 0001 calls it "the one genuinely new domain concept".

3. State Transitions​

Source: internal/domain/capabilityoffer/capability_offer.go (Basis constants, New, Compute); migrations/0004_capability_offers.up.sql.

The "states" are the two values of Basis. A new snapshot replaces an offer (CapabilityOfferRepo.Save upserts on (sku, site_id)); an offer is never mutated. Omitted: nothing else, because the type has no mutators.

4. Enforced Invariants​

InvariantEnforced by
A SKU is namedNew → ErrEmptySKU
A site is namedNew → ErrEmptySiteId
The advertised quantity is never negative (zero is valid)New → ErrNegativeQuantity; Compute clamps a negative capacity to 0; DB CHECK advertised_quantity >= 0
Never advertise more than physically existsNew → ErrAdvertisedExceedsPhysical
Basis is a closed setNew → ErrUnknownBasis; DB CHECK basis IN (...)
computedAt is stored in UTCNew normalises it with .UTC()

5. Corrective Policies​

  • Unknown capacity falls back to physical. Compute with throughputKnown=false (no schedule or no observed path figure) yields PHYSICAL and never advertises zero on an unproven number.
  • One bad SKU never blocks the pass. RecomputeCapabilityOffers logs and skips a SKU whose inventory lookup, compute or save fails.
  • Boot blocks until the caches replay (WaitReady), so an empty cache never under-advertises.

6. Handled Commands​

CommandMethodIssued by
Compute an offerCompute (which calls New)RecomputeCapabilityOffers (ticker, RECOMPUTE_INTERVAL)

7. Created Events​

None. The offer is persisted for GET /capability-offers and list_capability_offers, and read by the inventory feed (FeedInventory, ADR 0027 part 2), which submits it to the network in live mode as part of a per-site feed. It is not published to Kafka.

8. Throughput​

Estimate. One write per known SKU per recompute pass (default every minute) at a single SITE_ID. There is a single writer (the cmd/netfulfil ticker) and no contention.

9. Size​

Estimate. Five scalar fields per offer, one row per (sku, site). The row lives indefinitely and is overwritten in place each pass. It produces 0 events.

Not aggregates​

These hold state but are read models, projections or infrastructure, not aggregates:

  • Process-path capability cache (processpathcache.Consumer): an in-memory view of paths, cycle times and the CPT schedule, behind ports.ProcessPathCapability.
  • Path capacity cache (pathcapacitycache.Consumer): an in-memory remaining capacity per (path, cutoff), behind ports.PathCapacity.
  • Poller stats (poller.Stats): counters behind GET /inbound-status.
  • Acknowledgement report (acknowledgement_rollup, analytics_processed_events, analytics_consumed_events in the analytical DB): the projection written by cmd/netfulfil-projector.
  • Outbox (outbox_events): infrastructure for the transactional outbox.
  • Product translation (memory.ProductTranslation): a dictionary loaded from a file.