Warehouse service contract¶
warehouse-service owns warehouse fulfilment: shipments, returns (RMA),
suppliers and purchase orders. The backend (backend-rs) keeps users,
JWT issuance, products, stock, cart, coupons, reviews, wishlist and orders.
This document is the boundary both sides implement. Business rules are the ones
already specified for the original Java backend in
test-secure-backend/docs/COMMERCE_AND_FULFILMENT.md (Tier 2 section,
archived); only their location changes.
Runtime¶
| Item | Value |
|---|---|
| Repository | slawekradzyminski/warehouse-service-rs (Rust port of the archived Java warehouse-service) |
| Stack | Rust (axum, sqlx); errors keep the ErrorDto {message} shape |
| Image | slawekradzyminski/warehouse-service-rs (Rust; source), about 7–10 MiB RSS measured |
| Port | 4003 |
| Database | Postgres schema warehouse in the existing database (Flyway-compatible history in schema warehouse, currentSchema=warehouse) |
| Profiles | local (Postgres localhost:5432/testdb, backend at http://localhost:4001, demo suppliers), docker (Postgres, backend at http://backend:4001), demo (seeds demo suppliers) |
| Deployed in | lightweight, full and server Compose profiles |
| Requires | backend 3.16.0 or later from warehouse-service 1.3.0 (event feed; see the addendum below) |
Public API (unchanged paths)¶
The gateway routes these paths to warehouse-service; request and response bodies stay exactly as in backend PR #85, so the frontend keeps its calls.
/api/v1/warehouse/**(queue, shipments, pick list, pick/pack/ship/deliver/cancel)GET /api/v1/orders/{id}/shipmentPOST /api/v1/orders/{orderId}/returns,GET /api/v1/returns,GET /api/v1/returns/{id}/api/v1/admin/returns/**/api/v1/admin/suppliers,/api/v1/admin/purchase-orders/**GET /api/v1/admin/inventory/reorder-suggestions
warehouse-service serves its OpenAPI at /v3/api-docs (port 4003); the gateway
exposes it at /warehouse/v3/api-docs, and the backend's Swagger UI lists it as
the "Warehouse service" definition. The document's server URL follows the
gateway's X-Forwarded-* headers (SpringDocProxyConfig, as in the backend),
so "Try it out" calls https://awesome.byst.re through the gateway.
Authentication¶
warehouse-service validates the backend's access tokens itself:
- RS256 JWT signed by the backend (
JWT_SIGNING_KEY). warehouse-service holds no signing material: it resolves the verification key by the token'skidfromGET /internal/v1/jwks.json, caches it, and refetches the set when an unknownkidappears (at most once per 10 seconds). Tokens with another algorithm, nokidor an unknownkidare 401; a backend outage before the key is cached is 503. subis the username; theauthclaim carries the roles exactly as the backend writes them (ROLE_ADMIN,ROLE_CLIENT,ROLE_WAREHOUSE).- No user lookup: the token is the source of truth. 401 for missing, expired
or invalid tokens; 403 for wrong roles, with the backend's
ErrorDtobodies. - Role rules as in PR #85: warehouse endpoints for
ROLE_WAREHOUSEorROLE_ADMIN; admin returns, suppliers, purchase orders and reorder suggestions forROLE_ADMIN; customer return and tracking endpoints for any authenticated user, scoped to their own orders (admins may track any order).
Internal API (backend, called by warehouse-service)¶
Base path /internal/v1. Not routed by the gateway. Every request carries
X-Service-Token: ${WAREHOUSE_SERVICE_TOKEN}; the backend rejects missing or
wrong tokens with 401 and the endpoints are excluded from JWT auth, CORS,
traffic capture and the public OpenAPI document. When
WAREHOUSE_SERVICE_TOKEN is unset the internal API is disabled (404).
| Method and path | Purpose | Response |
|---|---|---|
GET /internal/v1/orders/{id} |
Order snapshot | InternalOrderDto or 404 |
GET /internal/v1/orders?status=PAID&fulfilment=NONE&page=&size= |
Fulfilment queue, oldest first (also fulfilment=AWAITING_PICK for released orders) |
PageDto<InternalOrderDto> |
GET /internal/v1/orders?ids=1,2 |
Order snapshots in any status, at most 100 | List<InternalOrderDto> |
PUT /internal/v1/orders/{id}/fulfilment |
Mirror the shipment state onto the order | InternalOrderDto; repeating the current state is a no-op; 409 when the transition is not allowed |
POST /internal/v1/orders/{id}/refunds |
Book the refund of a return | InternalOrderDto; idempotent per requestId; 409 unless DELIVERED or when refunds would exceed the total |
POST /internal/v1/orders/{id}/warehouse-cancel |
Cancel an order whose shipment the warehouse cancels | InternalOrderDto; 409 unless the order is PAID and fulfilmentState is AWAITING_PICK or PICKED |
GET /internal/v1/products?ids=1,2 (or no ids for all) |
Product snapshots | List<InternalProductDto> |
POST /internal/v1/inventory/receipts |
410 Gone in backend 3.22.0 and 3.23.0, removed in 3.24.0: receipts are local ledger writes in warehouse-service 1.6.0 | see INVENTORY_OWNERSHIP_CONTRACT.md |
POST /internal/v1/inventory/levels |
Stock-level push into the backend's projection (backend 3.22.0) | {applied, ignored} |
POST /internal/v1/notifications |
Email a customer; the backend renders the text | 202; a repeated requestId sends nothing |
GET /internal/v1/jwks.json |
Access-token verification keys | JSON Web Key Set |
GET /internal/v1/events?after=&limit=&types=order.cancelled |
Domain event feed (backend 3.16.0; also accepts the payment and, from 3.21.0, the notification token) | {events, nextCursor, hasMore}; see EVENT_FEED.md |
InternalOrderDto { id, username, status, fulfilmentState, subtotalAmount,
discountAmount, totalAmount, couponCode, refundedAmount,
shippingAddress {street, city, state, zipCode, country},
items [{productId, productName, category, quantity, unitPrice}],
createdAt, updatedAt }
PUT fulfilment body { state: AWAITING_PICK|PICKED|PACKED|SHIPPED|DELIVERED|CANCELLED }
InternalProductDto { id, name, category, price, stockQuantity }
receipts body { requestId: UUID, type: PURCHASE_RECEIVED|RETURN_RESTOCKED,
orderId?: Long, reference: String,
lines: [{productId, quantity}] }
refunds body { requestId: UUID, amount, reference }
notifications body { requestId: UUID, username,
template: ORDER_SHIPPED|ORDER_DELIVERED|RETURN_UPDATED,
properties: {string: string} }
ORDER_SHIPPED: orderId, carrier, trackingNumber
ORDER_DELIVERED: orderId
RETURN_UPDATED: returnId, orderId, status, refundAmount?, note?
Fulfilment state on the backend¶
The backend stores orders.fulfilment_state
(NONE, AWAITING_PICK, PICKED, PACKED, SHIPPED, DELIVERED, CANCELLED;
default NONE) instead of a shipments table. The PUT .../fulfilment rules:
NONE → AWAITING_PICKonly forPAIDorders (409 otherwise). RepeatingAWAITING_PICK(or any current state) is a no-op, so a retried release is safe.- Forward steps only:
AWAITING_PICK → PICKED → PACKED → SHIPPED → DELIVERED. SHIPPEDsets order statusSHIPPED;DELIVEREDsetsDELIVERED.CANCELLEDis set only throughwarehouse-cancelor customer cancellation.
The customer and admin cancellation rules from PR #85 now read this column:
cancellation is allowed while fulfilmentState is NONE or AWAITING_PICK
(then the state becomes CANCELLED), and 409 from PICKED on; the legacy
admin status endpoint returns 409 while the state is AWAITING_PICK through
SHIPPED.
Behaviour that crosses the boundary¶
| Action in warehouse-service | Backend calls, in order |
|---|---|
| Create shipment | GET order (must be PAID, fulfilmentState NONE, or AWAITING_PICK without a local shipment), save shipment, PUT fulfilment AWAITING_PICK; on 409 delete the local shipment; on 503 GET order again and keep the shipment if the order is AWAITING_PICK |
| Pick / pack | PUT fulfilment PICKED / PACKED after the local transition is validated |
| Ship / deliver | PUT fulfilment SHIPPED / DELIVERED, then an outbox notification (ORDER_SHIPPED / ORDER_DELIVERED) |
| Cancel shipment | POST warehouse-cancel (a 409 for an order that is already CANCELLED counts as done); then mark the shipment CANCELLED |
| Request return | GET order for ownership, status DELIVERED, items, totals |
| Receive return | Local stock-ledger write (RETURN_RESTOCKED, requestId = deterministic UUID from the return id) for resellable lines, from 1.6.0; the backend's projection follows through the stock-level push. Before 1.6.0: POST inventory/receipts |
| Refund return | POST orders/{id}/refunds (requestId = deterministic UUID from the return id), then mark the return REFUNDED |
| Approve / reject / refund | Outbox notification (RETURN_UPDATED) |
order.cancelled from the event feed (every 5 s) |
GET events?after={cursor}&types=order.cancelled; cancels the local AWAITING_PICK or PICKED shipment without calling the backend (the order is already cancelled there) |
| Reconcile (every 10 minutes from 1.3.0, a safety net behind the feed) | GET orders?ids= for AWAITING_PICK shipments, cancelling those whose order is CANCELLED; GET orders?status=PAID&fulfilment=AWAITING_PICK, adopting orders older than two minutes that have no shipment |
| Receive purchase order | Local stock-ledger write (PURCHASE_RECEIVED, the receipt's requestId) from 1.6.0, then the stock-level push. Before 1.6.0: POST inventory/receipts |
| Reorder suggestions | GET products (all) plus local open purchase-order lines |
| Queue | GET orders?status=PAID&fulfilment=NONE |
The order of local and remote writes is chosen so that a failed remote call
leaves no orphaned local state: validate locally, call the backend, then
persist. Notifications are the exception: they are written to a
notification_outbox table in the same transaction as the change, sent right
after the commit and retried with backoff while the backend answers 503; the
backend drops repeated requestIds, so a retry never sends a second email. The backend calls are idempotent where a retry could repeat them
(requestId, forward-only fulfilment transitions). Backend 4xx responses are
mapped to the same status and message for the caller; backend unavailability
becomes 503 {message: "Backend unavailable"}.
Backend changes (relative to PR #85)¶
- Remove shipments, returns, suppliers, purchase orders, their controllers, services, repositories, DTOs, tests and tables (rewrite V7, which is not released yet).
- Keep
ROLE_WAREHOUSE, thewarehousedemo user, inventory movement typesPURCHASE_RECEIVEDandRETURN_RESTOCKED,InventoryService.receive, the email templates and the notification listener (now fed by the internal notifications endpoint). - Add
orders.fulfilment_stateand the internal API above.
Frontend changes¶
- Paths are unchanged behind the gateway. For direct-to-backend development
add
VITE_WAREHOUSE_API_BASE_URL(defaults to the API base URL) and send warehouse paths there. - Add a second OpenAPI snapshot
openapi/warehouse-api-docs.jsonwith generated types, and pointsrc/types/commerce.tswarehouse aliases at it.
localstack changes¶
- New
warehouse-serviceservice in lightweight, full and server profiles,mem_limit: 160m, healthcheck on/actuator/health, envWAREHOUSE_SERVICE_TOKEN,BACKEND_BASE_URL, datasource settings for thewarehouserole, after the one-shotpostgres-rolesservice. - Backend gets
WAREHOUSE_SERVICE_TOKEN. - Gateway locations for the public paths above, placed before the generic
/api/v1/location, plus/warehouse/v3/api-docs. - The aitesters sandbox runs its own
aitesters-warehouse-service(same image, 160m) paired withaitesters-backend. It verifies the sandbox JWT key, uses its ownaitesters_warehouse_service_token, and stores data in thewarehouseschema ofaitesters-postgres(160m), the sandbox backend's database. The nightlyaitesters-resetunit recreates all three with a fresh database volume. The aitesters gateway block routes the same public paths to it and keeps/internal/at 404. - The consumer runs its Rust port (consumer-rs) in 64m, with the binary as its healthcheck probe.
Addendum: shipment tracking (warehouse-service 1.2.0)¶
warehouse-service 1.2.0 simulates a parcel carrier (Flyway V3 adds
shipments.simulated and tracking_events).
ShipShipmentDto.trackingNumberis optional. Omitted, the shipment uses the simulated carrier and gets a generated tracking number that matches the carrier's format (simulated = true); supplied, the manual flow is unchanged.- Tracking statuses:
LABEL_CREATED,IN_TRANSIT,OUT_FOR_DELIVERY,DELIVERY_FAILED,DELIVERED. - A scheduler (
warehouse.carrier.enabled, defaulttrue;warehouse.carrier.step-interval, defaultPT2M(PT30Sin thelocalanddemoprofiles), environmentWAREHOUSE_CARRIER_STEP_INTERVAL) moves every simulatedSHIPPEDshipment one step per interval. Deterministic failure: whenabs(trackingNumber.hashCode()) % 5 == 0the firstOUT_FOR_DELIVERYattempt becomesDELIVERY_FAILEDand the next step tries again.DELIVEREDreuses the existing deliver path (backend mirror plus theORDER_DELIVEREDemail). - New outbox templates
SHIPMENT_OUT_FOR_DELIVERYandSHIPMENT_DELIVERY_FAILED(propertiesorderId,carrier,trackingNumber); backend 3.15.0 adds them to its allowlist and renderer.
| Method and path | Access | Result |
|---|---|---|
GET /api/v1/orders/{id}/shipment/tracking |
owner or ROLE_ADMIN |
TrackingDto |
GET /api/v1/tracking/{trackingNumber} |
public, no token | TrackingDto without orderId; 404 for an unknown number |
POST /api/v1/warehouse/shipments/{id}/carrier/advance |
ROLE_WAREHOUSE or ROLE_ADMIN |
one step forward; 409 unless a simulated SHIPPED shipment |
TrackingDto { shipmentId, orderId, carrier, trackingNumber, simulated,
currentStatus, estimatedDelivery,
events [{status, location, description, occurredAt}] }
Gateway changes (every application gateway server block): the order regex
becomes ~ ^/api/v1/orders/\d+/(shipment|shipment/tracking|returns)$ and the
new prefix /api/v1/tracking/ goes to warehouse-service. Deployment verifies
that /api/v1/tracking/<unknown> answers 404 through the gateway (the backend
would answer 401 without a token). The default two-minute step interval is
used in every profile; trainers use the carrier/advance endpoint to skip
ahead.
Addendum: event feed (warehouse-service 1.3.0, backend 3.16.0)¶
The backend never calls warehouse-service. Customer and admin cancellations reach it through the backend's durable event feed (EVENT_FEED.md) within seconds instead of the next reconciler run. warehouse-service 1.3.0 requires backend 3.16.0: against an older backend the feed request answers 404, which is logged on every poll, and cancellations fall back to the reconciler.
Feed request and response¶
EventFeedPoller runs every warehouse.events.poll-interval (default PT5S)
and follows hasMore for up to ten pages per run:
GET /internal/v1/events?after={cursor}&limit=100&types=order.cancelled
X-Service-Token: <WAREHOUSE_SERVICE_TOKEN>
200 { events: [ { sequence, id, type, occurredAt, orderId, username, data } ],
nextCursor, hasMore }
Events are ordered by sequence, the event's feed position: positions follow
commit order, so a cursor never passes an event that commits later (see
EVENT_FEED.md). Events are kept for 30 days. After a page the
cursor moves to nextCursor, past events of other types.
order.cancelled handling¶
| Shipment state | Result |
|---|---|
AWAITING_PICK or PICKED |
CANCELLED, lastActor = "system", cancelledAt set; no backend call |
PACKED, SHIPPED |
Left alone and logged (the backend refuses those cancellations, so this means an inconsistency) |
DELIVERED, CANCELLED, or no shipment |
Ignored; a warehouse cancellation echoed by the feed is a no-op |
Each event is handled in its own transaction that locks the consumer's row in
event_cursors, skips event ids already in processed_events, applies the
change, records the event id and advances the cursor. Backend unavailable or a
4xx from the feed ends the run without moving the cursor. An event whose
handling fails (for example one without an orderId) is logged with its id and
recorded as processed, so it never blocks the feed.
Tables (Flyway V4, schema warehouse)¶
| Table | Columns |
|---|---|
event_cursors |
consumer (PK), last_sequence, updated_at |
processed_events |
event_id (PK, the feed event id), processed_at |
Configuration¶
| Environment variable | Property | Default |
|---|---|---|
WAREHOUSE_EVENTS_ENABLED |
warehouse.events.enabled |
true |
WAREHOUSE_EVENTS_POLL_INTERVAL |
warehouse.events.poll-interval |
PT5S |
WAREHOUSE_RECONCILE_ENABLED |
warehouse.reconcile.enabled |
true |
WAREHOUSE_RECONCILE_INTERVAL |
warehouse.reconcile.interval |
PT10M (was every minute before 1.3.0) |
The Compose files keep the defaults and set none of these variables.
Reconciler and reconcile-on-read¶
ShipmentReconciler stays as a safety net (feed outage longer than the 30-day
retention, a backend older than 3.16.0, a missed adoption) and now runs every
ten minutes. Reading a shipment (GET /api/v1/warehouse/shipments/{id}) or a
refused transition still reconciles it immediately, and the transition answers
409 "Order was cancelled by the customer". The read path changes state from a
GET; it is recorded as a removal candidate in
ARCHITECTURE_DECISIONS.md.