Skip to content

About

A lightweight, high-performance GraphQL test server built with Rust, async-graphql, and Poem - designed for API client testing with Samvad.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

10 Commits

Folders and files

Repository files navigation

GraphQL Server

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-ws and graphql-ws protocols)
  • Header & Connection Parameter Authentication (AuthGuard for queries, mutations, and subscriptions)
  • Live Hardware Telemetry (Real-time CPU, RAM/Swap, and Network metrics via sysinfo)

Server Endpoints

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 /).

Features Implemented

  • Complete GraphQL Operation Types: Root Query, Mutation, and Subscription.
  • WebSocket Streaming: Built on Poem's WebSocket adapter and async-graphql-poem supporting modern graphql-transport-ws and legacy graphql-ws subprotocols.
  • 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 tokio worker.
  • Multi-Level Authentication: Custom AuthGuard inspecting HTTP Authorization: Bearer <token> headers as well as WebSocket connection_init payload parameters.
  • Input Validation: Derives on inputs via validator ensuring strict payload constraint checks.
  • Embedded GraphiQL IDE: Served directly at the root URL with pre-wired WebSocket subscription endpoint /ws.

Schema Overview

1. Queries

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.

2. Mutations

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.

3. Subscriptions

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.

Quick Start

Prerequisites

Clone, Build, and Run

# Clone repository
git clone https://github.com/iamdhakrey/graphql-server.git
cd graphql-server

# Run test suite
cargo test

# Start the server
cargo run

The server binds to 0.0.0.0:8002.


Ready-to-Use Test Suite (Samvad, GraphiQL, & curl)

A. Testing Queries

1. Basic Public Query

curl -X POST http://localhost:8002/ \
  -H "Content-Type: application/json" \
  -d '{"query": "{ hello goodbye }"}'

Response:

{
  "data": {
    "hello": "Hello, world!",
    "goodbye": "Goodbye, world!"
  }
}

2. Authenticated Query (cpu_load / cpuLoad)

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
  }
}

3. Unauthorized Query Attempt

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"]
    }
  ]
}

4. Hardware Telemetry: Memory & System Info

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
    }
  }
}

5. Hardware Telemetry: Network Interfaces

curl -X POST http://localhost:8002/ \
  -H "Content-Type: application/json" \
  -d '{
    "query": "{ networkInterfaces { name macAddress rxBytes txBytes ipAddresses } }"
  }'

6. Paginated Items Query

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"
        }
      ]
    }
  }
}

7. GraphQL Union Query (Search)

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
      }
    ]
  }
}

8. Computed Field with Arguments (Human.height)

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
    }
  }
}

B. Testing Mutations

1. Create an Item

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"
    }
  }
}

2. Input Validation Failure Test

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"]
    }
  ]
}

3. Update an Item

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 } }"
  }'

4. Delete an Item

curl -X POST http://localhost:8002/ \
  -H "Content-Type: application/json" \
  -d '{
    "query": "mutation { deleteItem(id: \"3\") }"
  }'

Response:

{
  "data": {
    "deleteItem": true
  }
}

5. Authenticated Mutation (secureAction)

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"
  }
}

C. Testing Subscriptions (WebSockets)

Subscriptions stream real-time events over WebSockets at ws://localhost:8002/ws (and ws://localhost:8002/).

1. Testing in GraphiQL IDE (Easiest)

  1. Open http://localhost:8002 in your browser.
  2. In the query editor, paste:
    subscription {
      cpuUsageStream(intervalSeconds: 1)
    }
  3. Click the Execute Query (Play) button. You will see a live stream of CPU metrics arriving every second!

2. Testing in Samvad API Client

  1. URL: Set endpoint to http://localhost:8002/ (HTTP) or ws://localhost:8002/ws (WebSocket).
  2. Protocol: Select GraphQL WebSocket protocol (graphql-transport-ws or graphql-ws).
  3. Connection Params (for guarded subscriptions):
    {
      "Authorization": "Bearer my_secret_token"
    }
  4. Subscription Query:
    subscription {
      itemEvent {
        mutationType
        id
        item {
          id
          name
          price
          status
        }
      }
    }

3. Reactive End-to-End Test: Live Mutation Event Streaming

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
      }
    }
  }
}

4. Testing with CLI tools (wscat)

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}}}

Roadmap of Features

Phase 1: GraphQL Mutations Support

  • Replace async_graphql::EmptyMutation with an active Mutation struct.
  • Implement CRUD operations for test resources (createItem, updateItem, deleteItem, clearItems).
  • Add stateful mock resources to AppState to verify mutation side-effects across queries.
  • Support mutation input objects (CreateItemInput, UpdateItemInput) and custom validation errors.

Phase 2: Real-time GraphQL Subscriptions (WebSockets)

  • Replace async_graphql::EmptySubscription with real-time stream subscriptions.
  • Implement cpuUsageStream subscription pushing live CPU metrics at configurable intervals.
  • Add WebSocket endpoint (/ws and /) using Poem's WebSocket adapter (async_graphql_poem::GraphQLWebSocket).
  • Support authentication in subscriptions via WebSocket connection_init payload (secureCpuUsage).

Phase 3: Comprehensive System Telemetry (sysinfo)

  • 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::spawn loop periodically invoking System::refresh_cpu_usage, System::refresh_memory, and Networks::refresh.

Phase 4: Parameterized Queries, Pagination & Advanced Types

  • Add field arguments (e.g., cpuInfo(id: 1), items(limit, offset, status), counter(step)).
  • Add offset-based pagination model (PaginatedItems with items, totalCount, hasMore).
  • Introduce GraphQL Enums (ItemStatus, SortOrder, LengthUnit, MutationType), Computed Object fields (Human.height), and Union types (SearchResult).

Project Structure

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)

License

This project is licensed under the MIT License - see the LICENSE file for details.

About

A lightweight, high-performance GraphQL test server built with Rust, async-graphql, and Poem - designed for API client testing with Samvad.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages