Skip to main content

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 caseTriggerWritesEvent raised
DefinePathREST POST /process-pathsprocess_paths (insert-only)ProcessPathCreated
RevisePathREST PUT /process-paths/{pathId}process_paths (version-guarded)ProcessPathUpdated, only if something changed
DeactivatePathREST DELETE /process-paths/{pathId}process_pathsProcessPathDeactivated, only on the first deactivation
GetPathREST GET /process-paths/{pathId}; MCP get_process_path——
ListPathsREST GET /process-paths[?all=true]; MCP list_process_paths——
DefineCPTScheduleREST PUT /sites/{siteId}/cpt-schedulecpt_schedules, cpt_schedule_cutoffsCPTScheduleChanged, only if the schedule is new or changed
GetCPTScheduleREST GET /sites/{siteId}/cpt-schedule; MCP get_cpt_schedule——
DefineProcessFlowREST PUT /process-flows/{flowId}process_flows, process_flow_stagesProcessFlowDefined (first define), ProcessFlowRevised (a real change); nothing when the request changes nothing
RetireProcessFlowREST DELETE /process-flows/{flowId}process_flowsProcessFlowRetired, only on the first retirement
GetProcessFlowREST GET /process-flows/{flowId}; MCP get_process_flow; A2A get_process_flow——
ListProcessFlowsREST GET /process-flows[?all=true]; MCP list_process_flows; A2A list_process_flows——
RepublishCatalogueStart of cmd/pathmgmt, once per start, after the migrations and before the listener bindsoutbox_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:

  1. HTTP adapter: destinationLocationRole is empty or one of Drop, WorkCenter, Shipping; cycleTimeP95 parses as a Go duration; intake is a set of known demand sources (shared.ParseIntake, ErrInvalidIntake otherwise).
  2. No path with this id exists, active or deactivated (ErrPathAlreadyExists). A deactivated id can never be reused.
  3. processpath.Define: non-empty pathId, non-empty and lower-case matchPrefix, at least one capability, valid destination role, cycleTimeP95 > 0.
  4. Repo.Create is insert-only: a concurrent define that wins the race makes this one fail with ErrPathAlreadyExists instead 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:

  1. Unlocked pre-check: unknown → ErrPathNotFound; already deactivated → success, nothing published (idempotent).
  2. Inside the unit of work the row is re-read FOR UPDATE, then ListSiteIDsReferencingPath: if any site's CPT schedule lists the path in a cutoff, fail with ErrPathReferencedByCPTSchedule naming the sites (ADR 0026). The row lock serialises this against DefineCPTSchedule (ADR 0028).
  3. Then, still under the same row lock, ListActiveFlowIDsReferencingPath: if an ACTIVE process flow has a stage on the path, fail with ErrPathInActiveFlow (409 path-in-active-flow), naming the flows (ADR 0042). DefineProcessFlow holds the matching FOR SHARE lock 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, or ErrPathNotFound.
  • ListPaths(activeOnly) returns Active paths by default; ?all=true (REST) or activeOnly: false (MCP) includes deactivated ones. The REST query value must be exactly true or false.

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:

  1. HTTP adapter, per cutoff (cptschedule.NewCutoff): non-empty cptId; localTime exactly HH:MM 24-hour; at least one day, each Mon…Sun; non-empty shipMethod; at least one eligible path id.
  2. Inside the unit of work: the distinct eligiblePathIds across all cutoffs are sorted and locked FOR 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).
  3. cptschedule.Define (no schedule yet) or Revise (existing): non-empty, valid IANA timezone; at least one cutoff; cptId unique within the site.
  4. 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:

  1. Before any lock (processflow.ValidateDefinition): non-empty flowId and name; at least one stage; each stage's pathId non-empty and processType one of PICK, REBIN, PACK, SLAM, DISPATCH, ARRIVAL, RELOCATE, REPLENISH; a pathId at most once per flow.
  2. Inside the unit of work: an existing RETIRED flow is refused (ErrFlowRetired, 422 flow-retired).
  3. The distinct stage pathIds are sorted and locked FOR SHARE; every one must be an existing Active path (ErrIneligibleStagePath, 422 ineligible-stage-path), the same shape as DefineCPTSchedule's rule (ADR 0028).
  4. processflow.Define (new, version 1) or Revise (existing). A new flow is an insert-only Create; losing that race is ErrConcurrentModification (409), not a second ProcessFlowDefined.

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, or ErrFlowNotFound.
  • ListProcessFlows(activeOnly) returns ACTIVE flows by default; ?all=true (REST) or activeOnly: false (MCP, A2A) includes retired ones. REST pages by flowId keyset (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:

  1. ListActive paths, sorted by id, then LockByIDsForShare (ADR 0028); a path deactivated since the listing is skipped. Deactivated paths are never republished.
  2. CPTScheduleRepo.LockAllForShare, then one snapshot per site, sorted by site id.
  3. ProcessFlowRepo.LockActiveForShare, then one ProcessFlowRevised per ACTIVE flow (its current state and current version), sorted by flow id; RETIRED flows are not republished (ADR 0042).
  4. At most MaxRepublishedPerKind (1000) paths, 1000 schedules and 1000 flows per start. What exceeds the cap is counted in RepublishResult.Omitted and 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).