feat(docker-watcher): phase 11 - frontend embed & SSE

Embed SvelteKit static build in Go binary via go:embed. Event bus
for pub/sub with deploy log, instance status, and deploy status events.
SSE endpoints for real-time streaming. Frontend SSE client with
exponential backoff reconnection. Makefile for build pipeline.
Update Phase 12 auth plan with OAuth2/OIDC support.
This commit is contained in:
2026-03-27 22:30:25 +03:00
parent d40cf10f88
commit 5558396bb7
16 changed files with 844 additions and 73 deletions
+2 -26
View File
@@ -1,14 +1,11 @@
package api
import (
"errors"
"log"
"net/http"
"strconv"
"strings"
"github.com/go-chi/chi/v5"
"github.com/alexei/docker-watcher/internal/store"
)
@@ -30,29 +27,8 @@ func (s *Server) listDeploys(w http.ResponseWriter, r *http.Request) {
respondJSON(w, http.StatusOK, deploys)
}
// getDeployLogs handles GET /api/deploys/{id}/logs.
// This is an SSE stub that returns logs as JSON for now.
// Real SSE streaming will be implemented in Phase 11.
func (s *Server) getDeployLogs(w http.ResponseWriter, r *http.Request) {
deployID := chi.URLParam(r, "id")
// Verify deploy exists.
if _, err := s.store.GetDeployByID(deployID); err != nil {
if errors.Is(err, store.ErrNotFound) {
respondNotFound(w, "deploy")
return
}
respondError(w, http.StatusInternalServerError, "failed to get deploy: "+err.Error())
return
}
logs, err := s.store.GetDeployLogs(deployID)
if err != nil {
respondError(w, http.StatusInternalServerError, "failed to get deploy logs: "+err.Error())
return
}
respondJSON(w, http.StatusOK, logs)
}
// NOTE: getDeployLogs has been replaced by streamDeployLogs in sse.go.
// The new handler supports both SSE streaming and JSON fallback via Accept header.
// inspectRequest is the expected JSON body for POST /api/deploy/inspect.
type inspectRequest struct {
+8 -1
View File
@@ -4,6 +4,7 @@ import (
"github.com/go-chi/chi/v5"
"github.com/alexei/docker-watcher/internal/docker"
"github.com/alexei/docker-watcher/internal/events"
"github.com/alexei/docker-watcher/internal/store"
"github.com/alexei/docker-watcher/internal/webhook"
)
@@ -14,6 +15,7 @@ type Server struct {
docker *docker.Client
deployer DeployTriggerer
webhook *webhook.Handler
eventBus *events.Bus
encKey [32]byte
}
@@ -23,6 +25,7 @@ func NewServer(
dockerClient *docker.Client,
deployer DeployTriggerer,
webhookHandler *webhook.Handler,
eventBus *events.Bus,
encKey [32]byte,
) *Server {
return &Server{
@@ -30,6 +33,7 @@ func NewServer(
docker: dockerClient,
deployer: deployer,
webhook: webhookHandler,
eventBus: eventBus,
encKey: encKey,
}
}
@@ -73,7 +77,10 @@ func (s *Server) Router() chi.Router {
// Deploy endpoints.
r.Get("/deploys", s.listDeploys)
r.Get("/deploys/{id}/logs", s.getDeployLogs)
r.Get("/deploys/{id}/logs", s.streamDeployLogs)
// SSE endpoint for real-time instance status and deploy events.
r.Get("/events", s.streamEvents)
// Quick deploy endpoints.
r.Post("/deploy/inspect", s.inspectImage)
+192
View File
@@ -0,0 +1,192 @@
package api
import (
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
"strings"
"github.com/go-chi/chi/v5"
"github.com/alexei/docker-watcher/internal/events"
"github.com/alexei/docker-watcher/internal/store"
)
// streamDeployLogs handles GET /api/deploys/{id}/logs.
// It supports both SSE streaming and JSON fallback based on the Accept header.
//
// SSE mode (Accept: text/event-stream):
//
// Streams deploy log events in real-time. Existing logs are sent first,
// then new logs are pushed as they arrive via the event bus.
//
// JSON mode (default):
//
// Returns all existing deploy logs as a JSON array.
func (s *Server) streamDeployLogs(w http.ResponseWriter, r *http.Request) {
deployID := chi.URLParam(r, "id")
// Verify deploy exists.
deploy, err := s.store.GetDeployByID(deployID)
if err != nil {
if errors.Is(err, store.ErrNotFound) {
respondNotFound(w, "deploy")
return
}
respondError(w, http.StatusInternalServerError, "failed to get deploy: "+err.Error())
return
}
// JSON fallback: return existing logs as array.
accept := r.Header.Get("Accept")
if !strings.Contains(accept, "text/event-stream") {
logs, err := s.store.GetDeployLogs(deployID)
if err != nil {
respondError(w, http.StatusInternalServerError, "failed to get deploy logs: "+err.Error())
return
}
respondJSON(w, http.StatusOK, logs)
return
}
// SSE mode.
flusher, ok := w.(http.Flusher)
if !ok {
respondError(w, http.StatusInternalServerError, "streaming not supported")
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")
w.WriteHeader(http.StatusOK)
flusher.Flush()
// Send existing logs first.
existingLogs, err := s.store.GetDeployLogs(deployID)
if err != nil {
log.Printf("[sse] failed to get existing deploy logs: %v", err)
} else {
for _, entry := range existingLogs {
writeSSE(w, flusher, events.Event{
Type: events.EventDeployLog,
Payload: events.DeployLogPayload{
DeployID: deployID,
Message: entry.Message,
Level: entry.Level,
},
})
}
}
// If deploy is already finished, send completion and close.
if isTerminalStatus(deploy.Status) {
writeSSE(w, flusher, events.Event{
Type: events.EventDeployStatus,
Payload: events.DeployStatusPayload{
DeployID: deployID,
ProjectID: deploy.ProjectID,
StageID: deploy.StageID,
ImageTag: deploy.ImageTag,
Status: deploy.Status,
Error: deploy.Error,
},
})
return
}
// Subscribe to new deploy log events for this deploy.
sub := s.eventBus.Subscribe(func(evt events.Event) bool {
switch payload := evt.Payload.(type) {
case events.DeployLogPayload:
return payload.DeployID == deployID
case events.DeployStatusPayload:
return payload.DeployID == deployID
default:
return false
}
})
defer s.eventBus.Unsubscribe(sub)
ctx := r.Context()
for {
select {
case <-ctx.Done():
return
case evt, ok := <-sub:
if !ok {
return
}
writeSSE(w, flusher, evt)
// Close stream when deploy reaches terminal status.
if evt.Type == events.EventDeployStatus {
if payload, ok := evt.Payload.(events.DeployStatusPayload); ok {
if isTerminalStatus(payload.Status) {
return
}
}
}
}
}
}
// streamEvents handles GET /api/events.
// It streams instance status changes and deploy status changes via SSE.
func (s *Server) streamEvents(w http.ResponseWriter, r *http.Request) {
flusher, ok := w.(http.Flusher)
if !ok {
respondError(w, http.StatusInternalServerError, "streaming not supported")
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")
w.WriteHeader(http.StatusOK)
flusher.Flush()
// Subscribe to instance status and deploy status events.
sub := s.eventBus.Subscribe(func(evt events.Event) bool {
return evt.Type == events.EventInstanceStatus || evt.Type == events.EventDeployStatus
})
defer s.eventBus.Unsubscribe(sub)
ctx := r.Context()
for {
select {
case <-ctx.Done():
return
case evt, ok := <-sub:
if !ok {
return
}
writeSSE(w, flusher, evt)
}
}
}
// writeSSE writes a single SSE event to the response writer and flushes.
func writeSSE(w http.ResponseWriter, flusher http.Flusher, evt events.Event) {
data, err := json.Marshal(evt)
if err != nil {
log.Printf("[sse] marshal event: %v", err)
return
}
fmt.Fprintf(w, "data: %s\n\n", data)
flusher.Flush()
}
// isTerminalStatus returns true if the deploy status is final.
func isTerminalStatus(status string) bool {
switch status {
case "success", "failed", "rolled_back":
return true
default:
return false
}
}
+42
View File
@@ -0,0 +1,42 @@
package api
import (
"io/fs"
"net/http"
"strings"
)
// StaticHandler serves embedded SPA files with fallback to index.html
// for all non-API routes (SPA client-side routing support).
func StaticHandler(webFS fs.FS) http.Handler {
fileServer := http.FileServer(http.FS(webFS))
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Skip API routes — they are handled by the API router.
if strings.HasPrefix(r.URL.Path, "/api") {
http.NotFound(w, r)
return
}
// Try to serve the exact file.
path := strings.TrimPrefix(r.URL.Path, "/")
if path == "" {
path = "index.html"
}
// Check if file exists in the embedded FS.
f, err := webFS.Open(path)
if err == nil {
f.Close()
// Clear the JSON content-type set by middleware — let file server decide.
w.Header().Del("Content-Type")
fileServer.ServeHTTP(w, r)
return
}
// File not found: serve index.html for SPA client-side routing.
r.URL.Path = "/"
w.Header().Del("Content-Type")
fileServer.ServeHTTP(w, r)
})
}