feat: complete SyncServer implementation
Full-stack Go monolith with embedded React frontend for orchestrating rsync-over-SSH file synchronization with Wake-on-LAN support. Features: - JWT auth (HS256) with bcrypt password hashing - CRUD for machines (with WoL config) and sync_pairs - Ed25519 SSH key generation and known_hosts management - WoL magic packet sender + TCP-connect waiter with backoff - Sync engine: rsync subprocess, per-pair job queue, progress parsing - Homebrew cron parser for scheduled syncs - SSE stream for live job status (queued/waking_up/running/success/failed) - React+TS+Vite+Tailwind SPA embedded via embed.FS - Debian packaging with systemd unit, postinst/prerm/postrm Tech stack: - Go 1.22+ (CGO_ENABLED=0, pure SQLite via modernc.org/sqlite) - chi router for HTTP API - TypeScript + React 18 + Tailwind CSS frontend - Cross-compiled to Linux amd64 for Proxmox LXC deployment Tests: wol (MAC parsing, magic packet), syncengine/queue, scheduler/cron
This commit is contained in:
@@ -0,0 +1,69 @@
|
||||
package api
|
||||
|
||||
type MachineRequest struct {
|
||||
Name string `json:"name"`
|
||||
Host string `json:"host"`
|
||||
Port int `json:"port"`
|
||||
SSHUser string `json:"ssh_user"`
|
||||
SSHKeyID *int64 `json:"ssh_key_id"`
|
||||
MACAddress *string `json:"mac_address"`
|
||||
WoLEnabled bool `json:"wol_enabled"`
|
||||
BroadcastAddr *string `json:"broadcast_addr"`
|
||||
WakeTimeoutSeconds int `json:"wake_timeout_seconds"`
|
||||
WakeCheckIntervalSeconds int `json:"wake_check_interval_seconds"`
|
||||
}
|
||||
|
||||
type MachineResponse struct {
|
||||
ID int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Host string `json:"host"`
|
||||
Port int `json:"port"`
|
||||
SSHUser string `json:"ssh_user"`
|
||||
SSHKeyID *int64 `json:"ssh_key_id"`
|
||||
MACAddress *string `json:"mac_address"`
|
||||
WoLEnabled bool `json:"wol_enabled"`
|
||||
BroadcastAddr *string `json:"broadcast_addr"`
|
||||
WakeTimeoutSeconds int `json:"wake_timeout_seconds"`
|
||||
WakeCheckIntervalSeconds int `json:"wake_check_interval_seconds"`
|
||||
FingerprintConfirmed bool `json:"fingerprint_confirmed"`
|
||||
Status string `json:"status"`
|
||||
}
|
||||
|
||||
type SyncPairRequest struct {
|
||||
Name string `json:"name"`
|
||||
SourceMachineID *int64 `json:"source_machine_id"`
|
||||
SourcePath string `json:"source_path"`
|
||||
DestMachineID *int64 `json:"dest_machine_id"`
|
||||
DestPath string `json:"dest_path"`
|
||||
Direction string `json:"direction"`
|
||||
RsyncFlags string `json:"rsync_flags"`
|
||||
ExcludePatterns string `json:"exclude_patterns"`
|
||||
Enabled bool `json:"enabled"`
|
||||
}
|
||||
|
||||
type SyncPairResponse struct {
|
||||
ID int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
SourceMachineID *int64 `json:"source_machine_id"`
|
||||
SourcePath string `json:"source_path"`
|
||||
DestMachineID *int64 `json:"dest_machine_id"`
|
||||
DestPath string `json:"dest_path"`
|
||||
Direction string `json:"direction"`
|
||||
RsyncFlags string `json:"rsync_flags"`
|
||||
ExcludePatterns string `json:"exclude_patterns"`
|
||||
Enabled bool `json:"enabled"`
|
||||
}
|
||||
|
||||
type JobResponse struct {
|
||||
ID int64 `json:"id"`
|
||||
SyncPairID int64 `json:"sync_pair_id"`
|
||||
TriggerType string `json:"trigger_type"`
|
||||
Status string `json:"status"`
|
||||
StartedAt *string `json:"started_at"`
|
||||
FinishedAt *string `json:"finished_at"`
|
||||
LogFile *string `json:"log_file"`
|
||||
}
|
||||
|
||||
type ErrorResponse struct {
|
||||
Error string `json:"error"`
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
"github.com/syncserver/internal/auth"
|
||||
)
|
||||
|
||||
type AuthHandler struct {
|
||||
db *sql.DB
|
||||
}
|
||||
|
||||
func NewAuthHandler(db *sql.DB) *AuthHandler {
|
||||
return &AuthHandler{db: db}
|
||||
}
|
||||
|
||||
type LoginRequest struct {
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
type LoginResponse struct {
|
||||
User UserResponse `json:"user"`
|
||||
ExpiresAt string `json:"expires_at"`
|
||||
}
|
||||
|
||||
type UserResponse struct {
|
||||
ID int64 `json:"id"`
|
||||
Username string `json:"username"`
|
||||
Role string `json:"role"`
|
||||
}
|
||||
|
||||
func (h *AuthHandler) Login(w http.ResponseWriter, r *http.Request) {
|
||||
var req LoginRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
http.Error(w, `{"error":"invalid request"}`, http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
row := h.db.QueryRow(
|
||||
"SELECT id, username, password_hash, role FROM users WHERE username = ?",
|
||||
req.Username,
|
||||
)
|
||||
var u struct {
|
||||
ID int64
|
||||
Username string
|
||||
PasswordHash string
|
||||
Role string
|
||||
}
|
||||
if err := row.Scan(&u.ID, &u.Username, &u.PasswordHash, &u.Role); err != nil {
|
||||
http.Error(w, `{"error":"invalid credentials"}`, http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
if !auth.VerifyPassword([]byte(u.PasswordHash), req.Password) {
|
||||
http.Error(w, `{"error":"invalid credentials"}`, http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
jwtMgr := auth.GetJWTManager()
|
||||
if jwtMgr == nil {
|
||||
http.Error(w, `{"error":"server misconfigured"}`, http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
token, expiresAt, err := jwtMgr.Generate(u.ID, u.Username, u.Role)
|
||||
if err != nil {
|
||||
http.Error(w, `{"error":"failed to generate token"}`, http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
auth.SetAuthCookie(w, token, expiresAt)
|
||||
|
||||
resp := LoginResponse{
|
||||
User: UserResponse{
|
||||
ID: u.ID,
|
||||
Username: u.Username,
|
||||
Role: u.Role,
|
||||
},
|
||||
ExpiresAt: expiresAt.Format("2006-01-02T15:04:05Z07:00"),
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(resp)
|
||||
}
|
||||
|
||||
func (h *AuthHandler) Logout(w http.ResponseWriter, r *http.Request) {
|
||||
auth.ClearAuthCookie(w)
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (h *AuthHandler) Me(w http.ResponseWriter, r *http.Request) {
|
||||
claims := auth.GetClaims(r.Context())
|
||||
if claims == nil {
|
||||
http.Error(w, `{"error":"unauthorized"}`, http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
resp := UserResponse{
|
||||
ID: claims.UserID,
|
||||
Username: claims.Username,
|
||||
Role: claims.Role,
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]interface{}{"user": resp})
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"net/http"
|
||||
"os"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/syncserver/internal/models"
|
||||
"github.com/syncserver/internal/syncengine"
|
||||
)
|
||||
|
||||
type JobHandler struct {
|
||||
db *sql.DB
|
||||
engine *syncengine.Engine
|
||||
}
|
||||
|
||||
func NewJobHandler(db *sql.DB, engine *syncengine.Engine) *JobHandler {
|
||||
return &JobHandler{db: db, engine: engine}
|
||||
}
|
||||
|
||||
func (h *JobHandler) List(w http.ResponseWriter, r *http.Request) {
|
||||
limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))
|
||||
offset, _ := strconv.Atoi(r.URL.Query().Get("offset"))
|
||||
if limit <= 0 || limit > 100 {
|
||||
limit = 50
|
||||
}
|
||||
|
||||
repo := models.NewJobRepository(h.db)
|
||||
jobs, err := repo.GetAll(limit, offset)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to fetch jobs")
|
||||
return
|
||||
}
|
||||
|
||||
out := make([]JobResponse, len(jobs))
|
||||
for i, j := range jobs {
|
||||
out[i] = jobToResp(j)
|
||||
}
|
||||
writeJSON(w, out)
|
||||
}
|
||||
|
||||
func (h *JobHandler) Get(w http.ResponseWriter, r *http.Request) {
|
||||
id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid id")
|
||||
return
|
||||
}
|
||||
|
||||
repo := models.NewJobRepository(h.db)
|
||||
j, err := repo.GetByID(id)
|
||||
if err == sql.ErrNoRows {
|
||||
writeError(w, http.StatusNotFound, "job not found")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to fetch job")
|
||||
return
|
||||
}
|
||||
writeJSON(w, jobToResp(*j))
|
||||
}
|
||||
|
||||
func (h *JobHandler) Cancel(w http.ResponseWriter, r *http.Request) {
|
||||
id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid id")
|
||||
return
|
||||
}
|
||||
|
||||
repo := models.NewJobRepository(h.db)
|
||||
j, err := repo.GetByID(id)
|
||||
if err == sql.ErrNoRows {
|
||||
writeError(w, http.StatusNotFound, "job not found")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to fetch job")
|
||||
return
|
||||
}
|
||||
|
||||
if j.Status != "queued" && j.Status != "waking_up" && j.Status != "running" {
|
||||
writeError(w, http.StatusBadRequest, "job is not cancellable")
|
||||
return
|
||||
}
|
||||
|
||||
if h.engine != nil {
|
||||
h.engine.Cancel(id, j.SyncPairID)
|
||||
}
|
||||
|
||||
repo.UpdateStatus(id, "cancelled")
|
||||
writeJSON(w, map[string]string{"status": "cancelled"})
|
||||
}
|
||||
|
||||
func (h *JobHandler) TriggerRun(w http.ResponseWriter, r *http.Request) {
|
||||
pairID, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid id")
|
||||
return
|
||||
}
|
||||
|
||||
if h.engine == nil {
|
||||
writeError(w, http.StatusInternalServerError, "engine not available")
|
||||
return
|
||||
}
|
||||
|
||||
jobID, err := h.engine.CreateJob(pairID, "manual")
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to create job")
|
||||
return
|
||||
}
|
||||
|
||||
go func() {
|
||||
h.engine.Run(r.Context(), jobID, pairID)
|
||||
}()
|
||||
|
||||
jobRepo := models.NewJobRepository(h.db)
|
||||
j, _ := jobRepo.GetByID(jobID)
|
||||
writeJSON(w, jobToResp(*j), http.StatusCreated)
|
||||
}
|
||||
|
||||
func (h *JobHandler) StreamLog(w http.ResponseWriter, r *http.Request) {
|
||||
id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid id")
|
||||
return
|
||||
}
|
||||
|
||||
flusher, ok := w.(http.Flusher)
|
||||
if !ok {
|
||||
writeError(w, http.StatusInternalServerError, "streaming not supported")
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "text/plain")
|
||||
w.Header().Set("Cache-Control", "no-cache")
|
||||
w.Header().Set("Connection", "keep-alive")
|
||||
flusher.Flush()
|
||||
|
||||
jobRepo := models.NewJobRepository(h.db)
|
||||
j, err := jobRepo.GetByID(id)
|
||||
if err == nil && j.LogFile != nil {
|
||||
data, _ := os.ReadFile(*j.LogFile)
|
||||
w.Write(data)
|
||||
flusher.Flush()
|
||||
}
|
||||
}
|
||||
|
||||
func jobToResp(j models.Job) JobResponse {
|
||||
resp := JobResponse{
|
||||
ID: j.ID,
|
||||
SyncPairID: j.SyncPairID,
|
||||
TriggerType: j.TriggerType,
|
||||
Status: j.Status,
|
||||
LogFile: j.LogFile,
|
||||
}
|
||||
if j.StartedAt != nil {
|
||||
s := j.StartedAt.Format(time.RFC3339)
|
||||
resp.StartedAt = &s
|
||||
}
|
||||
if j.FinishedAt != nil {
|
||||
s := j.FinishedAt.Format(time.RFC3339)
|
||||
resp.FinishedAt = &s
|
||||
}
|
||||
return resp
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/syncserver/internal/models"
|
||||
)
|
||||
|
||||
type MachineHandler struct {
|
||||
db *sql.DB
|
||||
}
|
||||
|
||||
func NewMachineHandler(db *sql.DB) *MachineHandler {
|
||||
return &MachineHandler{db: db}
|
||||
}
|
||||
|
||||
var macRegex = regexp.MustCompile(`^([0-9A-Fa-f]{2}[:-]){5}[0-9A-Fa-f]{2}$`)
|
||||
|
||||
func (h *MachineHandler) List(w http.ResponseWriter, r *http.Request) {
|
||||
repo := models.NewMachineRepository(h.db)
|
||||
ms, err := repo.GetAll()
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to fetch machines")
|
||||
return
|
||||
}
|
||||
out := make([]MachineResponse, len(ms))
|
||||
for i, m := range ms {
|
||||
out[i] = machineToResp(m)
|
||||
}
|
||||
writeJSON(w, out)
|
||||
}
|
||||
|
||||
func (h *MachineHandler) Get(w http.ResponseWriter, r *http.Request) {
|
||||
id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid id")
|
||||
return
|
||||
}
|
||||
repo := models.NewMachineRepository(h.db)
|
||||
m, err := repo.GetByID(id)
|
||||
if err == sql.ErrNoRows {
|
||||
writeError(w, http.StatusNotFound, "machine not found")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to fetch machine")
|
||||
return
|
||||
}
|
||||
writeJSON(w, machineToResp(*m))
|
||||
}
|
||||
|
||||
func (h *MachineHandler) Create(w http.ResponseWriter, r *http.Request) {
|
||||
var req MachineRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid request body")
|
||||
return
|
||||
}
|
||||
|
||||
if req.Name == "" || req.Host == "" {
|
||||
writeError(w, http.StatusBadRequest, "name and host are required")
|
||||
return
|
||||
}
|
||||
if req.Port <= 0 || req.Port > 65535 {
|
||||
writeError(w, http.StatusBadRequest, "invalid port")
|
||||
return
|
||||
}
|
||||
if req.SSHUser == "" {
|
||||
req.SSHUser = "root"
|
||||
}
|
||||
if req.WakeTimeoutSeconds <= 0 {
|
||||
req.WakeTimeoutSeconds = 120
|
||||
}
|
||||
if req.WakeCheckIntervalSeconds <= 0 {
|
||||
req.WakeCheckIntervalSeconds = 5
|
||||
}
|
||||
if req.WoLEnabled && req.MACAddress != nil && !macRegex.MatchString(*req.MACAddress) {
|
||||
writeError(w, http.StatusBadRequest, "invalid mac_address format (expected AA:BB:CC:DD:EE:FF)")
|
||||
return
|
||||
}
|
||||
|
||||
m := &models.Machine{
|
||||
Name: req.Name,
|
||||
Host: req.Host,
|
||||
Port: req.Port,
|
||||
SSHUser: req.SSHUser,
|
||||
SSHKeyID: req.SSHKeyID,
|
||||
MACAddress: req.MACAddress,
|
||||
WoLEnabled: req.WoLEnabled,
|
||||
BroadcastAddr: req.BroadcastAddr,
|
||||
WakeTimeoutSeconds: req.WakeTimeoutSeconds,
|
||||
WakeCheckIntervalSeconds: req.WakeCheckIntervalSeconds,
|
||||
FingerprintConfirmed: false,
|
||||
Status: "unknown",
|
||||
}
|
||||
|
||||
repo := models.NewMachineRepository(h.db)
|
||||
id, err := repo.Create(m)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to create machine")
|
||||
return
|
||||
}
|
||||
m.ID = id
|
||||
w.Header().Set("Location", "/api/machines/"+strconv.FormatInt(id, 10))
|
||||
writeJSON(w, machineToResp(*m), http.StatusCreated)
|
||||
}
|
||||
|
||||
func (h *MachineHandler) Update(w http.ResponseWriter, r *http.Request) {
|
||||
id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid id")
|
||||
return
|
||||
}
|
||||
|
||||
var req MachineRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid request body")
|
||||
return
|
||||
}
|
||||
|
||||
if req.Name == "" || req.Host == "" {
|
||||
writeError(w, http.StatusBadRequest, "name and host are required")
|
||||
return
|
||||
}
|
||||
if req.Port <= 0 || req.Port > 65535 {
|
||||
writeError(w, http.StatusBadRequest, "invalid port")
|
||||
return
|
||||
}
|
||||
if req.SSHUser == "" {
|
||||
req.SSHUser = "root"
|
||||
}
|
||||
if req.WoLEnabled && req.MACAddress != nil && !macRegex.MatchString(*req.MACAddress) {
|
||||
writeError(w, http.StatusBadRequest, "invalid mac_address format")
|
||||
return
|
||||
}
|
||||
|
||||
repo := models.NewMachineRepository(h.db)
|
||||
existing, err := repo.GetByID(id)
|
||||
if err == sql.ErrNoRows {
|
||||
writeError(w, http.StatusNotFound, "machine not found")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to fetch machine")
|
||||
return
|
||||
}
|
||||
|
||||
existing.Name = req.Name
|
||||
existing.Host = req.Host
|
||||
existing.Port = req.Port
|
||||
existing.SSHUser = req.SSHUser
|
||||
existing.SSHKeyID = req.SSHKeyID
|
||||
existing.MACAddress = req.MACAddress
|
||||
existing.WoLEnabled = req.WoLEnabled
|
||||
existing.BroadcastAddr = req.BroadcastAddr
|
||||
if req.WakeTimeoutSeconds > 0 {
|
||||
existing.WakeTimeoutSeconds = req.WakeTimeoutSeconds
|
||||
}
|
||||
if req.WakeCheckIntervalSeconds > 0 {
|
||||
existing.WakeCheckIntervalSeconds = req.WakeCheckIntervalSeconds
|
||||
}
|
||||
|
||||
if err := repo.Update(existing); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to update machine")
|
||||
return
|
||||
}
|
||||
writeJSON(w, machineToResp(*existing))
|
||||
}
|
||||
|
||||
func (h *MachineHandler) Delete(w http.ResponseWriter, r *http.Request) {
|
||||
id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid id")
|
||||
return
|
||||
}
|
||||
|
||||
repo := models.NewMachineRepository(h.db)
|
||||
if err := repo.Delete(id); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to delete machine")
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func machineToResp(m models.Machine) MachineResponse {
|
||||
var status string
|
||||
if m.LastSeenAt != nil {
|
||||
status = m.Status + " (last seen " + m.LastSeenAt.Format(time.RFC3339) + ")"
|
||||
} else {
|
||||
status = m.Status
|
||||
}
|
||||
return MachineResponse{
|
||||
ID: m.ID,
|
||||
Name: m.Name,
|
||||
Host: m.Host,
|
||||
Port: m.Port,
|
||||
SSHUser: m.SSHUser,
|
||||
SSHKeyID: m.SSHKeyID,
|
||||
MACAddress: m.MACAddress,
|
||||
WoLEnabled: m.WoLEnabled,
|
||||
BroadcastAddr: m.BroadcastAddr,
|
||||
WakeTimeoutSeconds: m.WakeTimeoutSeconds,
|
||||
WakeCheckIntervalSeconds: m.WakeCheckIntervalSeconds,
|
||||
FingerprintConfirmed: m.FingerprintConfirmed,
|
||||
Status: status,
|
||||
}
|
||||
}
|
||||
|
||||
func writeError(w http.ResponseWriter, code int, msg string) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(code)
|
||||
json.NewEncoder(w).Encode(ErrorResponse{Error: msg})
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, data interface{}, codes ...int) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
if len(codes) > 0 {
|
||||
w.WriteHeader(codes[0])
|
||||
}
|
||||
json.NewEncoder(w).Encode(data)
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strconv"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/syncserver/internal/models"
|
||||
)
|
||||
|
||||
type SyncPairHandler struct {
|
||||
db *sql.DB
|
||||
}
|
||||
|
||||
func NewSyncPairHandler(db *sql.DB) *SyncPairHandler {
|
||||
return &SyncPairHandler{db: db}
|
||||
}
|
||||
|
||||
var directionRegex = regexp.MustCompile(`^(push|pull|mirror)$`)
|
||||
|
||||
func (h *SyncPairHandler) List(w http.ResponseWriter, r *http.Request) {
|
||||
repo := models.NewSyncPairRepository(h.db)
|
||||
pairs, err := repo.GetAll()
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to fetch sync pairs")
|
||||
return
|
||||
}
|
||||
out := make([]SyncPairResponse, len(pairs))
|
||||
for i, p := range pairs {
|
||||
out[i] = syncPairToResp(p)
|
||||
}
|
||||
writeJSON(w, out)
|
||||
}
|
||||
|
||||
func (h *SyncPairHandler) Get(w http.ResponseWriter, r *http.Request) {
|
||||
id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid id")
|
||||
return
|
||||
}
|
||||
repo := models.NewSyncPairRepository(h.db)
|
||||
p, err := repo.GetByID(id)
|
||||
if err == sql.ErrNoRows {
|
||||
writeError(w, http.StatusNotFound, "sync pair not found")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to fetch sync pair")
|
||||
return
|
||||
}
|
||||
writeJSON(w, syncPairToResp(*p))
|
||||
}
|
||||
|
||||
func (h *SyncPairHandler) Create(w http.ResponseWriter, r *http.Request) {
|
||||
var req SyncPairRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid request body")
|
||||
return
|
||||
}
|
||||
|
||||
if req.Name == "" || req.SourcePath == "" || req.DestPath == "" {
|
||||
writeError(w, http.StatusBadRequest, "name, source_path and dest_path are required")
|
||||
return
|
||||
}
|
||||
if req.Direction == "" {
|
||||
req.Direction = "push"
|
||||
}
|
||||
if !directionRegex.MatchString(req.Direction) {
|
||||
writeError(w, http.StatusBadRequest, "direction must be push, pull, or mirror")
|
||||
return
|
||||
}
|
||||
if req.RsyncFlags == "" {
|
||||
req.RsyncFlags = "-aP"
|
||||
}
|
||||
if !req.Enabled {
|
||||
req.Enabled = true
|
||||
}
|
||||
|
||||
sp := &models.SyncPair{
|
||||
Name: req.Name,
|
||||
SourceMachineID: req.SourceMachineID,
|
||||
SourcePath: req.SourcePath,
|
||||
DestMachineID: req.DestMachineID,
|
||||
DestPath: req.DestPath,
|
||||
Direction: req.Direction,
|
||||
RsyncFlags: req.RsyncFlags,
|
||||
ExcludePatterns: req.ExcludePatterns,
|
||||
Enabled: req.Enabled,
|
||||
}
|
||||
|
||||
repo := models.NewSyncPairRepository(h.db)
|
||||
id, err := repo.Create(sp)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to create sync pair")
|
||||
return
|
||||
}
|
||||
sp.ID = id
|
||||
w.Header().Set("Location", "/api/sync-pairs/"+strconv.FormatInt(id, 10))
|
||||
writeJSON(w, syncPairToResp(*sp), http.StatusCreated)
|
||||
}
|
||||
|
||||
func (h *SyncPairHandler) Update(w http.ResponseWriter, r *http.Request) {
|
||||
id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid id")
|
||||
return
|
||||
}
|
||||
|
||||
var req SyncPairRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid request body")
|
||||
return
|
||||
}
|
||||
|
||||
if req.Name == "" || req.SourcePath == "" || req.DestPath == "" {
|
||||
writeError(w, http.StatusBadRequest, "name, source_path and dest_path are required")
|
||||
return
|
||||
}
|
||||
if !directionRegex.MatchString(req.Direction) {
|
||||
writeError(w, http.StatusBadRequest, "direction must be push, pull, or mirror")
|
||||
return
|
||||
}
|
||||
|
||||
repo := models.NewSyncPairRepository(h.db)
|
||||
existing, err := repo.GetByID(id)
|
||||
if err == sql.ErrNoRows {
|
||||
writeError(w, http.StatusNotFound, "sync pair not found")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to fetch sync pair")
|
||||
return
|
||||
}
|
||||
|
||||
existing.Name = req.Name
|
||||
existing.SourceMachineID = req.SourceMachineID
|
||||
existing.SourcePath = req.SourcePath
|
||||
existing.DestMachineID = req.DestMachineID
|
||||
existing.DestPath = req.DestPath
|
||||
existing.Direction = req.Direction
|
||||
existing.RsyncFlags = req.RsyncFlags
|
||||
existing.ExcludePatterns = req.ExcludePatterns
|
||||
existing.Enabled = req.Enabled
|
||||
|
||||
if err := repo.Update(existing); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to update sync pair")
|
||||
return
|
||||
}
|
||||
writeJSON(w, syncPairToResp(*existing))
|
||||
}
|
||||
|
||||
func (h *SyncPairHandler) Delete(w http.ResponseWriter, r *http.Request) {
|
||||
id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid id")
|
||||
return
|
||||
}
|
||||
|
||||
repo := models.NewSyncPairRepository(h.db)
|
||||
if err := repo.Delete(id); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to delete sync pair")
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func syncPairToResp(p models.SyncPair) SyncPairResponse {
|
||||
return SyncPairResponse{
|
||||
ID: p.ID,
|
||||
Name: p.Name,
|
||||
SourceMachineID: p.SourceMachineID,
|
||||
SourcePath: p.SourcePath,
|
||||
DestMachineID: p.DestMachineID,
|
||||
DestPath: p.DestPath,
|
||||
Direction: p.Direction,
|
||||
RsyncFlags: p.RsyncFlags,
|
||||
ExcludePatterns: p.ExcludePatterns,
|
||||
Enabled: p.Enabled,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/syncserver/internal/syncengine"
|
||||
)
|
||||
|
||||
type SSEHandler struct {
|
||||
engine *syncengine.Engine
|
||||
}
|
||||
|
||||
func NewSSEHandler(engine *syncengine.Engine) *SSEHandler {
|
||||
return &SSEHandler{engine: engine}
|
||||
}
|
||||
|
||||
func (h *SSEHandler) Stream(w http.ResponseWriter, r *http.Request) {
|
||||
jobIDStr := r.URL.Query().Get("job_id")
|
||||
var filterJobID int64
|
||||
if jobIDStr != "" {
|
||||
filterJobID, _ = strconv.ParseInt(jobIDStr, 10, 64)
|
||||
}
|
||||
|
||||
flusher, ok := w.(http.Flusher)
|
||||
if !ok {
|
||||
http.Error(w, "SSE not supported", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
w.Header().Set("Cache-Control", "no-cache")
|
||||
w.Header().Set("Connection", "keep-alive")
|
||||
w.Header().Set("X-Accel-Buffering", "no")
|
||||
|
||||
flusher.Flush()
|
||||
|
||||
if h.engine == nil {
|
||||
return
|
||||
}
|
||||
|
||||
events := h.engine.Events()
|
||||
for {
|
||||
select {
|
||||
case evt := <-events:
|
||||
if filterJobID != 0 && evt.JobID != filterJobID {
|
||||
continue
|
||||
}
|
||||
data, _ := json.Marshal(evt)
|
||||
fmt.Fprintf(w, "event: %s\ndata: %s\n\n", evt.Type, data)
|
||||
flusher.Flush()
|
||||
|
||||
case <-r.Context().Done():
|
||||
return
|
||||
|
||||
case <-time.After(30 * time.Second):
|
||||
fmt.Fprintf(w, ": keepalive\n\n")
|
||||
flusher.Flush()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"net/http"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/go-chi/chi/v5/middleware"
|
||||
"github.com/syncserver/internal/auth"
|
||||
"github.com/syncserver/internal/config"
|
||||
"github.com/syncserver/internal/sshmanager"
|
||||
"github.com/syncserver/internal/syncengine"
|
||||
"github.com/syncserver/internal/webui"
|
||||
)
|
||||
|
||||
type Server struct {
|
||||
router *chi.Mux
|
||||
cfg *config.Config
|
||||
engine *syncengine.Engine
|
||||
}
|
||||
|
||||
func NewServer(cfg *config.Config, db *sql.DB, engine *syncengine.Engine) *Server {
|
||||
auth.InitJWTManager(cfg.Auth.JWTSecret, cfg.Auth.JWTExpiryH)
|
||||
|
||||
r := chi.NewRouter()
|
||||
r.Use(middleware.RequestID)
|
||||
r.Use(middleware.RealIP)
|
||||
r.Use(middleware.Logger)
|
||||
r.Use(middleware.Recoverer)
|
||||
|
||||
s := &Server{router: r, cfg: cfg, engine: engine}
|
||||
|
||||
authHandler := NewAuthHandler(db)
|
||||
machineHandler := NewMachineHandler(db)
|
||||
syncPairHandler := NewSyncPairHandler(db)
|
||||
jobHandler := NewJobHandler(db, engine)
|
||||
sseHandler := NewSSEHandler(engine)
|
||||
|
||||
r.Route("/api", func(r chi.Router) {
|
||||
r.Route("/auth", func(r chi.Router) {
|
||||
r.Post("/login", authHandler.Login)
|
||||
r.Post("/logout", authHandler.Logout)
|
||||
r.With(auth.RequireAuth).Get("/me", authHandler.Me)
|
||||
})
|
||||
|
||||
r.With(auth.RequireAuth).Route("/machines", func(r chi.Router) {
|
||||
r.Get("/", machineHandler.List)
|
||||
r.Post("/", machineHandler.Create)
|
||||
r.Get("/{id}", machineHandler.Get)
|
||||
r.Put("/{id}", machineHandler.Update)
|
||||
r.Delete("/{id}", machineHandler.Delete)
|
||||
})
|
||||
|
||||
r.With(auth.RequireAuth).Route("/sync-pairs", func(r chi.Router) {
|
||||
r.Get("/", syncPairHandler.List)
|
||||
r.Post("/", syncPairHandler.Create)
|
||||
r.Get("/{id}", syncPairHandler.Get)
|
||||
r.Put("/{id}", syncPairHandler.Update)
|
||||
r.Delete("/{id}", syncPairHandler.Delete)
|
||||
r.Post("/{id}/run", jobHandler.TriggerRun)
|
||||
})
|
||||
|
||||
r.With(auth.RequireAuth).Route("/jobs", func(r chi.Router) {
|
||||
r.Get("/", jobHandler.List)
|
||||
r.Get("/{id}", jobHandler.Get)
|
||||
r.Post("/{id}/cancel", jobHandler.Cancel)
|
||||
r.Get("/{id}/log", jobHandler.StreamLog)
|
||||
})
|
||||
|
||||
r.With(auth.RequireAuth).Get("/jobs/stream", sseHandler.Stream)
|
||||
|
||||
r.With(auth.RequireAuth).Get("/settings/pubkey", func(w http.ResponseWriter, r *http.Request) {
|
||||
_, _, pubKey, _ := sshmanager.EnsureServerKey(cfg.SSHDir())
|
||||
w.Header().Set("Content-Type", "text/plain")
|
||||
w.Write([]byte(pubKey))
|
||||
})
|
||||
})
|
||||
|
||||
r.Get("/health", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Write([]byte("ok"))
|
||||
}))
|
||||
|
||||
r.NotFound(func(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := webui.DistFS.Open("dist" + r.URL.Path); ok == nil {
|
||||
http.FileServer(http.FS(webui.DistFS)).ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
data, err := webui.DistFS.ReadFile("dist/index.html")
|
||||
if err != nil {
|
||||
http.Error(w, "not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/html")
|
||||
w.Write(data)
|
||||
})
|
||||
|
||||
return s
|
||||
}
|
||||
|
||||
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
s.router.ServeHTTP(w, r)
|
||||
}
|
||||
Reference in New Issue
Block a user