StateSet API is a comprehensive, scalable, and robust backend system for order management, inventory control, returns processing, warranty management, shipment tracking, and work order handling. Built with Rust, it leverages modern web technologies and best practices to provide a high-performance, reliable solution for e-commerce and manufacturing businesses.
-
Order Management:
- Create, retrieve, update, and delete orders
- Support for complex order workflows (hold, cancel, archive, merge)
- Order item management and tracking
- Fulfillment order creation and status updates
-
Inventory Control:
- Real-time inventory tracking across multiple locations
- Allocation, reservation, and release workflows
- Lot tracking and cycle counting
- Safety stock and reorder alerts
-
Returns Processing:
- Streamlined return authorization and processing
- Approval, rejection, and restocking workflows
- Refund integration
-
Warranty Management:
- Track and manage product warranties
- Warranty claim processing with approval/rejection flows
-
Shipment Tracking:
- Carrier assignment and tracking integration
- Advanced shipping notice (ASN) creation and management
- Delivery confirmation workflows
-
Manufacturing & Production:
- Bill of materials (BOM) creation and management
- Work order scheduling and tracking
- Component and raw material management
-
Financial Operations:
- Cash sale creation and tracking
- Invoice generation with persistent storage
- Payment processing with stored records
- Item receipt recording for purchase orders
Our carefully selected tech stack ensures high performance, scalability, and maintainability:
- Language: Rust (for performance, safety, and concurrency)
- Web Framework: Axum (async web framework from the Tokio team)
- Database: PostgreSQL with SeaORM (async ORM)
- Async Runtime: Tokio (efficient async runtime for Rust)
- REST API: Primary interface for client applications
- gRPC: Interface for service-to-service communication with Protocol Buffers
- Tracing: OpenTelemetry integration for distributed request tracing
- Health Checks: Comprehensive service health monitoring
- Error Handling: Structured error system with detailed context
The API exposes metrics at /metrics
(text) and /metrics/json
(JSON).
-
Route-level metrics (via
metrics
crate):http_requests_total{method,route,status}
: Request counts per route.http_request_duration_ms{method,route,status}
: Request latency histogram (ms).rate_limit_denied_total{key_type,path}
/rate_limit_allowed_total{key_type,path}
.auth_failures_total{code,status}
.
-
Aggregated metrics (custom registry also visible at
/metrics
):- Counters:
http_requests_total
,errors_total
,cache_hits_total
,cache_misses_total
. - Histograms:
http_request_duration_seconds_count/sum
. - Business:
orders_created_total
,returns_processed_total
, etc.
- Counters:
Standard response headers:
X-Request-Id
: Unique id for tracing.- Rate limit:
X-RateLimit-Limit
,X-RateLimit-Remaining
,X-RateLimit-Reset
(and RFCRateLimit-*
).
stateset-api/
├── migrations/ # Database migrations
├── proto/ # Protocol Buffer definitions
├── src/
│ ├── bin/ # Binary executables
│ ├── commands/ # Command handlers (write operations)
│ ├── entities/ # Database entity definitions
│ ├── errors/ # Error types and handling
│ ├── events/ # Event definitions and processing
│ ├── handlers/ # HTTP request handlers
│ ├── models/ # Domain models
│ ├── queries/ # Query handlers (read operations)
│ ├── repositories/ # Data access layer
│ ├── services/ # Business logic services
│ └── config.rs # Application configuration
└── tests/ # Integration tests
Ensure you have the following installed:
- Rust (latest stable)
- Protocol Buffer compiler (for gRPC)
Note: The app defaults to SQLite for local development (via SeaORM). PostgreSQL is optional and can be enabled by changing configuration.
-
Clone the repository:
git clone https://github.com/stateset/stateset-api.git cd stateset-api
-
Configure the app (choose one):
- Using config files (recommended): edit
config/default.toml
(already set to SQLite by default). - Using env overrides: set environment variables with the
APP__
prefix (e.g.,APP__DATABASE_URL
,APP__HOST
,APP__PORT
).
Examples:
- SQLite (default):
APP__DATABASE_URL=sqlite://stateset.db?mode=rwc
- PostgreSQL:
APP__DATABASE_URL=postgres://user:pass@localhost:5432/stateset
- Using config files (recommended): edit
-
Run database migrations:
cargo run --bin migration
-
Build and run the project:
cargo run
The API will be available at http://localhost:8080
.
Requests to unknown routes return a JSON 404 response.
Docker: docker-compose up -d
starts the API and Redis. Compose reads values from .env
for container env, which is separate from the app’s APP__*
variables used by the config system.
StateSet API provides a rich set of RESTful endpoints:
POST /auth/login
- Authenticate user and get JWT tokenPOST /auth/register
- Register a new user
- Use
POST /api/v1/auth/login
with{ email, password }
to obtain a JWTaccess_token
andrefresh_token
. - Send
Authorization: Bearer <access_token>
on protected routes. API keys are also supported viaX-API-Key
. - Endpoints are permission-gated (e.g.,
orders:read
,orders:create
). Admins have full access. - Standard error responses include JSON with
error.code
and HTTP status;X-Request-Id
is included on responses for tracing.
GET /orders
- List all ordersGET /orders/:id
- Get order detailsPOST /orders
- Create a new orderPUT /orders/:id
- Update an orderPOST /orders/:id/hold
- Place an order on holdPOST /orders/:id/cancel
- Cancel an orderPOST /orders/:id/archive
- Archive an order
GET /inventory
- Get current inventory levelsPOST /inventory/adjust
- Adjust inventory quantityPOST /inventory/allocate
- Allocate inventoryPOST /inventory/reserve
- Reserve inventoryPOST /inventory/release
- Release reserved inventory
POST /returns
- Create a return requestGET /returns/:id
- Get return detailsPOST /returns/:id/approve
- Approve a returnPOST /returns/:id/reject
- Reject a returnPOST /returns/:id/restock
- Restock returned items
POST /warranties
- Create a warrantyPOST /warranties/claim
- Submit a warranty claimPOST /warranties/claims/:id/approve
- Approve a warranty claimPOST /warranties/claims/:id/reject
- Reject a warranty claim
POST /work-orders
- Create a work orderGET /work-orders/:id
- Get work order detailsPOST /work-orders/:id/start
- Start a work orderPOST /work-orders/:id/complete
- Complete a work order
GET /health
- Basic health checkGET /health/readiness
- Database readiness checkGET /health/version
- Build and version information
Run the test suite with:
# Run all tests
cargo test
# Run integration tests
cargo test --features integration
# Run a specific test with backtrace
RUST_BACKTRACE=1 cargo test test_name
- Linting:
cargo clippy
- Formatting:
cargo fmt
- Documentation:
cargo doc --open
StateSet API uses a structured error system with detailed context. API errors are returned as:
{
"error": {
"code": "ORDER_NOT_FOUND",
"message": "The requested order could not be found",
"status": 404,
"details": { "order_id": "123" }
}
}
- The API is designed for high throughput and low latency
- Connection pooling is used for database operations
- Async/await patterns are used throughout for non-blocking I/O
- Entity caching is implemented for frequently accessed data
- Idempotency: Mutating endpoints (POST/PUT/PATCH/DELETE) support
Idempotency-Key
headers. When provided, the API ensures each unique key is processed once per route+method and caches the response for 10 minutes (Redis-backed). - Rate Limiting: A global rate limiter is enforced with optional per-path, per‑API key, and per‑user policies. Standard headers (
X-RateLimit-*
,RateLimit-*
) are included when enabled.
Environment variables:
APP__RATE_LIMIT_REQUESTS_PER_WINDOW
/APP__RATE_LIMIT_WINDOW_SECONDS
APP__RATE_LIMIT_ENABLE_HEADERS=true|false
APP__RATE_LIMIT_PATH_POLICIES="/api/v1/orders:60:60,/api/v1/inventory:120:60"
APP__RATE_LIMIT_API_KEY_POLICIES="sk_live_abc:200:60"
APP__RATE_LIMIT_USER_POLICIES="user-123:500:60"
We welcome contributions! Please see CONTRIBUTING.md for guidelines.
This project is licensed under the MIT License - see the LICENSE.md file for details.