detached 388d3be

events.go RawHistoryFolder

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

Keyboard shortcuts

Single-key shortcuts are on. ctrl k and esc work whatever this says.

ctrl k :
go to a section, branch, tag, file or repository
?
this list
j k
move the row cursor down / up
enter
open the row under the cursor; on Files, a directory opens or closes in place
↑ ↓ ← → home end
in the file tree (focus on a row): previous / next row, close / open a directory or go to its parent / first entry, first / last row. They never open a file
l h
on Files: open a directory or a file / close a directory or go up to its parent, then to the parent page. Elsewhere: into the side panel (on a merge request, its files) / back to the content; there j k move between its controls
g g G
first / last row
/
filter the list; on Files, find a file anywhere in the repository (esc clears, enter opens the best match)
b
switch branch or tag
g s g f g c g b g m g i g r g a
tabs: summary, files, commits, branches & tags, merge requests, issues, releases, actions (when available)
g h
home
w
wide mode: use the whole width of the screen, or not (remembered)
y
copy a permalink pinned to the commit
d u x
diff: split / unified / collapse or expand all
e E
diff: the whole file in view / every file, with the lines the hunks hide
n
merge request: next note in the diff
esc
close a dialog, leave a field

Branches 4

Tags 45

↑↓ moveenter openesc close