1// SPDX-License-Identifier: AGPL-3.0-or-later
2
3package web
4
5import (
6 "context"
7 "errors"
8 "fmt"
9 "io"
10 "net/http"
11 "net/url"
12 "strconv"
13 "strings"
14 "sync"
15 "time"
16
17 "github.com/bnema/zerowrap"
18
19 "bnema.dev/ermite/internal/clientlimit"
20 "bnema.dev/ermite/internal/domain"
21 "bnema.dev/ermite/internal/ports"
22)
23
24// Live updates. A page that can change under the eyes of its reader opens
25// GET /-/events (the Live component of the hint badge). The handler follows
26// EventService.Watch as the principal of the request and turns each event into
27// the HTML fragments the page shows, sent as Server-Sent Events:
28//
29// GET /-/events?topic=home
30// GET /-/events?topic=owner&view=inbox[&repo=<name>] (the signed-in owner only)
31// GET /-/events?topic=repo:<name>&view=summary|refs
32// GET /-/events?topic=repo:<name>&view=commits&ref=<branch>&head=<sha>
33// GET /-/events?topic=repo:<name>&view=mrs
34// GET /-/events?topic=repo:<name>&view=mr&n=<number>&ref=<source branch>&target=<target branch>
35// GET /-/events?topic=repo:<name>&view=issues
36// GET /-/events?topic=repo:<name>&view=issue&n=<number>
37// GET /-/events?topic=repo:<name>&view=actions
38// GET /-/events?topic=repo:<name>&view=run&n=<run id>
39// GET /-/events?topic=repo:<name>&view=job&job=<job id>
40//
41// topic is the Watch topic. view says which fragments of a repository the
42// page shows, so that the server renders only those (summary when absent).
43// On the commits page, ref is the branch it lists and head the commit it
44// lists first: the banner counts the commits between that head and the new
45// tip, so it stays right however many pushes came in and however often the
46// stream reconnected. A Last-Event-ID header resumes the stream
47// (resume_after).
48//
49// Events, each with the id of the Watch event it comes from:
50//
51// home-list data: <li id="repo-<name>">…</li>, or <li id="repo-<name>" data-gone></li>
52// for a repository that is deleted or no longer visible
53// repo-last-push data: <dd id="last-push-<name>">…</dd>
54// refs-list data: <tbody id="ref-rows">…</tbody>, and again with
55// <dl id="refs-kv">…</dl>, the facts of the rail
56// commits-head data: <div id="commits-head">N new commits — reload</div>
57// mr-mergeability data: <div id="mr-mergeability">…</div>, on the merge request pages:
58// the badge of the merge box (a slot like mr-notice), when the
59// mergeability of the request shown settles or a push moves its
60// source or target
61// mr-notice data: <div id="mr-notice">…</div>, on the merge request and issue pages:
62// something changed, with the link that reloads the page
63// ci-run data: <tr id="run-<id>">…</tr> (the list of runs),
64// <section id="recent-actions">…</section> (the rail of the summary) or
65// <div id="run-body">…</div> (one run)
66// ci-job data: <h2 id="job-head">…</h2> and <ol id="job-steps">…</ol>; the log
67// itself is never sent in this stream: the page follows it on its own
68// feed, /<repo>/actions/runs/<id>/job/<job>/stream?from=<line>
69// gap data: gap; events were lost, or what the page shows is gone or
70// changed: the page fetches itself again (ermiteLive in ermite.js)
71//
72// The data of an event is one fragment, a top-level element with an id, one
73// "data:" line per line of HTML; the page swaps the element that has that id
74// (ermiteLive.swap). The slots of the banners (commits-head, mr-notice) are
75// status regions that stay in the page: only their children are replaced, so
76// that a screen reader announces the banner.
77// An event that changes nothing on the page is still sent as an id alone, so
78// that a reconnection resumes after it.
79
80// DefaultHeartbeat is how often an idle stream gets a comment line, so that
81// proxies keep it open and a dead peer is noticed.
82const DefaultHeartbeat = 25 * time.Second
83
84const (
85 // writeWindow bounds one write to the visitor, whatever the write timeout
86 // of the server is.
87 writeWindow = 30 * time.Second
88 // retryAfter is the delay asked from a visitor refused for lack of room.
89 retryAfter = 10
90)
91
92// ownerTopic is the stream of the inbox: the merge requests and issues of every
93// repository, for the owner.
94const ownerTopic = "owner"
95
96// parseTopic reads "home", "owner" or "repo:<name>"; repo is "" for home and
97// owner.
98func parseTopic(topic string) (repo string, ok bool) {
99 if topic == "home" || topic == ownerTopic {
100 return "", true
101 }
102 if name, found := strings.CutPrefix(topic, "repo:"); found && name != "" {
103 return name, true
104 }
105 return "", false
106}
107
108// ownerStreamOK tells whether the request may follow the owner topic: the
109// signed-in owner, with the inbox view and a valid repository filter, on a
110// server that has the inbox.
111func (s *Server) ownerStreamOK(ctx context.Context, q url.Values) bool {
112 if s.cfg.Inbox == nil || !SignedIn(ctx) || q.Get("view") != "inbox" {
113 return false
114 }
115 if f := q.Get("repo"); f != "" {
116 if _, err := domain.ParseRepoName(f); err != nil {
117 return false
118 }
119 }
120 return true
121}
122
123// events is GET /-/events.
124func (s *Server) events(w http.ResponseWriter, r *http.Request) {
125 if s.cfg.Events == nil {
126 http.NotFound(w, r)
127 return
128 }
129 q := r.URL.Query()
130 topic := q.Get("topic")
131 repo, ok := parseTopic(topic)
132 if topic == ownerTopic {
133 // Anyone but the signed-in owner gets the answer of an unknown topic.
134 ok = s.ownerStreamOK(r.Context(), q)
135 repo = ""
136 }
137 if !ok {
138 denyStream(w, http.StatusBadRequest, "topic must be home or repo:<name>")
139 return
140 }
141 ctx, cancel := context.WithCancel(r.Context())
142 defer cancel()
143 log := zerowrap.FromCtx(ctx)
144
145 if repo != "" {
146 // A repository the visitor cannot see is a missing one (AC2).
147 cctx, ccancel := context.WithTimeout(ctx, requestTimeout)
148 err := s.canSee(cctx, repo)
149 if err == nil {
150 if v := q.Get("view"); v == "issues" || v == "issue" {
151 err = s.issuesOn(cctx, repo)
152 }
153 }
154 ccancel()
155 if err != nil {
156 s.denyEvents(ctx, w, err)
157 return
158 }
159 }
160
161 // The commit of the run of a job page is read once here: the annotations of
162 // the live job fragments link to files at it, and it never changes, so a
163 // job update does not read the run again. A run that is not there or not
164 // readable refuses the stream like a missing repository.
165 var sha string
166 if repo != "" && q.Get("view") == "job" && s.cfg.Runs != nil {
167 cctx, ccancel := context.WithTimeout(ctx, requestTimeout)
168 var err error
169 sha, err = s.jobRunSha(cctx, repo, q.Get("job"))
170 ccancel()
171 if err != nil {
172 s.denyEvents(ctx, w, err)
173 return
174 }
175 }
176
177 // The watch runs in a goroutine and hands each event to this one through
178 // an unbuffered channel: a visitor that reads slowly holds the watch in
179 // its send, falls behind the buffer of the use case, and gets a gap.
180 msgs := make(chan recvd)
181 started := make(chan struct{})
182 var startOnce sync.Once
183 start := func() { startOnce.Do(func() { close(started) }) }
184 finished := make(chan struct{})
185 params := ports.WatchParams{
186 Topics: []string{topic}, ResumeAfter: r.Header.Get("Last-Event-ID"),
187 // The visitor is the client of the watch, for the limit per client.
188 Client: clientlimit.Key(clientlimit.ClientAddr(r, s.cfg.TrustedProxies)),
189 Ready: start,
190 }
191 go func() {
192 defer close(finished)
193 defer close(msgs)
194 // net/http only recovers the handler goroutine: a panic in the watch
195 // would end the process. It ends this stream as an error instead.
196 defer func() {
197 if v := recover(); v != nil {
198 log.Error().Interface("panic", v).Msg("event watch panicked")
199 select {
200 case msgs <- recvd{err: fmt.Errorf("watch panicked: %v", v)}:
201 case <-ctx.Done():
202 }
203 }
204 }()
205 err := s.cfg.Events.Watch(ctx, principal(ctx), params, func(we ports.WatchEvent) error {
206 start()
207 select {
208 case msgs <- recvd{ev: we}:
209 return nil
210 case <-ctx.Done():
211 return ctx.Err()
212 }
213 })
214 if err != nil && ctx.Err() == nil {
215 select {
216 case msgs <- recvd{err: err}:
217 case <-ctx.Done():
218 }
219 }
220 }()
221 defer func() {
222 cancel()
223 <-finished
224 }()
225
226 // The watch is registered (or refused, which ends it before): only then
227 // does the answer commit to 200.
228 var first *recvd
229 select {
230 case <-started:
231 case m, open := <-msgs:
232 if !open {
233 return // the server is stopping
234 }
235 if m.err != nil {
236 s.denyEvents(ctx, w, m.err)
237 return
238 }
239 first = &m
240 case <-ctx.Done():
241 return
242 }
243
244 rc := http.NewResponseController(w)
245 hdr := w.Header()
246 hdr.Set("Content-Type", "text/event-stream")
247 cacheHeaders(ctx, hdr, "no-cache, no-transform", sessionCache+", no-transform")
248 if hdr.Get("Cache-Control") == noStore { // an invalid cookie was cleared
249 hdr.Set("Cache-Control", noStore+", no-transform")
250 }
251 hdr.Set("X-Accel-Buffering", "no")
252 _ = rc.SetWriteDeadline(time.Now().Add(writeWindow))
253 w.WriteHeader(http.StatusOK)
254 out := &sseWriter{w: w, rc: rc}
255 if err := out.raw(": connected\n\n"); err != nil {
256 return
257 }
258
259 st := &liveStream{s: s, repo: repo, view: q.Get("view"), ref: q.Get("ref"), head: q.Get("head"), n: q.Get("n"), target: q.Get("target"), job: q.Get("job"), sha: sha}
260 if topic == ownerTopic {
261 st.filter = q.Get("repo")
262 }
263 handle := func(m recvd) bool {
264 if m.err != nil {
265 if ctx.Err() == nil && !errors.Is(m.err, context.Canceled) {
266 log.Debug().Err(m.err).Str("topic", topic).Msg("event stream ended")
267 }
268 return false
269 }
270 if !liveEvent(m.ev) {
271 return true // nothing to show, not even an id to resume after
272 }
273 // An owner's stream ends when the session does, before it sends
274 // anything more: an event can carry what only the owner may see, and
275 // waiting for the next heartbeat would leave a window.
276 if SignedIn(ctx) && !s.sessionStillValid(ctx, r) {
277 return false
278 }
279 rctx, rcancel := context.WithTimeout(ctx, requestTimeout)
280 frags, err := st.render(rctx, m.ev)
281 rcancel()
282 if err != nil {
283 if ctx.Err() != nil {
284 return false
285 }
286 // What the page shows can no longer be told from the events:
287 // have it fetch itself again.
288 log.Warn().Err(err).Str("topic", topic).Msg("render live fragment")
289 frags = gap
290 }
291 return out.send(m.ev.ID, frags) == nil
292 }
293 if first != nil && !handle(*first) {
294 return
295 }
296
297 beat := s.cfg.Heartbeat
298 if beat <= 0 {
299 beat = DefaultHeartbeat
300 }
301 tick := time.NewTicker(beat)
302 defer tick.Stop()
303 for {
304 select {
305 case m, open := <-msgs:
306 if !open || !handle(m) {
307 return
308 }
309 case <-tick.C:
310 // A stream opened by the owner ends when the session does
311 // (sign out everywhere, expiry): the page reconnects as it can.
312 if SignedIn(ctx) && !s.sessionStillValid(ctx, r) {
313 return
314 }
315 if out.raw(": heartbeat\n\n") != nil {
316 return
317 }
318 case <-ctx.Done():
319 return
320 }
321 }
322}
323
324// recvd is a message of the Watch stream, or how it failed.
325type recvd struct {
326 ev ports.WatchEvent
327 err error
328}
329
330// canSee checks that the caller of the request may see the repository named in
331// a topic: one it may not is as missing as one that does not exist.
332func (s *Server) canSee(ctx context.Context, rawName string) error {
333 name, err := domain.ParseRepoName(rawName)
334 if err != nil {
335 return err
336 }
337 _, err = s.cfg.Repos.Get(ctx, principal(ctx), name)
338 return err
339}
340
341// issuesOn is domain.ErrNotFound unless the repository has issues on and
342// s.cfg.Issues is set: the same answer as for a repository the visitor cannot see.
343func (s *Server) issuesOn(ctx context.Context, rawName string) error {
344 if s.cfg.Issues == nil {
345 return domain.ErrNotFound
346 }
347 name, err := domain.ParseRepoName(rawName)
348 if err != nil {
349 return err
350 }
351 v, err := s.cfg.Repos.Get(ctx, principal(ctx), name)
352 if err != nil {
353 return err
354 }
355 if v.Settings.Issues.OrDefault() == domain.IssuesOff {
356 return domain.ErrNotFound
357 }
358 return nil
359}
360
361// denyStream answers a request that gets no stream.
362func denyStream(w http.ResponseWriter, status int, msg string) {
363 w.Header().Set("Cache-Control", "no-store")
364 http.Error(w, msg, status)
365}
366
367// denyEvents maps an error of a use case, before the stream started, to a
368// status. Not found and invalid are 404 whatever the reason: a private
369// repository is a missing one.
370func (s *Server) denyEvents(ctx context.Context, w http.ResponseWriter, err error) {
371 switch {
372 case errors.Is(err, context.Canceled):
373 // The visitor is gone.
374 case errors.Is(err, domain.ErrNotFound), domain.IsInvalid(err):
375 denyStream(w, http.StatusNotFound, "not found")
376 case errors.Is(err, domain.ErrResourceExhausted):
377 w.Header().Set("Retry-After", strconv.Itoa(retryAfter))
378 denyStream(w, http.StatusServiceUnavailable, "too many event streams, retry later")
379 case errors.Is(err, domain.ErrUnauthenticated):
380 denyStream(w, http.StatusUnauthorized, "unauthorized")
381 default:
382 log := zerowrap.FromCtx(ctx)
383 log.Error().Err(err).Msg("open event stream")
384 denyStream(w, http.StatusInternalServerError, "internal error")
385 }
386}
387
388// fragment is one SSE event to send: the name and the HTML of the fragment.
389type fragment struct{ event, html string }
390
391// sseWriter writes events to a visitor, flushing each, under a deadline of
392// its own so that the write timeout of the server cannot end the stream.
393type sseWriter struct {
394 w http.ResponseWriter
395 rc *http.ResponseController
396}
397
398func (o *sseWriter) raw(s string) error {
399 _ = o.rc.SetWriteDeadline(time.Now().Add(writeWindow))
400 if _, err := io.WriteString(o.w, s); err != nil {
401 return err
402 }
403 return o.rc.Flush()
404}
405
406// send writes the fragments of one Watch event under its id. An event that
407// has no fragment still carries its id, so that a reconnection resumes after
408// it.
409func (o *sseWriter) send(id string, frags []fragment) error {
410 if len(frags) == 0 {
411 if id == "" {
412 return nil
413 }
414 return o.raw(formatEvent(id, "", "", false))
415 }
416 for _, f := range frags {
417 if err := o.raw(formatEvent(id, f.event, f.html, true)); err != nil {
418 return err
419 }
420 }
421 return nil
422}
423
424// formatEvent is one SSE event. Each line of data is a "data:" field, and a
425// browser joins them back with newlines.
426func formatEvent(id, event, data string, hasData bool) string {
427 var b strings.Builder
428 if event != "" {
429 b.WriteString("event: " + event + "\n")
430 }
431 if id != "" {
432 b.WriteString("id: " + id + "\n")
433 }
434 if hasData {
435 data = strings.ReplaceAll(strings.ReplaceAll(data, "\r\n", "\n"), "\r", "\n")
436 for line := range strings.SplitSeq(data, "\n") {
437 b.WriteString("data: " + line + "\n")
438 }
439 }
440 b.WriteString("\n")
441 return b.String()
442}
443
444// liveURL is the stream a page follows: the topic and, for a repository
445// page, what it shows (see the comment on events).
446func liveURL(topic, query string) string {
447 u := "/-/events?topic=" + url.QueryEscape(topic)
448 if query != "" {
449 u += "&" + query
450 }
451 return u
452}