hmr.go

82 lines
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
package frontend

import (
	"fmt"
	"net/http"
)

// hmrHub is a single goroutine that owns the client map.
// All access is serialized through channels — no mutex needed.
func (f *Frontend) hmrHub() {
	clients := make(map[chan struct{}]struct{})
	for {
		select {
		case ch := <-f.hmrJoin:
			clients[ch] = struct{}{}
		case ch := <-f.hmrLeave:
			delete(clients, ch)
		case <-f.hmrReload:
			for ch := range clients {
				select {
				case ch <- struct{}{}:
				default:
				}
			}
		case <-f.hmrDone:
			for ch := range clients {
				close(ch)
			}
			return
		}
	}
}

// handleHMR handles SSE connections for hot module replacement.
func (f *Frontend) handleHMR(w http.ResponseWriter, r *http.Request) {
	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")
	if f.DevMode {
		w.Header().Set("Access-Control-Allow-Origin", "*")
	}

	// Subscribe to reload signals via the hub
	ch := make(chan struct{}, 1)
	select {
	case f.hmrJoin <- ch:
	case <-f.hmrDone:
		return
	}

	// Send initial connection message
	fmt.Fprintf(w, "data: connected\n\n")
	flusher.Flush()

	// Wait for reload signal or disconnect
	select {
	case <-ch:
		fmt.Fprintf(w, "data: reload\n\n")
		flusher.Flush()
	case <-r.Context().Done():
	}

	// Unsubscribe — safe even after hub shutdown
	select {
	case f.hmrLeave <- ch:
	case <-f.hmrDone:
	}
}

// notifyClients signals all connected HMR clients to reload.
func (f *Frontend) notifyClients() {
	select {
	case f.hmrReload <- struct{}{}:
	default:
	}
}