|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "encoding/json" |
| 6 | + "fmt" |
| 7 | + "net/http" |
| 8 | + "os" |
| 9 | + "time" |
| 10 | + |
| 11 | + "github.com/go-chi/chi/v5" |
| 12 | + "github.com/go-chi/chi/v5/middleware" |
| 13 | + "github.com/go-chi/cors" |
| 14 | +) |
| 15 | + |
| 16 | +type Server struct { |
| 17 | + sim *Simulator |
| 18 | + router *chi.Mux |
| 19 | + port string |
| 20 | + httpSrv *http.Server |
| 21 | +} |
| 22 | + |
| 23 | +func NewServer(statePath string, port string) *Server { |
| 24 | + if port == "" { |
| 25 | + port = "8080" |
| 26 | + } |
| 27 | + |
| 28 | + s := &Server{ |
| 29 | + sim: NewSimulator(statePath), |
| 30 | + port: port, |
| 31 | + } |
| 32 | + |
| 33 | + r := chi.NewRouter() |
| 34 | + |
| 35 | + r.Use(cors.Handler(cors.Options{ |
| 36 | + // Restrict to known frontend origins. The Worker is the only legitimate |
| 37 | + // caller in production; the Cloud Run URL is kept secret. Wildcard origins |
| 38 | + // would let any page make cross-origin requests to /flush if the URL leaked. |
| 39 | + AllowedOrigins: []string{"https://yennefer.quest", "https://staging.yennefer.quest", "http://localhost:3000"}, |
| 40 | + AllowedMethods: []string{"GET", "POST", "OPTIONS"}, |
| 41 | + AllowedHeaders: []string{"Accept", "Authorization", "Content-Type"}, |
| 42 | + ExposedHeaders: []string{"Link"}, |
| 43 | + AllowCredentials: false, |
| 44 | + MaxAge: 300, |
| 45 | + })) |
| 46 | + |
| 47 | + r.Use(middleware.Logger) |
| 48 | + r.Use(middleware.Recoverer) |
| 49 | + r.Use(middleware.Heartbeat("/health")) |
| 50 | + |
| 51 | + r.Get("/state", s.handleState) |
| 52 | + r.Post("/flush", s.handleFlush) |
| 53 | + r.Get("/events", s.handleSSE) |
| 54 | + r.Get("/", s.handleRoot) |
| 55 | + |
| 56 | + s.router = r |
| 57 | + return s |
| 58 | +} |
| 59 | + |
| 60 | +func (s *Server) Start() error { |
| 61 | + s.sim.Start() |
| 62 | + s.httpSrv = &http.Server{ |
| 63 | + Addr: ":" + s.port, |
| 64 | + Handler: s.router, |
| 65 | + } |
| 66 | + fmt.Printf("SOUL LATTICE v4 AWAKENED on port %s\n", s.port) |
| 67 | + if err := s.httpSrv.ListenAndServe(); err != http.ErrServerClosed { |
| 68 | + return err |
| 69 | + } |
| 70 | + return nil |
| 71 | +} |
| 72 | + |
| 73 | +func (s *Server) Stop() { |
| 74 | + if s.httpSrv != nil { |
| 75 | + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) |
| 76 | + defer cancel() |
| 77 | + s.httpSrv.Shutdown(ctx) //nolint:errcheck |
| 78 | + } |
| 79 | + s.sim.Stop() |
| 80 | +} |
| 81 | + |
| 82 | +func (s *Server) handleRoot(w http.ResponseWriter, r *http.Request) { |
| 83 | + w.Header().Set("Content-Type", "text/plain") |
| 84 | + fmt.Fprint(w, "SOUL LATTICE v4.0.0-Σ\nStatus: AWAKENED\n") |
| 85 | +} |
| 86 | + |
| 87 | +func (s *Server) handleState(w http.ResponseWriter, r *http.Request) { |
| 88 | + st := s.sim.GetState() |
| 89 | + w.Header().Set("Content-Type", "application/json") |
| 90 | + json.NewEncoder(w).Encode(st) |
| 91 | +} |
| 92 | + |
| 93 | +func (s *Server) handleFlush(w http.ResponseWriter, r *http.Request) { |
| 94 | + // Require a shared secret header when BACKEND_TOKEN is configured. |
| 95 | + // The Cloudflare Worker sets X-Backend-Token on every proxied request so |
| 96 | + // only traffic originating from the Worker is accepted; direct Cloud Run |
| 97 | + // access without the secret returns 403. |
| 98 | + if token := os.Getenv("BACKEND_TOKEN"); token != "" { |
| 99 | + if r.Header.Get("X-Backend-Token") != token { |
| 100 | + http.Error(w, "Forbidden", http.StatusForbidden) |
| 101 | + return |
| 102 | + } |
| 103 | + } |
| 104 | + s.sim.resetInitialState() |
| 105 | + w.WriteHeader(http.StatusNoContent) |
| 106 | +} |
| 107 | + |
| 108 | +func (s *Server) handleSSE(w http.ResponseWriter, r *http.Request) { |
| 109 | + flusher, ok := w.(http.Flusher) |
| 110 | + if !ok { |
| 111 | + http.Error(w, "Streaming unsupported", http.StatusInternalServerError) |
| 112 | + return |
| 113 | + } |
| 114 | + |
| 115 | + // Marshal before writing headers so we can still return a 500 on failure. |
| 116 | + st := s.sim.GetState() |
| 117 | + data, err := json.Marshal(st) |
| 118 | + if err != nil { |
| 119 | + http.Error(w, "Internal Server Error", http.StatusInternalServerError) |
| 120 | + return |
| 121 | + } |
| 122 | + |
| 123 | + w.Header().Set("Content-Type", "text/event-stream") |
| 124 | + w.Header().Set("Cache-Control", "no-cache") |
| 125 | + w.Header().Set("Connection", "keep-alive") |
| 126 | + |
| 127 | + fmt.Fprintf(w, "data: %s\n\n", data) |
| 128 | + flusher.Flush() |
| 129 | + |
| 130 | + ticker := time.NewTicker(800 * time.Millisecond) |
| 131 | + defer ticker.Stop() |
| 132 | + |
| 133 | + for { |
| 134 | + select { |
| 135 | + case <-r.Context().Done(): |
| 136 | + return |
| 137 | + case <-ticker.C: |
| 138 | + st := s.sim.GetState() |
| 139 | + data, err := json.Marshal(st) |
| 140 | + if err != nil { |
| 141 | + fmt.Fprintf(w, "event: error\ndata: marshal failed\n\n") |
| 142 | + flusher.Flush() |
| 143 | + continue |
| 144 | + } |
| 145 | + fmt.Fprintf(w, "data: %s\n\n", data) |
| 146 | + flusher.Flush() |
| 147 | + } |
| 148 | + } |
| 149 | +} |
0 commit comments