Skip to main content

Architecture

shopping-cart follows the fleet's hexagonal (ports and adapters) layout: dependencies point inward, the domain imports nothing from the rest of the module, and only cmd/ wires the layers together. Everything on this page is on develop.

Layout​

LayerPathRole
Domaininternal/domain/cartThe Cart aggregate: lines, destination, DeliveryQuote (QuoteGroup, QuotedOffer, TierUnavailable), Selection, CheckoutReadiness, the lifecycle (AbandonInactive, CloseOnCheckoutCompleted, MergeInto), AcceptRequotedOffers, the domain errors and the four domain events (CartLineAdded, CartDeliveryQuoted, CartAbandoned, CartCheckedOut).
Domaininternal/domain/estimateThe pure Compute of the labelled estimate over prices, the delivery charge Schedule and the TaxTable; reports Complete instead of guessing. Imports cart for vocabulary only.
Domaininternal/domain/sharedEvent, Header, ErrValidation, ErrIllegalTransition, id and UTC helpers.
Applicationinternal/application/usecasesOne use case per command, policy and consumed event (see Use cases), the Consumer (inbox claim plus effect in one unit of work), the view that renders a cart with its estimate and readiness.
Applicationinternal/application/portsThe OUT ports: CartRepository, ItemRepository, ScheduleRepository, TaxTableRepository, QuoteOffers, Inbox, EventOutbox, UnitOfWork, IdempotencyStore, Clock, IDGenerator, CartMetrics. Interfaces only.
Applicationinternal/application/{readmodel,views,outbox,idempotency}The read-model item, the cart view, the already-encoded outbox Message, the stored idempotency Record (TTL 24 h).
Inbound adapterinternal/adapters/inbound/httpchi router for apis/openapi.yaml: handlers, RFC 9457 problem mapping (errors.go), the Idempotency-Key middleware, the NUL guard, /healthz and /readyz. No auth middleware.
Inbound adapterinternal/adapters/inbound/kafkaThe three consumers (offer-availability, pricing, checkout): CloudEvents decode, dispatch on the full type, retry with backoff, dead-letter topic, a consumer span per attempt. Decode only; every effect is a use case.
Inbound adapterinternal/adapters/inbound/schedulerTimer-driven jobs that call the AbandonInactive and PurgeAbandonedCarts use cases in batches of 200.
Inbound adapterinternal/adapters/inbound/a2aThe A2A skills get_cart and list_shopper_carts, the Agent Card, strict skill-request parsing. Read-only; depends on application and domain only.
Inbound adapterinternal/adapters/inbound/mcpThe MCP tools get_cart and list_shopper_carts (authority L1), the cart resource and the review_cart prompt over the stateless Streamable HTTP handler (ADR 0009). Read-only; depends on application and domain only, and only cmd/mcp imports it.
Inbound adapterinternal/adapters/inbound/requestlogThe access-log middleware (method, route pattern, status, duration, request id).
Outbound adapterinternal/adapters/outbound/postgrespgxpool repositories (carts, read models, inbox, idempotency, outbox), the unit of work (pgtx), embedded migrations (migrate.go), trace-header injection into outbox rows.
Outbound adapterinternal/adapters/outbound/kafkaThe CloudEvents Encoder for the four published events, NewWriter (acks from all replicas, hash balancer, no fixed topic), the relay Sink, BrokerCheck (the Kafka half of /readyz).
Outbound adapterinternal/adapters/outbound/outboxThe relay loop that drains outbox_events to the sink.
Outbound adapterinternal/adapters/outbound/deliverypromiseThe HTTP client of POST /delivery-quotes and the time-zone resolution of offer windows (ADR 0007).
Outbound adapterinternal/adapters/outbound/{telemetry,clock,ids}OpenTelemetry setup and the cart.lines.added counter; the system clock; the cart id generator.
Outbound adapterinternal/adapters/outbound/memoryIn-memory implementation of every port: a test double for the unit and godog suites. The shipped binaries never import it (TestRuntimeBinaryHasNoInMemoryAdapters).
Kafka envelopeinternal/adapters/kafka/cloudeventsThe only place a CloudEvents 1.0 envelope is built or decoded: New(Spec), Decode, Type, DataSchema. Repo/Context = shopping-cart, Source = /retailnetwork/shopping-cart.
Supportinternal/bootretryExponential-backoff retry for the first outbound dials at boot (migrations, Postgres ping).
Composition rootscmd/api, cmd/a2a, cmd/mcpmain.go, config.go, telemetry.go, tzdata.go (embeds the zone database) and, for a2a and mcp, router.go.
Test supportinternal/testing/{kafkatest,pgtest}, internal/adapters/outbound/repocontractTestcontainers helpers and the repository contract suite run against both the memory and Postgres adapters.
Fitness testsinternal/architecturearch-go and source-scanning tests, see Testing.

Binaries and ports​

BinaryRolePortProbes
cmd/apiREST API, the outbox relay, the offer-availability, pricing and checkout consumers and the AbandonInactive and PurgeAbandonedCarts sweeps, all always on, in one process, on real Postgres and Kafka.HTTP_ADDR, default :8080GET /healthz (liveness), GET /readyz (drain gate, Postgres ping, a Kafka broker answers a metadata request)
cmd/a2aRead-only Agent2Agent agent (ADR 0006): JSON-RPC 2.0 at / and /a2a, Agent Card at /.well-known/agent-card.json. Same Postgres and the same GetCart and ListCarts use cases as the REST reads; no Kafka, outbox, consumer, sweeper or delivery-promise client.A2A_ADDR, default :8093GET /healthz
cmd/mcpRead-only MCP server (ADR 0009): Streamable HTTP at /mcp and /, the tools get_cart and list_shopper_carts, one resource, one prompt (MCP tools). Same Postgres and the same two use cases; no Kafka, outbox, consumer, sweeper or delivery-promise client.MCP_ADDR, default :8090GET /healthz

The three binaries run the same embedded migration at boot (idempotent), so any of them may start first. Startup order, shutdown order and the probes are in the Runbook; every variable is in Configuration.

Container diagram​

Source: cmd/api/main.go (buildAdapters, startConsumers, startOutboxRelay, startSchedulers), cmd/a2a/main.go (buildDeps) and cmd/a2a/router.go, internal/application/ports/ports.go, the import lists of internal/domain/*/*.go (estimate imports cart) and internal/architecture/architecture_test.go. The in-memory adapters are not in the diagram because no binary wires them.

Data stores​

One Postgres database, created by the single embedded migration (internal/adapters/outbound/postgres/migrations/0001_shopping_cart_schema.up.sql):

TableHolds
cartsThe Cart aggregate: state, destination, lines, quote and selections as jsonb, created_at, last_changed_at, version (the optimistic-concurrency token).
rm_itemsPurchasabilityView: per catalogue item catalogued, discontinued, priced, price_minor, currency, price_version. A row may be a stub when a price event arrives before CatalogItemCreated.
rm_current_schedule, rm_current_tax_tableEstimateView: the one current delivery charge schedule and tax table (singleton rows, each with its version).
processed_eventsThe inbox: CloudEvents id claims that make the consumers idempotent.
idempotency_keysStored first answers per (route, key); a record older than 24 h is treated as absent and overwritten.
outbox_eventsThe transactional outbox, one row per message with its topic, key, encoded CloudEvent, headers (including traceparent), attempts and last_error.

Postgres is the only store: both binaries refuse to boot without DATABASE_URL and nothing is served from process memory. The schema holds no PII and no card data. Kafka is the fleet's single broker; this service produces to retailnetwork.shopping-cart.analytics and consumes retailnetwork.offer-availability.events, retailnetwork.pricing.events and retailnetwork.checkout.events. It never creates a topic through an admin API: the broker auto-creates each on first write (including <topic>.dlq), and /readyz does not wait for any topic.

Rules enforced by internal/architecture​

The tests run on every PR (arch-test job, make arch-test); the full list is on Testing. The ones that shape this layout:

TestRule
TestHexagonalArchitecture (6 subtests)domain depends only on domain; application only on domain and application; inbound and outbound adapters never depend on each other; nothing under internal/ imports cmd; internal/application/ports holds only interfaces.
TestRuntimeBinaryHasNoInMemoryAdaptersno non-test file under cmd/** imports the in-memory adapter: the binaries run on Postgres and Kafka only.
TestA2AAdapterDependencyRule, TestA2ASurfaceIsReadOnlythe A2A adapter depends only on application and domain and reaches only read use cases.
TestNoAuthMiddlewareReintroducedREST carries no bearer or JWT handling: unauthenticated fleet-wide.
TestKafkaConsumerGroupNeverHardcodedInlineconsumer group ids come from the three *_CONSUMER_GROUP variables.
TestCloudEventsOnly, TestEventCatalogueMatchesContractCloudEvents 1.0 is the only envelope; every type in apis/asyncapi.yaml is in ADR 0004.
TestOutboxRelaysPassAttemptCapthe relay is built with WithMaxAttempts, so a poison row cannot block it.