|
| 1 | +// Package sse provides Server-Sent Events (SSE) endpoint for streaming log files. |
| 2 | +package sse |
| 3 | + |
| 4 | +import ( |
| 5 | + "evolve/util" |
| 6 | + "fmt" |
| 7 | + "io" |
| 8 | + "net/http" |
| 9 | + "path/filepath" |
| 10 | + "strings" |
| 11 | + "time" |
| 12 | + |
| 13 | + "github.com/hpcloud/tail" |
| 14 | +) |
| 15 | + |
| 16 | +const ( |
| 17 | + logDir = "live" // Directory where <runId>.str files are stored. |
| 18 | + runIdHeader = "X-RUN-ID" // Header key for the run ID. |
| 19 | + retrySeconds = 3 // SSE retry interval suggestion for clients. |
| 20 | +) |
| 21 | + |
| 22 | +// GetSSEHandler creates and returns an http.HandlerFunc for the SSE endpoint. |
| 23 | +// It takes the application's logger as an argument. |
| 24 | +func GetSSEHandler(logger util.Logger) http.HandlerFunc { |
| 25 | + return func(w http.ResponseWriter, r *http.Request) { |
| 26 | + serveSSE(logger, w, r) |
| 27 | + } |
| 28 | +} |
| 29 | + |
| 30 | +// serveSSE handles incoming SSE requests. |
| 31 | +func serveSSE(logger util.Logger, w http.ResponseWriter, r *http.Request) { |
| 32 | + ctx := r.Context() // Get context from the request |
| 33 | + |
| 34 | + // --- 1. Get Run ID from Header --- |
| 35 | + runId := r.Header.Get(runIdHeader) |
| 36 | + if runId == "" { |
| 37 | + logger.Warn(fmt.Sprintf("[SSE Handler] Missing %s header", runIdHeader)) |
| 38 | + http.Error(w, fmt.Sprintf("Missing %s header", runIdHeader), http.StatusBadRequest) |
| 39 | + return |
| 40 | + } |
| 41 | + |
| 42 | + // --- Basic Sanitize Run ID (Prevent path traversal) --- |
| 43 | + // Ensure runId doesn't contain potentially harmful sequences. |
| 44 | + // A more robust solution might involve checking against a list of valid run IDs. |
| 45 | + if strings.Contains(runId, "..") || strings.ContainsAny(runId, "/\\") { |
| 46 | + logger.Warn(fmt.Sprintf("[SSE Handler] Invalid characters in %s header: %s", runIdHeader, runId)) |
| 47 | + http.Error(w, "Invalid Run ID format", http.StatusBadRequest) |
| 48 | + return |
| 49 | + } |
| 50 | + |
| 51 | + logFileName := fmt.Sprintf("%s.str", runId) |
| 52 | + logFilePath := filepath.Join(logDir, logFileName) |
| 53 | + |
| 54 | + logger.Info(fmt.Sprintf("[SSE Handler] Request received for runId: %s (File: %s)", runId, logFilePath)) |
| 55 | + |
| 56 | + // --- 2. Set SSE Headers --- |
| 57 | + w.Header().Set("Content-Type", "text/event-stream") |
| 58 | + w.Header().Set("Cache-Control", "no-cache") |
| 59 | + w.Header().Set("Connection", "keep-alive") |
| 60 | + w.Header().Set("X-Accel-Buffering", "no") |
| 61 | + |
| 62 | + // Suggest a retry interval to the client |
| 63 | + fmt.Fprintf(w, "retry: %d\n\n", retrySeconds*1000) // retry is in milliseconds |
| 64 | + |
| 65 | + // --- 3. Get Flusher --- |
| 66 | + rc := http.NewResponseController(w) |
| 67 | + if rc == nil { |
| 68 | + logger.Error(fmt.Sprintf("[SSE Handler] Failed to get ResponseController for runId: %s", runId)) |
| 69 | + http.Error(w, "Failed to get ResponseController", http.StatusInternalServerError) |
| 70 | + return |
| 71 | + } |
| 72 | + |
| 73 | + if err := rc.Flush(); err != nil { |
| 74 | + logger.Error(fmt.Sprintf("[SSE Handler] Error flushing response for runId %s: %v", runId, err)) |
| 75 | + http.Error(w, "Error flushing response", http.StatusInternalServerError) |
| 76 | + return |
| 77 | + } |
| 78 | + |
| 79 | + // --- 4. Configure and Start Tailing --- |
| 80 | + tailConfig := tail.Config{ |
| 81 | + Location: &tail.SeekInfo{Offset: 0, Whence: io.SeekStart}, // Start from the beginning of the file |
| 82 | + ReOpen: true, // Re-open file if recreated (log rotation) |
| 83 | + MustExist: false, // Don't fail if file doesn't exist yet |
| 84 | + Poll: true, // Use polling (more reliable across FS types/network mounts than pure inotify) - tune if needed |
| 85 | + Follow: true, // Keep following the file for new lines |
| 86 | + // Logger: tail.DiscardingLogger, // Uncomment to disable tail library's internal logging |
| 87 | + } |
| 88 | + |
| 89 | + tailer, err := tail.TailFile(logFilePath, tailConfig) |
| 90 | + if err != nil { |
| 91 | + logger.Error(fmt.Sprintf("[SSE Tailing] Failed to start tailing file %s for runId %s: %v", logFilePath, runId, err)) |
| 92 | + // Don't send HTTP error here as headers are already sent. Client will retry or disconnect. |
| 93 | + return |
| 94 | + } |
| 95 | + |
| 96 | + // Ensure tailer is stopped when the handler exits |
| 97 | + defer func() { |
| 98 | + logger.Info(fmt.Sprintf("[SSE Handler] Stopping tailer for runId: %s", runId)) |
| 99 | + // Stopping the tailer closes its internal channels |
| 100 | + if stopErr := tailer.Stop(); stopErr != nil { |
| 101 | + logger.Error(fmt.Sprintf("[SSE Tailing] Error stopping tailer for runId %s: %v", runId, stopErr)) |
| 102 | + } |
| 103 | + }() |
| 104 | + |
| 105 | + logger.Info(fmt.Sprintf("[SSE Handler] Started tailing %s for runId: %s", logFilePath, runId)) |
| 106 | + |
| 107 | + // --- 5. Event Loop: Send lines and handle disconnect --- |
| 108 | + for { |
| 109 | + select { |
| 110 | + case <-ctx.Done(): // Client disconnected |
| 111 | + logger.Info(fmt.Sprintf("[SSE Handler] Client disconnected for runId: %s", runId)) |
| 112 | + return // Exit handler, defer will stop tailer |
| 113 | + |
| 114 | + case line, ok := <-tailer.Lines: // New line from file |
| 115 | + if !ok { |
| 116 | + // Channel closed, tailer might have stopped or encountered an error |
| 117 | + tailErr := tailer.Err() |
| 118 | + if tailErr != nil && tailErr != io.EOF { // io.EOF might occur normally on stop |
| 119 | + logger.Error(fmt.Sprintf("[SSE Tailing] Error during tailing for runId %s: %v", runId, tailErr)) |
| 120 | + } else { |
| 121 | + logger.Info(fmt.Sprintf("[SSE Tailing] Tailer lines channel closed for runId: %s", runId)) |
| 122 | + } |
| 123 | + return // Exit handler |
| 124 | + } |
| 125 | + |
| 126 | + fmt.Printf("[SSE Handler] New line for runId %s: %s\n", runId, line.Text) // Debug log |
| 127 | + |
| 128 | + // ---> CHECK FOR END MARKER <--- |
| 129 | + if line.Text == "__END__" { |
| 130 | + logger.Info(fmt.Sprintf("[SSE Handler] Detected END marker for run %s. Closing stream.", runId)) |
| 131 | + return |
| 132 | + } |
| 133 | + |
| 134 | + // Format and send SSE message |
| 135 | + // Use fmt.Fprintf to write directly to the ResponseWriter |
| 136 | + _, writeErr := fmt.Fprintf(w, "data: %s\n\n", line.Text) // SSE format: "data: content\n\n" |
| 137 | + |
| 138 | + if writeErr != nil { |
| 139 | + // Likely client disconnected or network error |
| 140 | + logger.Warn(fmt.Sprintf("[SSE Handler] Error writing to client for runId %s: %v", runId, writeErr)) |
| 141 | + return // Exit handler, defer will stop tailer |
| 142 | + } |
| 143 | + |
| 144 | + if err := rc.Flush(); err != nil { |
| 145 | + logger.Error(fmt.Sprintf("[SSE Handler] Error flushing response for runId %s: %v", runId, err)) |
| 146 | + return // Exit handler, defer will stop tailer |
| 147 | + } |
| 148 | + |
| 149 | + time.Sleep(50 * time.Millisecond) |
| 150 | + } |
| 151 | + } |
| 152 | +} |
0 commit comments