Use cases
The application layer (internal/application/usecases) has twelve use cases,
one struct each. Six are writes triggered only by REST; the five reads are
also exposed as MCP tools (and, for paths and flows, as A2A skills). The twelfth, RepublishCatalogue, is triggered by
neither: cmd/pathmgmt runs it once at every start
(ADR 0038). There is no
Kafka-triggered use case and nothing runs a use case on a timer: this service
consumes no sibling topic, and its background jobs (the outbox relay and the
housekeeping sweeper) are infrastructure in
internal/adapters/outbound/postgres, not use cases.
| Use case | Trigger | Writes | Event raised |
|---|---|---|---|
DefinePath | REST POST /process-paths | process_paths (insert-only) | ProcessPathCreated |
RevisePath | REST PUT /process-paths/{pathId} | process_paths (version-guarded) | ProcessPathUpdated, only if something changed |
DeactivatePath | REST DELETE /process-paths/{pathId} | process_paths | ProcessPathDeactivated, only on the first deactivation |
GetPath | REST GET /process-paths/{pathId}; MCP get_process_path | — | — |
ListPaths | REST GET /process-paths[?all=true]; MCP list_process_paths | — | — |
DefineCPTSchedule | REST PUT /sites/{siteId}/cpt-schedule | cpt_schedules, cpt_schedule_cutoffs | CPTScheduleChanged, only if the schedule is new or changed |
GetCPTSchedule | REST GET /sites/{siteId}/cpt-schedule; MCP get_cpt_schedule | — | — |
DefineProcessFlow | REST PUT /process-flows/{flowId} | process_flows, process_flow_stages | ProcessFlowDefined (first define), ProcessFlowRevised (a real change); nothing when the request changes nothing |
RetireProcessFlow | REST DELETE /process-flows/{flowId} | process_flows | ProcessFlowRetired, only on the first retirement |
GetProcessFlow | REST GET /process-flows/{flowId}; MCP get_process_flow; A2A get_process_flow | — | — |
ListProcessFlows | REST GET /process-flows[?all=true]; MCP list_process_flows; A2A list_process_flows | — | — |
RepublishCatalogue | Start of cmd/pathmgmt, once per start, after the migrations and before the listener binds | outbox_events (integration-topic rows only) | ProcessPathUpdated per ACTIVE path, then CPTScheduleChanged per site, then ProcessFlowRevised per ACTIVE flow |
Every write runs inside UnitOfWork.Execute, so
the aggregate row and the outbox_events rows commit together
(ADR 0003); unit tests over the
in-memory doubles simply run the save and the publish back to back. Event payloads
are on Domain events; the problem types each error
maps to are on Troubleshooting.
DefinePath
internal/application/usecases/define_path.go
Inputs: pathId, matchPrefix, direct, requiredCapabilities[],
optional destinationLocationRole, cycleTimeP95 (Go duration string),
optional eligibility (maxUnitsPerLine, requiredProductAttributes,
excludedProductAttributes, nonSortable), optional intake (demand
sources, ADR 0034; absent = []).
With Postgres, the HTTP route also requires an Idempotency-Key header.
Checks, in order:
- HTTP adapter:
destinationLocationRoleis empty or one ofDrop,WorkCenter,Shipping;cycleTimeP95parses as a Go duration;intakeis a set of known demand sources (shared.ParseIntake,ErrInvalidIntakeotherwise). - No path with this id exists, active or deactivated
(
ErrPathAlreadyExists). A deactivated id can never be reused. processpath.Define: non-emptypathId, non-empty and lower-casematchPrefix, at least one capability, valid destination role,cycleTimeP95 > 0.Repo.Createis insert-only: a concurrent define that wins the race makes this one fail withErrPathAlreadyExistsinstead of overwriting.
Raises: ProcessPathCreated with the full definition.
Metrics: process_path_management.paths.defined{outcome=accepted|rejected}
(rejections at steps 2–4).
Declared entries. scripts/seed_catalogue.py (make seed-catalogue)
calls this use case, through the same REST route, for every entry of
catalogue/paths.json that the store does not hold yet. It calls RevisePath
for an entry whose revisable fields drifted, and it never calls either for an
identical or deactivated entry. The file declares PICK, PACK, REBIN, SLAM,
RELOCATE (matchPrefix relocate, direct, capability relocate, intake
SLOT_RELOCATION), which carries slot-plan moves, and DISPATCH
(matchPrefix dispatch, direct, capability dispatch, intake
STOCK_TRANSFER), which carries the transfer dispatch leg, and REPLENISH
(matchPrefix replenish, direct, capability replenish, intake
REPLENISHMENT), which carries pick-face top-ups; every entry
declares its intake
(ADR 0033,
ADR 0034,
ADR 0035,
Process-path catalogue).
RevisePath
internal/application/usecases/revise_path.go
Inputs: pathId (URL), matchPrefix, requiredCapabilities[],
cycleTimeP95, optional eligibility, optional intake (absent or
null keeps the current intake; [] clears it). direct and
destinationLocationRole are not revisable.
Checks: the path exists (ErrPathNotFound); it is Active
(ErrPathDeactivated); the same field invariants as define. The save is
guarded by the row's version column; a concurrent writer makes it fail
with ErrConcurrentModification
(ADR 0017).
Raises: ProcessPathUpdated with the full new definition, only when
matchPrefix, capabilities, cycle time, eligibility or intake actually changed. An
identical body returns 200 and publishes nothing.
DeactivatePath
internal/application/usecases/deactivate_path.go
Inputs: pathId (URL).
Checks:
- Unlocked pre-check: unknown →
ErrPathNotFound; already deactivated → success, nothing published (idempotent). - Inside the unit of work the row is re-read
FOR UPDATE, thenListSiteIDsReferencingPath: if any site's CPT schedule lists the path in a cutoff, fail withErrPathReferencedByCPTSchedulenaming the sites (ADR 0026). The row lock serialises this againstDefineCPTSchedule(ADR 0028). - Then, still under the same row lock,
ListActiveFlowIDsReferencingPath: if an ACTIVE process flow has a stage on the path, fail withErrPathInActiveFlow(409path-in-active-flow), naming the flows (ADR 0042).DefineProcessFlowholds the matchingFOR SHARElock on every path it names until commit. Retiring or revising the flow clears the refusal.
Raises: ProcessPathDeactivated (path_id only). Deactivation is
terminal: nothing reactivates a path.
GetPath and ListPaths
internal/application/usecases/queries.go
GetPath(pathId)returns the path in any status, orErrPathNotFound.ListPaths(activeOnly)returns Active paths by default;?all=true(REST) oractiveOnly: false(MCP) includes deactivated ones. The REST query value must be exactlytrueorfalse.
No invariants, no events.
DefineCPTSchedule
internal/application/usecases/cpt_schedule.go
Inputs: siteId (URL), timezone, cutoffs[] each with cptId,
localTime, daysOfWeek[], shipMethod, eligiblePathIds[]. Every PUT
replaces the whole schedule; there is no partial update.
Checks, in order:
- HTTP adapter, per cutoff (
cptschedule.NewCutoff): non-emptycptId;localTimeexactlyHH:MM24-hour; at least one day, eachMon…Sun; non-emptyshipMethod; at least one eligible path id. - Inside the unit of work: the distinct
eligiblePathIdsacross all cutoffs are sorted and lockedFOR SHARE; every one must be an existing Active path (ErrIneligiblePathId). This is the only cross-aggregate invariant, enforced here rather than by a foreign key (ADR 0010). cptschedule.Define(no schedule yet) orRevise(existing): non-empty, valid IANAtimezone; at least one cutoff;cptIdunique within the site.- The upsert is version-guarded (
ErrConcurrentModification).
Raises: CPTScheduleChanged carrying the full schedule snapshot, when
the schedule is new or differs from the stored one. An identical PUT
returns 200 and publishes nothing.
GetCPTSchedule
Returns the site's schedule or ErrCPTScheduleNotFound. No events.
DefineProcessFlow
internal/application/usecases/process_flow.go
Inputs: flowId (URL), name, stages[] each with pathId and
processType. Every PUT replaces the name and all stages; there is no
partial update and no Idempotency-Key.
Checks, in order:
- Before any lock (
processflow.ValidateDefinition): non-emptyflowIdandname; at least one stage; each stage'spathIdnon-empty andprocessTypeone ofPICK,REBIN,PACK,SLAM,DISPATCH,ARRIVAL,RELOCATE,REPLENISH; apathIdat most once per flow. - Inside the unit of work: an existing RETIRED flow is refused
(
ErrFlowRetired, 422flow-retired). - The distinct stage
pathIds are sorted and lockedFOR SHARE; every one must be an existing Active path (ErrIneligibleStagePath, 422ineligible-stage-path), the same shape asDefineCPTSchedule's rule (ADR 0028). processflow.Define(new, version 1) orRevise(existing). A new flow is an insert-onlyCreate; losing that race isErrConcurrentModification(409), not a secondProcessFlowDefined.
Raises: ProcessFlowDefined on the first define, ProcessFlowRevised
when the name or the stages changed. Both carry the full state and the
version (1, then +1 per accepted change). An identical PUT returns 200,
publishes nothing and keeps the version. REST answers 201 for a new flow,
200 otherwise (ADR 0042).
RetireProcessFlow
internal/application/usecases/process_flow.go
Inputs: flowId (URL). An unknown id is ErrFlowNotFound (404
flow-not-found); retiring an already RETIRED flow succeeds and publishes
nothing.
Raises: ProcessFlowRetired, the full state with status RETIRED and
the next version. A retired flow cannot be revised, and the paths it used
can be deactivated again.
GetProcessFlow and ListProcessFlows
internal/application/usecases/process_flow.go
GetProcessFlow(flowId)returns the flow in any status, orErrFlowNotFound.ListProcessFlows(activeOnly)returns ACTIVE flows by default;?all=true(REST) oractiveOnly: false(MCP, A2A) includes retired ones. REST pages byflowIdkeyset (limit,cursor).
No invariants, no events.
RepublishCatalogue
internal/application/usecases/republish_catalogue.go; wired by
buildRepublishCatalogue and run by republishCatalogueAtStartup in
cmd/pathmgmt/republish.go, which cmd/pathmgmt/main.go calls once before
serveHTTP starts the listener and the outbox relay.
Inputs: none. It reads the store.
Steps, all in one unit of work:
ListActivepaths, sorted by id, thenLockByIDsForShare(ADR 0028); a path deactivated since the listing is skipped. Deactivated paths are never republished.CPTScheduleRepo.LockAllForShare, then one snapshot per site, sorted by site id.ProcessFlowRepo.LockActiveForShare, then oneProcessFlowRevisedper ACTIVE flow (its current state and currentversion), sorted by flow id; RETIRED flows are not republished (ADR 0042).- At most
MaxRepublishedPerKind(1000) paths, 1000 schedules and 1000 flows per start. What exceeds the cap is counted inRepublishResult.Omittedand logged at ERROR.
Raises: one ProcessPathUpdated per ACTIVE path (the payload
RevisePath builds, processPathUpdated), one CPTScheduleChanged per
site (cptschedule.ToSnapshot) and one ProcessFlowRevised per ACTIVE flow
(ProcessFlow.RevisedEvent), through the same transactional outbox, on
the integration topic only: buildRepublishCatalogue gives the
OutboxPublisher the integration encoder alone, so nothing reaches the
analytics topic and paths_revised is not inflated by restarts.
Failure: it never fails the boot. A run is all-or-nothing, bounded by a
30 s timeout, logged at ERROR on failure or truncation, and counted on
process_path_management.catalogue.republished
(kind=path|schedule|flow, outcome=accepted|failed).
Outside the application layer: the analytics projection
The catalogue-growth read model is not built by a use case in
internal/application. pathmgmt-projector consumes this service's own
analytics topic (internal/adapters/inbound/kafka/analytics_consumer.go) and
applies each ProcessPathCreated/Updated/Deactivated to the
report.ProjectionStore port (internal/analytics/report), incrementing the
paths_defined/paths_revised/paths_deactivated counter of the event's
UTC day. It is idempotent per CloudEvents id and raises no events. The
reader side is report.ReportStore, served by pathmgmt-reports
(Runbook). See
ADR 0007.
Sequence of a write
Source: internal/application/usecases/revise_path.go,
internal/adapters/outbound/postgres/outbox_publisher.go,
internal/adapters/outbound/postgres/outbox_relay.go.
Omits: the transaction boundary (steps 6 to 8 run in one UnitOfWork; the
read in step 3 does not), error paths, and the idempotency middleware (POST
only).