Skip to main content

Architecture

order-sourcing 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/assignmentThe Assignment aggregate (FulfillmentAssignment): states, transitions, commands, the domain events it records, snapshots, typed errors.
Domaininternal/domain/sourcingThe pure search: Search over a World, candidate cost, ReleaseAt, the tier rules. No I/O.
Domaininternal/domain/networkValue types of the local read models: Node, Lane, Departure, Wave, ServiceArea, Region, Listing, Scorecard, Pressure.
Domaininternal/domain/sharedThe Event interface every domain event satisfies.
Applicationinternal/application/usecasesThe use cases (see Use cases): QueueAssignment, SweepQueue, ReoptimiseAssignment, ReleaseToNode, HandleNodeRefusal, LockAssignment, MarkShipped, MarkDelivered, RecordPickupMoved, CancelAssignment, ApplyRevisedPromise, Projector, RecordProcessed, and the read-only Queries.
Applicationinternal/application/ports, repository, views, outboxThe OUT ports (AssignmentRepository, ReadModels, WorldReader, EventOutbox, Inbox, UnitOfWork, Clock, IDGenerator, IdempotencyStore, SourcingMetrics), the filter and world-query structs, the read views returned by queries, and the outbox record. ports holds only interfaces.
Inbound adapterinternal/adapters/inbound/httpchi router for apis/openapi.yaml: handlers, RFC 9457 problem mapping (errors.go), the Idempotency-Key middleware, /healthz and /readyz. No auth middleware.
Inbound adapterinternal/adapters/inbound/kafkaOne consumer per consumed topic (nine): CloudEvents decode, dispatch on the full type, retry with backoff, dead-letter topic. Decode only; every effect is a use case.
Inbound adapterinternal/adapters/inbound/mcpRead-only MCP tools list_assignments and get_assignment.
Inbound adapterinternal/adapters/inbound/a2aRead-only A2A agent: skills find_assignments and assignment_detail, the Agent Card.
Inbound adapterinternal/adapters/inbound/requestlogRequest logging shared by the HTTP-facing binaries.
Outbound adapterinternal/adapters/outbound/postgrespgxpool repositories, the unit of work (pgtx), the world reader and read-model writers, the outbox and the inbox, embedded migrations (migrations/0001_order_sourcing_schema.up.sql).
Outbound adapterinternal/adapters/outbound/memoryIn-memory implementation of the repository ports: a test double for the unit and BDD suites. No shipped binary imports it (TestRuntimeBinaryHasNoInMemoryAdapters).
Outbound adapterinternal/adapters/outbound/repocontractThe repository contract suite run against both the memory and the Postgres adapters.
Outbound adapterinternal/adapters/outbound/kafkaEncoder (domain event to CloudEvents message and topic), Writer (acks all, hash balancer, auto-create), RelaySink, BrokerCheck (the Kafka half of /readyz).
Outbound adapterinternal/adapters/outbound/outboxThe relay loop that drains outbox_events to the sink, with the attempt cap.
Outbound adapterinternal/adapters/outbound/telemetryOpenTelemetry setup, the slog bridge, the sourcing.groups.sourced counter (SourcingMetrics).
Outbound adapterinternal/adapters/outbound/clock, idsThe system clock and the UUID assignment ids, the two adapters that need no infrastructure.
Kafka envelopeinternal/adapters/kafka/cloudeventsThe only place a CloudEvents 1.0 envelope is built or decoded.
Supportinternal/bootretryExponential-backoff retry for the first outbound dials at boot.
Composition rootscmd/api, cmd/mcp, cmd/a2aEnvironment parsing, wiring, workers, shutdown order.
Test supportinternal/testing/pgtestShared testcontainers helper for Postgres integration tests.
Fitness testsinternal/architectureSource-scanning and import-graph tests; see below.
Operator UIweb/The order_sourcing_mfe Module Federation remote (ADR 0007); not a Go binary.

The domain's central dependency is one-way: assignment imports sourcing and network, sourcing imports network, and none imports application or an adapter. The search is a pure function of an immutable World snapshot that the application layer loads through WorldReader for one search; the aggregate only stores the chosen candidate and the exclusion list.

Binaries and ports​

BinaryRolePortProbes
cmd/apiREST API, nine Kafka consumers, the virtual-queue sweep and the outbox relay in one process, always on real Postgres and Kafka.HTTP_ADDR, default :8080GET /healthz (liveness), GET /readyz (drain gate, Postgres ping, a Kafka broker answers a metadata request; never topics)
cmd/mcpRead-only MCP server (Streamable HTTP) over the query use cases; Postgres only, no relay, consumer or Kafka (ADR 0006).MCP_ADDR, default :8090GET /healthz
cmd/a2aRead-only A2A (Agent2Agent) server over the same queries: JSON-RPC at / and /a2a, Agent Card at /.well-known/agent-card.json; Postgres only (ADR 0009).A2A_ADDR, default :8093GET /healthz

How each binary boots, drains and stops is on Runtime; every variable is in Configuration.

Container diagram​

Source: cmd/api/main.go (buildServices, startConsumers, startOutboxRelay, startSweep), cmd/mcp/main.go, cmd/a2a/main.go, internal/application/ports/ports.go, the import lists of internal/domain/*/*.go 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 (the OLTP one), created by 0001_order_sourcing_schema.up.sql in internal/adapters/outbound/postgres/migrations/ and altered by 0002_idempotency_global_key, 0003_rm_lane_wave_cost and 0004_rm_listings_owner_ref, none of which adds a table (applied by golang-migrate at every boot):

TableHolds
assignmentsThe FulfillmentAssignment aggregate: one row per (order_id, group_no) (unique), the chosen candidate and release_at, the release history, excluded nodes, lock, shipment and delivery facts; version guards every update. A partial index serves the queue (state = 'QUEUED' by release_at).
rm_nodes, rm_lanes, rm_departures, rm_waves, rm_service_areas, rm_regionsThe network view: node profiles, the lane graph, pickup departures with remaining capacity, delivery waves, postal-prefix service areas and regions.
rm_listings, rm_discontinued_itemsThe availability view: per node and item quantity and the discontinued item set.
rm_scorecardsThe node scorecard grade per (node_id, score_window).
rm_book_pressureThe promise-book pressure per book_id, used as the 500 point cost term.
processed_eventsCloudEvents ids already applied: the inbox that makes the consumers idempotent.
outbox_eventsThe transactional outbox; one row per message, with attempts, last_error and published_at.
idempotency_keysStored answers of POST /assignments/{assignmentId}/reoptimisations, replayed for 24 hours.

cmd/api refuses to boot without DATABASE_URL, and nothing is served from process memory. The only other store is the separate analytical Postgres database (4 tables: queued_groups, sourcing_decisions, unsourceable_declarations, analytics_processed_events, from analytics/migrations/0001_sourcing_facts.up.sql) that cmd/os-projector writes and cmd/os-reports reads when analytics.enabled is set; cmd/api never opens it. See the Entity relationship page. Kafka is the platform's single broker. This service consumes nine retailnetwork.<producer>.events topics (see Integration) and produces to retailnetwork.order-sourcing.events and retailnetwork.order-sourcing.analytics. It never creates a topic through an admin API: the broker auto-creates each on first write (the relay's writer allows it), 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 list and the sensor tests that prove each detector bites are on Testing. The ones that shape the layout:

TestRule
TestHexagonalArchitectureDomain depends only on domain; application only on domain and application; inbound and outbound adapters do not depend on each other; nothing under internal/ imports cmd; ports holds only interfaces.
TestMCPAdapterDependencyRule, TestMCPOptionalToolInputsCarryOmitemptyThe MCP adapter depends only on application and domain and nothing depends on it; optional tool inputs carry omitempty.
TestA2AAdapterDependencyRule, TestA2AAgentIsReadOnly, TestA2AHasNoOutboundClient, TestA2ABinaryIsKafkaFreeAndReadOnlyThe A2A adapter and cmd/a2a reach only read use cases, no Kafka, and no file imports an A2A client.
TestNoAuthMiddlewareReintroducedNo bearer-token or JWT code under internal/adapters/inbound: the surface is unauthenticated fleet-wide.
TestRuntimeBinaryHasNoInMemoryAdaptersNo non-test file under cmd/** imports internal/adapters/outbound/memory or repocontract.
TestKafkaConsumerGroupNeverHardcodedInline, TestKafkaWritersSetRequiredAcks, TestKafkaWriterTopicNotSetTwice, TestReplayConsumersSetCommitInterval, TestDeadLetterCallsGuardCancellationConsumer groups come from the environment, every writer sets RequiredAcks, the topic is set on the message or the writer but not both, and a shutdown never dead-letters a message that was only mid-flight.
TestOutboxRelaysPassAttemptCapEvery relay is built with WithMaxAttempts(...).
TestCloudEventsOnly, TestNoEventEnvelopeToggleOrFlatEnvelope, TestEventCatalogueMatchesContractCloudEvents 1.0 is the only envelope and the AsyncAPI catalogue matches the ADR.
TestNoGoFilesAtRepoRootNo Go file sits at the repository root.