Repository Public
1package api23import (4 "errors"5 "fmt"6 "net/http"7 "strconv"8 "strings"9 "time"1011 "clustr.spboucher.ai/mcc/internal/authz"12 "clustr.spboucher.ai/mcc/internal/events"13 "clustr.spboucher.ai/mcc/internal/httpx"14)1516// topicPermission maps each event topic to the permission needed to receive it.17var topicPermission = map[string]authz.Permission{18 "node.state": authz.NodesRead, "node.updated": authz.NodesRead, "service.changed": authz.ServicesRead,19 "alert.changed": authz.AlertsRead, "incident.changed": authz.AlertsRead, "action.changed": authz.ActionsRead,20 "action.output": authz.LogsRead, "job.changed": authz.JobsRead, "maintenance.changed": authz.MaintenanceRead,21 "audit.appended": authz.AuditRead, "model.changed": authz.ModelsRead,22}2324const (25 sseHeartbeat = 15 * time.Second26 sseMaxSession = 30 * time.Minute // the client reconnects with Last-Event-ID; bounds use of a since-revoked session27 sseBatch = 50028)2930// serveEvents streams committed events as Server-Sent Events.31//32// id: <seq> monotonically increasing; resume with Last-Event-ID33// event: <topic>34// data: <json payload>35//36// A client whose position is no longer retained receives "event: resync"37// and must reload its state. Topics the session may not read are skipped.38func (s *Server) serveEvents(w http.ResponseWriter, r *http.Request) {39 c := s.core40 p, err := c.admit(w, r, "StreamEvents")41 if err != nil {42 httpx.WriteError(w, r, err)43 return44 }45 fl, ok := w.(http.Flusher)46 if !ok {47 httpx.WriteError(w, r, errors.New("streaming unsupported by the connection"))48 return49 }50 ctx := r.Context()51 allowed := map[string]bool{}52 for topic, perm := range topicPermission {53 if ok, err := c.can(ctx, p.Session, perm, authz.Resource{}); err == nil && ok {54 allowed[topic] = true55 }56 }57 if want := r.URL.Query().Get("topics"); want != "" {58 sel := map[string]bool{}59 for _, t := range strings.Split(want, ",") {60 if t = strings.TrimSpace(t); allowed[t] {61 sel[t] = true62 }63 }64 allowed = sel65 }6667 last := r.Header.Get("Last-Event-ID")68 if last == "" {69 last = r.URL.Query().Get("last_event_id")70 }71 var pos int6472 resume := false73 if last != "" {74 if n, err := strconv.ParseInt(last, 10, 64); err == nil && n >= 0 {75 pos, resume = n, true76 }77 }78 head, err := c.Hub.Head(ctx)79 if err != nil {80 httpx.WriteError(w, r, httpx.ErrUnavailable)81 return82 }83 if !resume {84 pos = head // a new stream starts at the present; state is loaded through the REST endpoints85 }8687 h := w.Header()88 h.Set("Content-Type", "text/event-stream; charset=utf-8")89 h.Set("Cache-Control", "no-store")90 h.Set("X-Accel-Buffering", "no")91 w.WriteHeader(http.StatusOK)92 fmt.Fprintf(w, "retry: 3000\nevent: hello\ndata: {\"head\":%d}\n\n", head)93 fl.Flush()9495 wake, unsub := c.Hub.Subscribe()96 defer unsub()97 beat := time.NewTicker(sseHeartbeat)98 defer beat.Stop()99 deadline := time.NewTimer(sseMaxSession)100 defer deadline.Stop()101 recheck := time.NewTicker(time.Minute)102 defer recheck.Stop()103 token, kind := p.SessionToken, "cookie"104 if token == "" {105 token, kind = strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer "), "bearer"106 }107108 for {109 for {110 evs, err := c.Hub.Since(ctx, pos, sseBatch)111 if errors.Is(err, events.ErrResync) {112 if head, err = c.Hub.Head(ctx); err != nil {113 return114 }115 pos = head116 fmt.Fprintf(w, "id: %d\nevent: resync\ndata: {}\n\n", pos)117 fl.Flush()118 break119 }120 if err != nil {121 return // database unavailable: close; the client reconnects with its last id122 }123 for _, e := range evs {124 pos = e.Seq125 if !allowed[e.Topic] {126 continue127 }128 fmt.Fprintf(w, "id: %d\nevent: %s\ndata: %s\n\n", e.Seq, e.Topic, e.Payload)129 }130 fl.Flush()131 if len(evs) < sseBatch {132 break133 }134 }135 select {136 case <-ctx.Done():137 return138 case <-deadline.C:139 return140 case <-recheck.C:141 // A revoked or expired session stops receiving events within a minute.142 if _, err := c.Identity.Authenticate(ctx, token, kind); err != nil {143 return144 }145 case <-beat.C:146 if _, err := fmt.Fprint(w, ": ping\n\n"); err != nil {147 return148 }149 fl.Flush()150 case <-wake:151 }152 }153}154