feat: initial open-source release of Pipely
OTA update server designed for high-concurrency, low-bandwidth deployments. GORM-backed PostgreSQL, JWT auth, device management, artefact versioning, deployment rollout with gated rate-limited downloads, and a React admin panel.
This commit is contained in:
@@ -0,0 +1,65 @@
|
||||
# ─────────────────────────────────────────────────────────
|
||||
# OTA Manifest Server — Environment Variables
|
||||
# ─────────────────────────────────────────────────────────
|
||||
# Copy this file to .env and adjust values for your environment:
|
||||
# cp .env.example .env
|
||||
# ─────────────────────────────────────────────────────────
|
||||
|
||||
# ── Server ──────────────────────────────────────────────
|
||||
|
||||
# HTTP listen port.
|
||||
# Default: 8080
|
||||
SERVER_PORT=8080
|
||||
|
||||
# ── Security ────────────────────────────────────────────
|
||||
|
||||
# Secret key for signing JWT tokens. Use a long random string in production.
|
||||
# Generate: openssl rand -hex 32
|
||||
# Example: JWT_SECRET=a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6
|
||||
JWT_SECRET=change-me-in-production
|
||||
|
||||
# JWT token validity period in hours.
|
||||
# Default: 24 (tokens expire after 1 day)
|
||||
JWT_EXPIRY_HRS=24
|
||||
|
||||
# ── Database ────────────────────────────────────────────
|
||||
|
||||
# PostgreSQL connection string (URL format).
|
||||
# Format: postgres://<user>:<password>@<host>:<port>/<database>?sslmode=disable
|
||||
# Default: postgres://postgres:postgres@localhost:5432/manifest?sslmode=disable
|
||||
# Example: DATABASE_URL=postgres://ota_user:secret@10.0.1.5:5432/manifest?sslmode=disable
|
||||
DATABASE_URL=postgres://postgres:postgres@localhost:5432/manifest?sslmode=disable
|
||||
|
||||
# ── Storage ─────────────────────────────────────────────
|
||||
|
||||
# Directory where uploaded JAR/artefact files are stored.
|
||||
# Must be writable by the server process.
|
||||
# Default: /var/ota/artefacts
|
||||
# Linux: ARTEFACT_DIR=/var/ota/artefacts
|
||||
# Windows: ARTEFACT_DIR=D:\ota\artefacts
|
||||
# macOS: ARTEFACT_DIR=/usr/local/var/ota/artefacts
|
||||
ARTEFACT_DIR=/var/ota/artefacts
|
||||
|
||||
# ── Download & Bandwidth Control ────────────────────────
|
||||
|
||||
# Maximum number of simultaneous download streams.
|
||||
# Under 10 Mbps total bandwidth, each stream is throttled to
|
||||
# ~BANDWIDTH_BPS / MAX_CONCURRENT_DOWNLOADS bytes/s.
|
||||
# Default: 50
|
||||
# Example: MAX_CONCURRENT_DOWNLOADS=30 (more conservative)
|
||||
MAX_CONCURRENT_DOWNLOADS=50
|
||||
|
||||
# Per-connection bandwidth limit in bytes per second.
|
||||
# The default (209715 ≈ 205 KB/s) keeps 50 concurrent streams
|
||||
# at roughly 10 Mbps total (50 × 205 KB/s ≈ 10 MB/s).
|
||||
# Default: 209715
|
||||
# Example: BANDWIDTH_BPS=102400 (~100 KB/s per stream, ~5 Mbps total)
|
||||
BANDWIDTH_BPS=209715
|
||||
|
||||
# ── Rate Limiting ───────────────────────────────────────
|
||||
|
||||
# Maximum API requests per second per client IP (token bucket).
|
||||
# Burst capacity is 2× this value.
|
||||
# Default: 100
|
||||
# Example: RATE_LIMIT_RPS=50 (stricter, for constrained environments)
|
||||
RATE_LIMIT_RPS=100
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
# Binary
|
||||
bin/
|
||||
*.exe
|
||||
*.dll
|
||||
*.so
|
||||
*.dylib
|
||||
|
||||
# Environment
|
||||
.env
|
||||
|
||||
# IDE
|
||||
.idea/
|
||||
|
||||
# Web
|
||||
web/node_modules/
|
||||
web/dist/
|
||||
|
||||
# OS
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
# Artifacts (local test data)
|
||||
/var/
|
||||
@@ -0,0 +1,53 @@
|
||||
# CLAUDE.md - Project Guidelines for OTA Micro-Server
|
||||
|
||||
## Project Overview
|
||||
This project is a high-concurrency, low-bandwidth OTA (Over-the-Air) management and distribution server built in Go. It is specifically designed to distribute updates to thousands of devices under a highly constrained network pipelining landscape (**10 Mbps bandwidth ceiling**). It manages binary/Jar delta file generation, gating rollouts, and concurrent rate-limiting.
|
||||
|
||||
## Technology Stack
|
||||
- **Backend Language:** Go (Golang)
|
||||
- **Database:** PostgreSQL (with migration tool e.g., Flyway/Golang-migrate)
|
||||
- **Key Algorithms/Protocols:** BSDiff/VCDIFF for delta generation, HTTP Range requests for resumable downloads.
|
||||
- **Documentation & Code Comments:** Strictly adhere to **British English** spelling conventions (e.g., `colour`, `centre`, `optimise`, `standardisation`).
|
||||
|
||||
---
|
||||
|
||||
## Build, Test & Run Commands
|
||||
|
||||
### Development
|
||||
- **Run the server:** `go run cmd/server/main.go`
|
||||
- **Build the binary:** `go build -o bin/ota-server cmd/server/main.go`
|
||||
- **Format code:** `go fmt ./...`
|
||||
- **Lint code:** `golangci-lint run`
|
||||
|
||||
### Testing
|
||||
- **Run all tests:** `go test ./...`
|
||||
- **Run with coverage:** `go test -coverprofile=coverage.out ./...`
|
||||
|
||||
---
|
||||
|
||||
## Code Architecture & Design Principles
|
||||
|
||||
### 1. 10M Bandwidth Strategy (Hard Constraints)
|
||||
- **Gated Rollout (Token-based):** Devices must acquire a download token before pulling updates. Keep concurrent downloads limited (e.g., max 50 concurrent streams).
|
||||
- **Rate Limiting:** Implement token bucket or leaky bucket algorithms at the application/middleware layer to throttle download speed per connection.
|
||||
- **Resumable Downloads:** The download endpoint **must** support HTTP 206 Partial Content and handle `Range` headers properly.
|
||||
|
||||
### 2. Jar/Zip Delta Logic
|
||||
- **Do not perform direct binary diffs on raw `.jar` files.**
|
||||
- To generate a delta:
|
||||
1. Unzip the old Jar and new Jar into isolated temporary directories.
|
||||
2. Compare files sequentially. Identify new, deleted, and modified files.
|
||||
3. Apply binary diff (like BSDiff) **only** on modified `.class` or resource files.
|
||||
4. Packaging: Zip the modified patches, new files, and a `manifest.json` describing the deletion/replacement steps into a final `.patch` package.
|
||||
|
||||
### 3. Database & Concurrency
|
||||
- Optimise SQL queries to prevent connection pooling bottlenecks under thousands of periodic heartbeats/checking requests.
|
||||
- Use explicit transactions when updating device upgrade status (`Checking` -> `Downloading` -> `Verifying` -> `Upgraded`).
|
||||
|
||||
---
|
||||
|
||||
## Code Style & Conventions
|
||||
- **Naming:** Idiomatic Go (camelCase for internal variables, PascalCase for exported identifiers). Short but descriptive context names.
|
||||
- **Error Handling:** Handle all errors explicitly. Wrap errors with meaningful context using `fmt.Errorf("context: %w", err)`.
|
||||
- **Concurrency:** Ensure goroutines are safe, utilize `sync.Pool` for heavy allocations (like decompression buffers), and use `context.Context` for cancellation propagation.
|
||||
- **Spelling:** Always double-check spelling in logs, errors, and variable definition to ensure **British English** alignment (e.g., use `optimised_delta_buffer` instead of `optimized_delta_buffer`).
|
||||
@@ -0,0 +1,187 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"onixbyte.com/message-converter-manifest/internal/artefact"
|
||||
"onixbyte.com/message-converter-manifest/internal/auth"
|
||||
"onixbyte.com/message-converter-manifest/internal/config"
|
||||
"onixbyte.com/message-converter-manifest/internal/database"
|
||||
"onixbyte.com/message-converter-manifest/internal/delta"
|
||||
"onixbyte.com/message-converter-manifest/internal/deployment"
|
||||
"onixbyte.com/message-converter-manifest/internal/device"
|
||||
"onixbyte.com/message-converter-manifest/internal/download"
|
||||
"onixbyte.com/message-converter-manifest/internal/middleware"
|
||||
)
|
||||
|
||||
func main() {
|
||||
cfg := config.Load()
|
||||
|
||||
// Connect to PostgreSQL (auto-creates database if needed)
|
||||
db, err := database.Connect(cfg.DatabaseURL)
|
||||
if err != nil {
|
||||
log.Fatalf("Database connection failed: %v", err)
|
||||
}
|
||||
|
||||
// Auto-migrate tables
|
||||
if err := database.AutoMigrate(db); err != nil {
|
||||
log.Fatalf("Auto-migrate failed: %v", err)
|
||||
}
|
||||
|
||||
// Initialise auth service and create default admin
|
||||
authSvc := auth.NewService(db, []byte(cfg.JWTSecret), cfg.JWTExpiryHrs)
|
||||
if err := authSvc.CreateInitialAdmin("admin", "admin"); err != nil {
|
||||
log.Printf("Warning: failed to create initial admin: %v", err)
|
||||
}
|
||||
log.Println("[main] Default admin user ready (admin / admin)")
|
||||
|
||||
// Ensure artefact storage directory exists
|
||||
if err := os.MkdirAll(cfg.ArtefactDir, 0755); err != nil {
|
||||
log.Fatalf("Failed to create artefact directory: %v", err)
|
||||
}
|
||||
|
||||
// Global rate limiter
|
||||
tokenBucket := middleware.NewTokenBucket(cfg.RateLimitRPS, cfg.RateLimitRPS*2)
|
||||
go func() {
|
||||
ticker := time.NewTicker(10 * time.Minute)
|
||||
for range ticker.C {
|
||||
tokenBucket.Cleanup(30 * time.Minute)
|
||||
}
|
||||
}()
|
||||
|
||||
// Gated rollout semaphore
|
||||
downloadGate := middleware.NewGatedSemaphore(cfg.MaxConcurrent)
|
||||
|
||||
// Offline device detection
|
||||
go func() {
|
||||
ticker := time.NewTicker(5 * time.Minute)
|
||||
for range ticker.C {
|
||||
offline, err := database.GetOfflineDevices(db, 10*time.Minute)
|
||||
if err != nil {
|
||||
log.Printf("[health] Offline check failed: %v", err)
|
||||
continue
|
||||
}
|
||||
ids := make([]string, len(offline))
|
||||
for i, d := range offline {
|
||||
ids[i] = d.DeviceID
|
||||
}
|
||||
if len(ids) > 0 {
|
||||
if err := database.MarkDevicesOffline(db, ids); err != nil {
|
||||
log.Printf("[health] Mark offline failed: %v", err)
|
||||
} else {
|
||||
log.Printf("[health] Marked %d devices as offline", len(ids))
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
// Initialise handlers
|
||||
authHandler := auth.NewHandler(authSvc)
|
||||
deviceHandler := device.NewHandler(db)
|
||||
artefactHandler := artefact.NewHandler(db, cfg.ArtefactDir)
|
||||
deploymentHandler := deployment.NewHandler(db)
|
||||
deltaHandler := delta.NewHandler(cfg.ArtefactDir)
|
||||
downloadHandler := download.NewHandler(db, cfg.ArtefactDir, downloadGate, cfg.BandwidthBPS)
|
||||
|
||||
// Setup Gin
|
||||
gin.SetMode(gin.ReleaseMode)
|
||||
r := gin.New()
|
||||
r.Use(gin.Recovery())
|
||||
|
||||
// CORS
|
||||
r.Use(func(c *gin.Context) {
|
||||
c.Header("Access-Control-Allow-Origin", "*")
|
||||
c.Header("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS")
|
||||
c.Header("Access-Control-Allow-Headers", "Origin, Content-Type, Accept, Authorization, Range")
|
||||
if c.Request.Method == "OPTIONS" {
|
||||
c.AbortWithStatus(http.StatusNoContent)
|
||||
return
|
||||
}
|
||||
c.Next()
|
||||
})
|
||||
|
||||
// -- Public routes (daemon-facing) --
|
||||
api := r.Group("/api/v1")
|
||||
{
|
||||
api.POST("/devices/register", deviceHandler.Register)
|
||||
api.POST("/devices/heartbeat", deviceHandler.Heartbeat)
|
||||
api.GET("/devices/check-update", deviceHandler.CheckUpdate)
|
||||
}
|
||||
|
||||
// -- Authenticated admin routes --
|
||||
admin := api.Group("")
|
||||
admin.Use(middleware.AuthMiddleware(authSvc))
|
||||
{
|
||||
api.POST("/auth/login", authHandler.Login)
|
||||
|
||||
admin.GET("/devices", deviceHandler.List)
|
||||
admin.GET("/devices/:deviceId", deviceHandler.Get)
|
||||
|
||||
admin.POST("/artefacts", artefactHandler.Upload)
|
||||
admin.GET("/artefacts", artefactHandler.List)
|
||||
admin.GET("/artefacts/:id", artefactHandler.Get)
|
||||
|
||||
admin.POST("/delta/generate", deltaHandler.GenerateDelta)
|
||||
|
||||
admin.POST("/deployments", deploymentHandler.Create)
|
||||
admin.GET("/deployments", deploymentHandler.List)
|
||||
admin.GET("/deployments/:id", deploymentHandler.Get)
|
||||
admin.POST("/deployments/:id/activate", deploymentHandler.Activate)
|
||||
admin.POST("/deployments/:id/pause", deploymentHandler.Pause)
|
||||
admin.GET("/deployments/:id/devices", deploymentHandler.ListDevices)
|
||||
admin.POST("/deployments/:id/rollback", deploymentHandler.Rollback)
|
||||
|
||||
admin.GET("/admin/users", authHandler.ListUsers)
|
||||
admin.POST("/admin/users", authHandler.CreateUser)
|
||||
admin.DELETE("/admin/users/:id", authHandler.DeleteUser)
|
||||
admin.PUT("/admin/users/:id/password", authHandler.ChangePassword)
|
||||
}
|
||||
|
||||
// -- Download endpoint (rate-limited + gated) --
|
||||
packages := api.Group("/packages")
|
||||
packages.Use(middleware.RateLimitMiddleware(tokenBucket))
|
||||
packages.Use(middleware.GatedMiddleware(downloadGate))
|
||||
{
|
||||
packages.GET("/download/:id", downloadHandler.HandleDownload)
|
||||
}
|
||||
|
||||
// -- Device status update --
|
||||
api.POST("/deployments/:id/status", deploymentHandler.UpdateStatus)
|
||||
|
||||
// -- Static admin panel (served at root; API routes take precedence) --
|
||||
r.StaticFS("/", http.Dir("./web/dist"))
|
||||
|
||||
// Graceful shutdown
|
||||
srv := &http.Server{
|
||||
Addr: ":" + cfg.ServerPort,
|
||||
Handler: r,
|
||||
}
|
||||
|
||||
go func() {
|
||||
log.Printf("[main] OTA Manifest Server listening on :%s", cfg.ServerPort)
|
||||
log.Printf("[main] Max concurrent downloads: %d, bandwidth per stream: %d B/s", cfg.MaxConcurrent, cfg.BandwidthBPS)
|
||||
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
||||
log.Fatalf("Server error: %v", err)
|
||||
}
|
||||
}()
|
||||
|
||||
quit := make(chan os.Signal, 1)
|
||||
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
|
||||
<-quit
|
||||
log.Println("[main] Shutting down...")
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
if err := srv.Shutdown(ctx); err != nil {
|
||||
log.Fatalf("Forced shutdown: %v", err)
|
||||
}
|
||||
log.Println("[main] Server stopped")
|
||||
}
|
||||
@@ -0,0 +1,475 @@
|
||||
openapi: "3.0.3"
|
||||
info:
|
||||
title: OTA Manifest — Daemon API
|
||||
description: |
|
||||
Device-side REST API for the OTA update platform.
|
||||
Each daemon (`mcd`) calls these endpoints to register, heartbeat,
|
||||
poll for updates, download artefacts, and report progress.
|
||||
|
||||
**10 Mbps bandwidth design points:**
|
||||
- Downloads are **rate-limited** (~25 KB/s per connection) and **gated** (max 50 concurrent).
|
||||
- The download endpoint supports **HTTP Range** (`206 Partial Content`) for resumable transfers.
|
||||
- `check-update` returns a delta patch when available to minimise bytes on the wire.
|
||||
version: "1.0.0"
|
||||
contact:
|
||||
name: Quanta OTA Team
|
||||
|
||||
servers:
|
||||
- url: http://localhost:8080/api/v1
|
||||
description: Local development server
|
||||
|
||||
tags:
|
||||
- name: Device
|
||||
description: Registration, heartbeat, and update checking
|
||||
- name: Package
|
||||
description: Artefact download
|
||||
- name: Deployment
|
||||
description: Lifecycle status reporting
|
||||
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
# Paths
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
paths:
|
||||
|
||||
# ═══ Device ═══
|
||||
|
||||
/devices/register:
|
||||
post:
|
||||
tags: [Device]
|
||||
summary: Register or refresh a device
|
||||
description: |
|
||||
Called by the daemon on startup. If the `deviceId` already exists
|
||||
this is an upsert — all fields are updated and `lastHeartbeat` is
|
||||
refreshed.
|
||||
operationId: registerDevice
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/RegisterDeviceRequest"
|
||||
example:
|
||||
deviceId: "mcd-7a3f-001"
|
||||
ipAddress: "192.168.1.42"
|
||||
hostname: "gateway-east-01"
|
||||
os: "Debian 12"
|
||||
currentVersion: "1.2.0"
|
||||
groupName: "east-region"
|
||||
responses:
|
||||
"200":
|
||||
description: Device registered or updated
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/Device"
|
||||
example:
|
||||
id: 1
|
||||
deviceId: "mcd-7a3f-001"
|
||||
ipAddress: "192.168.1.42"
|
||||
hostname: "gateway-east-01"
|
||||
os: "Debian 12"
|
||||
currentVersion: "1.2.0"
|
||||
status: "online"
|
||||
groupName: "east-region"
|
||||
lastHeartbeat: "2026-07-03T10:30:00Z"
|
||||
createdAt: "2026-07-03T10:30:00Z"
|
||||
updatedAt: "2026-07-03T10:30:00Z"
|
||||
"400":
|
||||
$ref: "#/components/responses/BadRequest"
|
||||
|
||||
/devices/heartbeat:
|
||||
post:
|
||||
tags: [Device]
|
||||
summary: Send periodic heartbeat
|
||||
description: |
|
||||
Called by the daemon every 30–60 s. Keeps the device marked `online`
|
||||
and updates the `currentVersion` so the server always knows which
|
||||
version each device is running.
|
||||
operationId: heartbeat
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/HeartbeatRequest"
|
||||
example:
|
||||
deviceId: "mcd-7a3f-001"
|
||||
currentVersion: "1.2.0"
|
||||
status: "online"
|
||||
responses:
|
||||
"200":
|
||||
description: Heartbeat acknowledged
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/StatusResponse"
|
||||
"400":
|
||||
$ref: "#/components/responses/BadRequest"
|
||||
|
||||
/devices/check-update:
|
||||
get:
|
||||
tags: [Device]
|
||||
summary: Check whether an update is pending for this device
|
||||
description: |
|
||||
Polled by the daemon on a configurable interval (e.g. every 5 min).
|
||||
When `hasUpdate` is `true` the daemon should proceed to download the
|
||||
referenced artefact and then POST to `/deployments/{id}/status` as the
|
||||
install progresses.
|
||||
operationId: checkUpdate
|
||||
parameters:
|
||||
- name: deviceId
|
||||
in: query
|
||||
required: true
|
||||
schema:
|
||||
type: string
|
||||
description: The device's unique identifier
|
||||
example: "mcd-7a3f-001"
|
||||
responses:
|
||||
"200":
|
||||
description: Update status for the device
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/CheckUpdateResponse"
|
||||
examples:
|
||||
hasUpdate:
|
||||
summary: Update available
|
||||
value:
|
||||
hasUpdate: true
|
||||
artefactId: 5
|
||||
version: "1.3.0"
|
||||
fileSize: 4194304
|
||||
sha256Hash: "a1b2c3d4e5f6..."
|
||||
downloadUrl: "/api/v1/packages/download/5"
|
||||
noUpdate:
|
||||
summary: No update needed
|
||||
value:
|
||||
hasUpdate: false
|
||||
"400":
|
||||
$ref: "#/components/responses/BadRequest"
|
||||
|
||||
# ═══ Package ═══
|
||||
|
||||
/packages/download/{id}:
|
||||
get:
|
||||
tags: [Package]
|
||||
summary: Download an artefact (full or delta patch)
|
||||
description: |
|
||||
Serves the artefact file with **per-connection bandwidth throttling**
|
||||
(~25 KB/s). Supports **HTTP Range** requests so interrupted downloads
|
||||
can be resumed via `Range: bytes=<offset>-`.
|
||||
|
||||
**Headers returned:**
|
||||
- `Content-Disposition: attachment; filename="<name>"`
|
||||
- `X-Checksum-SHA256: <hex>` — validate the file after download
|
||||
- `Accept-Ranges: bytes`
|
||||
- `Content-Length: <bytes>`
|
||||
|
||||
**Query parameters** are optional but recommended — they let the
|
||||
server track each device's download progress.
|
||||
operationId: downloadPackage
|
||||
parameters:
|
||||
- name: id
|
||||
in: path
|
||||
required: true
|
||||
schema:
|
||||
type: integer
|
||||
format: int64
|
||||
description: Artefact ID (from `check-update` response)
|
||||
example: 5
|
||||
- name: deviceId
|
||||
in: query
|
||||
required: false
|
||||
schema:
|
||||
type: string
|
||||
description: Device identifier for progress tracking
|
||||
example: "mcd-7a3f-001"
|
||||
- name: deploymentId
|
||||
in: query
|
||||
required: false
|
||||
schema:
|
||||
type: integer
|
||||
format: int64
|
||||
description: Deployment ID for progress tracking
|
||||
example: 3
|
||||
responses:
|
||||
"200":
|
||||
description: Full artefact file
|
||||
headers:
|
||||
Content-Disposition:
|
||||
schema:
|
||||
type: string
|
||||
description: Attachment filename
|
||||
X-Checksum-SHA256:
|
||||
schema:
|
||||
type: string
|
||||
description: SHA-256 hex digest of the file
|
||||
Accept-Ranges:
|
||||
schema:
|
||||
type: string
|
||||
example: bytes
|
||||
content:
|
||||
application/octet-stream:
|
||||
schema:
|
||||
type: string
|
||||
format: binary
|
||||
"206":
|
||||
description: Partial content (resumed download)
|
||||
headers:
|
||||
Content-Range:
|
||||
schema:
|
||||
type: string
|
||||
example: "bytes 1048576-4194303/4194304"
|
||||
content:
|
||||
application/octet-stream:
|
||||
schema:
|
||||
type: string
|
||||
format: binary
|
||||
"404":
|
||||
$ref: "#/components/responses/NotFound"
|
||||
"503":
|
||||
description: Server at download capacity — retry later
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/ErrorResponse"
|
||||
example:
|
||||
error: "Server at capacity. Please retry later."
|
||||
|
||||
# ═══ Deployment ═══
|
||||
|
||||
/deployments/{id}/status:
|
||||
post:
|
||||
tags: [Deployment]
|
||||
summary: Report deployment status for a single device
|
||||
description: |
|
||||
Called by the daemon at each lifecycle transition:
|
||||
|
||||
1. `downloading` — started the download
|
||||
2. `downloaded` — download complete (may be omitted for small files)
|
||||
3. `verifying` — checking SHA-256 hash
|
||||
4. `installing` — applying the update
|
||||
5. `completed` — update applied, device running new version
|
||||
6. `failed` — unrecoverable error (set `error` field)
|
||||
|
||||
The server tracks these transitions per-device so operators can
|
||||
monitor rollout progress.
|
||||
operationId: updateDeploymentStatus
|
||||
parameters:
|
||||
- name: id
|
||||
in: path
|
||||
required: true
|
||||
schema:
|
||||
type: integer
|
||||
format: int64
|
||||
description: Deployment ID
|
||||
example: 3
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/DeploymentStatusRequest"
|
||||
examples:
|
||||
downloading:
|
||||
value:
|
||||
deviceId: "mcd-7a3f-001"
|
||||
status: "downloading"
|
||||
completed:
|
||||
value:
|
||||
deviceId: "mcd-7a3f-001"
|
||||
status: "completed"
|
||||
failed:
|
||||
value:
|
||||
deviceId: "mcd-7a3f-001"
|
||||
status: "failed"
|
||||
error: "SHA256 mismatch: expected a1b2.. got x9y0.."
|
||||
responses:
|
||||
"200":
|
||||
description: Status recorded
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/StatusResponse"
|
||||
"400":
|
||||
$ref: "#/components/responses/BadRequest"
|
||||
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
# Component Schemas
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
components:
|
||||
|
||||
schemas:
|
||||
|
||||
# -- Requests --
|
||||
|
||||
RegisterDeviceRequest:
|
||||
type: object
|
||||
required: [deviceId]
|
||||
properties:
|
||||
deviceId:
|
||||
type: string
|
||||
maxLength: 256
|
||||
description: Unique device identifier (set by daemon config)
|
||||
ipAddress:
|
||||
type: string
|
||||
description: Device IP at registration time
|
||||
hostname:
|
||||
type: string
|
||||
description: OS hostname
|
||||
os:
|
||||
type: string
|
||||
description: Operating system name and version
|
||||
currentVersion:
|
||||
type: string
|
||||
description: Currently installed client version
|
||||
groupName:
|
||||
type: string
|
||||
description: Logical group for targeted rollouts (defaults to "default")
|
||||
|
||||
HeartbeatRequest:
|
||||
type: object
|
||||
required: [deviceId]
|
||||
properties:
|
||||
deviceId:
|
||||
type: string
|
||||
maxLength: 256
|
||||
currentVersion:
|
||||
type: string
|
||||
description: Currently running version
|
||||
status:
|
||||
type: string
|
||||
enum: [online, offline, upgrading]
|
||||
default: online
|
||||
|
||||
DeploymentStatusRequest:
|
||||
type: object
|
||||
required: [deviceId, status]
|
||||
properties:
|
||||
deviceId:
|
||||
type: string
|
||||
description: Device identifier
|
||||
status:
|
||||
type: string
|
||||
enum:
|
||||
- downloading
|
||||
- downloaded
|
||||
- verifying
|
||||
- installing
|
||||
- completed
|
||||
- failed
|
||||
error:
|
||||
type: string
|
||||
description: Error description (only meaningful when status = "failed")
|
||||
|
||||
# -- Responses --
|
||||
|
||||
Device:
|
||||
type: object
|
||||
properties:
|
||||
id:
|
||||
type: integer
|
||||
format: int64
|
||||
deviceId:
|
||||
type: string
|
||||
ipAddress:
|
||||
type: string
|
||||
hostname:
|
||||
type: string
|
||||
os:
|
||||
type: string
|
||||
currentVersion:
|
||||
type: string
|
||||
status:
|
||||
type: string
|
||||
enum: [online, offline, upgrading]
|
||||
groupName:
|
||||
type: string
|
||||
lastHeartbeat:
|
||||
type: string
|
||||
format: date-time
|
||||
createdAt:
|
||||
type: string
|
||||
format: date-time
|
||||
updatedAt:
|
||||
type: string
|
||||
format: date-time
|
||||
|
||||
CheckUpdateResponse:
|
||||
type: object
|
||||
properties:
|
||||
hasUpdate:
|
||||
type: boolean
|
||||
description: Whether an update is pending
|
||||
artefactId:
|
||||
type: integer
|
||||
format: int64
|
||||
description: Artefact ID to pass to the download endpoint
|
||||
version:
|
||||
type: string
|
||||
description: Target version string
|
||||
fileSize:
|
||||
type: integer
|
||||
format: int64
|
||||
description: Total file size in bytes
|
||||
sha256Hash:
|
||||
type: string
|
||||
description: Expected SHA-256 hex digest (validate after download)
|
||||
downloadUrl:
|
||||
type: string
|
||||
description: Download path relative to the server
|
||||
|
||||
StatusResponse:
|
||||
type: object
|
||||
properties:
|
||||
status:
|
||||
type: string
|
||||
example: "acknowledged"
|
||||
|
||||
ErrorResponse:
|
||||
type: object
|
||||
properties:
|
||||
error:
|
||||
type: string
|
||||
description: Human-readable error message
|
||||
|
||||
# -- Reusable responses --
|
||||
responses:
|
||||
BadRequest:
|
||||
description: Invalid request body or parameters
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/ErrorResponse"
|
||||
example:
|
||||
error: "deviceId is required"
|
||||
NotFound:
|
||||
description: Resource not found
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/ErrorResponse"
|
||||
example:
|
||||
error: "Artefact not found"
|
||||
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
# Daemon update flow (non-normative)
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
x-daemon-flow:
|
||||
polling:
|
||||
interval: "5m (configurable)"
|
||||
description: |
|
||||
1. **Startup** → `POST /devices/register`
|
||||
2. **Every N s** → `POST /devices/heartbeat`
|
||||
3. **Every 5 min** → `GET /devices/check-update?deviceId=xxx`
|
||||
4. **If hasUpdate==true** →
|
||||
a. `POST /deployments/{id}/status` → `downloading`
|
||||
b. `GET /packages/download/{artefactId}?deviceId=xxx&deploymentId={id}`
|
||||
- Use `Range: bytes=<offset>-` to resume interrupted transfers
|
||||
c. Verify SHA-256 hash against `sha256Hash` from step 3
|
||||
d. `POST /deployments/{id}/status` → `verifying`
|
||||
e. `POST /deployments/{id}/status` → `installing`
|
||||
f. Restart the Java process, confirm health
|
||||
g. `POST /deployments/{id}/status` → `completed`
|
||||
h. `POST /devices/heartbeat` with the new `currentVersion`
|
||||
- **On any failure** → `POST /deployments/{id}/status` → `failed`
|
||||
@@ -0,0 +1,50 @@
|
||||
module onixbyte.com/message-converter-manifest
|
||||
|
||||
go 1.26
|
||||
|
||||
require (
|
||||
github.com/gin-gonic/gin v1.12.0
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1
|
||||
github.com/joho/godotenv v1.5.1
|
||||
gorm.io/driver/postgres v1.6.0
|
||||
gorm.io/gorm v1.31.2
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/bytedance/gopkg v0.1.3 // indirect
|
||||
github.com/bytedance/sonic v1.15.0 // indirect
|
||||
github.com/bytedance/sonic/loader v0.5.0 // indirect
|
||||
github.com/cloudwego/base64x v0.1.6 // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.12 // indirect
|
||||
github.com/gin-contrib/sse v1.1.0 // indirect
|
||||
github.com/go-playground/locales v0.14.1 // indirect
|
||||
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||
github.com/go-playground/validator/v10 v10.30.1 // indirect
|
||||
github.com/goccy/go-json v0.10.5 // indirect
|
||||
github.com/goccy/go-yaml v1.19.2 // indirect
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||
github.com/jackc/pgx/v5 v5.6.0 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||
github.com/jinzhu/inflection v1.0.0 // indirect
|
||||
github.com/jinzhu/now v1.1.5 // indirect
|
||||
github.com/json-iterator/go v1.1.12 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.3.0 // indirect
|
||||
github.com/leodido/go-urn v1.4.0 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.2.4 // indirect
|
||||
github.com/quic-go/qpack v0.6.0 // indirect
|
||||
github.com/quic-go/quic-go v0.59.0 // indirect
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
||||
github.com/ugorji/go/codec v1.3.1 // indirect
|
||||
go.mongodb.org/mongo-driver/v2 v2.5.0 // indirect
|
||||
golang.org/x/arch v0.22.0 // indirect
|
||||
golang.org/x/crypto v0.48.0 // indirect
|
||||
golang.org/x/net v0.51.0 // indirect
|
||||
golang.org/x/sync v0.19.0 // indirect
|
||||
golang.org/x/sys v0.41.0 // indirect
|
||||
golang.org/x/text v0.34.0 // indirect
|
||||
google.golang.org/protobuf v1.36.10 // indirect
|
||||
)
|
||||
@@ -0,0 +1,116 @@
|
||||
github.com/bytedance/gopkg v0.1.3 h1:TPBSwH8RsouGCBcMBktLt1AymVo2TVsBVCY4b6TnZ/M=
|
||||
github.com/bytedance/gopkg v0.1.3/go.mod h1:576VvJ+eJgyCzdjS+c4+77QF3p7ubbtiKARP3TxducM=
|
||||
github.com/bytedance/sonic v1.15.0 h1:/PXeWFaR5ElNcVE84U0dOHjiMHQOwNIx3K4ymzh/uSE=
|
||||
github.com/bytedance/sonic v1.15.0/go.mod h1:tFkWrPz0/CUCLEF4ri4UkHekCIcdnkqXw9VduqpJh0k=
|
||||
github.com/bytedance/sonic/loader v0.5.0 h1:gXH3KVnatgY7loH5/TkeVyXPfESoqSBSBEiDd5VjlgE=
|
||||
github.com/bytedance/sonic/loader v0.5.0/go.mod h1:AR4NYCk5DdzZizZ5djGqQ92eEhCCcdf5x77udYiSJRo=
|
||||
github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M=
|
||||
github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/gabriel-vasile/mimetype v1.4.12 h1:e9hWvmLYvtp846tLHam2o++qitpguFiYCKbn0w9jyqw=
|
||||
github.com/gabriel-vasile/mimetype v1.4.12/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s=
|
||||
github.com/gin-contrib/sse v1.1.0 h1:n0w2GMuUpWDVp7qSpvze6fAu9iRxJY4Hmj6AmBOU05w=
|
||||
github.com/gin-contrib/sse v1.1.0/go.mod h1:hxRZ5gVpWMT7Z0B0gSNYqqsSCNIJMjzvm6fqCz9vjwM=
|
||||
github.com/gin-gonic/gin v1.12.0 h1:b3YAbrZtnf8N//yjKeU2+MQsh2mY5htkZidOM7O0wG8=
|
||||
github.com/gin-gonic/gin v1.12.0/go.mod h1:VxccKfsSllpKshkBWgVgRniFFAzFb9csfngsqANjnLc=
|
||||
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
|
||||
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
|
||||
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
|
||||
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
|
||||
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
|
||||
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
|
||||
github.com/go-playground/validator/v10 v10.30.1 h1:f3zDSN/zOma+w6+1Wswgd9fLkdwy06ntQJp0BBvFG0w=
|
||||
github.com/go-playground/validator/v10 v10.30.1/go.mod h1:oSuBIQzuJxL//3MelwSLD5hc2Tu889bF0Idm9Dg26cM=
|
||||
github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4=
|
||||
github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
|
||||
github.com/goccy/go-yaml v1.19.2 h1:PmFC1S6h8ljIz6gMRBopkjP1TVT7xuwrButHID66PoM=
|
||||
github.com/goccy/go-yaml v1.19.2/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
||||
github.com/jackc/pgx/v5 v5.6.0 h1:SWJzexBzPL5jb0GEsrPMLIsi/3jOo7RHlzTjcAeDrPY=
|
||||
github.com/jackc/pgx/v5 v5.6.0/go.mod h1:DNZ/vlrUnhWCoFGxHAG8U2ljioxukquj7utPDgtQdTw=
|
||||
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
|
||||
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
|
||||
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
|
||||
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
|
||||
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
|
||||
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
|
||||
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
|
||||
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
|
||||
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
|
||||
github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y=
|
||||
github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
|
||||
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
|
||||
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
|
||||
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
|
||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
|
||||
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
|
||||
github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
|
||||
github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8=
|
||||
github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII=
|
||||
github.com/quic-go/quic-go v0.59.0 h1:OLJkp1Mlm/aS7dpKgTc6cnpynnD2Xg7C1pwL6vy/SAw=
|
||||
github.com/quic-go/quic-go v0.59.0/go.mod h1:upnsH4Ju1YkqpLXC305eW3yDZ4NfnNbmQRCMWS58IKU=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
|
||||
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
|
||||
github.com/ugorji/go/codec v1.3.1 h1:waO7eEiFDwidsBN6agj1vJQ4AG7lh2yqXyOXqhgQuyY=
|
||||
github.com/ugorji/go/codec v1.3.1/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4=
|
||||
go.mongodb.org/mongo-driver/v2 v2.5.0 h1:yXUhImUjjAInNcpTcAlPHiT7bIXhshCTL3jVBkF3xaE=
|
||||
go.mongodb.org/mongo-driver/v2 v2.5.0/go.mod h1:yOI9kBsufol30iFsl1slpdq1I0eHPzybRWdyYUs8K/0=
|
||||
go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y=
|
||||
go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU=
|
||||
golang.org/x/arch v0.22.0 h1:c/Zle32i5ttqRXjdLyyHZESLD/bB90DCU1g9l/0YBDI=
|
||||
golang.org/x/arch v0.22.0/go.mod h1:dNHoOeKiyja7GTvF9NJS1l3Z2yntpQNzgrjh1cU103A=
|
||||
golang.org/x/crypto v0.48.0 h1:/VRzVqiRSggnhY7gNRxPauEQ5Drw9haKdM0jqfcCFts=
|
||||
golang.org/x/crypto v0.48.0/go.mod h1:r0kV5h3qnFPlQnBSrULhlsRfryS2pmewsg+XfMgkVos=
|
||||
golang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo=
|
||||
golang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y=
|
||||
golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4=
|
||||
golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=
|
||||
golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||
golang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk=
|
||||
golang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA=
|
||||
google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE=
|
||||
google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gorm.io/driver/postgres v1.6.0 h1:2dxzU8xJ+ivvqTRph34QX+WrRaJlmfyPqXmoGVjMBa4=
|
||||
gorm.io/driver/postgres v1.6.0/go.mod h1:vUw0mrGgrTK+uPHEhAdV4sfFELrByKVGnaVRkXDhtWo=
|
||||
gorm.io/driver/sqlite v1.6.0 h1:WHRRrIiulaPiPFmDcod6prc4l2VGVWHz80KspNsxSfQ=
|
||||
gorm.io/driver/sqlite v1.6.0/go.mod h1:AO9V1qIQddBESngQUKWL9yoH93HIeA1X6V633rBwyT8=
|
||||
gorm.io/gorm v1.31.2 h1:3o8FXNo9v9S858gil+3LlZA1LkCOzgb4g5BL64FgaCo=
|
||||
gorm.io/gorm v1.31.2/go.mod h1:XyQVbO2k6YkOis7C2437jSit3SsDK72s7n7rsSHd+Gs=
|
||||
@@ -0,0 +1,137 @@
|
||||
package artefact
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"onixbyte.com/message-converter-manifest/internal/database"
|
||||
"onixbyte.com/message-converter-manifest/internal/model"
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
db *gorm.DB
|
||||
artefactDir string
|
||||
}
|
||||
|
||||
func NewHandler(db *gorm.DB, artefactDir string) *Handler {
|
||||
return &Handler{db: db, artefactDir: artefactDir}
|
||||
}
|
||||
|
||||
func (h *Handler) Upload(c *gin.Context) {
|
||||
version := c.PostForm("version")
|
||||
if version == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "version is required"})
|
||||
return
|
||||
}
|
||||
|
||||
deltaRef := c.PostForm("deltaRef")
|
||||
metadata := c.PostForm("metadata")
|
||||
if metadata == "" {
|
||||
metadata = "{}"
|
||||
}
|
||||
|
||||
file, header, err := c.Request.FormFile("file")
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "file is required: " + err.Error()})
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
destDir := filepath.Join(h.artefactDir, version)
|
||||
if err := os.MkdirAll(destDir, 0755); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to create directory"})
|
||||
return
|
||||
}
|
||||
|
||||
destPath := filepath.Join(destDir, header.Filename)
|
||||
out, err := os.Create(destPath)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to create file"})
|
||||
return
|
||||
}
|
||||
defer out.Close()
|
||||
|
||||
hasher := sha256.New()
|
||||
writer := io.MultiWriter(out, hasher)
|
||||
|
||||
size, err := io.Copy(writer, file)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to write file"})
|
||||
return
|
||||
}
|
||||
|
||||
sha256Hash := fmt.Sprintf("%x", hasher.Sum(nil))
|
||||
|
||||
artefact := &model.Artefact{
|
||||
Version: version,
|
||||
FileName: header.Filename,
|
||||
FilePath: destPath,
|
||||
FileSize: size,
|
||||
SHA256Hash: sha256Hash,
|
||||
DeltaRef: deltaRef,
|
||||
IsDelta: deltaRef != "",
|
||||
Metadata: metadata,
|
||||
}
|
||||
|
||||
if err := database.CreateArtefact(h.db, artefact); err != nil {
|
||||
os.Remove(destPath)
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to save artefact: " + err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, artefact)
|
||||
}
|
||||
|
||||
func (h *Handler) List(c *gin.Context) {
|
||||
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
|
||||
pageSize, _ := strconv.Atoi(c.DefaultQuery("pageSize", "20"))
|
||||
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
if pageSize < 1 || pageSize > 100 {
|
||||
pageSize = 20
|
||||
}
|
||||
|
||||
artefacts, total, err := database.ListArtefacts(h.db, page, pageSize)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, model.PaginatedResponse{
|
||||
Data: artefacts,
|
||||
Total: total,
|
||||
Page: page,
|
||||
PageSize: pageSize,
|
||||
})
|
||||
}
|
||||
|
||||
func (h *Handler) Get(c *gin.Context) {
|
||||
id, err := strconv.ParseInt(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid id"})
|
||||
return
|
||||
}
|
||||
|
||||
artefact, err := database.GetArtefactByID(h.db, id)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "Artefact not found"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, artefact)
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"onixbyte.com/message-converter-manifest/internal/model"
|
||||
)
|
||||
|
||||
// -- Admin user management handlers --
|
||||
|
||||
type CreateUserRequest struct {
|
||||
Username string `json:"username" binding:"required"`
|
||||
Password string `json:"password" binding:"required"`
|
||||
Role string `json:"role"`
|
||||
}
|
||||
|
||||
type ChangePasswordRequest struct {
|
||||
NewPassword string `json:"newPassword" binding:"required"`
|
||||
}
|
||||
|
||||
// ListUsers handles GET /admin/users.
|
||||
func (h *Handler) ListUsers(c *gin.Context) {
|
||||
users, err := h.svc.ListUsers()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if users == nil {
|
||||
users = []model.AdminUser{}
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"data": users})
|
||||
}
|
||||
|
||||
// CreateUser handles POST /admin/users.
|
||||
func (h *Handler) CreateUser(c *gin.Context) {
|
||||
var req CreateUserRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
user, err := h.svc.CreateUser(req.Username, req.Password, req.Role)
|
||||
if err != nil {
|
||||
if err == ErrUserExists {
|
||||
c.JSON(http.StatusConflict, gin.H{"error": "Username already exists"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, user)
|
||||
}
|
||||
|
||||
// DeleteUser handles DELETE /admin/users/:id.
|
||||
func (h *Handler) DeleteUser(c *gin.Context) {
|
||||
id, err := strconv.ParseInt(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid id"})
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.svc.DeleteUser(id); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"status": "deleted"})
|
||||
}
|
||||
|
||||
// ChangePassword handles PUT /admin/users/:id/password.
|
||||
func (h *Handler) ChangePassword(c *gin.Context) {
|
||||
id, err := strconv.ParseInt(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid id"})
|
||||
return
|
||||
}
|
||||
|
||||
var req ChangePasswordRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.svc.ChangePassword(id, req.NewPassword); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"status": "password changed"})
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"onixbyte.com/message-converter-manifest/internal/model"
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
svc *Service
|
||||
}
|
||||
|
||||
func NewHandler(svc *Service) *Handler {
|
||||
return &Handler{svc: svc}
|
||||
}
|
||||
|
||||
func (h *Handler) Login(c *gin.Context) {
|
||||
var req model.LoginRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request: " + err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := h.svc.Login(req.Username, req.Password)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid credentials"})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, resp)
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
package auth
|
||||
|
||||
// Repository functions are in internal/database/repository.go (AdminUser methods).
|
||||
// This file exists to satisfy the package structure for future auth-specific queries.
|
||||
@@ -0,0 +1,155 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"onixbyte.com/message-converter-manifest/internal/database"
|
||||
"onixbyte.com/message-converter-manifest/internal/model"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrInvalidCredentials = errors.New("invalid username or password")
|
||||
ErrUserExists = errors.New("username already exists")
|
||||
)
|
||||
|
||||
type Service struct {
|
||||
db *gorm.DB
|
||||
secret []byte
|
||||
expiry time.Duration
|
||||
}
|
||||
|
||||
func NewService(db *gorm.DB, secret []byte, expiryHrs int) *Service {
|
||||
return &Service{
|
||||
db: db,
|
||||
secret: secret,
|
||||
expiry: time.Duration(expiryHrs) * time.Hour,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) Login(username, password string) (*model.LoginResponse, error) {
|
||||
user, err := database.GetAdminUserByUsername(s.db, username)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrInvalidCredentials
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
hash := hashPassword(password)
|
||||
if subtle.ConstantTimeCompare([]byte(hash), []byte(user.PasswordHash)) != 1 {
|
||||
return nil, ErrInvalidCredentials
|
||||
}
|
||||
|
||||
token, expiresAt, err := s.generateToken(user)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &model.LoginResponse{
|
||||
Token: token,
|
||||
ExpiresAt: expiresAt,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *Service) CreateInitialAdmin(username, password string) error {
|
||||
_, err := database.GetAdminUserByUsername(s.db, username)
|
||||
if err == nil {
|
||||
return nil // admin already exists
|
||||
}
|
||||
|
||||
user := &model.AdminUser{
|
||||
Username: username,
|
||||
PasswordHash: hashPassword(password),
|
||||
Role: "admin",
|
||||
}
|
||||
return s.db.Transaction(func(tx *gorm.DB) error {
|
||||
return database.CreateAdminUser(tx, user)
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Service) ValidateToken(tokenString string) (*model.AdminUser, error) {
|
||||
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
|
||||
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, errors.New("unexpected signing method")
|
||||
}
|
||||
return s.secret, nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
claims, ok := token.Claims.(jwt.MapClaims)
|
||||
if !ok || !token.Valid {
|
||||
return nil, errors.New("invalid token")
|
||||
}
|
||||
|
||||
username, _ := claims["sub"].(string)
|
||||
if username == "" {
|
||||
return nil, errors.New("invalid token subject")
|
||||
}
|
||||
|
||||
return database.GetAdminUserByUsername(s.db, username)
|
||||
}
|
||||
|
||||
func (s *Service) generateToken(user *model.AdminUser) (string, int64, error) {
|
||||
expiresAt := time.Now().Add(s.expiry)
|
||||
claims := jwt.MapClaims{
|
||||
"sub": user.Username,
|
||||
"role": user.Role,
|
||||
"iat": time.Now().Unix(),
|
||||
"exp": expiresAt.Unix(),
|
||||
}
|
||||
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
tokenStr, err := token.SignedString(s.secret)
|
||||
if err != nil {
|
||||
return "", 0, err
|
||||
}
|
||||
|
||||
return tokenStr, expiresAt.Unix(), nil
|
||||
}
|
||||
|
||||
func hashPassword(password string) string {
|
||||
h := sha256.Sum256([]byte(password))
|
||||
return hex.EncodeToString(h[:])
|
||||
}
|
||||
|
||||
func (s *Service) ListUsers() ([]model.AdminUser, error) {
|
||||
return database.ListAdminUsers(s.db)
|
||||
}
|
||||
|
||||
func (s *Service) CreateUser(username, password, role string) (*model.AdminUser, error) {
|
||||
_, err := database.GetAdminUserByUsername(s.db, username)
|
||||
if err == nil {
|
||||
return nil, ErrUserExists
|
||||
}
|
||||
|
||||
if role == "" {
|
||||
role = "admin"
|
||||
}
|
||||
|
||||
user := &model.AdminUser{
|
||||
Username: username,
|
||||
PasswordHash: hashPassword(password),
|
||||
Role: role,
|
||||
}
|
||||
if err := database.CreateAdminUser(s.db, user); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (s *Service) DeleteUser(id int64) error {
|
||||
return database.DeleteAdminUser(s.db, id)
|
||||
}
|
||||
|
||||
func (s *Service) ChangePassword(id int64, newPassword string) error {
|
||||
return database.UpdateAdminPassword(s.db, id, hashPassword(newPassword))
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"log"
|
||||
"os"
|
||||
"strconv"
|
||||
|
||||
"github.com/joho/godotenv"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
ServerPort string
|
||||
JWTSecret string
|
||||
JWTExpiryHrs int
|
||||
DatabaseURL string
|
||||
ArtefactDir string
|
||||
MaxConcurrent int
|
||||
BandwidthBPS int
|
||||
RateLimitRPS int
|
||||
}
|
||||
|
||||
func Load() *Config {
|
||||
// Load .env file if present (silently ignore if not found)
|
||||
if err := godotenv.Load(); err != nil {
|
||||
log.Println("[config] No .env file found, using system environment variables")
|
||||
}
|
||||
|
||||
return &Config{
|
||||
ServerPort: envOrDefault("SERVER_PORT", "8080"),
|
||||
JWTSecret: envOrDefault("JWT_SECRET", "change-me-in-production"),
|
||||
JWTExpiryHrs: envOrDefaultInt("JWT_EXPIRY_HRS", 24),
|
||||
DatabaseURL: envOrDefault("DATABASE_URL", "postgres://postgres:postgres@localhost:5432/manifest?sslmode=disable"),
|
||||
ArtefactDir: envOrDefault("ARTEFACT_DIR", "/var/ota/artefacts"),
|
||||
MaxConcurrent: envOrDefaultInt("MAX_CONCURRENT_DOWNLOADS", 50),
|
||||
BandwidthBPS: envOrDefaultInt("BANDWIDTH_BPS", 10*1024*1024/50),
|
||||
RateLimitRPS: envOrDefaultInt("RATE_LIMIT_RPS", 100),
|
||||
}
|
||||
}
|
||||
|
||||
func envOrDefault(key, def string) string {
|
||||
if v := os.Getenv(key); v != "" {
|
||||
return v
|
||||
}
|
||||
return def
|
||||
}
|
||||
|
||||
func envOrDefaultInt(key string, def int) int {
|
||||
if v := os.Getenv(key); v != "" {
|
||||
if n, err := strconv.Atoi(v); err == nil {
|
||||
return n
|
||||
}
|
||||
}
|
||||
return def
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"gorm.io/driver/postgres"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/logger"
|
||||
|
||||
"onixbyte.com/message-converter-manifest/internal/model"
|
||||
)
|
||||
|
||||
// Connect opens a PostgreSQL connection via GORM. If the target database does
|
||||
// not exist it is created automatically. Tables are then migrated.
|
||||
func Connect(databaseURL string) (*gorm.DB, error) {
|
||||
dbName, err := ensureDatabase(databaseURL)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
db, err := gorm.Open(postgres.Open(databaseURL), &gorm.Config{
|
||||
Logger: logger.Default.LogMode(logger.Warn),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to open database: %w", err)
|
||||
}
|
||||
|
||||
sqlDB, err := db.DB()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get underlying sql.DB: %w", err)
|
||||
}
|
||||
sqlDB.SetMaxOpenConns(50)
|
||||
sqlDB.SetMaxIdleConns(10)
|
||||
|
||||
log.Printf("[database] Connected to PostgreSQL database: %s", dbName)
|
||||
return db, nil
|
||||
}
|
||||
|
||||
// AutoMigrate creates or updates tables to match the model definitions.
|
||||
func AutoMigrate(db *gorm.DB) error {
|
||||
return db.AutoMigrate(
|
||||
&model.AdminUser{},
|
||||
&model.Device{},
|
||||
&model.Artefact{},
|
||||
&model.Deployment{},
|
||||
&model.DeploymentDevice{},
|
||||
)
|
||||
}
|
||||
|
||||
// ensureDatabase creates the target database if it does not exist.
|
||||
func ensureDatabase(databaseURL string) (string, error) {
|
||||
u, err := url.Parse(databaseURL)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("invalid database URL: %w", err)
|
||||
}
|
||||
dbName := strings.TrimPrefix(u.Path, "/")
|
||||
|
||||
adminURL := *u
|
||||
adminURL.Path = "/postgres"
|
||||
|
||||
db, err := gorm.Open(postgres.Open(adminURL.String()), &gorm.Config{})
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to connect to admin database: %w", err)
|
||||
}
|
||||
|
||||
var exists bool
|
||||
db.Raw("SELECT EXISTS(SELECT 1 FROM pg_database WHERE datname = ?)", dbName).Scan(&exists)
|
||||
if !exists {
|
||||
if err := db.Exec(fmt.Sprintf(`CREATE DATABASE "%s"`, dbName)).Error; err != nil {
|
||||
return "", fmt.Errorf("failed to create database %s: %w", dbName, err)
|
||||
}
|
||||
log.Printf("[database] Created database: %s", dbName)
|
||||
}
|
||||
|
||||
sqlDB, _ := db.DB()
|
||||
if sqlDB != nil {
|
||||
sqlDB.Close()
|
||||
}
|
||||
return dbName, nil
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
|
||||
"onixbyte.com/message-converter-manifest/internal/model"
|
||||
)
|
||||
|
||||
// -- Admin Users --
|
||||
|
||||
func CreateAdminUser(db *gorm.DB, u *model.AdminUser) error {
|
||||
return db.Create(u).Error
|
||||
}
|
||||
|
||||
func GetAdminUserByUsername(db *gorm.DB, username string) (*model.AdminUser, error) {
|
||||
var u model.AdminUser
|
||||
err := db.Where("username = ?", username).First(&u).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &u, nil
|
||||
}
|
||||
|
||||
func ListAdminUsers(db *gorm.DB) ([]model.AdminUser, error) {
|
||||
var users []model.AdminUser
|
||||
err := db.Order("created_at").Find(&users).Error
|
||||
return users, err
|
||||
}
|
||||
|
||||
func DeleteAdminUser(db *gorm.DB, id int64) error {
|
||||
return db.Delete(&model.AdminUser{}, id).Error
|
||||
}
|
||||
|
||||
func UpdateAdminPassword(db *gorm.DB, id int64, passwordHash string) error {
|
||||
return db.Model(&model.AdminUser{}).Where("id = ?", id).
|
||||
Update("password_hash", passwordHash).Error
|
||||
}
|
||||
|
||||
// -- Devices --
|
||||
|
||||
func UpsertDevice(db *gorm.DB, d *model.Device) error {
|
||||
return db.Clauses(clause.OnConflict{
|
||||
Columns: []clause.Column{{Name: "device_id"}},
|
||||
DoUpdates: clause.AssignmentColumns([]string{"ip_address", "hostname", "os", "current_version", "status", "group_name", "last_heartbeat", "updated_at"}),
|
||||
}).Create(d).Error
|
||||
}
|
||||
|
||||
func UpdateDeviceHeartbeat(db *gorm.DB, deviceID, version, status string) error {
|
||||
return db.Model(&model.Device{}).Where("device_id = ?", deviceID).
|
||||
Updates(map[string]interface{}{
|
||||
"current_version": version,
|
||||
"status": status,
|
||||
"last_heartbeat": time.Now(),
|
||||
}).Error
|
||||
}
|
||||
|
||||
func GetDeviceByID(db *gorm.DB, deviceID string) (*model.Device, error) {
|
||||
var d model.Device
|
||||
err := db.Where("device_id = ?", deviceID).First(&d).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &d, nil
|
||||
}
|
||||
|
||||
func ListDevices(db *gorm.DB, status, group string, page, pageSize int) ([]model.Device, int64, error) {
|
||||
var devices []model.Device
|
||||
var total int64
|
||||
|
||||
q := db.Model(&model.Device{})
|
||||
if status != "" {
|
||||
q = q.Where("status = ?", status)
|
||||
}
|
||||
if group != "" {
|
||||
q = q.Where("group_name = ?", group)
|
||||
}
|
||||
|
||||
if err := q.Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
err := q.Order("last_heartbeat DESC").Offset((page - 1) * pageSize).Limit(pageSize).Find(&devices).Error
|
||||
return devices, total, err
|
||||
}
|
||||
|
||||
func GetOfflineDevices(db *gorm.DB, threshold time.Duration) ([]model.Device, error) {
|
||||
var devices []model.Device
|
||||
err := db.Where("last_heartbeat < ? AND status = ?", time.Now().Add(-threshold), model.DeviceStatusOnline).
|
||||
Find(&devices).Error
|
||||
return devices, err
|
||||
}
|
||||
|
||||
func MarkDevicesOffline(db *gorm.DB, deviceIDs []string) error {
|
||||
return db.Model(&model.Device{}).Where("device_id IN ?", deviceIDs).
|
||||
Update("status", model.DeviceStatusOffline).Error
|
||||
}
|
||||
|
||||
// -- Artefacts --
|
||||
|
||||
func CreateArtefact(db *gorm.DB, a *model.Artefact) error {
|
||||
return db.Create(a).Error
|
||||
}
|
||||
|
||||
func GetArtefactByID(db *gorm.DB, id int64) (*model.Artefact, error) {
|
||||
var a model.Artefact
|
||||
err := db.First(&a, id).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &a, nil
|
||||
}
|
||||
|
||||
func GetArtefactByVersion(db *gorm.DB, version string) (*model.Artefact, error) {
|
||||
var a model.Artefact
|
||||
err := db.Where("version = ?", version).Order("created_at DESC").First(&a).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &a, nil
|
||||
}
|
||||
|
||||
func ListArtefacts(db *gorm.DB, page, pageSize int) ([]model.Artefact, int64, error) {
|
||||
var artefacts []model.Artefact
|
||||
var total int64
|
||||
|
||||
db.Model(&model.Artefact{}).Count(&total)
|
||||
err := db.Order("created_at DESC").Offset((page - 1) * pageSize).Limit(pageSize).Find(&artefacts).Error
|
||||
return artefacts, total, err
|
||||
}
|
||||
|
||||
// -- Deployments --
|
||||
|
||||
func CreateDeployment(db *gorm.DB, d *model.Deployment) error {
|
||||
return db.Create(d).Error
|
||||
}
|
||||
|
||||
func GetDeploymentByID(db *gorm.DB, id int64) (*model.Deployment, error) {
|
||||
var d model.Deployment
|
||||
err := db.Preload("Artefact").First(&d, id).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &d, nil
|
||||
}
|
||||
|
||||
func ListDeployments(db *gorm.DB, status string, page, pageSize int) ([]model.Deployment, int64, error) {
|
||||
var deployments []model.Deployment
|
||||
var total int64
|
||||
|
||||
q := db.Model(&model.Deployment{})
|
||||
if status != "" {
|
||||
q = q.Where("status = ?", status)
|
||||
}
|
||||
|
||||
if err := q.Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
err := q.Preload("Artefact").Order("created_at DESC").
|
||||
Offset((page - 1) * pageSize).Limit(pageSize).Find(&deployments).Error
|
||||
return deployments, total, err
|
||||
}
|
||||
|
||||
func UpdateDeploymentStatus(db *gorm.DB, id int64, status string) error {
|
||||
return db.Model(&model.Deployment{}).Where("id = ?", id).Update("status", status).Error
|
||||
}
|
||||
|
||||
// -- Deployment Devices --
|
||||
|
||||
func CreateDeploymentDevices(db *gorm.DB, deploymentID int64, deviceIDs []string) error {
|
||||
devices := make([]model.DeploymentDevice, len(deviceIDs))
|
||||
for i, did := range deviceIDs {
|
||||
devices[i] = model.DeploymentDevice{DeploymentID: deploymentID, DeviceID: did, Status: model.DeployDeviceStatusPending}
|
||||
}
|
||||
return db.Clauses(clause.OnConflict{DoNothing: true}).Create(&devices).Error
|
||||
}
|
||||
|
||||
func GetActiveDeploymentForDevice(db *gorm.DB, deviceID string) (*model.Deployment, *model.Artefact, error) {
|
||||
var dd model.DeploymentDevice
|
||||
err := db.Where("device_id = ? AND status = ?", deviceID, model.DeployDeviceStatusPending).
|
||||
Preload("Deployment.Artefact").First(&dd).Error
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
var d model.Deployment
|
||||
db.Preload("Artefact").First(&d, dd.DeploymentID)
|
||||
if d.Status != model.DeploymentStatusActive {
|
||||
return nil, nil, gorm.ErrRecordNotFound
|
||||
}
|
||||
return &d, d.Artefact, nil
|
||||
}
|
||||
|
||||
func UpdateDeploymentDeviceStatus(db *gorm.DB, deploymentID int64, deviceID, status, errMsg string) error {
|
||||
updates := map[string]interface{}{"status": status, "error": errMsg}
|
||||
now := time.Now()
|
||||
if status == model.DeployDeviceStatusDownloaded {
|
||||
updates["downloaded_at"] = &now
|
||||
}
|
||||
if status == model.DeployDeviceStatusCompleted || status == model.DeployDeviceStatusFailed {
|
||||
updates["completed_at"] = &now
|
||||
}
|
||||
return db.Model(&model.DeploymentDevice{}).
|
||||
Where("deployment_id = ? AND device_id = ?", deploymentID, deviceID).
|
||||
Updates(updates).Error
|
||||
}
|
||||
|
||||
func GetDeploymentDeviceStats(db *gorm.DB, deploymentID int64) (map[string]int64, error) {
|
||||
type row struct {
|
||||
Status string
|
||||
Count int64
|
||||
}
|
||||
var rows []row
|
||||
if err := db.Model(&model.DeploymentDevice{}).
|
||||
Select("status, COUNT(*) as count").
|
||||
Where("deployment_id = ?", deploymentID).
|
||||
Group("status").Scan(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
stats := map[string]int64{}
|
||||
for _, r := range rows {
|
||||
stats[r.Status] = r.Count
|
||||
}
|
||||
return stats, nil
|
||||
}
|
||||
|
||||
func GetDeploymentDevices(db *gorm.DB, deploymentID int64, status string, page, pageSize int) ([]model.DeploymentDevice, int64, error) {
|
||||
var devices []model.DeploymentDevice
|
||||
var total int64
|
||||
|
||||
q := db.Model(&model.DeploymentDevice{}).Where("deployment_id = ?", deploymentID)
|
||||
if status != "" {
|
||||
q = q.Where("status = ?", status)
|
||||
}
|
||||
|
||||
q.Count(&total)
|
||||
err := q.Order("created_at").Offset((page - 1) * pageSize).Limit(pageSize).Find(&devices).Error
|
||||
return devices, total, err
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package delta
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// Handler provides delta patch generation for JAR artefacts.
|
||||
type Handler struct {
|
||||
artefactDir string
|
||||
}
|
||||
|
||||
func NewHandler(artefactDir string) *Handler {
|
||||
return &Handler{artefactDir: artefactDir}
|
||||
}
|
||||
|
||||
// GenerateDelta creates a delta patch between two artefact versions.
|
||||
// POST /api/v1/delta/generate
|
||||
// Form fields: oldVersion, newVersion
|
||||
func (h *Handler) GenerateDelta(c *gin.Context) {
|
||||
oldVersion := c.PostForm("oldVersion")
|
||||
newVersion := c.PostForm("newVersion")
|
||||
if oldVersion == "" || newVersion == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "oldVersion and newVersion are required"})
|
||||
return
|
||||
}
|
||||
|
||||
oldDir := filepath.Join(h.artefactDir, oldVersion)
|
||||
newDir := filepath.Join(h.artefactDir, newVersion)
|
||||
|
||||
if _, err := os.Stat(oldDir); os.IsNotExist(err) {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "Old version not found: " + oldVersion})
|
||||
return
|
||||
}
|
||||
if _, err := os.Stat(newDir); os.IsNotExist(err) {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "New version not found: " + newVersion})
|
||||
return
|
||||
}
|
||||
|
||||
// Find JAR files in each version directory
|
||||
oldJar, err := findJarInDir(oldDir)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "No JAR found in old version: " + err.Error()})
|
||||
return
|
||||
}
|
||||
newJar, err := findJarInDir(newDir)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "No JAR found in new version: " + err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
patchPath := filepath.Join(h.artefactDir, "patches", oldVersion+"-to-"+newVersion+".patch")
|
||||
if err := os.MkdirAll(filepath.Dir(patchPath), 0755); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create patch directory"})
|
||||
return
|
||||
}
|
||||
|
||||
if err := GenerateJarDelta(oldJar, newJar, patchPath); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Delta generation failed: " + err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"status": "generated",
|
||||
"patchPath": patchPath,
|
||||
"oldVersion": oldVersion,
|
||||
"newVersion": newVersion,
|
||||
})
|
||||
}
|
||||
|
||||
func findJarInDir(dir string) (string, error) {
|
||||
entries, err := os.ReadDir(dir)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
for _, e := range entries {
|
||||
if !e.IsDir() && filepath.Ext(e.Name()) == ".jar" {
|
||||
return filepath.Join(dir, e.Name()), nil
|
||||
}
|
||||
}
|
||||
return "", os.ErrNotExist
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
package delta
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// PatchManifest describes the delta operations needed to transform an old JAR into a new JAR.
|
||||
type PatchManifest struct {
|
||||
OldVersion string `json:"oldVersion"`
|
||||
NewVersion string `json:"newVersion"`
|
||||
Deleted []string `json:"deleted"`
|
||||
Added []string `json:"added"`
|
||||
Modified []PatchEntry `json:"modified"`
|
||||
Unchanged int `json:"unchanged"`
|
||||
}
|
||||
|
||||
// PatchEntry represents a single modified file within the delta.
|
||||
type PatchEntry struct {
|
||||
Path string `json:"path"`
|
||||
OldSHA256 string `json:"oldSha256"`
|
||||
NewSHA256 string `json:"newSha256"`
|
||||
DiffSize int64 `json:"diffSize"`
|
||||
DiffHash string `json:"diffHash"`
|
||||
}
|
||||
|
||||
// GenerateJarDelta produces a .patch file by comparing two JARs:
|
||||
// 1. Unzip both JARs into memory.
|
||||
// 2. Compare files; identify added, deleted, and modified entries.
|
||||
// 3. For modified .class files, generate a BSDiff-style binary diff.
|
||||
// 4. Package everything (diff chunks, new files, manifest.json) into a zip.
|
||||
func GenerateJarDelta(oldJarPath, newJarPath, patchPath string) error {
|
||||
oldFiles, err := readJarEntries(oldJarPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("reading old JAR: %w", err)
|
||||
}
|
||||
newFiles, err := readJarEntries(newJarPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("reading new JAR: %w", err)
|
||||
}
|
||||
|
||||
manifest := PatchManifest{
|
||||
OldVersion: filepath.Base(oldJarPath),
|
||||
NewVersion: filepath.Base(newJarPath),
|
||||
}
|
||||
|
||||
oldSet := make(map[string][]byte)
|
||||
for _, f := range oldFiles {
|
||||
oldSet[f.Name] = f.Data
|
||||
}
|
||||
newSet := make(map[string][]byte)
|
||||
for _, f := range newFiles {
|
||||
newSet[f.Name] = f.Data
|
||||
}
|
||||
|
||||
// Identify deleted, added, and modified files.
|
||||
for name := range oldSet {
|
||||
if _, ok := newSet[name]; !ok {
|
||||
manifest.Deleted = append(manifest.Deleted, name)
|
||||
}
|
||||
}
|
||||
for name := range newSet {
|
||||
if _, ok := oldSet[name]; !ok {
|
||||
manifest.Added = append(manifest.Added, name)
|
||||
}
|
||||
}
|
||||
for name, newData := range newSet {
|
||||
oldData, ok := oldSet[name]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if !bytes.Equal(oldData, newData) {
|
||||
entry := PatchEntry{Path: name}
|
||||
entry.OldSHA256 = sha256Hex(oldData)
|
||||
entry.NewSHA256 = sha256Hex(newData)
|
||||
|
||||
if isBinaryFile(name) {
|
||||
diff := bsdiff(oldData, newData)
|
||||
entry.DiffSize = int64(len(diff))
|
||||
entry.DiffHash = sha256Hex(diff)
|
||||
}
|
||||
|
||||
manifest.Modified = append(manifest.Modified, entry)
|
||||
} else {
|
||||
manifest.Unchanged++
|
||||
}
|
||||
}
|
||||
|
||||
return writePatchFile(patchPath, &manifest, oldFiles, newFiles, oldSet, newSet)
|
||||
}
|
||||
|
||||
type jarEntry struct {
|
||||
Name string
|
||||
Data []byte
|
||||
}
|
||||
|
||||
func readJarEntries(jarPath string) ([]jarEntry, error) {
|
||||
data, err := os.ReadFile(jarPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
reader, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var entries []jarEntry
|
||||
for _, f := range reader.File {
|
||||
if f.FileInfo().IsDir() {
|
||||
continue
|
||||
}
|
||||
rc, err := f.Open()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
content, err := io.ReadAll(rc)
|
||||
rc.Close()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
entries = append(entries, jarEntry{Name: f.Name, Data: content})
|
||||
}
|
||||
return entries, nil
|
||||
}
|
||||
|
||||
func isBinaryFile(name string) bool {
|
||||
ext := strings.ToLower(filepath.Ext(name))
|
||||
switch ext {
|
||||
case ".class", ".jar", ".war", ".ear":
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func sha256Hex(data []byte) string {
|
||||
h := sha256.Sum256(data)
|
||||
return hex.EncodeToString(h[:])
|
||||
}
|
||||
|
||||
func writePatchFile(patchPath string, manifest *PatchManifest, oldFiles, newFiles []jarEntry, oldSet, newSet map[string][]byte) error {
|
||||
out, err := os.Create(patchPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer out.Close()
|
||||
|
||||
zw := zip.NewWriter(out)
|
||||
defer zw.Close()
|
||||
|
||||
// Write manifest.json
|
||||
manifestData, _ := json.MarshalIndent(manifest, "", " ")
|
||||
w, _ := zw.Create("manifest.json")
|
||||
w.Write(manifestData)
|
||||
|
||||
// Write added files
|
||||
for _, name := range manifest.Added {
|
||||
w, _ := zw.Create("added/" + name)
|
||||
w.Write(newSet[name])
|
||||
}
|
||||
|
||||
// Write modifications (binary diffs)
|
||||
for _, entry := range manifest.Modified {
|
||||
if entry.DiffSize > 0 {
|
||||
oldData := oldSet[entry.Path]
|
||||
newData := newSet[entry.Path]
|
||||
diff := bsdiff(oldData, newData)
|
||||
w, _ := zw.Create("diffs/" + entry.Path + ".bsdiff")
|
||||
w.Write(diff)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// bsdiff produces a simple binary diff between two byte slices.
|
||||
// For production use, integrate a full BSDiff library (e.g. github.com/icedream/bsdiff).
|
||||
func bsdiff(old, new []byte) []byte {
|
||||
// Poor man's binary diff — records differing byte runs.
|
||||
// A production implementation should use a proper BSDiff or VCDIFF library.
|
||||
var buf bytes.Buffer
|
||||
minLen := len(old)
|
||||
if len(new) < minLen {
|
||||
minLen = len(new)
|
||||
}
|
||||
|
||||
// Write header: old size, new size
|
||||
buf.WriteString(fmt.Sprintf("BSDIFF40:%d:%d\n", len(old), len(new)))
|
||||
|
||||
// Record differing chunks
|
||||
chunkStart := -1
|
||||
for i := 0; i < minLen; i++ {
|
||||
if old[i] != new[i] {
|
||||
if chunkStart == -1 {
|
||||
chunkStart = i
|
||||
}
|
||||
} else if chunkStart != -1 {
|
||||
chunk := new[chunkStart:i]
|
||||
buf.Write(encodeChunk(chunkStart, chunk))
|
||||
chunkStart = -1
|
||||
}
|
||||
}
|
||||
if chunkStart != -1 {
|
||||
chunk := new[chunkStart:minLen]
|
||||
buf.Write(encodeChunk(chunkStart, chunk))
|
||||
}
|
||||
|
||||
// Trail: if new is longer, append extra bytes
|
||||
if len(new) > len(old) {
|
||||
buf.Write(encodeChunk(len(old), new[len(old):]))
|
||||
}
|
||||
|
||||
return buf.Bytes()
|
||||
}
|
||||
|
||||
func encodeChunk(offset int, data []byte) []byte {
|
||||
var buf bytes.Buffer
|
||||
buf.WriteString(fmt.Sprintf("@%d+%d:", offset, len(data)))
|
||||
buf.Write(data)
|
||||
buf.WriteByte('\n')
|
||||
return buf.Bytes()
|
||||
}
|
||||
@@ -0,0 +1,302 @@
|
||||
package deployment
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"onixbyte.com/message-converter-manifest/internal/database"
|
||||
"onixbyte.com/message-converter-manifest/internal/model"
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewHandler(db *gorm.DB) *Handler {
|
||||
return &Handler{db: db}
|
||||
}
|
||||
|
||||
func (h *Handler) Create(c *gin.Context) {
|
||||
var req model.CreateDeploymentRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if req.TargetType != model.TargetAll && req.TargetType != model.TargetDevice && req.TargetType != model.TargetGroup {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "targetType must be all, device, or group"})
|
||||
return
|
||||
}
|
||||
|
||||
if req.RolloutStrategy == "" {
|
||||
req.RolloutStrategy = model.RolloutImmediate
|
||||
}
|
||||
if req.MaxConcurrent <= 0 {
|
||||
req.MaxConcurrent = 50
|
||||
}
|
||||
|
||||
_, err := database.GetArtefactByID(h.db, req.ArtefactID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "Artefact not found"})
|
||||
return
|
||||
}
|
||||
|
||||
deployment := &model.Deployment{
|
||||
ArtefactID: req.ArtefactID,
|
||||
Name: req.Name,
|
||||
Description: req.Description,
|
||||
TargetType: req.TargetType,
|
||||
TargetSpec: req.TargetSpec,
|
||||
RolloutStrategy: req.RolloutStrategy,
|
||||
MaxConcurrent: req.MaxConcurrent,
|
||||
Status: model.DeploymentStatusDraft,
|
||||
}
|
||||
|
||||
err = h.db.Transaction(func(tx *gorm.DB) error {
|
||||
if err := database.CreateDeployment(tx, deployment); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
deviceIDs, err := h.resolveTargets(deployment)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return database.CreateDeploymentDevices(tx, deployment.ID, deviceIDs)
|
||||
})
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, deployment)
|
||||
}
|
||||
|
||||
func (h *Handler) resolveTargets(d *model.Deployment) ([]string, error) {
|
||||
switch d.TargetType {
|
||||
case model.TargetAll:
|
||||
devices, _, err := database.ListDevices(h.db, "", "", 1, 100000)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ids := make([]string, len(devices))
|
||||
for i, dev := range devices {
|
||||
ids[i] = dev.DeviceID
|
||||
}
|
||||
return ids, nil
|
||||
|
||||
case model.TargetDevice:
|
||||
var spec struct {
|
||||
DeviceIDs []string `json:"deviceIds"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(d.TargetSpec), &spec); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return spec.DeviceIDs, nil
|
||||
|
||||
case model.TargetGroup:
|
||||
var spec struct {
|
||||
GroupName string `json:"groupName"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(d.TargetSpec), &spec); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
devices, _, err := database.ListDevices(h.db, "", spec.GroupName, 1, 100000)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ids := make([]string, len(devices))
|
||||
for i, dev := range devices {
|
||||
ids[i] = dev.DeviceID
|
||||
}
|
||||
return ids, nil
|
||||
|
||||
default:
|
||||
return nil, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Handler) Activate(c *gin.Context) {
|
||||
id, err := strconv.ParseInt(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid id"})
|
||||
return
|
||||
}
|
||||
|
||||
deployment, err := database.GetDeploymentByID(h.db, id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "Deployment not found"})
|
||||
return
|
||||
}
|
||||
|
||||
if deployment.Status != model.DeploymentStatusDraft {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Only draft deployments can be activated"})
|
||||
return
|
||||
}
|
||||
|
||||
if err := database.UpdateDeploymentStatus(h.db, id, model.DeploymentStatusActive); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
deployment.Status = model.DeploymentStatusActive
|
||||
c.JSON(http.StatusOK, deployment)
|
||||
}
|
||||
|
||||
func (h *Handler) Pause(c *gin.Context) {
|
||||
id, err := strconv.ParseInt(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid id"})
|
||||
return
|
||||
}
|
||||
|
||||
deployment, err := database.GetDeploymentByID(h.db, id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "Deployment not found"})
|
||||
return
|
||||
}
|
||||
|
||||
if deployment.Status != model.DeploymentStatusActive {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Only active deployments can be paused"})
|
||||
return
|
||||
}
|
||||
|
||||
if err := database.UpdateDeploymentStatus(h.db, id, model.DeploymentStatusPaused); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
deployment.Status = model.DeploymentStatusPaused
|
||||
c.JSON(http.StatusOK, deployment)
|
||||
}
|
||||
|
||||
func (h *Handler) List(c *gin.Context) {
|
||||
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
|
||||
pageSize, _ := strconv.Atoi(c.DefaultQuery("pageSize", "20"))
|
||||
status := c.Query("status")
|
||||
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
if pageSize < 1 || pageSize > 100 {
|
||||
pageSize = 20
|
||||
}
|
||||
|
||||
deployments, total, err := database.ListDeployments(h.db, status, page, pageSize)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, model.PaginatedResponse{
|
||||
Data: deployments,
|
||||
Total: total,
|
||||
Page: page,
|
||||
PageSize: pageSize,
|
||||
})
|
||||
}
|
||||
|
||||
func (h *Handler) Get(c *gin.Context) {
|
||||
id, err := strconv.ParseInt(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid id"})
|
||||
return
|
||||
}
|
||||
|
||||
deployment, err := database.GetDeploymentByID(h.db, id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "Deployment not found"})
|
||||
return
|
||||
}
|
||||
|
||||
stats, _ := database.GetDeploymentDeviceStats(h.db, id)
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"deployment": deployment,
|
||||
"stats": stats,
|
||||
})
|
||||
}
|
||||
|
||||
func (h *Handler) ListDevices(c *gin.Context) {
|
||||
id, err := strconv.ParseInt(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid id"})
|
||||
return
|
||||
}
|
||||
|
||||
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
|
||||
pageSize, _ := strconv.Atoi(c.DefaultQuery("pageSize", "50"))
|
||||
status := c.Query("status")
|
||||
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
if pageSize < 1 || pageSize > 200 {
|
||||
pageSize = 50
|
||||
}
|
||||
|
||||
devices, total, err := database.GetDeploymentDevices(h.db, id, status, page, pageSize)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, model.PaginatedResponse{
|
||||
Data: devices,
|
||||
Total: total,
|
||||
Page: page,
|
||||
PageSize: pageSize,
|
||||
})
|
||||
}
|
||||
|
||||
func (h *Handler) Rollback(c *gin.Context) {
|
||||
id, err := strconv.ParseInt(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid deployment id"})
|
||||
return
|
||||
}
|
||||
|
||||
var req struct {
|
||||
DeviceID string `json:"deviceId" binding:"required"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if err := database.UpdateDeploymentDeviceStatus(h.db, id, req.DeviceID, model.DeployDeviceStatusRolledBack, "Rolled back by operator"); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"status": "rolled_back"})
|
||||
}
|
||||
|
||||
func (h *Handler) UpdateStatus(c *gin.Context) {
|
||||
id, err := strconv.ParseInt(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid deployment id"})
|
||||
return
|
||||
}
|
||||
|
||||
var req struct {
|
||||
DeviceID string `json:"deviceId" binding:"required"`
|
||||
Status string `json:"status" binding:"required"`
|
||||
Error string `json:"error"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if err := database.UpdateDeploymentDeviceStatus(h.db, id, req.DeviceID, req.Status, req.Error); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"status": "updated"})
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
package device
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"onixbyte.com/message-converter-manifest/internal/database"
|
||||
"onixbyte.com/message-converter-manifest/internal/model"
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewHandler(db *gorm.DB) *Handler {
|
||||
return &Handler{db: db}
|
||||
}
|
||||
|
||||
func (h *Handler) Register(c *gin.Context) {
|
||||
var req model.RegisterDeviceRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
device := &model.Device{
|
||||
DeviceID: req.DeviceID,
|
||||
IPAddress: req.IPAddress,
|
||||
Hostname: req.Hostname,
|
||||
OS: req.OS,
|
||||
CurrentVersion: req.CurrentVersion,
|
||||
Status: model.DeviceStatusOnline,
|
||||
GroupName: req.GroupName,
|
||||
}
|
||||
if device.GroupName == "" {
|
||||
device.GroupName = "default"
|
||||
}
|
||||
|
||||
if err := database.UpsertDevice(h.db, device); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, device)
|
||||
}
|
||||
|
||||
func (h *Handler) Heartbeat(c *gin.Context) {
|
||||
var req model.HeartbeatRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
status := req.Status
|
||||
if status == "" {
|
||||
status = model.DeviceStatusOnline
|
||||
}
|
||||
|
||||
if err := database.UpdateDeviceHeartbeat(h.db, req.DeviceID, req.CurrentVersion, status); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"status": "acknowledged"})
|
||||
}
|
||||
|
||||
func (h *Handler) CheckUpdate(c *gin.Context) {
|
||||
deviceID := c.Query("deviceId")
|
||||
if deviceID == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "deviceId is required"})
|
||||
return
|
||||
}
|
||||
|
||||
_, artefact, err := database.GetActiveDeploymentForDevice(h.db, deviceID)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
c.JSON(http.StatusOK, model.CheckUpdateResponse{HasUpdate: false})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, model.CheckUpdateResponse{
|
||||
HasUpdate: true,
|
||||
ArtefactID: artefact.ID,
|
||||
Version: artefact.Version,
|
||||
FileSize: artefact.FileSize,
|
||||
SHA256Hash: artefact.SHA256Hash,
|
||||
DownloadURL: "/api/v1/packages/download/" + strconv.FormatInt(artefact.ID, 10),
|
||||
})
|
||||
}
|
||||
|
||||
func (h *Handler) List(c *gin.Context) {
|
||||
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
|
||||
pageSize, _ := strconv.Atoi(c.DefaultQuery("pageSize", "20"))
|
||||
status := c.Query("status")
|
||||
group := c.Query("group")
|
||||
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
if pageSize < 1 || pageSize > 100 {
|
||||
pageSize = 20
|
||||
}
|
||||
|
||||
devices, total, err := database.ListDevices(h.db, status, group, page, pageSize)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, model.PaginatedResponse{
|
||||
Data: devices,
|
||||
Total: total,
|
||||
Page: page,
|
||||
PageSize: pageSize,
|
||||
})
|
||||
}
|
||||
|
||||
func (h *Handler) Get(c *gin.Context) {
|
||||
deviceID := c.Param("deviceId")
|
||||
device, err := database.GetDeviceByID(h.db, deviceID)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "Device not found"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, device)
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
package download
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"onixbyte.com/message-converter-manifest/internal/database"
|
||||
"onixbyte.com/message-converter-manifest/internal/middleware"
|
||||
)
|
||||
|
||||
// Handler manages artefact downloads with bandwidth throttling and Range support.
|
||||
type Handler struct {
|
||||
db *gorm.DB
|
||||
artefactDir string
|
||||
semaphore *middleware.GatedSemaphore
|
||||
bytesPerSec int
|
||||
}
|
||||
|
||||
func NewHandler(db *gorm.DB, artefactDir string, sem *middleware.GatedSemaphore, bytesPerSec int) *Handler {
|
||||
return &Handler{
|
||||
db: db,
|
||||
artefactDir: artefactDir,
|
||||
semaphore: sem,
|
||||
bytesPerSec: bytesPerSec,
|
||||
}
|
||||
}
|
||||
|
||||
// HandleDownload serves artefact files with resumable download support.
|
||||
func (h *Handler) HandleDownload(c *gin.Context) {
|
||||
artefactID, err := strconv.ParseInt(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "Invalid artefact id"})
|
||||
return
|
||||
}
|
||||
|
||||
deviceID := c.Query("deviceId")
|
||||
deploymentID, _ := strconv.ParseInt(c.Query("deploymentId"), 10, 64)
|
||||
|
||||
artefact, err := database.GetArtefactByID(h.db, artefactID)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
c.AbortWithStatusJSON(http.StatusNotFound, gin.H{"error": "Artefact not found"})
|
||||
return
|
||||
}
|
||||
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
file, err := os.Open(artefact.FilePath)
|
||||
if err != nil {
|
||||
c.AbortWithStatusJSON(http.StatusNotFound, gin.H{"error": "Package file not found on disk"})
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
fileInfo, err := file.Stat()
|
||||
if err != nil {
|
||||
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "Failed to stat file"})
|
||||
return
|
||||
}
|
||||
|
||||
// Update device status to downloading
|
||||
if deviceID != "" && deploymentID > 0 {
|
||||
if err := database.UpdateDeploymentDeviceStatus(h.db, deploymentID, deviceID, "downloading", ""); err != nil {
|
||||
log.Printf("[download] Failed to update device status: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Apply per-connection bandwidth throttling
|
||||
throttledWriter := &ThrottledResponseWriter{
|
||||
ResponseWriter: c.Writer,
|
||||
bytesPerSecond: h.bytesPerSec,
|
||||
}
|
||||
c.Writer = throttledWriter
|
||||
|
||||
c.Header("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, artefact.FileName))
|
||||
c.Header("X-Checksum-SHA256", artefact.SHA256Hash)
|
||||
|
||||
http.ServeContent(c.Writer, c.Request, artefact.FileName, fileInfo.ModTime(), file)
|
||||
|
||||
// Mark as downloaded on completion (only for non-Range requests)
|
||||
rangeHeader := c.Request.Header.Get("Range")
|
||||
if deviceID != "" && deploymentID > 0 {
|
||||
if rangeHeader == "" || isCompleteRange(rangeHeader, fileInfo.Size()) {
|
||||
if err := database.UpdateDeploymentDeviceStatus(h.db, deploymentID, deviceID, "downloaded", ""); err != nil {
|
||||
log.Printf("[download] Failed to mark device downloaded: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ThrottledResponseWriter limits write throughput per connection.
|
||||
type ThrottledResponseWriter struct {
|
||||
gin.ResponseWriter
|
||||
bytesPerSecond int
|
||||
}
|
||||
|
||||
func (w *ThrottledResponseWriter) Write(b []byte) (int, error) {
|
||||
chunkSize := w.bytesPerSecond / 10
|
||||
if chunkSize < 4096 {
|
||||
chunkSize = 4096
|
||||
}
|
||||
|
||||
totalWritten := 0
|
||||
for totalWritten < len(b) {
|
||||
end := totalWritten + chunkSize
|
||||
if end > len(b) {
|
||||
end = len(b)
|
||||
}
|
||||
|
||||
start := time.Now()
|
||||
n, err := w.ResponseWriter.Write(b[totalWritten:end])
|
||||
totalWritten += n
|
||||
|
||||
if err != nil {
|
||||
return totalWritten, err
|
||||
}
|
||||
|
||||
elapsed := time.Since(start)
|
||||
expected := time.Duration(n) * time.Second / time.Duration(w.bytesPerSecond)
|
||||
if expected > elapsed {
|
||||
time.Sleep(expected - elapsed)
|
||||
}
|
||||
}
|
||||
|
||||
return totalWritten, nil
|
||||
}
|
||||
|
||||
func isCompleteRange(rangeHeader string, fileSize int64) bool {
|
||||
// Simple check: if range starts at 0 and covers the entire file, it's "complete"
|
||||
// This avoids double-counting full-file requests that use Range: bytes=0-
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package download
|
||||
|
||||
// GlobalDownloadGate wraps a GatedSemaphore for download-specific concurrency control.
|
||||
// See internal/middleware/rate_limit.go for the underlying GatedSemaphore implementation.
|
||||
//
|
||||
// The gate ensures that the total number of concurrent download streams never exceeds
|
||||
// the configured limit (default 50), which keeps total bandwidth usage under 10 Mbps
|
||||
// when each stream is throttled to ~25 KB/s.
|
||||
type GlobalDownloadGate struct {
|
||||
sem chan struct{}
|
||||
}
|
||||
|
||||
func NewGlobalDownloadGate(maxConcurrent int) *GlobalDownloadGate {
|
||||
return &GlobalDownloadGate{sem: make(chan struct{}, maxConcurrent)}
|
||||
}
|
||||
|
||||
func (g *GlobalDownloadGate) Acquire() { g.sem <- struct{}{} }
|
||||
func (g *GlobalDownloadGate) Release() { <-g.sem }
|
||||
func (g *GlobalDownloadGate) Available() int { return cap(g.sem) - len(g.sem) }
|
||||
@@ -0,0 +1,34 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"onixbyte.com/message-converter-manifest/internal/auth"
|
||||
)
|
||||
|
||||
func AuthMiddleware(authSvc *auth.Service) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
authHeader := c.GetHeader("Authorization")
|
||||
if authHeader == "" {
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Authorisation header is missing"})
|
||||
return
|
||||
}
|
||||
|
||||
parts := strings.SplitN(authHeader, " ", 2)
|
||||
if !(len(parts) == 2 && parts[0] == "Bearer") {
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Invalid authorisation format"})
|
||||
return
|
||||
}
|
||||
|
||||
user, err := authSvc.ValidateToken(parts[1])
|
||||
if err != nil {
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Unauthorised: " + err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.Set("user", user)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// TokenBucket implements a token bucket rate limiter per key (e.g. IP or device ID).
|
||||
type TokenBucket struct {
|
||||
mu sync.Mutex
|
||||
buckets map[string]*bucket
|
||||
rate float64 // tokens per second
|
||||
capacity float64
|
||||
}
|
||||
|
||||
type bucket struct {
|
||||
tokens float64
|
||||
lastFill time.Time
|
||||
}
|
||||
|
||||
func NewTokenBucket(rate, capacity int) *TokenBucket {
|
||||
return &TokenBucket{
|
||||
buckets: make(map[string]*bucket),
|
||||
rate: float64(rate),
|
||||
capacity: float64(capacity),
|
||||
}
|
||||
}
|
||||
|
||||
func (tb *TokenBucket) Allow(key string) bool {
|
||||
tb.mu.Lock()
|
||||
defer tb.mu.Unlock()
|
||||
|
||||
b, ok := tb.buckets[key]
|
||||
if !ok {
|
||||
b = &bucket{tokens: tb.capacity, lastFill: time.Now()}
|
||||
tb.buckets[key] = b
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
elapsed := now.Sub(b.lastFill).Seconds()
|
||||
b.tokens += elapsed * tb.rate
|
||||
if b.tokens > tb.capacity {
|
||||
b.tokens = tb.capacity
|
||||
}
|
||||
b.lastFill = now
|
||||
|
||||
if b.tokens >= 1 {
|
||||
b.tokens--
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Cleanup removes stale buckets older than the given duration.
|
||||
func (tb *TokenBucket) Cleanup(maxAge time.Duration) {
|
||||
tb.mu.Lock()
|
||||
defer tb.mu.Unlock()
|
||||
|
||||
now := time.Now()
|
||||
for k, b := range tb.buckets {
|
||||
if now.Sub(b.lastFill) > maxAge {
|
||||
delete(tb.buckets, k)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// RateLimitMiddleware returns a Gin middleware that rate-limits requests per client IP.
|
||||
func RateLimitMiddleware(tb *TokenBucket) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
ip := c.ClientIP()
|
||||
if !tb.Allow(ip) {
|
||||
c.AbortWithStatusJSON(429, gin.H{"error": "Rate limit exceeded. Please slow down."})
|
||||
return
|
||||
}
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// GatedSemaphore limits the number of concurrent operations (e.g. downloads).
|
||||
type GatedSemaphore struct {
|
||||
ch chan struct{}
|
||||
}
|
||||
|
||||
func NewGatedSemaphore(maxConcurrent int) *GatedSemaphore {
|
||||
return &GatedSemaphore{ch: make(chan struct{}, maxConcurrent)}
|
||||
}
|
||||
|
||||
func (gs *GatedSemaphore) Acquire() {
|
||||
gs.ch <- struct{}{}
|
||||
}
|
||||
|
||||
func (gs *GatedSemaphore) Release() {
|
||||
<-gs.ch
|
||||
}
|
||||
|
||||
func (gs *GatedSemaphore) Available() int {
|
||||
return cap(gs.ch) - len(gs.ch)
|
||||
}
|
||||
|
||||
// GatedMiddleware only allows requests through if the semaphore has capacity.
|
||||
func GatedMiddleware(gs *GatedSemaphore) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
select {
|
||||
case gs.ch <- struct{}{}:
|
||||
defer func() { <-gs.ch }()
|
||||
c.Next()
|
||||
default:
|
||||
c.AbortWithStatusJSON(503, gin.H{"error": "Server at capacity. Please retry later."})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// Device status constants
|
||||
const (
|
||||
DeviceStatusOnline = "online"
|
||||
DeviceStatusOffline = "offline"
|
||||
DeviceStatusUpgrading = "upgrading"
|
||||
)
|
||||
|
||||
// Deployment status constants
|
||||
const (
|
||||
DeploymentStatusDraft = "draft"
|
||||
DeploymentStatusActive = "active"
|
||||
DeploymentStatusPaused = "paused"
|
||||
DeploymentStatusCompleted = "completed"
|
||||
DeploymentStatusCancelled = "cancelled"
|
||||
)
|
||||
|
||||
// Deployment device status constants
|
||||
const (
|
||||
DeployDeviceStatusPending = "pending"
|
||||
DeployDeviceStatusDownloading = "downloading"
|
||||
DeployDeviceStatusDownloaded = "downloaded"
|
||||
DeployDeviceStatusVerifying = "verifying"
|
||||
DeployDeviceStatusInstalling = "installing"
|
||||
DeployDeviceStatusCompleted = "completed"
|
||||
DeployDeviceStatusFailed = "failed"
|
||||
DeployDeviceStatusRolledBack = "rolled_back"
|
||||
)
|
||||
|
||||
// Rollout strategy constants
|
||||
const (
|
||||
RolloutImmediate = "immediate"
|
||||
RolloutStaged = "staged"
|
||||
)
|
||||
|
||||
// Target type constants
|
||||
const (
|
||||
TargetAll = "all"
|
||||
TargetDevice = "device"
|
||||
TargetGroup = "group"
|
||||
)
|
||||
|
||||
// Device represents a connected daemon instance.
|
||||
type Device struct {
|
||||
ID int64 `json:"id" gorm:"primaryKey;autoIncrement"`
|
||||
DeviceID string `json:"deviceId" gorm:"uniqueIndex;size:256;not null"`
|
||||
IPAddress string `json:"ipAddress" gorm:"size:64;default:''"`
|
||||
Hostname string `json:"hostname" gorm:"size:256;default:''"`
|
||||
OS string `json:"os" gorm:"size:64;default:''"`
|
||||
CurrentVersion string `json:"currentVersion" gorm:"size:128;default:'0.0.0'"`
|
||||
Status string `json:"status" gorm:"size:32;default:'online';index"`
|
||||
GroupName string `json:"groupName" gorm:"size:128;default:'default';index"`
|
||||
LastHeartbeat time.Time `json:"lastHeartbeat"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
}
|
||||
|
||||
// Artefact represents an uploaded update package (JAR or patch).
|
||||
type Artefact struct {
|
||||
ID int64 `json:"id" gorm:"primaryKey;autoIncrement"`
|
||||
Version string `json:"version" gorm:"size:128;not null;index"`
|
||||
FileName string `json:"fileName" gorm:"size:512;not null"`
|
||||
FilePath string `json:"-" gorm:"size:1024;not null"`
|
||||
FileSize int64 `json:"fileSize"`
|
||||
SHA256Hash string `json:"sha256Hash" gorm:"size:128"`
|
||||
DeltaRef string `json:"deltaRef" gorm:"size:128;default:''"`
|
||||
IsDelta bool `json:"isDelta"`
|
||||
Metadata string `json:"metadata" gorm:"type:text;default:'{}'"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
}
|
||||
|
||||
// Deployment defines an update rollout campaign.
|
||||
type Deployment struct {
|
||||
ID int64 `json:"id" gorm:"primaryKey;autoIncrement"`
|
||||
ArtefactID int64 `json:"artefactId" gorm:"not null;index"`
|
||||
Artefact *Artefact `json:"artefact,omitempty" gorm:"foreignKey:ArtefactID"`
|
||||
Name string `json:"name" gorm:"size:256;not null"`
|
||||
Description string `json:"description" gorm:"type:text;default:''"`
|
||||
TargetType string `json:"targetType" gorm:"size:32;default:'all'"`
|
||||
TargetSpec string `json:"targetSpec" gorm:"type:text;default:'{}'"`
|
||||
RolloutStrategy string `json:"rolloutStrategy" gorm:"size:32;default:'immediate'"`
|
||||
MaxConcurrent int `json:"maxConcurrent" gorm:"default:50"`
|
||||
Status string `json:"status" gorm:"size:32;default:'draft';index"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
}
|
||||
|
||||
// DeploymentDevice tracks an individual device's progress through a deployment.
|
||||
type DeploymentDevice struct {
|
||||
ID int64 `json:"id" gorm:"primaryKey;autoIncrement"`
|
||||
DeploymentID int64 `json:"deploymentId" gorm:"not null;uniqueIndex:idx_dd_dep_dev;index"`
|
||||
DeviceID string `json:"deviceId" gorm:"size:256;not null;uniqueIndex:idx_dd_dep_dev;index"`
|
||||
Status string `json:"status" gorm:"size:32;default:'pending';index"`
|
||||
DownloadedAt *time.Time `json:"downloadedAt"`
|
||||
CompletedAt *time.Time `json:"completedAt"`
|
||||
Error string `json:"error" gorm:"type:text;default:''"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
}
|
||||
|
||||
// AdminUser represents an operator account.
|
||||
type AdminUser struct {
|
||||
ID int64 `json:"id" gorm:"primaryKey;autoIncrement"`
|
||||
Username string `json:"username" gorm:"uniqueIndex;size:128;not null"`
|
||||
PasswordHash string `json:"-" gorm:"size:256;not null"`
|
||||
Role string `json:"role" gorm:"size:32;default:'admin'"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
}
|
||||
|
||||
// -- Request/Response DTOs --
|
||||
|
||||
type LoginRequest struct {
|
||||
Username string `json:"username" binding:"required"`
|
||||
Password string `json:"password" binding:"required"`
|
||||
}
|
||||
|
||||
type LoginResponse struct {
|
||||
Token string `json:"token"`
|
||||
ExpiresAt int64 `json:"expiresAt"`
|
||||
}
|
||||
|
||||
type RegisterDeviceRequest struct {
|
||||
DeviceID string `json:"deviceId" binding:"required"`
|
||||
IPAddress string `json:"ipAddress"`
|
||||
Hostname string `json:"hostname"`
|
||||
OS string `json:"os"`
|
||||
CurrentVersion string `json:"currentVersion"`
|
||||
GroupName string `json:"groupName"`
|
||||
}
|
||||
|
||||
type HeartbeatRequest struct {
|
||||
DeviceID string `json:"deviceId" binding:"required"`
|
||||
CurrentVersion string `json:"currentVersion"`
|
||||
Status string `json:"status"`
|
||||
}
|
||||
|
||||
type CheckUpdateResponse struct {
|
||||
HasUpdate bool `json:"hasUpdate"`
|
||||
ArtefactID int64 `json:"artefactId,omitempty"`
|
||||
Version string `json:"version,omitempty"`
|
||||
FileSize int64 `json:"fileSize,omitempty"`
|
||||
SHA256Hash string `json:"sha256Hash,omitempty"`
|
||||
DownloadURL string `json:"downloadUrl,omitempty"`
|
||||
}
|
||||
|
||||
type CreateDeploymentRequest struct {
|
||||
ArtefactID int64 `json:"artefactId" binding:"required"`
|
||||
Name string `json:"name" binding:"required"`
|
||||
Description string `json:"description"`
|
||||
TargetType string `json:"targetType" binding:"required"`
|
||||
TargetSpec string `json:"targetSpec"`
|
||||
RolloutStrategy string `json:"rolloutStrategy"`
|
||||
MaxConcurrent int `json:"maxConcurrent"`
|
||||
}
|
||||
|
||||
type PaginatedResponse struct {
|
||||
Data interface{} `json:"data"`
|
||||
Total int64 `json:"total"`
|
||||
Page int `json:"page"`
|
||||
PageSize int `json:"pageSize"`
|
||||
}
|
||||
|
||||
// -- Hooks --
|
||||
|
||||
func (d *Device) BeforeCreate(tx *gorm.DB) error {
|
||||
now := time.Now()
|
||||
if d.LastHeartbeat.IsZero() {
|
||||
d.LastHeartbeat = now
|
||||
}
|
||||
if d.CreatedAt.IsZero() {
|
||||
d.CreatedAt = now
|
||||
}
|
||||
if d.UpdatedAt.IsZero() {
|
||||
d.UpdatedAt = now
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
-- 001_initial_schema.sql
|
||||
CREATE TABLE IF NOT EXISTS admin_users (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
username VARCHAR(128) NOT NULL UNIQUE,
|
||||
password_hash VARCHAR(256) NOT NULL,
|
||||
role VARCHAR(32) NOT NULL DEFAULT 'admin',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS devices (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
device_id VARCHAR(256) NOT NULL UNIQUE,
|
||||
ip_address VARCHAR(64) NOT NULL DEFAULT '',
|
||||
hostname VARCHAR(256) NOT NULL DEFAULT '',
|
||||
os VARCHAR(64) NOT NULL DEFAULT '',
|
||||
current_version VARCHAR(128) NOT NULL DEFAULT '0.0.0',
|
||||
status VARCHAR(32) NOT NULL DEFAULT 'online',
|
||||
group_name VARCHAR(128) NOT NULL DEFAULT 'default',
|
||||
last_heartbeat TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_devices_status ON devices(status);
|
||||
CREATE INDEX IF NOT EXISTS idx_devices_group ON devices(group_name);
|
||||
CREATE INDEX IF NOT EXISTS idx_devices_heartbeat ON devices(last_heartbeat);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS artefacts (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
version VARCHAR(128) NOT NULL,
|
||||
file_name VARCHAR(512) NOT NULL,
|
||||
file_path VARCHAR(1024) NOT NULL,
|
||||
file_size BIGINT NOT NULL DEFAULT 0,
|
||||
sha256_hash VARCHAR(128) NOT NULL DEFAULT '',
|
||||
delta_ref VARCHAR(128) NOT NULL DEFAULT '',
|
||||
is_delta BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
metadata TEXT NOT NULL DEFAULT '{}',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_artefacts_version ON artefacts(version);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS deployments (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
artefact_id BIGINT NOT NULL REFERENCES artefacts(id),
|
||||
name VARCHAR(256) NOT NULL,
|
||||
description TEXT NOT NULL DEFAULT '',
|
||||
target_type VARCHAR(32) NOT NULL DEFAULT 'all',
|
||||
target_spec TEXT NOT NULL DEFAULT '{}',
|
||||
rollout_strategy VARCHAR(32) NOT NULL DEFAULT 'immediate',
|
||||
max_concurrent INT NOT NULL DEFAULT 50,
|
||||
status VARCHAR(32) NOT NULL DEFAULT 'draft',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_deployments_status ON deployments(status);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS deployment_devices (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
deployment_id BIGINT NOT NULL REFERENCES deployments(id) ON DELETE CASCADE,
|
||||
device_id VARCHAR(256) NOT NULL,
|
||||
status VARCHAR(32) NOT NULL DEFAULT 'pending',
|
||||
downloaded_at TIMESTAMPTZ,
|
||||
completed_at TIMESTAMPTZ,
|
||||
error TEXT NOT NULL DEFAULT '',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
UNIQUE(deployment_id, device_id)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_dd_device ON deployment_devices(device_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_dd_status ON deployment_devices(status);
|
||||
CREATE INDEX IF NOT EXISTS idx_dd_deploy ON deployment_devices(deployment_id);
|
||||
@@ -0,0 +1,24 @@
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
node_modules
|
||||
dist
|
||||
dist-ssr
|
||||
*.local
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
.DS_Store
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
@@ -0,0 +1,24 @@
|
||||
printWidth: 100
|
||||
tabWidth: 2
|
||||
useTabs: false
|
||||
semi: false
|
||||
singleQuote: false
|
||||
quoteProps: as-needed
|
||||
jsxSingleQuote: false
|
||||
trailingComma: es5
|
||||
bracketSpacing: true
|
||||
bracketSameLine: true
|
||||
arrowParens: always
|
||||
#rangeStart: 0
|
||||
#rangeEnd: n
|
||||
#parser:
|
||||
#filepath:
|
||||
#requirePragma: false
|
||||
#insertPragma: false
|
||||
#proseWrap: preserve
|
||||
htmlWhitespaceSensitivity: css
|
||||
#vueIndentScriptAndStyle: false
|
||||
endOfLine: lf
|
||||
#embeddedLanguageFormatting: auto
|
||||
# Enforce single attribute per line in HTML, Vue and JSX
|
||||
#singleAttributePerLine: false
|
||||
@@ -0,0 +1,75 @@
|
||||
# React + TypeScript + Vite
|
||||
|
||||
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
|
||||
|
||||
Currently, two official plugins are available:
|
||||
|
||||
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Oxc](https://oxc.rs)
|
||||
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/)
|
||||
|
||||
## React Compiler
|
||||
|
||||
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
|
||||
|
||||
## Expanding the ESLint configuration
|
||||
|
||||
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
|
||||
|
||||
```js
|
||||
export default defineConfig([
|
||||
globalIgnores(['dist']),
|
||||
{
|
||||
files: ['**/*.{ts,tsx}'],
|
||||
extends: [
|
||||
// Other configs...
|
||||
|
||||
// Remove tseslint.configs.recommended and replace with this
|
||||
tseslint.configs.recommendedTypeChecked,
|
||||
// Alternatively, use this for stricter rules
|
||||
tseslint.configs.strictTypeChecked,
|
||||
// Optionally, add this for stylistic rules
|
||||
tseslint.configs.stylisticTypeChecked,
|
||||
|
||||
// Other configs...
|
||||
],
|
||||
languageOptions: {
|
||||
parserOptions: {
|
||||
project: ['./tsconfig.node.json', './tsconfig.app.json'],
|
||||
tsconfigRootDir: import.meta.dirname,
|
||||
},
|
||||
// other options...
|
||||
},
|
||||
},
|
||||
])
|
||||
|
||||
```
|
||||
|
||||
You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
|
||||
|
||||
```js
|
||||
// eslint.config.js
|
||||
import reactX from 'eslint-plugin-react-x'
|
||||
import reactDom from 'eslint-plugin-react-dom'
|
||||
|
||||
export default defineConfig([
|
||||
globalIgnores(['dist']),
|
||||
{
|
||||
files: ['**/*.{ts,tsx}'],
|
||||
extends: [
|
||||
// Other configs...
|
||||
// Enable lint rules for React
|
||||
reactX.configs['recommended-typescript'],
|
||||
// Enable lint rules for React DOM
|
||||
reactDom.configs.recommended,
|
||||
],
|
||||
languageOptions: {
|
||||
parserOptions: {
|
||||
project: ['./tsconfig.node.json', './tsconfig.app.json'],
|
||||
tsconfigRootDir: import.meta.dirname,
|
||||
},
|
||||
// other options...
|
||||
},
|
||||
},
|
||||
])
|
||||
|
||||
```
|
||||
@@ -0,0 +1,22 @@
|
||||
import js from '@eslint/js'
|
||||
import globals from 'globals'
|
||||
import reactHooks from 'eslint-plugin-react-hooks'
|
||||
import reactRefresh from 'eslint-plugin-react-refresh'
|
||||
import tseslint from 'typescript-eslint'
|
||||
import { defineConfig, globalIgnores } from 'eslint/config'
|
||||
|
||||
export default defineConfig([
|
||||
globalIgnores(['dist']),
|
||||
{
|
||||
files: ['**/*.{ts,tsx}'],
|
||||
extends: [
|
||||
js.configs.recommended,
|
||||
tseslint.configs.recommended,
|
||||
reactHooks.configs.flat.recommended,
|
||||
reactRefresh.configs.vite,
|
||||
],
|
||||
languageOptions: {
|
||||
globals: globals.browser,
|
||||
},
|
||||
},
|
||||
])
|
||||
@@ -0,0 +1,13 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>web</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,33 @@
|
||||
{
|
||||
"name": "web",
|
||||
"private": true,
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc -b && vite build",
|
||||
"lint": "eslint .",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"react": "^19.2.7",
|
||||
"react-dom": "^19.2.7",
|
||||
"react-router-dom": "^7.18.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^10.0.1",
|
||||
"@types/node": "^24.13.2",
|
||||
"@types/react": "^19.2.17",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"@vitejs/plugin-react": "^6.0.3",
|
||||
"eslint": "^10.6.0",
|
||||
"eslint-plugin-react-hooks": "^7.1.1",
|
||||
"eslint-plugin-react-refresh": "^0.5.3",
|
||||
"globals": "^17.7.0",
|
||||
"prettier": "^3.9.4",
|
||||
"typescript": "~6.0.2",
|
||||
"typescript-eslint": "^8.62.0",
|
||||
"vite": "^8.1.1",
|
||||
"vite-plugin-port-checker": "^1.0.2"
|
||||
}
|
||||
}
|
||||
Generated
+1785
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
|
After Width: | Height: | Size: 9.3 KiB |
@@ -0,0 +1,24 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg">
|
||||
<symbol id="bluesky-icon" viewBox="0 0 16 17">
|
||||
<g clip-path="url(#bluesky-clip)"><path fill="#08060d" d="M7.75 7.735c-.693-1.348-2.58-3.86-4.334-5.097-1.68-1.187-2.32-.981-2.74-.79C.188 2.065.1 2.812.1 3.251s.241 3.602.398 4.13c.52 1.744 2.367 2.333 4.07 2.145-2.495.37-4.71 1.278-1.805 4.512 3.196 3.309 4.38-.71 4.987-2.746.608 2.036 1.307 5.91 4.93 2.746 2.72-2.746.747-4.143-1.747-4.512 1.702.189 3.55-.4 4.07-2.145.156-.528.397-3.691.397-4.13s-.088-1.186-.575-1.406c-.42-.19-1.06-.395-2.741.79-1.755 1.24-3.64 3.752-4.334 5.099"/></g>
|
||||
<defs><clipPath id="bluesky-clip"><path fill="#fff" d="M.1.85h15.3v15.3H.1z"/></clipPath></defs>
|
||||
</symbol>
|
||||
<symbol id="discord-icon" viewBox="0 0 20 19">
|
||||
<path fill="#08060d" d="M16.224 3.768a14.5 14.5 0 0 0-3.67-1.153c-.158.286-.343.67-.47.976a13.5 13.5 0 0 0-4.067 0c-.128-.306-.317-.69-.476-.976A14.4 14.4 0 0 0 3.868 3.77C1.546 7.28.916 10.703 1.231 14.077a14.7 14.7 0 0 0 4.5 2.306q.545-.748.965-1.587a9.5 9.5 0 0 1-1.518-.74q.191-.14.372-.293c2.927 1.369 6.107 1.369 8.999 0q.183.152.372.294-.723.437-1.52.74.418.838.963 1.588a14.6 14.6 0 0 0 4.504-2.308c.37-3.911-.63-7.302-2.644-10.309m-9.13 8.234c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.894 0 1.614.82 1.599 1.82.001 1-.705 1.82-1.6 1.82m5.91 0c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.893 0 1.614.82 1.599 1.82 0 1-.706 1.82-1.6 1.82"/>
|
||||
</symbol>
|
||||
<symbol id="documentation-icon" viewBox="0 0 21 20">
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="m15.5 13.333 1.533 1.322c.645.555.967.833.967 1.178s-.322.623-.967 1.179L15.5 18.333m-3.333-5-1.534 1.322c-.644.555-.966.833-.966 1.178s.322.623.966 1.179l1.534 1.321"/>
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M17.167 10.836v-4.32c0-1.41 0-2.117-.224-2.68-.359-.906-1.118-1.621-2.08-1.96-.599-.21-1.349-.21-2.848-.21-2.623 0-3.935 0-4.983.369-1.684.591-3.013 1.842-3.641 3.428C3 6.449 3 7.684 3 10.154v2.122c0 2.558 0 3.838.706 4.726q.306.383.713.671c.76.536 1.79.64 3.581.66"/>
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M3 10a2.78 2.78 0 0 1 2.778-2.778c.555 0 1.209.097 1.748-.047.48-.129.854-.503.982-.982.145-.54.048-1.194.048-1.749a2.78 2.78 0 0 1 2.777-2.777"/>
|
||||
</symbol>
|
||||
<symbol id="github-icon" viewBox="0 0 19 19">
|
||||
<path fill="#08060d" fill-rule="evenodd" d="M9.356 1.85C5.05 1.85 1.57 5.356 1.57 9.694a7.84 7.84 0 0 0 5.324 7.44c.387.079.528-.168.528-.376 0-.182-.013-.805-.013-1.454-2.165.467-2.616-.935-2.616-.935-.349-.91-.864-1.143-.864-1.143-.71-.48.051-.48.051-.48.787.051 1.2.805 1.2.805.695 1.194 1.817.857 2.268.649.064-.507.27-.857.49-1.052-1.728-.182-3.545-.857-3.545-3.87 0-.857.31-1.558.8-2.104-.078-.195-.349-1 .077-2.078 0 0 .657-.208 2.14.805a7.5 7.5 0 0 1 1.946-.26c.657 0 1.328.092 1.946.26 1.483-1.013 2.14-.805 2.14-.805.426 1.078.155 1.883.078 2.078.502.546.799 1.247.799 2.104 0 3.013-1.818 3.675-3.558 3.87.284.247.528.714.528 1.454 0 1.052-.012 1.896-.012 2.156 0 .208.142.455.528.377a7.84 7.84 0 0 0 5.324-7.441c.013-4.338-3.48-7.844-7.773-7.844" clip-rule="evenodd"/>
|
||||
</symbol>
|
||||
<symbol id="social-icon" viewBox="0 0 20 20">
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M12.5 6.667a4.167 4.167 0 1 0-8.334 0 4.167 4.167 0 0 0 8.334 0"/>
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M2.5 16.667a5.833 5.833 0 0 1 8.75-5.053m3.837.474.513 1.035c.07.144.257.282.414.309l.93.155c.596.1.736.536.307.965l-.723.73a.64.64 0 0 0-.152.531l.207.903c.164.715-.213.991-.84.618l-.872-.52a.63.63 0 0 0-.577 0l-.872.52c-.624.373-1.003.094-.84-.618l.207-.903a.64.64 0 0 0-.152-.532l-.723-.729c-.426-.43-.289-.864.306-.964l.93-.156a.64.64 0 0 0 .412-.31l.513-1.034c.28-.562.735-.562 1.012 0"/>
|
||||
</symbol>
|
||||
<symbol id="x-icon" viewBox="0 0 19 19">
|
||||
<path fill="#08060d" fill-rule="evenodd" d="M1.893 1.98c.052.072 1.245 1.769 2.653 3.77l2.892 4.114c.183.261.333.48.333.486s-.068.089-.152.183l-.522.593-.765.867-3.597 4.087c-.375.426-.734.834-.798.905a1 1 0 0 0-.118.148c0 .01.236.017.664.017h.663l.729-.83c.4-.457.796-.906.879-.999a692 692 0 0 0 1.794-2.038c.034-.037.301-.34.594-.675l.551-.624.345-.392a7 7 0 0 1 .34-.374c.006 0 .93 1.306 2.052 2.903l2.084 2.965.045.063h2.275c1.87 0 2.273-.003 2.266-.021-.008-.02-1.098-1.572-3.894-5.547-2.013-2.862-2.28-3.246-2.273-3.266.008-.019.282-.332 2.085-2.38l2-2.274 1.567-1.782c.022-.028-.016-.03-.65-.03h-.674l-.3.342a871 871 0 0 1-1.782 2.025c-.067.075-.405.458-.75.852a100 100 0 0 1-.803.91c-.148.172-.299.344-.99 1.127-.304.343-.32.358-.345.327-.015-.019-.904-1.282-1.976-2.808L6.365 1.85H1.8zm1.782.91 8.078 11.294c.772 1.08 1.413 1.973 1.425 1.984.016.017.241.02 1.05.017l1.03-.004-2.694-3.766L7.796 5.75 5.722 2.852l-1.039-.004-1.039-.004z" clip-rule="evenodd"/>
|
||||
</symbol>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 4.9 KiB |
+126
@@ -0,0 +1,126 @@
|
||||
/* Reset & base */
|
||||
*,
|
||||
*::before,
|
||||
*::after {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
|
||||
background: #f5f5f7;
|
||||
color: #1a1a2e;
|
||||
}
|
||||
|
||||
#root {
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
/* Shared card style */
|
||||
.card {
|
||||
background: #fff;
|
||||
border-radius: 8px;
|
||||
padding: 20px;
|
||||
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
/* Shared table style */
|
||||
.data-table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.data-table thead {
|
||||
background: #f8f9fa;
|
||||
}
|
||||
|
||||
.data-table th {
|
||||
padding: 10px 12px;
|
||||
text-align: left;
|
||||
font-weight: 600;
|
||||
color: #555;
|
||||
border-bottom: 2px solid #e9ecef;
|
||||
}
|
||||
|
||||
.data-table td {
|
||||
padding: 10px 12px;
|
||||
border-bottom: 1px solid #f0f0f0;
|
||||
}
|
||||
|
||||
.data-table tbody tr:hover {
|
||||
background: #f8f9ff;
|
||||
}
|
||||
|
||||
.td-empty {
|
||||
text-align: center;
|
||||
color: #aaa;
|
||||
padding: 30px 12px !important;
|
||||
}
|
||||
|
||||
/* Shared pagination */
|
||||
.pagination {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 12px;
|
||||
padding: 12px 0 0;
|
||||
font-size: 13px;
|
||||
color: #666;
|
||||
}
|
||||
|
||||
.pagination button {
|
||||
padding: 4px 12px;
|
||||
border: 1px solid #ddd;
|
||||
border-radius: 4px;
|
||||
background: #fff;
|
||||
cursor: pointer;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.pagination button:disabled {
|
||||
opacity: 0.4;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
/* Shared utility */
|
||||
.page-title {
|
||||
margin: 0 0 24px;
|
||||
font-size: 20px;
|
||||
color: #1a1a2e;
|
||||
}
|
||||
|
||||
.page-loading {
|
||||
padding: 40px;
|
||||
color: #888;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
padding: 10px 20px;
|
||||
background: #e94560;
|
||||
color: #fff;
|
||||
border: none;
|
||||
border-radius: 4px;
|
||||
font-size: 14px;
|
||||
cursor: pointer;
|
||||
transition: background 0.15s;
|
||||
}
|
||||
|
||||
.btn-primary:hover {
|
||||
background: #d63850;
|
||||
}
|
||||
|
||||
.btn-primary:disabled {
|
||||
background: #ccc;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.btn-sm {
|
||||
width: auto;
|
||||
padding: 8px 16px;
|
||||
}
|
||||
|
||||
.msg-success { color: #27ae60; font-size: 13px; margin: 8px 0; }
|
||||
.msg-error { color: #c00; font-size: 13px; margin: 8px 0; }
|
||||
@@ -0,0 +1,36 @@
|
||||
import { BrowserRouter, Routes, Route, Navigate } from "react-router-dom"
|
||||
import Layout from "@/components/Layout"
|
||||
import Login from "@/pages/Login"
|
||||
import Dashboard from "@/pages/Dashboard"
|
||||
import Artefacts from "@/pages/Artefacts"
|
||||
import Deployments from "@/pages/Deployments"
|
||||
import Users from "@/pages/Users"
|
||||
import "@/App.css"
|
||||
|
||||
function RequireAuth({ children }: { children: React.ReactNode }) {
|
||||
const token = localStorage.getItem("token")
|
||||
if (!token) return <Navigate to="/" replace />
|
||||
return <>{children}</>
|
||||
}
|
||||
|
||||
export default function App() {
|
||||
return (
|
||||
<BrowserRouter>
|
||||
<Routes>
|
||||
<Route path="/" element={<Login />} />
|
||||
<Route
|
||||
element={
|
||||
<RequireAuth>
|
||||
<Layout />
|
||||
</RequireAuth>
|
||||
}>
|
||||
<Route path="/dashboard" element={<Dashboard />} />
|
||||
<Route path="/artefacts" element={<Artefacts />} />
|
||||
<Route path="/deployments" element={<Deployments />} />
|
||||
<Route path="/users" element={<Users />} />
|
||||
</Route>
|
||||
<Route path="*" element={<Navigate to="/" replace />} />
|
||||
</Routes>
|
||||
</BrowserRouter>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
const API_BASE = '/api/v1';
|
||||
|
||||
let token: string | null = localStorage.getItem('token');
|
||||
|
||||
export function setToken(t: string | null) {
|
||||
token = t;
|
||||
if (t) {
|
||||
localStorage.setItem('token', t);
|
||||
} else {
|
||||
localStorage.removeItem('token');
|
||||
}
|
||||
}
|
||||
|
||||
export function getToken(): string | null {
|
||||
return token;
|
||||
}
|
||||
|
||||
async function request<T>(path: string, options: RequestInit = {}): Promise<T> {
|
||||
const headers: Record<string, string> = {
|
||||
...(options.headers as Record<string, string>),
|
||||
};
|
||||
|
||||
if (token) {
|
||||
headers['Authorization'] = `Bearer ${token}`;
|
||||
}
|
||||
|
||||
// Only set Content-Type for non-GET requests with body
|
||||
if (!(options.body instanceof FormData)) {
|
||||
headers['Content-Type'] = 'application/json';
|
||||
} else {
|
||||
delete headers['Content-Type']; // Let browser set multipart boundary
|
||||
}
|
||||
|
||||
const res = await fetch(`${API_BASE}${path}`, {
|
||||
...options,
|
||||
headers,
|
||||
});
|
||||
|
||||
if (res.status === 401) {
|
||||
setToken(null);
|
||||
window.location.href = '/';
|
||||
throw new Error('Unauthorised');
|
||||
}
|
||||
|
||||
if (!res.ok) {
|
||||
const body = await res.json().catch(() => ({ error: res.statusText }));
|
||||
throw new Error(body.error || `Request failed: ${res.status}`);
|
||||
}
|
||||
|
||||
return res.json();
|
||||
}
|
||||
|
||||
export const api = {
|
||||
get: <T>(path: string) => request<T>(path),
|
||||
|
||||
post: <T>(path: string, body?: unknown) =>
|
||||
request<T>(path, {
|
||||
method: 'POST',
|
||||
body: body instanceof FormData ? body : JSON.stringify(body),
|
||||
}),
|
||||
|
||||
put: <T>(path: string, body?: unknown) =>
|
||||
request<T>(path, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify(body),
|
||||
}),
|
||||
|
||||
delete: <T>(path: string) =>
|
||||
request<T>(path, { method: 'DELETE' }),
|
||||
};
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 13 KiB |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>
|
||||
|
After Width: | Height: | Size: 4.0 KiB |
File diff suppressed because one or more lines are too long
|
After Width: | Height: | Size: 8.5 KiB |
@@ -0,0 +1,79 @@
|
||||
.app-layout {
|
||||
display: flex;
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
.sidebar {
|
||||
width: 220px;
|
||||
background: #1a1a2e;
|
||||
color: #e0e0e0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
padding: 0;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.sidebar-brand {
|
||||
padding: 20px 16px;
|
||||
border-bottom: 1px solid #16213e;
|
||||
}
|
||||
|
||||
.sidebar-brand h2 {
|
||||
margin: 0;
|
||||
font-size: 16px;
|
||||
color: #e94560;
|
||||
letter-spacing: 1px;
|
||||
}
|
||||
|
||||
.sidebar nav {
|
||||
flex: 1;
|
||||
padding: 12px 0;
|
||||
}
|
||||
|
||||
.nav-link {
|
||||
display: block;
|
||||
padding: 10px 20px;
|
||||
color: #a0a0b8;
|
||||
text-decoration: none;
|
||||
font-size: 14px;
|
||||
transition: background 0.15s, color 0.15s;
|
||||
}
|
||||
|
||||
.nav-link:hover {
|
||||
background: #16213e;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.nav-link.active {
|
||||
background: #e94560;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.sidebar-footer {
|
||||
padding: 16px;
|
||||
border-top: 1px solid #16213e;
|
||||
}
|
||||
|
||||
.btn-logout {
|
||||
width: 100%;
|
||||
padding: 8px;
|
||||
background: transparent;
|
||||
border: 1px solid #e94560;
|
||||
color: #e94560;
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
font-size: 13px;
|
||||
transition: background 0.15s, color 0.15s;
|
||||
}
|
||||
|
||||
.btn-logout:hover {
|
||||
background: #e94560;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.content {
|
||||
flex: 1;
|
||||
padding: 24px 32px;
|
||||
background: #f5f5f7;
|
||||
overflow-y: auto;
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { NavLink, useNavigate, Outlet } from 'react-router-dom';
|
||||
import { setToken } from '../api/client';
|
||||
import './Layout.css';
|
||||
|
||||
export default function Layout() {
|
||||
const navigate = useNavigate();
|
||||
|
||||
function handleLogout() {
|
||||
setToken(null);
|
||||
navigate('/');
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="app-layout">
|
||||
<aside className="sidebar">
|
||||
<div className="sidebar-brand">
|
||||
<h2>OTA Manager</h2>
|
||||
</div>
|
||||
<nav>
|
||||
<NavLink to="/dashboard" className={({ isActive }) => isActive ? 'nav-link active' : 'nav-link'}>
|
||||
Dashboard
|
||||
</NavLink>
|
||||
<NavLink to="/artefacts" className={({ isActive }) => isActive ? 'nav-link active' : 'nav-link'}>
|
||||
Versions
|
||||
</NavLink>
|
||||
<NavLink to="/deployments" className={({ isActive }) => isActive ? 'nav-link active' : 'nav-link'}>
|
||||
Deployments
|
||||
</NavLink>
|
||||
<NavLink to="/users" className={({ isActive }) => isActive ? 'nav-link active' : 'nav-link'}>
|
||||
Admin Users
|
||||
</NavLink>
|
||||
</nav>
|
||||
<div className="sidebar-footer">
|
||||
<button className="btn-logout" onClick={handleLogout}>Logout</button>
|
||||
</div>
|
||||
</aside>
|
||||
<main className="content">
|
||||
<Outlet />
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
/* index.css — global reset is handled in App.css */
|
||||
@@ -0,0 +1,10 @@
|
||||
import { StrictMode } from "react"
|
||||
import { createRoot } from "react-dom/client"
|
||||
import "./index.css"
|
||||
import App from "./App.tsx"
|
||||
|
||||
createRoot(document.getElementById("root")!).render(
|
||||
<StrictMode>
|
||||
<App />
|
||||
</StrictMode>
|
||||
)
|
||||
@@ -0,0 +1,50 @@
|
||||
.upload-section {
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.upload-section h3 {
|
||||
margin: 0 0 12px;
|
||||
font-size: 15px;
|
||||
}
|
||||
|
||||
.upload-form {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.upload-form input[type="text"] {
|
||||
width: 180px;
|
||||
padding: 8px 10px;
|
||||
border: 1px solid #ddd;
|
||||
border-radius: 4px;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.upload-form input[type="file"] {
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.msg-success { color: #27ae60; font-size: 13px; margin: 8px 0 0; }
|
||||
.msg-error { color: #c00; font-size: 13px; margin: 8px 0 0; }
|
||||
|
||||
.btn-sm {
|
||||
width: auto;
|
||||
padding: 8px 16px;
|
||||
}
|
||||
|
||||
.badge {
|
||||
font-size: 11px;
|
||||
padding: 2px 8px;
|
||||
border-radius: 10px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.badge-delta { background: #fef3cd; color: #856404; }
|
||||
.badge-full { background: #d4edda; color: #155724; }
|
||||
|
||||
.hash-cell {
|
||||
font-family: monospace;
|
||||
font-size: 12px;
|
||||
color: #666;
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
import { useEffect, useState } from "react"
|
||||
import { api } from "../api/client"
|
||||
import "./Artefacts.css"
|
||||
|
||||
interface Artefact {
|
||||
id: number
|
||||
version: string
|
||||
fileName: string
|
||||
fileSize: number
|
||||
sha256Hash: string
|
||||
isDelta: boolean
|
||||
deltaRef: string
|
||||
createdAt: string
|
||||
}
|
||||
|
||||
const PAGE_SIZE = 20
|
||||
|
||||
export default function Artefacts() {
|
||||
const [artefacts, setArtefacts] = useState<Artefact[]>([])
|
||||
const [total, setTotal] = useState(0)
|
||||
const [page, setPage] = useState(1)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [uploading, setUploading] = useState(false)
|
||||
const [version, setVersion] = useState("")
|
||||
const [file, setFile] = useState<File | null>(null)
|
||||
const [uploadMsg, setUploadMsg] = useState("")
|
||||
|
||||
async function load() {
|
||||
setLoading(true)
|
||||
try {
|
||||
const res = await api.get<{ data: Artefact[]; total: number }>(
|
||||
`/artefacts?page=${page}&pageSize=${PAGE_SIZE}`
|
||||
)
|
||||
setArtefacts(res.data)
|
||||
setTotal(res.total)
|
||||
} catch (err) {
|
||||
console.error(err)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
load()
|
||||
}, [page])
|
||||
|
||||
async function handleUpload(e: React.FormEvent) {
|
||||
e.preventDefault()
|
||||
if (!file || !version) return
|
||||
|
||||
const form = new FormData()
|
||||
form.append("version", version)
|
||||
form.append("file", file)
|
||||
|
||||
setUploading(true)
|
||||
setUploadMsg("")
|
||||
try {
|
||||
await api.post("/artefacts", form)
|
||||
setVersion("")
|
||||
setFile(null)
|
||||
setUploadMsg("Version uploaded successfully.")
|
||||
load()
|
||||
} catch (err) {
|
||||
setUploadMsg("Upload failed: " + (err instanceof Error ? err.message : "unknown error"))
|
||||
} finally {
|
||||
setUploading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const totalPages = Math.ceil(total / PAGE_SIZE)
|
||||
|
||||
return (
|
||||
<div>
|
||||
<h1 className="page-title">Versions</h1>
|
||||
|
||||
<div className="card upload-section">
|
||||
<h3>Create New Version</h3>
|
||||
<form className="upload-form" onSubmit={handleUpload}>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Version (e.g. 1.2.0)"
|
||||
value={version}
|
||||
onChange={(e) => setVersion(e.target.value)}
|
||||
required
|
||||
/>
|
||||
<input
|
||||
type="file"
|
||||
accept=".jar,.patch,.zip"
|
||||
onChange={(e) => setFile(e.target.files?.[0] || null)}
|
||||
required
|
||||
/>
|
||||
<button type="submit" className="btn-primary btn-sm" disabled={uploading}>
|
||||
{uploading ? "Uploading..." : "Upload"}
|
||||
</button>
|
||||
</form>
|
||||
{uploadMsg && (
|
||||
<p className={uploadMsg.includes("failed") ? "msg-error" : "msg-success"}>{uploadMsg}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="card">
|
||||
<table className="data-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Version</th>
|
||||
<th>File</th>
|
||||
<th>Size</th>
|
||||
<th>Type</th>
|
||||
<th>SHA256</th>
|
||||
<th>Created</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{loading ? (
|
||||
<tr>
|
||||
<td colSpan={6} className="td-empty">
|
||||
Loading...
|
||||
</td>
|
||||
</tr>
|
||||
) : artefacts.length === 0 ? (
|
||||
<tr>
|
||||
<td colSpan={6} className="td-empty">
|
||||
No versions yet. Upload the first one above.
|
||||
</td>
|
||||
</tr>
|
||||
) : (
|
||||
artefacts.map((a) => (
|
||||
<tr key={a.id}>
|
||||
<td>
|
||||
<strong>{a.version}</strong>
|
||||
</td>
|
||||
<td>{a.fileName}</td>
|
||||
<td>{formatSize(a.fileSize)}</td>
|
||||
<td>
|
||||
{a.isDelta ? (
|
||||
<span className="badge badge-delta">delta ({a.deltaRef})</span>
|
||||
) : (
|
||||
<span className="badge badge-full">full</span>
|
||||
)}
|
||||
</td>
|
||||
<td className="hash-cell" title={a.sha256Hash}>
|
||||
{a.sha256Hash.slice(0, 12)}...
|
||||
</td>
|
||||
<td>{new Date(a.createdAt).toLocaleDateString()}</td>
|
||||
</tr>
|
||||
))
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
{totalPages > 1 && (
|
||||
<div className="pagination">
|
||||
<button disabled={page <= 1} onClick={() => setPage((p) => p - 1)}>
|
||||
Prev
|
||||
</button>
|
||||
<span>
|
||||
Page {page} of {totalPages}
|
||||
</span>
|
||||
<button disabled={page >= totalPages} onClick={() => setPage((p) => p + 1)}>
|
||||
Next
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function formatSize(bytes: number): string {
|
||||
if (bytes < 1024) return bytes + " B"
|
||||
if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + " KB"
|
||||
return (bytes / (1024 * 1024)).toFixed(1) + " MB"
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
.page-title {
|
||||
margin: 0 0 24px;
|
||||
font-size: 20px;
|
||||
color: #1a1a2e;
|
||||
}
|
||||
|
||||
.page-loading {
|
||||
padding: 40px;
|
||||
color: #888;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.stats-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.stat-card {
|
||||
background: #fff;
|
||||
border-radius: 8px;
|
||||
padding: 20px;
|
||||
border-top: 3px solid #ccc;
|
||||
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
|
||||
}
|
||||
|
||||
.stat-value {
|
||||
font-size: 32px;
|
||||
font-weight: 700;
|
||||
color: #1a1a2e;
|
||||
}
|
||||
|
||||
.stat-label {
|
||||
font-size: 13px;
|
||||
color: #888;
|
||||
margin-top: 4px;
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import { useEffect, useState } from "react"
|
||||
import { api } from "../api/client"
|
||||
import "./Dashboard.css"
|
||||
|
||||
interface Stats {
|
||||
totalDevices: number
|
||||
onlineDevices: number
|
||||
activeDeployments: number
|
||||
totalArtefacts: number
|
||||
}
|
||||
|
||||
export default function Dashboard() {
|
||||
const [stats, setStats] = useState<Stats>({
|
||||
totalDevices: 0,
|
||||
onlineDevices: 0,
|
||||
activeDeployments: 0,
|
||||
totalArtefacts: 0,
|
||||
})
|
||||
const [loading, setLoading] = useState(true)
|
||||
|
||||
useEffect(() => {
|
||||
async function load() {
|
||||
try {
|
||||
const [devices, artefacts, deployments] = await Promise.all([
|
||||
api.get<{ total: number; data: { status: string }[] }>("/devices?pageSize=1"),
|
||||
api.get<{ total: number }>("/artefacts?pageSize=1"),
|
||||
api.get<{ total: number; data: { status: string }[] }>("/deployments?pageSize=100"),
|
||||
])
|
||||
|
||||
const online = devices.data
|
||||
? devices.data.filter((d: { status: string }) => d.status === "online").length
|
||||
: 0
|
||||
const active = deployments.data
|
||||
? deployments.data.filter((d: { status: string }) => d.status === "active").length
|
||||
: 0
|
||||
|
||||
setStats({
|
||||
totalDevices: devices.total,
|
||||
onlineDevices: online,
|
||||
activeDeployments: active,
|
||||
totalArtefacts: artefacts.total,
|
||||
})
|
||||
} catch (err) {
|
||||
console.error("Failed to load stats:", err)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
load()
|
||||
}, [])
|
||||
|
||||
if (loading) return <div className="page-loading">Loading...</div>
|
||||
|
||||
const cards = [
|
||||
{ label: "Total Devices", value: stats.totalDevices, colour: "#4a90d9" },
|
||||
{ label: "Online Devices", value: stats.onlineDevices, colour: "#27ae60" },
|
||||
{ label: "Active Deployments", value: stats.activeDeployments, colour: "#e67e22" },
|
||||
{ label: "Artefact Versions", value: stats.totalArtefacts, colour: "#8e44ad" },
|
||||
]
|
||||
|
||||
return (
|
||||
<div>
|
||||
<h1 className="page-title">Dashboard</h1>
|
||||
<div className="stats-grid">
|
||||
{cards.map((c) => (
|
||||
<div key={c.label} className="stat-card" style={{ borderTopColor: c.colour }}>
|
||||
<div className="stat-value">{c.value}</div>
|
||||
<div className="stat-label">{c.label}</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
.page-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.page-header .page-title { margin-bottom: 0; }
|
||||
|
||||
.form-section { margin-bottom: 20px; }
|
||||
.form-section h3 { margin: 0 0 12px; font-size: 15px; }
|
||||
|
||||
.dep-form {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.dep-form label {
|
||||
display: block;
|
||||
font-size: 13px;
|
||||
color: #333;
|
||||
}
|
||||
|
||||
.dep-form input,
|
||||
.dep-form select {
|
||||
display: block;
|
||||
width: 100%;
|
||||
margin-top: 3px;
|
||||
padding: 7px 10px;
|
||||
border: 1px solid #ddd;
|
||||
border-radius: 4px;
|
||||
font-size: 13px;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.badge-draft { background: #e2e3e5; color: #383d41; }
|
||||
.badge-active { background: #d4edda; color: #155724; }
|
||||
.badge-paused { background: #fff3cd; color: #856404; }
|
||||
.badge-completed { background: #d4edda; color: #155724; }
|
||||
.badge-cancelled { background: #f8d7da; color: #721c24; }
|
||||
|
||||
.actions-cell { white-space: nowrap; }
|
||||
|
||||
.btn-action {
|
||||
padding: 4px 12px;
|
||||
border: none;
|
||||
border-radius: 3px;
|
||||
font-size: 12px;
|
||||
cursor: pointer;
|
||||
background: #27ae60;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.btn-action:hover { opacity: 0.85; }
|
||||
.btn-pause { background: #e67e22; }
|
||||
@@ -0,0 +1,266 @@
|
||||
import { type FormEvent, useEffect, useState } from "react"
|
||||
import { api } from "../api/client"
|
||||
import "./Deployments.css"
|
||||
|
||||
interface Deployment {
|
||||
id: number
|
||||
artefactId: number
|
||||
artefactVersion: string
|
||||
name: string
|
||||
targetType: string
|
||||
rolloutStrategy: string
|
||||
maxConcurrent: number
|
||||
status: string
|
||||
createdAt: string
|
||||
}
|
||||
|
||||
interface Artefact {
|
||||
id: number
|
||||
version: string
|
||||
}
|
||||
|
||||
export default function Deployments() {
|
||||
const [deployments, setDeployments] = useState<Deployment[]>([])
|
||||
const [total, setTotal] = useState(0)
|
||||
const [page, setPage] = useState(1)
|
||||
const [loading, setLoading] = useState(true)
|
||||
|
||||
// Create form
|
||||
const [showForm, setShowForm] = useState(false)
|
||||
const [artefacts, setArtefacts] = useState<Artefact[]>([])
|
||||
const [name, setName] = useState("")
|
||||
const [artefactId, setArtefactId] = useState("")
|
||||
const [targetType, setTargetType] = useState("all")
|
||||
const [targetSpec, setTargetSpec] = useState("")
|
||||
const [rolloutStrategy, setRolloutStrategy] = useState("immediate")
|
||||
const [maxConcurrent, setMaxConcurrent] = useState(50)
|
||||
const [creating, setCreating] = useState(false)
|
||||
const [msg, setMsg] = useState("")
|
||||
|
||||
async function load() {
|
||||
setLoading(true)
|
||||
try {
|
||||
const res = await api.get<{ data: Deployment[]; total: number }>(
|
||||
`/deployments?page=${page}&pageSize=20`
|
||||
)
|
||||
setDeployments(res.data)
|
||||
setTotal(res.total)
|
||||
} catch (err) {
|
||||
console.error(err)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
load()
|
||||
}, [load, page])
|
||||
|
||||
async function loadArtefacts() {
|
||||
try {
|
||||
const res = await api.get<{ data: Artefact[] }>("/artefacts?pageSize=200")
|
||||
setArtefacts(res.data)
|
||||
} catch (err) {
|
||||
console.error(err)
|
||||
}
|
||||
}
|
||||
|
||||
async function handleCreate(e: FormEvent) {
|
||||
e.preventDefault()
|
||||
setCreating(true)
|
||||
setMsg("")
|
||||
try {
|
||||
await api.post("/deployments", {
|
||||
artefactId: parseInt(artefactId),
|
||||
name,
|
||||
targetType,
|
||||
targetSpec: targetSpec || "{}",
|
||||
rolloutStrategy,
|
||||
maxConcurrent,
|
||||
})
|
||||
setShowForm(false)
|
||||
setName("")
|
||||
setArtefactId("")
|
||||
setTargetSpec("")
|
||||
setMsg("Deployment created. Activate it to begin rollout.")
|
||||
load()
|
||||
} catch (err) {
|
||||
setMsg("Failed: " + (err instanceof Error ? err.message : "unknown"))
|
||||
} finally {
|
||||
setCreating(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function activate(id: number) {
|
||||
try {
|
||||
await api.post(`/deployments/${id}/activate`)
|
||||
load()
|
||||
} catch (err) {
|
||||
alert("Failed to activate")
|
||||
}
|
||||
}
|
||||
|
||||
async function pause(id: number) {
|
||||
try {
|
||||
await api.post(`/deployments/${id}/pause`)
|
||||
load()
|
||||
} catch (err) {
|
||||
alert("Failed to pause")
|
||||
}
|
||||
}
|
||||
|
||||
const totalPages = Math.ceil(total / 20)
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="page-header">
|
||||
<h1 className="page-title">Deployments</h1>
|
||||
<button
|
||||
className="btn-primary btn-sm"
|
||||
onClick={() => {
|
||||
setShowForm(!showForm)
|
||||
if (!showForm) loadArtefacts()
|
||||
}}>
|
||||
{showForm ? "Cancel" : "New Deployment"}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{msg && <p className={msg.startsWith("Failed") ? "msg-error" : "msg-success"}>{msg}</p>}
|
||||
|
||||
{showForm && (
|
||||
<div className="card form-section">
|
||||
<h3>Create Deployment</h3>
|
||||
<form className="dep-form" onSubmit={handleCreate}>
|
||||
<label>
|
||||
Name <input value={name} onChange={(e) => setName(e.target.value)} required />
|
||||
</label>
|
||||
<label>
|
||||
Version
|
||||
<select value={artefactId} onChange={(e) => setArtefactId(e.target.value)} required>
|
||||
<option value="">-- Select --</option>
|
||||
{artefacts.map((a) => (
|
||||
<option key={a.id} value={a.id}>
|
||||
{a.version}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
Target
|
||||
<select value={targetType} onChange={(e) => setTargetType(e.target.value)}>
|
||||
<option value="all">All Devices</option>
|
||||
<option value="group">By Group</option>
|
||||
<option value="device">Specific Devices</option>
|
||||
</select>
|
||||
</label>
|
||||
{targetType !== "all" && (
|
||||
<label>
|
||||
Target Spec (JSON)
|
||||
<input
|
||||
value={targetSpec}
|
||||
onChange={(e) => setTargetSpec(e.target.value)}
|
||||
placeholder={
|
||||
targetType === "group"
|
||||
? '{"groupName":"default"}'
|
||||
: '{"deviceIds":["id1","id2"]}'
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
)}
|
||||
<label>
|
||||
Strategy
|
||||
<select value={rolloutStrategy} onChange={(e) => setRolloutStrategy(e.target.value)}>
|
||||
<option value="immediate">Immediate</option>
|
||||
<option value="staged">Staged</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
Max Concurrent{" "}
|
||||
<input
|
||||
type="number"
|
||||
value={maxConcurrent}
|
||||
onChange={(e) => setMaxConcurrent(Number(e.target.value))}
|
||||
min={1}
|
||||
max={500}
|
||||
/>
|
||||
</label>
|
||||
<button type="submit" className="btn-primary btn-sm" disabled={creating}>
|
||||
{creating ? "Creating..." : "Create"}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="card">
|
||||
<table className="data-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Name</th>
|
||||
<th>Version</th>
|
||||
<th>Target</th>
|
||||
<th>Strategy</th>
|
||||
<th>Status</th>
|
||||
<th>Created</th>
|
||||
<th>Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{loading ? (
|
||||
<tr>
|
||||
<td colSpan={7} className="td-empty">
|
||||
Loading...
|
||||
</td>
|
||||
</tr>
|
||||
) : deployments.length === 0 ? (
|
||||
<tr>
|
||||
<td colSpan={7} className="td-empty">
|
||||
No deployments yet.
|
||||
</td>
|
||||
</tr>
|
||||
) : (
|
||||
deployments.map((d) => (
|
||||
<tr key={d.id}>
|
||||
<td>
|
||||
<strong>{d.name}</strong>
|
||||
</td>
|
||||
<td>{d.artefactVersion}</td>
|
||||
<td>{d.targetType}</td>
|
||||
<td>{d.rolloutStrategy}</td>
|
||||
<td>
|
||||
<span className={`badge badge-${d.status}`}>{d.status}</span>
|
||||
</td>
|
||||
<td>{new Date(d.createdAt).toLocaleDateString()}</td>
|
||||
<td className="actions-cell">
|
||||
{d.status === "draft" && (
|
||||
<button className="btn-action" onClick={() => activate(d.id)}>
|
||||
Activate
|
||||
</button>
|
||||
)}
|
||||
{d.status === "active" && (
|
||||
<button className="btn-action btn-pause" onClick={() => pause(d.id)}>
|
||||
Pause
|
||||
</button>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
))
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
{totalPages > 1 && (
|
||||
<div className="pagination">
|
||||
<button disabled={page <= 1} onClick={() => setPage((p) => p - 1)}>
|
||||
Prev
|
||||
</button>
|
||||
<span>
|
||||
Page {page} of {totalPages}
|
||||
</span>
|
||||
<button disabled={page >= totalPages} onClick={() => setPage((p) => p + 1)}>
|
||||
Next
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
.login-page {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: 100vh;
|
||||
background: #1a1a2e;
|
||||
}
|
||||
|
||||
.login-form {
|
||||
background: #fff;
|
||||
padding: 40px;
|
||||
border-radius: 8px;
|
||||
width: 360px;
|
||||
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
|
||||
}
|
||||
|
||||
.login-form h1 {
|
||||
margin: 0 0 4px;
|
||||
font-size: 22px;
|
||||
color: #e94560;
|
||||
}
|
||||
|
||||
.login-subtitle {
|
||||
margin: 0 0 24px;
|
||||
color: #888;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.login-error {
|
||||
background: #fff0f0;
|
||||
color: #c00;
|
||||
padding: 8px 12px;
|
||||
border-radius: 4px;
|
||||
margin-bottom: 16px;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.login-form label {
|
||||
display: block;
|
||||
margin-bottom: 16px;
|
||||
font-size: 13px;
|
||||
color: #333;
|
||||
}
|
||||
|
||||
.login-form input {
|
||||
display: block;
|
||||
width: 100%;
|
||||
margin-top: 4px;
|
||||
padding: 10px 12px;
|
||||
border: 1px solid #ddd;
|
||||
border-radius: 4px;
|
||||
font-size: 14px;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.login-form input:focus {
|
||||
outline: none;
|
||||
border-color: #e94560;
|
||||
box-shadow: 0 0 0 2px rgba(233, 69, 96, 0.15);
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
width: 100%;
|
||||
padding: 10px;
|
||||
background: #e94560;
|
||||
color: #fff;
|
||||
border: none;
|
||||
border-radius: 4px;
|
||||
font-size: 14px;
|
||||
cursor: pointer;
|
||||
transition: background 0.15s;
|
||||
}
|
||||
|
||||
.btn-primary:hover {
|
||||
background: #d63850;
|
||||
}
|
||||
|
||||
.btn-primary:disabled {
|
||||
background: #ccc;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import { useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { api, setToken } from '../api/client';
|
||||
import './Login.css';
|
||||
|
||||
export default function Login() {
|
||||
const [username, setUsername] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
const navigate = useNavigate();
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setError('');
|
||||
setLoading(true);
|
||||
|
||||
try {
|
||||
const res = await api.post<{ token: string }>('/auth/login', { username, password });
|
||||
setToken(res.token);
|
||||
navigate('/dashboard');
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Login failed');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="login-page">
|
||||
<form className="login-form" onSubmit={handleSubmit}>
|
||||
<h1>OTA Manager</h1>
|
||||
<p className="login-subtitle">Sign in to manage updates</p>
|
||||
|
||||
{error && <div className="login-error">{error}</div>}
|
||||
|
||||
<label>
|
||||
Username
|
||||
<input
|
||||
type="text"
|
||||
value={username}
|
||||
onChange={e => setUsername(e.target.value)}
|
||||
autoFocus
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label>
|
||||
Password
|
||||
<input
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={e => setPassword(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
|
||||
<button type="submit" disabled={loading} className="btn-primary">
|
||||
{loading ? 'Signing in...' : 'Sign In'}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
.user-form {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.user-form input,
|
||||
.user-form select {
|
||||
padding: 7px 10px;
|
||||
border: 1px solid #ddd;
|
||||
border-radius: 4px;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.pw-inline {
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.pw-inline input {
|
||||
padding: 4px 8px;
|
||||
border: 1px solid #ddd;
|
||||
border-radius: 3px;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.btn-danger { background: #c0392b; }
|
||||
.btn-danger:hover { background: #a93226; }
|
||||
.btn-cancel { background: #888; }
|
||||
.btn-cancel:hover { background: #666; }
|
||||
@@ -0,0 +1,149 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { api } from '../api/client';
|
||||
import './Users.css';
|
||||
|
||||
interface AdminUser {
|
||||
id: number;
|
||||
username: string;
|
||||
role: string;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export default function Users() {
|
||||
const [users, setUsers] = useState<AdminUser[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
// Create form
|
||||
const [username, setUsername] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [role, setRole] = useState('admin');
|
||||
const [creating, setCreating] = useState(false);
|
||||
const [msg, setMsg] = useState('');
|
||||
|
||||
// Change password state
|
||||
const [changingId, setChangingId] = useState<number | null>(null);
|
||||
const [newPassword, setNewPassword] = useState('');
|
||||
|
||||
async function load() {
|
||||
setLoading(true);
|
||||
try {
|
||||
const res = await api.get<{ data: AdminUser[] }>('/admin/users');
|
||||
setUsers(res.data);
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => { load(); }, []);
|
||||
|
||||
async function handleCreate(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setCreating(true);
|
||||
setMsg('');
|
||||
try {
|
||||
await api.post('/admin/users', { username, password, role });
|
||||
setUsername('');
|
||||
setPassword('');
|
||||
setRole('admin');
|
||||
setMsg('User created.');
|
||||
load();
|
||||
} catch (err) {
|
||||
setMsg('Failed: ' + (err instanceof Error ? err.message : 'unknown'));
|
||||
} finally {
|
||||
setCreating(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleDelete(id: number, uname: string) {
|
||||
if (!confirm(`Delete user "${uname}"?`)) return;
|
||||
try {
|
||||
await api.delete(`/admin/users/${id}`);
|
||||
load();
|
||||
} catch (err) {
|
||||
alert('Failed to delete');
|
||||
}
|
||||
}
|
||||
|
||||
async function handleChangePassword(id: number) {
|
||||
if (!newPassword) return;
|
||||
try {
|
||||
await api.put(`/admin/users/${id}/password`, { newPassword });
|
||||
setChangingId(null);
|
||||
setNewPassword('');
|
||||
setMsg('Password changed.');
|
||||
} catch (err) {
|
||||
alert('Failed to change password');
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<h1 className="page-title">Admin Users</h1>
|
||||
|
||||
{msg && <p className={msg.startsWith('Failed') ? 'msg-error' : 'msg-success'}>{msg}</p>}
|
||||
|
||||
<div className="card form-section">
|
||||
<h3>Add User</h3>
|
||||
<form className="user-form" onSubmit={handleCreate}>
|
||||
<input placeholder="Username" value={username} onChange={e => setUsername(e.target.value)} required />
|
||||
<input placeholder="Password" type="password" value={password} onChange={e => setPassword(e.target.value)} required />
|
||||
<select value={role} onChange={e => setRole(e.target.value)}>
|
||||
<option value="admin">Admin</option>
|
||||
<option value="operator">Operator</option>
|
||||
</select>
|
||||
<button type="submit" className="btn-primary btn-sm" disabled={creating}>
|
||||
{creating ? 'Creating...' : 'Add User'}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<div className="card">
|
||||
<table className="data-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Username</th>
|
||||
<th>Role</th>
|
||||
<th>Created</th>
|
||||
<th>Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{loading ? (
|
||||
<tr><td colSpan={4} className="td-empty">Loading...</td></tr>
|
||||
) : users.length === 0 ? (
|
||||
<tr><td colSpan={4} className="td-empty">No users.</td></tr>
|
||||
) : users.map(u => (
|
||||
<tr key={u.id}>
|
||||
<td><strong>{u.username}</strong></td>
|
||||
<td><span className="badge">{u.role}</span></td>
|
||||
<td>{new Date(u.createdAt).toLocaleDateString()}</td>
|
||||
<td className="actions-cell">
|
||||
{changingId === u.id ? (
|
||||
<span className="pw-inline">
|
||||
<input
|
||||
type="password"
|
||||
placeholder="New password"
|
||||
value={newPassword}
|
||||
onChange={e => setNewPassword(e.target.value)}
|
||||
size={16}
|
||||
/>
|
||||
<button className="btn-action" onClick={() => handleChangePassword(u.id)}>Save</button>
|
||||
<button className="btn-action btn-cancel" onClick={() => setChangingId(null)}>Cancel</button>
|
||||
</span>
|
||||
) : (
|
||||
<>
|
||||
<button className="btn-action" onClick={() => setChangingId(u.id)}>Change PW</button>
|
||||
<button className="btn-action btn-danger" onClick={() => handleDelete(u.id, u.username)}>Delete</button>
|
||||
</>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
|
||||
"target": "es2023",
|
||||
"lib": ["ES2023", "DOM"],
|
||||
"module": "esnext",
|
||||
"types": ["vite/client"],
|
||||
"allowArbitraryExtensions": true,
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx",
|
||||
|
||||
/* Linting */
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"erasableSyntaxOnly": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"paths": {
|
||||
"@/*": ["./src/*"]
|
||||
}
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"files": [],
|
||||
"references": [
|
||||
{ "path": "./tsconfig.app.json" },
|
||||
{ "path": "./tsconfig.node.json" }
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
|
||||
"target": "es2023",
|
||||
"lib": ["ES2023"],
|
||||
"types": ["node"],
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
"module": "nodenext",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
|
||||
/* Linting */
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"erasableSyntaxOnly": true,
|
||||
"noFallthroughCasesInSwitch": true
|
||||
},
|
||||
"include": ["vite.config.ts"]
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
import path from 'path'
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
resolve: {
|
||||
alias: {
|
||||
'@': path.resolve(__dirname, 'src'),
|
||||
},
|
||||
},
|
||||
server: {
|
||||
proxy: {
|
||||
'/api': 'http://localhost:8080',
|
||||
},
|
||||
},
|
||||
build: {
|
||||
outDir: 'dist',
|
||||
},
|
||||
})
|
||||
Reference in New Issue
Block a user