A lightweight, high-performance GraphQL server built with Rust, async-graphql, and Poem.
This project serves as a comprehensive, reliable local test target for developing GraphQL clients and API testers (such as Samvad), enabling full verification of:
- Queries & Introspection (Scalars, Objects, Enums, Unions, Interfaces, Computed fields, Arguments, and Pagination)
- Mutations & Validation (Stateful CRUD, InputObject validation with
validator, and partial error handling) - Real-Time Subscriptions (WebSockets via
graphql-transport-wsandgraphql-wsprotocols) - Header & Connection Parameter Authentication (
AuthGuardfor queries, mutations, and subscriptions) - Live Hardware Telemetry (Real-time CPU, RAM/Swap, and Network metrics via
sysinfo)
| Protocol | URL | Description |
|---|---|---|
| HTTP (GraphQL / Introspection) | http://localhost:8002/ |
GraphQL POST query/mutation execution and schema introspection. |
| HTTP (GraphiQL IDE) | http://localhost:8002/ |
Interactive web playground with pre-configured subscription support. |
| WebSocket (Subscriptions) | ws://localhost:8002/ws |
Full duplex WebSocket endpoint for real-time subscriptions (also upgrades on /). |
- Complete GraphQL Operation Types: Root
Query,Mutation, andSubscription. - WebSocket Streaming: Built on Poem's WebSocket adapter and
async-graphql-poemsupporting moderngraphql-transport-wsand legacygraphql-wssubprotocols. - Stateful In-Memory Store: Thread-safe CRUD operations (
items) with asynchronous event broadcasting (tokio::sync::broadcast). - Live System Telemetry: Continually updated CPU usage, memory/swap metrics, and network interface metrics powered by a background
tokioworker. - Multi-Level Authentication: Custom
AuthGuardinspecting HTTPAuthorization: Bearer <token>headers as well as WebSocketconnection_initpayload parameters. - Input Validation: Derives on inputs via
validatorensuring strict payload constraint checks. - Embedded GraphiQL IDE: Served directly at the root URL with pre-wired WebSocket subscription endpoint
/ws.
| Field | Arguments | Type | Auth Required | Description |
|---|---|---|---|---|
hello |
- | String! |
No | Returns "Hello, world!". |
goodbye |
- | String! |
No | Returns "Goodbye, world!". |
cpu_load / cpuLoad |
- | Float! |
Yes (Bearer my_secret_token) |
Current global CPU usage percentage (0.0 – 100.0). |
cpuInfo |
id: Int! |
CpuInfo |
Yes | Mock CPU hardware metadata lookup. |
memoryInfo |
- | MemoryInfo! |
No | Total, used, free RAM and Swap statistics with usage %. |
systemInfo |
- | SystemInfo! |
No | Host name, OS name, kernel, uptime, and CPU count. |
networkInterfaces |
- | [NetworkInterfaceInfo!]! |
No | All network interfaces with MAC address, IPs, and RX/TX bytes. |
topInterfaces |
limit: Int = 5, order: SortOrder = DESC |
[String!]! |
Yes | Network interfaces sorted by traffic. |
filteredMetrics |
filter: NetworkFilter! |
[String!]! |
Yes | Filter interfaces by name prefix and minimum received bytes. |
items |
limit: Int = 10, offset: Int = 0, status: ItemStatus |
PaginatedItems! |
No | Paginated item catalogue with status filter. |
item |
id: ID! |
Item |
No | Fetch a single item by unique ID. |
search |
query: String! |
[SearchResult!]! |
No | Union search returning Human or Item types. |
human |
id: String! |
Human |
No | Person record with computed height(unit: LengthUnit). |
queryUser |
userId: String! |
String! |
Yes | Authenticated user query test field. |
| Field | Arguments | Return Type | Auth Required | Description |
|---|---|---|---|---|
createItem |
input: CreateItemInput! |
Item! |
No | Create an item. Emits CREATED event to subscribers. |
updateItem |
input: UpdateItemInput! |
Item! |
No | Update an item by ID. Emits UPDATED event to subscribers. |
deleteItem |
id: ID! |
Boolean! |
No | Delete item by ID. Emits DELETED event to subscribers. |
clearItems |
- | Int! |
No | Delete all items and return total removed count. |
secureAction |
action: String! |
String! |
Yes (Bearer my_secret_token) |
Protected mutation for client auth header validation. |
| Field | Arguments | Stream Item | Auth Required | Description |
|---|---|---|---|---|
cpuUsageStream |
intervalSeconds: Int = 1 |
Float! |
No | Emits live CPU usage percentage periodically. |
itemEvent |
- | ItemMutationEvent! |
No | Real-time reactive stream of item mutations (CREATED, UPDATED, DELETED). |
counter |
step: Int = 1 |
Int! |
No | Emits an incrementing integer every second. |
secureCpuUsage |
- | Float! |
Yes | Authenticated stream requiring token in connection init payload. |
- Rust & Cargo (Rust 1.85+ / 2024 edition)
# Clone repository
git clone https://github.com/iamdhakrey/graphql-server.git
cd graphql-server
# Run test suite
cargo test
# Start the server
cargo runThe server binds to 0.0.0.0:8002.
curl -X POST http://localhost:8002/ \
-H "Content-Type: application/json" \
-d '{"query": "{ hello goodbye }"}'Response:
{
"data": {
"hello": "Hello, world!",
"goodbye": "Goodbye, world!"
}
}Requires Authorization: Bearer my_secret_token:
curl -X POST http://localhost:8002/ \
-H "Content-Type: application/json" \
-H "Authorization: Bearer my_secret_token" \
-d '{"query": "{ cpuLoad }"}'Response:
{
"data": {
"cpuLoad": 14.8
}
}Omitting or supplying an invalid token returns a GraphQL error:
curl -X POST http://localhost:8002/ \
-H "Content-Type: application/json" \
-d '{"query": "{ cpuLoad }"}'Response:
{
"data": null,
"errors": [
{
"message": "Unauthorized",
"locations": [{"line": 1, "column": 3}],
"path": ["cpuLoad"]
}
]
}curl -X POST http://localhost:8002/ \
-H "Content-Type: application/json" \
-d '{
"query": "{ memoryInfo { totalBytes usedBytes freeBytes usedPercentage } systemInfo { osName hostName uptimeSeconds cpuCount } }"
}'Response:
{
"data": {
"memoryInfo": {
"totalBytes": 16777216000,
"usedBytes": 8388608000,
"freeBytes": 8388608000,
"usedPercentage": 50.0
},
"systemInfo": {
"osName": "Linux",
"hostName": "workstation",
"uptimeSeconds": 86400,
"cpuCount": 12
}
}
}curl -X POST http://localhost:8002/ \
-H "Content-Type: application/json" \
-d '{
"query": "{ networkInterfaces { name macAddress rxBytes txBytes ipAddresses } }"
}'curl -X POST http://localhost:8002/ \
-H "Content-Type: application/json" \
-d '{
"query": "{ items(limit: 2, offset: 0, status: ACTIVE) { totalCount hasMore items { id name price status } } }"
}'Response:
{
"data": {
"items": {
"totalCount": 2,
"hasMore": false,
"items": [
{
"id": "1",
"name": "Mechanical Keyboard",
"price": 129.99,
"status": "ACTIVE"
},
{
"id": "2",
"name": "Wireless Mouse",
"price": 79.99,
"status": "ACTIVE"
}
]
}
}
}Tests client handling of polymorphic Union types and __typename:
curl -X POST http://localhost:8002/ \
-H "Content-Type: application/json" \
-d '{
"query": "{ search(query: \"keyboard\") { __typename ... on Item { id name price } ... on Human { id name } } }"
}'Response:
{
"data": {
"search": [
{
"__typename": "Item",
"id": "1",
"name": "Mechanical Keyboard",
"price": 129.99
}
]
}
}curl -X POST http://localhost:8002/ \
-H "Content-Type: application/json" \
-d '{
"query": "{ human(id: \"1000\") { name heightMeters: height(unit: METER) heightFeet: height(unit: FOOT) } }"
}'Response:
{
"data": {
"human": {
"name": "Luke Skywalker",
"heightMeters": 1.72,
"heightFeet": 5.6430448
}
}
}curl -X POST http://localhost:8002/ \
-H "Content-Type: application/json" \
-d '{
"query": "mutation { createItem(input: { name: \"4K Monitor\", description: \"Ultra HD IPS Display\", price: 349.99, status: ACTIVE }) { id name price status createdAt } }"
}'Response:
{
"data": {
"createItem": {
"id": "3",
"name": "4K Monitor",
"price": 349.99,
"status": "ACTIVE",
"createdAt": "1787816021.120Z"
}
}
}The schema uses validator (e.g. name must be between 2 and 50 chars, price >= 0.0). Submitting invalid data yields a structured validation error:
curl -X POST http://localhost:8002/ \
-H "Content-Type: application/json" \
-d '{
"query": "mutation { createItem(input: { name: \"x\", price: -10.0 }) { id } }"
}'Response:
{
"data": null,
"errors": [
{
"message": "Invalid input: name: Name must be between 2 and 50 characters, price: Price must be non-negative",
"locations": [{"line": 1, "column": 12}],
"path": ["createItem"]
}
]
}curl -X POST http://localhost:8002/ \
-H "Content-Type: application/json" \
-d '{
"query": "mutation { updateItem(input: { id: \"3\", price: 319.99, status: ACTIVE }) { id name price status } }"
}'curl -X POST http://localhost:8002/ \
-H "Content-Type: application/json" \
-d '{
"query": "mutation { deleteItem(id: \"3\") }"
}'Response:
{
"data": {
"deleteItem": true
}
}curl -X POST http://localhost:8002/ \
-H "Content-Type: application/json" \
-H "Authorization: Bearer my_secret_token" \
-d '{
"query": "mutation { secureAction(action: \"FLUSH_CACHE\") }"
}'Response:
{
"data": {
"secureAction": "Authenticated action executed successfully: FLUSH_CACHE"
}
}Subscriptions stream real-time events over WebSockets at ws://localhost:8002/ws (and ws://localhost:8002/).
- Open http://localhost:8002 in your browser.
- In the query editor, paste:
subscription { cpuUsageStream(intervalSeconds: 1) }
- Click the Execute Query (Play) button. You will see a live stream of CPU metrics arriving every second!
- URL: Set endpoint to
http://localhost:8002/(HTTP) orws://localhost:8002/ws(WebSocket). - Protocol: Select GraphQL WebSocket protocol (
graphql-transport-wsorgraphql-ws). - Connection Params (for guarded subscriptions):
{ "Authorization": "Bearer my_secret_token" } - Subscription Query:
subscription { itemEvent { mutationType id item { id name price status } } }
Verify real-time event broadcasting between client sessions:
Step 1: In GraphiQL or Samvad, start listening to itemEvent:
subscription {
itemEvent {
mutationType
id
item {
id
name
price
}
}
}Step 2: In a separate terminal or client tab, execute the createItem mutation:
curl -X POST http://localhost:8002/ \
-H "Content-Type: application/json" \
-d '{
"query": "mutation { createItem(input: { name: \"Studio Headphones\", price: 199.99, status: ACTIVE }) { id } }"
}'Step 3: Notice that your subscription client immediately receives:
{
"data": {
"itemEvent": {
"mutationType": "CREATED",
"id": "3",
"item": {
"id": "3",
"name": "Studio Headphones",
"price": 199.99
}
}
}
}If you have wscat installed:
# Connect with graphql-transport-ws protocol
wscat -c ws://localhost:8002/ws -s graphql-transport-ws
# 1. Send connection initialization:
> {"type":"connection_init","payload":{}}
< {"type":"connection_ack"}
# 2. Start counter subscription:
> {"id":"1","type":"subscribe","payload":{"query":"subscription { counter(step: 1) }"}}
< {"id":"1","type":"next","payload":{"data":{"counter":1}}}
< {"id":"1","type":"next","payload":{"data":{"counter":2}}}
< {"id":"1","type":"next","payload":{"data":{"counter":3}}}- Replace
async_graphql::EmptyMutationwith an activeMutationstruct. - Implement CRUD operations for test resources (
createItem,updateItem,deleteItem,clearItems). - Add stateful mock resources to
AppStateto verify mutation side-effects across queries. - Support mutation input objects (
CreateItemInput,UpdateItemInput) and custom validation errors.
- Replace
async_graphql::EmptySubscriptionwith real-time stream subscriptions. - Implement
cpuUsageStreamsubscription pushing live CPU metrics at configurable intervals. - Add WebSocket endpoint (
/wsand/) using Poem's WebSocket adapter (async_graphql_poem::GraphQLWebSocket). - Support authentication in subscriptions via WebSocket
connection_initpayload (secureCpuUsage).
- Network Metrics: Expose the
nets: Arc<RwLock<Networks>>state:- Network interface list (names, MAC addresses, IP addresses).
- Incoming/outgoing bytes transferred (
rx_bytes,tx_bytes,total_rx_bytes,total_tx_bytes).
- Memory & Swap Metrics: Query total, used, and free RAM/Swap with percentage calculation (
memoryInfo). - Background Refresh Task: Implement a background
tokio::spawnloop periodically invokingSystem::refresh_cpu_usage,System::refresh_memory, andNetworks::refresh.
- Add field arguments (e.g.,
cpuInfo(id: 1),items(limit, offset, status),counter(step)). - Add offset-based pagination model (
PaginatedItemswithitems,totalCount,hasMore). - Introduce GraphQL Enums (
ItemStatus,SortOrder,LengthUnit,MutationType), Computed Object fields (Human.height), and Union types (SearchResult).
graphql-server/
├── Cargo.toml # Crate dependencies (async-graphql, poem, tokio, sysinfo)
├── Cargo.lock # Dependency lockfile
├── LICENSE # MIT License
├── README.md # Comprehensive documentation and test suite
└── src/
├── main.rs # App initialization, background telemetry loop, server listener
├── state.rs # Shared thread-safe state (items, item_events broadcast, sys, nets)
├── auth.rs # AuthGuard implementation inspecting AuthToken
├── server/
│ ├── mod.rs # Server module definition
│ └── handlers.rs # HTTP graphql, WebSocket subscription, and GraphiQL handlers
└── graphql/
├── mod.rs # Schema builder (Schema::build) and unit/integration test suite
├── types.rs # Object, InputObject, Enum, and Union definitions
├── query.rs # Root Query resolvers (telemetry, items, search, user, misc)
├── mutation.rs # Root Mutation resolvers (CRUD, validation, event broadcast)
└── subscription.rs # Root Subscription resolvers (cpuUsageStream, itemEvent, counter)
This project is licensed under the MIT License - see the LICENSE file for details.