12 KiB
Mock Gateway Implementation
This document describes the mock gateway implementation for the SPORE Gateway project.
Overview
The mock gateway is a fully-featured simulation of the real SPORE Gateway that implements all functionality (WebSocket, REST API) without requiring actual SPORE nodes. It reuses all types defined for the real gateway, ensuring complete API compatibility.
Project Structure
spore-gateway/
├── cmd/
│ └── mock-gateway/
│ ├── main.go # Mock gateway entry point
│ └── README.md # Detailed usage documentation
├── internal/
│ ├── mock/
│ │ ├── discovery.go # Mock node discovery implementation
│ │ ├── server.go # Mock HTTP server with all endpoints
│ │ ├── websocket.go # Mock WebSocket server
│ │ └── data.go # Mock data generators
│ ├── discovery/ # (Reused types)
│ └── websocket/ # (Reused for upgrader)
├── pkg/
│ ├── client/ # (Reused types)
│ ├── config/ # (Reused types)
│ └── registry/ # (Reused types)
└── scripts/
└── run-mock-gateway.sh # Convenient runner script
Key Features
1. Complete REST API Implementation
All endpoints from the real gateway are implemented with realistic mock data:
Discovery Endpoints:
GET /api/discovery/nodes- Returns all mock nodesPOST /api/discovery/refresh- Mock refresh operationPOST /api/discovery/random-primary- Selects random primaryPOST /api/discovery/primary/{ip}- Sets specific primary
Cluster Endpoints:
GET /api/cluster/members- Returns mock cluster membersPOST /api/cluster/refresh- Mock cluster refreshGET /api/cluster/node/versions- Returns node versionsPOST /api/rollout- Simulates firmware rollout with progress
Node Endpoints:
GET /api/node/status- Mock system statusGET /api/node/status/{ip}- Specific node statusGET /api/node/endpoints- Mock API capabilitiesPOST /api/node/update- Simulated firmware upload
Task Endpoints:
GET /api/tasks/status- Mock task scheduler status
Monitoring Endpoints:
GET /api/monitoring/resources- Real-time resource monitoring for all nodes
Proxy Endpoints:
POST /api/proxy-call- Mock proxied calls
Registry Endpoints:
GET /api/registry/health- Mock registry healthGET /api/registry/firmware- Mock firmware listPOST /api/registry/firmware- Mock firmware uploadGET /api/registry/firmware/{name}/{version}- Mock firmware downloadPUT /api/registry/firmware/{name}/{version}- Mock metadata updateDELETE /api/registry/firmware/{name}/{version}- Mock deletion
WebSocket:
GET /ws- WebSocket endpoint for real-time updates
Health:
GET /api/health- Gateway health check
2. WebSocket Implementation
The mock gateway implements full WebSocket functionality with real-time broadcasts:
Broadcast Types:
- Cluster Updates: Periodic and event-driven cluster state updates
- Node Discovery: Node join/leave/update events
- Firmware Upload Status: Upload progress notifications
- Rollout Progress: Step-by-step rollout progress with percentage
Message Format: Identical to real gateway for compatibility
3. Mock Node Discovery
Simulates node discovery without UDP:
- Configurable number of nodes (default: 5)
- Realistic node data (IP, hostname, labels, metrics)
- Automatic heartbeat simulation
- Primary node selection
- Node status management (active/inactive)
Generated Nodes:
- IPs:
192.168.1.100,192.168.1.101, etc. - Hostnames:
spore-node-1,spore-node-2, etc. - Labels: version (matches firmware registry), stable, env, zone, type
- Resources: freeHeap, cpuFreqMHz, flashChipSize
- Latency: Random realistic values
- Firmware Distribution: 40% on v1.0.0, 40% on v1.1.0, 20% on v1.2.0 (beta)
4. Type Reuse
The mock gateway reuses all types from the real gateway:
From internal/discovery:
NodeInfo- Node information structureClusterStatus- Cluster stateNodeStatus- Node status enumNodeUpdateCallback- Callback function type
From pkg/client:
ClusterMember- Cluster member infoClusterStatusResponse- Cluster status responseTaskStatusResponse- Task statusSystemStatusResponse- System statusCapabilitiesResponse- API capabilitiesEndpointInfo- Endpoint informationParameterInfo- Parameter detailsFirmwareUpdateResponse- Firmware update result
From pkg/registry:
FirmwareRecord- Firmware metadataGroupedFirmware- Grouped firmware listFirmwareMetadata- Firmware metadata for uploads
From pkg/config:
Config- Configuration structure
This ensures complete API compatibility and type safety.
Usage
Quick Start
# Build and run
go build -o mock-gateway cmd/mock-gateway/main.go
./mock-gateway
# Or use the convenience script
./scripts/run-mock-gateway.sh
Configuration Options
./mock-gateway [options]
-port string
HTTP server port (default "3001")
-mock-nodes int
Number of mock nodes to simulate (default 5)
-heartbeat-rate int
Heartbeat interval in seconds (default 5)
-log-level string
Log level: debug, info, warn, error (default "info")
-enable-ws bool
Enable WebSocket broadcasts (default true)
-config string
Path to configuration file
Example Usage
# Development with debug logging
./mock-gateway -log-level debug -mock-nodes 3
# Production-like setup
./mock-gateway -port 3001 -mock-nodes 10 -heartbeat-rate 5
# Testing without WebSocket
./mock-gateway -enable-ws=false
# Large cluster simulation
./mock-gateway -mock-nodes 20 -heartbeat-rate 2
Using the Convenience Script
# Basic usage
./scripts/run-mock-gateway.sh
# With options
./scripts/run-mock-gateway.sh -p 8080 -n 10 -l debug
# Show help
./scripts/run-mock-gateway.sh --help
Mock Data
Pre-configured Firmware
spore-firmware:
- v1.0.0 - Stable, production (40% of nodes)
- v1.1.0 - Stable, production (40% of nodes)
- v1.2.0 - Beta (20% of nodes)
sensor-firmware:
- v2.0.0 - Stable, sensor type
- v2.1.0 - Stable, sensor type
Node labels automatically match the firmware versions in the registry, ensuring consistency between running firmware and available versions.
Simulated Behaviors
Firmware Uploads:
- 2-second simulated processing time
- 90% success rate
- WebSocket status broadcasts
- In-memory storage
Rollouts:
- Step-by-step simulation:
- Label update (500ms)
- Firmware upload (1s)
- Completion (500ms)
- WebSocket progress broadcasts
- Node version updates
Node Updates:
- Periodic heartbeat simulation
- Random metric updates (latency, heap)
- Automatic status management
Cluster Changes:
- Automatic primary selection
- Node discovery events
- WebSocket broadcasts
API Compatibility
The mock gateway is fully compatible with:
- Frontend applications expecting the real gateway API
- Client libraries using the gateway
- Testing frameworks
- CI/CD pipelines
All responses match the real gateway's format and structure.
Testing Use Cases
Frontend Development
# Run mock gateway for UI development
./mock-gateway -port 3001 -mock-nodes 5 -log-level info
Load Testing
# Simulate large cluster
./mock-gateway -mock-nodes 50 -heartbeat-rate 1
Integration Testing
# Headless mode for automated tests
./mock-gateway -log-level error -enable-ws=false
Demonstrations
# Clean output for demos
./mock-gateway -log-level warn -mock-nodes 8
Implementation Details
Mock Discovery (internal/mock/discovery.go)
Features:
- In-memory node storage
- Configurable node count
- Automatic heartbeat simulation
- Primary node management
- Callback system for updates
- Thread-safe operations
Key Functions:
NewMockNodeDiscovery()- Creates discovery with N nodesStart()- Begins heartbeat simulationGetNodes()- Returns all nodesSetPrimaryNode()- Sets specific primarySelectRandomPrimaryNode()- Random selectionUpdateNodeVersion()- Updates node version (for rollouts)
Mock Server (internal/mock/server.go)
Features:
- All REST endpoints implemented
- CORS middleware
- JSON middleware
- Logging middleware
- In-memory firmware storage
- Rollout simulation
Key Functions:
NewMockHTTPServer()- Creates serversetupRoutes()- Configures all endpointssimulateRollout()- Simulates rollout process- All endpoint handlers matching real gateway
Mock WebSocket (internal/mock/websocket.go)
Features:
- WebSocket connection management
- Periodic broadcasts
- Event-driven broadcasts
- Client heartbeat (ping/pong)
- Graceful shutdown
Key Functions:
NewMockWebSocketServer()- Creates WS serverHandleWebSocket()- Handles connectionsBroadcastClusterUpdate()- Cluster updatesBroadcastFirmwareUploadStatus()- Upload statusBroadcastRolloutProgress()- Rollout progress
Mock Data Generators (internal/mock/data.go)
Functions:
GenerateMockClusterMembers()- Cluster member dataGenerateMockTaskStatus()- Task scheduler statusGenerateMockSystemStatus()- System statusGenerateMockCapabilities()- API endpointsGenerateMockFirmwareList()- Firmware registryGenerateMockFirmwareBinary()- Firmware binaryGenerateMockProxyResponse()- Proxy call responsesGenerateMockMonitoringResources()- Comprehensive resource monitoring data
Monitoring Data Includes:
- CPU Metrics: Frequency, usage percentage, temperature
- Memory Metrics: Total, free, used bytes, usage percentage
- Network Metrics: Bytes sent/received, packets sent/received, RSSI, signal quality
- Flash Metrics: Total, used, free bytes, usage percentage
- Summary Statistics: Aggregate averages across all nodes
Comparison: Real vs Mock Gateway
| Feature | Real Gateway | Mock Gateway |
|---|---|---|
| REST API | ✅ All endpoints | ✅ All endpoints |
| WebSocket | ✅ Real-time | ✅ Real-time |
| Type Safety | ✅ Shared types | ✅ Shared types |
| UDP Discovery | ✅ Real UDP | ❌ Simulated |
| SPORE Node Calls | ✅ Real HTTP | ❌ Mocked |
| Registry Service | ✅ External | ❌ In-memory |
| Firmware Storage | ✅ Disk/Registry | ❌ Memory |
| Node Count | Dynamic (real) | Configurable |
| Setup Required | Hardware + Network | None |
| Dependencies | SPORE nodes + Registry | None |
Advantages of Mock Gateway
- No Hardware Required: Runs without any SPORE nodes
- No Network Setup: No UDP discovery configuration needed
- Fast Iteration: Instant startup and teardown
- Predictable: Consistent, reproducible behavior
- Scalable: Easily simulate hundreds of nodes
- Safe: No risk to actual hardware
- Portable: Runs anywhere Go runs
- Complete: All features implemented
When to Use Which
Use Real Gateway:
- Production deployment
- Real hardware testing
- Actual firmware updates
- Network topology testing
- Performance benchmarking
Use Mock Gateway:
- Frontend development
- API client development
- Automated testing
- Demonstrations
- CI/CD pipelines
- Local development
- Load testing
Maintenance
The mock gateway is designed to stay in sync with the real gateway:
- Types: All types are shared, so changes propagate automatically
- Endpoints: New endpoints should be added to both implementations
- Responses: Mock responses should mirror real responses
- Behaviors: Simulate realistic timing and error rates
Future Enhancements
Potential improvements:
- Configuration file support (currently CLI only)
- Persistent storage option
- Configurable error injection
- Network latency simulation
- Node failure scenarios
- Custom firmware metadata
- API recording/playback
- Performance metrics
Contributing
When adding new endpoints to the real gateway:
- Add corresponding mock implementation in
internal/mock/server.go - Add mock data generators in
internal/mock/data.goif needed - Ensure type reuse from shared packages
- Update this documentation
- Test both real and mock implementations
License
Same as main SPORE Gateway project.