Files
skillshare/internal/server/handler_audit_stream.go
T
Willie 344b067806 feat(ui): add SSE streaming for update, check, and diff pages
Replace sequential POST loops and blocking useQuery calls with
Server-Sent Events for real-time progress feedback on Update, Check,
and Diff operations. Extract shared helpers to reduce duplication:

- initSSE() in middleware.go consolidates SSE preamble across 4 handlers
- createSSEStream() in client.ts unifies EventSource lifecycle management
- StreamProgressBar component replaces 3 near-identical progress bars
- handleDiff now delegates to computeTargetDiff (eliminates ~150 lines)
- Paginate audit results (20 cards + 10 findings per card) to prevent
  DOM overload with large skill counts
2026-03-05 02:13:21 +08:00

80 lines
1.9 KiB
Go

package server
import (
"net/http"
"sync"
"sync/atomic"
"time"
"skillshare/internal/audit"
)
// handleAuditStream serves an SSE endpoint that streams audit progress in real time.
// Events:
// - "start" → {"total": N} after skill discovery
// - "progress" → {"scanned": N} every 200ms during scan
// - "done" → {"results":…,"summary":…} final payload (same shape as GET /api/audit)
func (s *Server) handleAuditStream(w http.ResponseWriter, r *http.Request) {
safeSend, ok := initSSE(w)
if !ok {
return
}
start := time.Now()
policy := s.auditPolicy()
// 1. Discover skills
skills, err := discoverAuditSkills(s.cfg.Source)
if err != nil {
safeSend("error", map[string]string{"error": err.Error()})
return
}
safeSend("start", map[string]int{"total": len(skills)})
// 2. Atomic counter + ticker for progress events
var scanned atomic.Int64
ctx := r.Context()
done := make(chan struct{})
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
ticker := time.NewTicker(200 * time.Millisecond)
defer ticker.Stop()
for {
select {
case <-ticker.C:
safeSend("progress", map[string]int64{"scanned": scanned.Load()})
case <-done:
return
case <-ctx.Done():
return
}
}
}()
onDone := func() { scanned.Add(1) }
projectRoot := s.projectRoot
if !s.IsProjectMode() {
projectRoot = ""
}
// 3. Parallel scan (blocks until all skills are scanned)
outputs := audit.ParallelScan(skillsToAuditInputs(skills), projectRoot, onDone, nil)
close(done) // signal ticker goroutine to stop
wg.Wait() // wait for it to fully exit before writing to w
// 4. Process results
agg := processAuditResults(skills, outputs, policy)
s.writeAuditLog(agg.Status, start, agg.LogArgs, agg.Message)
// 5. Send final result (no concurrent writers at this point)
safeSend("done", map[string]any{
"results": agg.Results,
"summary": agg.Summary,
})
}