426 lines
12 KiB
Markdown
426 lines
12 KiB
Markdown
# 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 nodes
|
|
- `POST /api/discovery/refresh` - Mock refresh operation
|
|
- `POST /api/discovery/random-primary` - Selects random primary
|
|
- `POST /api/discovery/primary/{ip}` - Sets specific primary
|
|
|
|
**Cluster Endpoints**:
|
|
- `GET /api/cluster/members` - Returns mock cluster members
|
|
- `POST /api/cluster/refresh` - Mock cluster refresh
|
|
- `GET /api/cluster/node/versions` - Returns node versions
|
|
- `POST /api/rollout` - Simulates firmware rollout with progress
|
|
|
|
**Node Endpoints**:
|
|
- `GET /api/node/status` - Mock system status
|
|
- `GET /api/node/status/{ip}` - Specific node status
|
|
- `GET /api/node/endpoints` - Mock API capabilities
|
|
- `POST /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 health
|
|
- `GET /api/registry/firmware` - Mock firmware list
|
|
- `POST /api/registry/firmware` - Mock firmware upload
|
|
- `GET /api/registry/firmware/{name}/{version}` - Mock firmware download
|
|
- `PUT /api/registry/firmware/{name}/{version}` - Mock metadata update
|
|
- `DELETE /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 structure
|
|
- `ClusterStatus` - Cluster state
|
|
- `NodeStatus` - Node status enum
|
|
- `NodeUpdateCallback` - Callback function type
|
|
|
|
**From `pkg/client`**:
|
|
- `ClusterMember` - Cluster member info
|
|
- `ClusterStatusResponse` - Cluster status response
|
|
- `TaskStatusResponse` - Task status
|
|
- `SystemStatusResponse` - System status
|
|
- `CapabilitiesResponse` - API capabilities
|
|
- `EndpointInfo` - Endpoint information
|
|
- `ParameterInfo` - Parameter details
|
|
- `FirmwareUpdateResponse` - Firmware update result
|
|
|
|
**From `pkg/registry`**:
|
|
- `FirmwareRecord` - Firmware metadata
|
|
- `GroupedFirmware` - Grouped firmware list
|
|
- `FirmwareMetadata` - Firmware metadata for uploads
|
|
|
|
**From `pkg/config`**:
|
|
- `Config` - Configuration structure
|
|
|
|
This ensures complete API compatibility and type safety.
|
|
|
|
## Usage
|
|
|
|
### Quick Start
|
|
|
|
```bash
|
|
# 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
|
|
|
|
```bash
|
|
./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
|
|
|
|
```bash
|
|
# 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
|
|
|
|
```bash
|
|
# 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:
|
|
1. Label update (500ms)
|
|
2. Firmware upload (1s)
|
|
3. 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
|
|
```bash
|
|
# Run mock gateway for UI development
|
|
./mock-gateway -port 3001 -mock-nodes 5 -log-level info
|
|
```
|
|
|
|
### Load Testing
|
|
```bash
|
|
# Simulate large cluster
|
|
./mock-gateway -mock-nodes 50 -heartbeat-rate 1
|
|
```
|
|
|
|
### Integration Testing
|
|
```bash
|
|
# Headless mode for automated tests
|
|
./mock-gateway -log-level error -enable-ws=false
|
|
```
|
|
|
|
### Demonstrations
|
|
```bash
|
|
# 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 nodes
|
|
- `Start()` - Begins heartbeat simulation
|
|
- `GetNodes()` - Returns all nodes
|
|
- `SetPrimaryNode()` - Sets specific primary
|
|
- `SelectRandomPrimaryNode()` - Random selection
|
|
- `UpdateNodeVersion()` - 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 server
|
|
- `setupRoutes()` - Configures all endpoints
|
|
- `simulateRollout()` - 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 server
|
|
- `HandleWebSocket()` - Handles connections
|
|
- `BroadcastClusterUpdate()` - Cluster updates
|
|
- `BroadcastFirmwareUploadStatus()` - Upload status
|
|
- `BroadcastRolloutProgress()` - Rollout progress
|
|
|
|
### Mock Data Generators (`internal/mock/data.go`)
|
|
|
|
**Functions**:
|
|
- `GenerateMockClusterMembers()` - Cluster member data
|
|
- `GenerateMockTaskStatus()` - Task scheduler status
|
|
- `GenerateMockSystemStatus()` - System status
|
|
- `GenerateMockCapabilities()` - API endpoints
|
|
- `GenerateMockFirmwareList()` - Firmware registry
|
|
- `GenerateMockFirmwareBinary()` - Firmware binary
|
|
- `GenerateMockProxyResponse()` - Proxy call responses
|
|
- `GenerateMockMonitoringResources()` - 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
|
|
|
|
1. **No Hardware Required**: Runs without any SPORE nodes
|
|
2. **No Network Setup**: No UDP discovery configuration needed
|
|
3. **Fast Iteration**: Instant startup and teardown
|
|
4. **Predictable**: Consistent, reproducible behavior
|
|
5. **Scalable**: Easily simulate hundreds of nodes
|
|
6. **Safe**: No risk to actual hardware
|
|
7. **Portable**: Runs anywhere Go runs
|
|
8. **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:
|
|
|
|
1. **Types**: All types are shared, so changes propagate automatically
|
|
2. **Endpoints**: New endpoints should be added to both implementations
|
|
3. **Responses**: Mock responses should mirror real responses
|
|
4. **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:
|
|
|
|
1. Add corresponding mock implementation in `internal/mock/server.go`
|
|
2. Add mock data generators in `internal/mock/data.go` if needed
|
|
3. Ensure type reuse from shared packages
|
|
4. Update this documentation
|
|
5. Test both real and mock implementations
|
|
|
|
## License
|
|
|
|
Same as main SPORE Gateway project.
|