detached 59d5a0b

events.go RawHistoryFolder

1// SPDX-License-Identifier: AGPL-3.0-or-later
2
3package usecase
4
5import (
6	"context"
7	"errors"
8	"fmt"
9	"strconv"
10	"strings"
11	"sync"
12	"time"
13
14	"github.com/bnema/zerowrap"
15
16	"bnema.dev/ermite/internal/domain"
17	"bnema.dev/ermite/internal/ports"
18)
19
20// DefaultEventBuffer is the number of events the Events use case remembers.
21const DefaultEventBuffer = 1024
22
23// Limits of the watchers.
24const (
25	// MaxWatchTopics is the most topics one watch may follow.
26	MaxWatchTopics = 64
27	// MaxWatchers is the most watches in progress at once.
28	MaxWatchers = 256
29	// MaxWatchersPerClient is the most watches in progress for one client
30	// address (see ports.WatchParams.Client).
31	MaxWatchersPerClient = 16
32	// DefaultRevalidateEvery is how long a watcher with a stored token goes
33	// without asking the token store whether the token still exists.
34	DefaultRevalidateEvery = 5 * time.Second
35)
36
37// Topics a watcher may follow.
38const (
39	// TopicHome follows every repository the caller may see.
40	TopicHome = "home"
41	// TopicOwner follows the merge requests and issues of every repository,
42	// for the owner only (the inbox). Anyone else is told it is an unknown
43	// topic.
44	TopicOwner = "owner"
45	// topicRepoPrefix starts the topic of one repository: "repo:<name>".
46	topicRepoPrefix = "repo:"
47)
48
49// bufferedEvent is an event with its sequence number in the buffer, and what
50// was true of its repository when it was buffered. Access to an event is
51// decided from that, and from the repository as it is when the event is
52// delivered: a repository made public later does not reveal what happened
53// while it was private, and a repository deleted and created again under the
54// same name does not inherit the events of the old one.
55type bufferedEvent struct {
56	seq uint64
57	ev  domain.Event
58
59	// known is false when the repository did not exist any more when the
60	// event was buffered: nobody is told about it.
61	known bool
62	// vis is the visibility of the repository at that time.
63	vis domain.Visibility
64	// created is the creation time of that repository.
65	created time.Time
66}
67
68// Events keeps the last events of the bus in a ring buffer, numbers them, and
69// lets callers watch them: live, or replayed from the id of the last event
70// they saw. Events of a private repository only reach callers that may read
71// it, checked again for every event.
72//
73// Event ids are opaque to clients: "<boot>-<seq>", where boot identifies this
74// run of the server, so that an id from before a restart is unknown rather
75// than taken for a newer event.
76//
77// The goroutine that feeds the buffer uses the logger of the context given to
78// NewEvents and lives until Close.
79type Events struct {
80	repos *Repos
81	auth  ports.Revalidator
82	clock ports.Clock
83	boot  string
84	size  int
85	every time.Duration // see EventsConfig.RevalidateEvery
86
87	stop context.CancelFunc
88	done chan struct{}
89
90	mu      sync.Mutex
91	ring    []bufferedEvent // capacity size, oldest first
92	nextSeq uint64          // sequence number of the next event, from 1
93	changed chan struct{}   // closed and replaced on every append and on close
94	closed  bool
95	watches int
96	clients map[string]int // watches in progress by client
97}
98
99var _ ports.EventService = (*Events)(nil)
100
101// EventsConfig configures Events.
102type EventsConfig struct {
103	// Size is the number of events remembered; DefaultEventBuffer when not
104	// positive.
105	Size int
106	// Auth confirms that the token of a watcher still exists. Required.
107	Auth ports.Revalidator
108	// RevalidateEvery is how long the answer of Auth is kept for a watcher;
109	// DefaultRevalidateEvery when zero, and negative to ask for every event.
110	RevalidateEvery time.Duration
111}
112
113// NewEvents subscribes to the bus and starts remembering its events. ctx
114// carries the logger; its cancellation is not followed, call Close.
115func NewEvents(ctx context.Context, repos *Repos, bus ports.EventBus, clock ports.Clock, cfg EventsConfig) *Events {
116	size := cfg.Size
117	if size <= 0 {
118		size = DefaultEventBuffer
119	}
120	every := cfg.RevalidateEvery
121	if every == 0 {
122		every = DefaultRevalidateEvery
123	}
124	run, stop := context.WithCancel(context.WithoutCancel(ctx))
125	e := &Events{
126		repos:   repos,
127		auth:    cfg.Auth,
128		clock:   clock,
129		every:   every,
130		clients: make(map[string]int),
131		boot:    strconv.FormatInt(clock.Now().UnixMilli(), 36),
132		size:    size,
133		stop:    stop,
134		done:    make(chan struct{}),
135		nextSeq: 1,
136		changed: make(chan struct{}),
137	}
138	sub := bus.Subscribe(run) // before returning: nothing published after is missed
139	go e.feed(run, sub)
140	return e
141}
142
143// feed appends the events of the bus until it stops.
144func (e *Events) feed(ctx context.Context, sub <-chan domain.Event) {
145	defer close(e.done)
146	defer e.shutdown()
147	for {
148		select {
149		case ev, ok := <-sub:
150			if !ok {
151				return
152			}
153			e.append(ctx, ev)
154		case <-ctx.Done():
155			return
156		}
157	}
158}
159
160// snapshot records the visibility and the generation of the repository an
161// event is about. Every event of the repository carries them.
162func (e *Events) snapshot(ctx context.Context, ev domain.Event) bufferedEvent {
163	switch ev := ev.(type) {
164	case domain.RepoCreated:
165		return bufferedEvent{known: true, vis: ev.Visibility, created: ev.At}
166	case domain.RepoUpdated:
167		return bufferedEvent{known: true, vis: ev.Visibility, created: ev.CreatedAt}
168	case domain.RepoDeleted:
169		return bufferedEvent{known: true, vis: ev.Visibility, created: ev.CreatedAt}
170	case domain.MirrorFailed:
171		return repoSnapshot(ev.Visibility, ev.CreatedAt)
172	case domain.MirrorRecovered:
173		return repoSnapshot(ev.Visibility, ev.CreatedAt)
174	case domain.PushEvent:
175		if ev.CreatedAt.IsZero() {
176			return bufferedEvent{} // repository unknown at publish time: nobody is told
177		}
178		return bufferedEvent{known: true, vis: ev.Visibility, created: ev.CreatedAt}
179	case domain.MergeRequestOpened:
180		return repoSnapshot(ev.Visibility, ev.CreatedAt)
181	case domain.MergeRequestMerged:
182		return repoSnapshot(ev.Visibility, ev.CreatedAt)
183	case domain.MergeRequestClosed:
184		return repoSnapshot(ev.Visibility, ev.CreatedAt)
185	case domain.MergeRequestAutoMergeEnabled:
186		return repoSnapshot(ev.Visibility, ev.CreatedAt)
187	case domain.MergeRequestAutoMergeCancelled:
188		return repoSnapshot(ev.Visibility, ev.CreatedAt)
189	case domain.MergeRequestReady:
190		return repoSnapshot(ev.Visibility, ev.CreatedAt)
191	case domain.CommentAdded:
192		return repoSnapshot(ev.Visibility, ev.CreatedAt)
193	case domain.IssueReferenced:
194		return repoSnapshot(ev.Visibility, ev.CreatedAt)
195	case domain.IssueOpened:
196		return repoSnapshot(ev.Visibility, ev.CreatedAt)
197	case domain.IssueClosed:
198		return repoSnapshot(ev.Visibility, ev.CreatedAt)
199	case domain.IssueReopened:
200		return repoSnapshot(ev.Visibility, ev.CreatedAt)
201	case domain.IssueCommented:
202		return repoSnapshot(ev.Visibility, ev.CreatedAt)
203	case domain.IssueSubmitted, domain.IssuePendingRemoved:
204		return bufferedEvent{known: true} // owner topic only: no repository snapshot
205	case domain.CommentEdited:
206		return repoSnapshot(ev.Visibility, ev.CreatedAt)
207	case domain.CommentDeleted:
208		return repoSnapshot(ev.Visibility, ev.CreatedAt)
209	case domain.CommentResolved:
210		return repoSnapshot(ev.Visibility, ev.CreatedAt)
211	case domain.MergeRequestMergeability:
212		return repoSnapshot(ev.Visibility, ev.CreatedAt)
213	case domain.RunUpdated:
214		return repoSnapshot(ev.Visibility, ev.CreatedAt)
215	case domain.JobUpdated:
216		return repoSnapshot(ev.Visibility, ev.CreatedAt)
217	}
218	return bufferedEvent{known: true}
219}
220
221// repoSnapshot is the snapshot of an event that carries the visibility and the
222// creation time of its repository; a zero creation time means the repository
223// was unknown when it was published, and nobody is told.
224func repoSnapshot(vis domain.Visibility, created time.Time) bufferedEvent {
225	if created.IsZero() {
226		return bufferedEvent{}
227	}
228	return bufferedEvent{known: true, vis: vis, created: created}
229}
230
231func (e *Events) append(ctx context.Context, ev domain.Event) {
232	be := e.snapshot(ctx, ev) // outside the lock: it reads the store
233	e.mu.Lock()
234	defer e.mu.Unlock()
235	if len(e.ring) == e.size {
236		copy(e.ring, e.ring[1:])
237		e.ring = e.ring[:e.size-1]
238	}
239	be.seq, be.ev = e.nextSeq, ev
240	e.ring = append(e.ring, be)
241	e.nextSeq++
242	e.wake()
243}
244
245// wake releases the watchers waiting for news. The caller holds mu.
246func (e *Events) wake() {
247	close(e.changed)
248	e.changed = make(chan struct{})
249}
250
251func (e *Events) shutdown() {
252	e.mu.Lock()
253	defer e.mu.Unlock()
254	if !e.closed {
255		e.closed = true
256		e.wake()
257	}
258}
259
260// Close ends every watch cleanly, stops feeding and waits for the feeder,
261// until ctx ends. It is safe to call more than once.
262func (e *Events) Close(ctx context.Context) {
263	e.stop()
264	select {
265	case <-e.done:
266	case <-ctx.Done():
267	}
268}
269
270// Watchers returns the number of watches in progress.
271func (e *Events) Watchers() int {
272	e.mu.Lock()
273	defer e.mu.Unlock()
274	return e.watches
275}
276
277func (e *Events) id(seq uint64) string { return e.boot + "-" + strconv.FormatUint(seq, 10) }
278
279// parseID returns the sequence number of an id of this run.
280func (e *Events) parseID(id string) (uint64, bool) {
281	boot, seq, ok := strings.Cut(id, "-")
282	if !ok || boot != e.boot {
283		return 0, false
284	}
285	n, err := strconv.ParseUint(seq, 10, 64)
286	return n, err == nil && n > 0
287}
288
289// watch is the state of one Watch call.
290type watch struct {
291	p     domain.Principal
292	home  bool
293	owner bool // the owner topic: merge request, issue, repo update and deletion events of every repository
294	repos map[domain.RepoName]bool
295
296	checked time.Time // when the token store last confirmed the principal
297}
298
299func (w *watch) wants(name domain.RepoName) bool { return w.home || w.repos[name] }
300
301// wantsEvent is wants for an event: the owner topic also follows the events
302// about merge requests and issues of every repository.
303func (w *watch) wantsEvent(name domain.RepoName, ev domain.Event) bool {
304	return w.wants(name) || (w.owner && (isItemEvent(ev) || isRepoLifecycleEvent(ev)))
305}
306
307// parseTopics validates the topics of a watch. A repository topic needs a
308// repository the principal may read (else domain.ErrNotFound); an unknown
309// topic, or more than MaxWatchTopics, is domain.ErrInvalid.
310func (e *Events) parseTopics(ctx context.Context, p domain.Principal, topics []string) (*watch, error) {
311	if len(topics) > MaxWatchTopics {
312		return nil, fmt.Errorf("%w: %d topics, at most %d", domain.ErrInvalid, len(topics), MaxWatchTopics)
313	}
314	w := &watch{p: p, repos: make(map[domain.RepoName]bool), checked: time.Now()}
315	if len(topics) == 0 {
316		w.home = true
317	}
318	for _, t := range topics {
319		if t == TopicHome {
320			w.home = true
321			continue
322		}
323		if t == TopicOwner && p.HasOwnerRights() {
324			w.owner = true
325			continue
326		}
327		raw, ok := strings.CutPrefix(t, topicRepoPrefix)
328		if !ok {
329			// Includes "owner" for anyone but the owner: the same error as
330			// any unknown topic.
331			return nil, fmt.Errorf("%w: unknown topic %q (want %q or \"repo:<name>\")", domain.ErrInvalid, t, TopicHome)
332		}
333		name, err := domain.ParseRepoName(raw)
334		if err != nil {
335			return nil, err
336		}
337		if _, err := e.repos.Get(ctx, p, name); err != nil {
338			return nil, err
339		}
340		w.repos[name] = true
341	}
342	return w, nil
343}
344
345// Watch calls send for the events the principal may see until ctx ends, the
346// buffer closes (both return nil) or send fails (its error is returned).
347//
348// A principal with a stored token is checked again for every event, and every
349// few seconds when idle: when the token expired or was revoked the watch ends
350// with domain.ErrUnauthenticated and nothing more is sent. More watches than
351// MaxWatchers, or than MaxWatchersPerClient for one Client, give
352// domain.ErrResourceExhausted.
353//
354// Without ResumeAfter only new events are sent. With it, the buffered events
355// after that id are sent first, then new ones. When the id is no longer
356// buffered, or was not issued by this run, a gap comes first and the oldest
357// buffered event follows. A watcher that falls more than the buffer behind
358// gets a gap too, and carries on with the oldest buffered event.
359func (e *Events) Watch(ctx context.Context, p domain.Principal, params ports.WatchParams, send func(ports.WatchEvent) error) error {
360	w, err := e.parseTopics(ctx, p, params.Topics)
361	if err != nil {
362		return err
363	}
364
365	e.mu.Lock()
366	next := e.nextSeq // only new events
367	gap := false
368	if params.ResumeAfter != "" {
369		seq, ok := e.parseID(params.ResumeAfter)
370		oldest := e.nextSeq - uint64(len(e.ring)) // first buffered sequence, nextSeq when empty
371		switch {
372		case ok && seq >= oldest-1 && seq < e.nextSeq:
373			next = seq + 1
374		default:
375			next, gap = oldest, true
376		}
377	}
378	if e.watches >= MaxWatchers || (params.Client != "" && e.clients[params.Client] >= MaxWatchersPerClient) {
379		e.mu.Unlock()
380		return fmt.Errorf("%w: too many watchers", domain.ErrResourceExhausted)
381	}
382	e.watches++
383	if params.Client != "" {
384		e.clients[params.Client]++
385	}
386	e.mu.Unlock()
387	defer func() {
388		e.mu.Lock()
389		e.watches--
390		if params.Client != "" {
391			if e.clients[params.Client]--; e.clients[params.Client] == 0 {
392				delete(e.clients, params.Client)
393			}
394		}
395		e.mu.Unlock()
396	}()
397
398	if params.Ready != nil {
399		params.Ready()
400	}
401	log := zerowrap.FromCtx(ctx)
402	log.Debug().Strs("topics", params.Topics).Bool("resume", params.ResumeAfter != "").Bool("gap", gap).Msg("watch started")
403	if gap {
404		if err := send(ports.WatchEvent{Gap: true}); err != nil {
405			return err
406		}
407	}
408	for {
409		if err := e.stillAllowed(ctx, w); err != nil {
410			return err
411		}
412		batch, changed, oldest, lost, closed := e.since(next)
413		if lost {
414			if err := send(ports.WatchEvent{Gap: true}); err != nil {
415				return err
416			}
417			next = oldest
418			continue
419		}
420		for _, be := range batch {
421			if err := e.deliver(ctx, w, be, send); err != nil {
422				return err
423			}
424			next = be.seq + 1
425		}
426		if len(batch) > 0 {
427			continue
428		}
429		if closed {
430			return nil
431		}
432		e.wait(ctx, w, changed)
433		if ctx.Err() != nil {
434			return nil
435		}
436	}
437}
438
439// wait blocks until more events arrive or ctx ends. A watcher with a stored
440// token also wakes up every few seconds, so that a revocation ends the watch
441// of a quiet forge too (the caller checks the token on the next turn).
442func (e *Events) wait(ctx context.Context, w *watch, changed <-chan struct{}) {
443	var idle <-chan time.Time
444	if w.p.TokenID() != "" {
445		t := time.NewTimer(e.idleCheck())
446		defer t.Stop()
447		idle = t.C
448	}
449	select {
450	case <-changed:
451	case <-idle:
452	case <-ctx.Done():
453	}
454}
455
456// idleCheck is how long a watcher with a stored token waits for news before
457// checking its token anyway.
458func (e *Events) idleCheck() time.Duration {
459	if e.every <= 0 {
460		return DefaultRevalidateEvery
461	}
462	return min(e.every, DefaultRevalidateEvery)
463}
464
465// stillAllowed checks that the holder of a stored token may still watch: the
466// token has not expired and, at most every few seconds, still exists. Root and
467// anonymous callers have nothing to lose. The owner topic needs nothing more:
468// a stored token with owner rights loses them only by ceasing to exist, which
469// is checked here, and the owner's web session, which this use case cannot see,
470// is checked by the web adapter before it sends anything.
471func (e *Events) stillAllowed(ctx context.Context, w *watch) error {
472	if w.p.TokenID() == "" {
473		return nil
474	}
475	if exp := w.p.ExpiresAt(); !exp.IsZero() && !e.clock.Now().Before(exp) {
476		return domain.ErrUnauthenticated
477	}
478	if e.every > 0 && time.Since(w.checked) < e.every {
479		return nil
480	}
481	if err := e.auth.Revalidate(ctx, w.p); err != nil {
482		if ctx.Err() != nil {
483			return nil
484		}
485		return err
486	}
487	w.checked = time.Now()
488	return nil
489}
490
491// since returns the buffered events from sequence next on, and the channel
492// that closes when more arrive. lost is true when next fell out of the buffer;
493// the caller then restarts from oldest, the first buffered sequence. The
494// returned slice is a copy.
495func (e *Events) since(next uint64) (batch []bufferedEvent, changed <-chan struct{}, oldest uint64, lost, closed bool) {
496	e.mu.Lock()
497	defer e.mu.Unlock()
498	oldest = e.nextSeq - uint64(len(e.ring))
499	if next < oldest {
500		return nil, e.changed, oldest, true, e.closed
501	}
502	batch = append(batch, e.ring[next-oldest:]...)
503	return batch, e.changed, oldest, false, e.closed
504}
505
506// deliver sends the event if the watcher follows its topic and may see it.
507func (e *Events) deliver(ctx context.Context, w *watch, be bufferedEvent, send func(ports.WatchEvent) error) error {
508	if err := e.stillAllowed(ctx, w); err != nil {
509		return err
510	}
511	out := ports.WatchEvent{ID: e.id(be.seq), Event: be.ev}
512	switch ev := be.ev.(type) {
513	case domain.EventGap:
514		// The feeder lost events: tell every watcher.
515		return send(ports.WatchEvent{Gap: true})
516	case domain.RepoDeleted:
517		// The repository is gone: use the visibility it had.
518		if !w.wantsEvent(ev.Repo, ev) || !canReadAs(w.p, ev.Repo, ev.Visibility) {
519			return nil
520		}
521		return send(out)
522	case domain.IssueSubmitted:
523		return e.deliverOwnerOnly(ctx, w, ev.Repo, out, send)
524	case domain.IssuePendingRemoved:
525		return e.deliverOwnerOnly(ctx, w, ev.Repo, out, send)
526	case domain.RepoCreated:
527		return e.deliverRepo(ctx, w, ev.Repo, true, be, out, send)
528	case domain.RepoUpdated:
529		return e.deliverRepo(ctx, w, ev.Repo, true, be, out, send)
530	case domain.MirrorFailed:
531		return e.deliverRepo(ctx, w, ev.Repo, false, be, out, send)
532	case domain.MirrorRecovered:
533		return e.deliverRepo(ctx, w, ev.Repo, false, be, out, send)
534	case domain.PushEvent:
535		return e.deliverRepo(ctx, w, ev.Repo, false, be, out, send)
536	case domain.MergeRequestOpened:
537		return e.deliverRepo(ctx, w, ev.MergeRequest.Repo, false, be, out, send)
538	case domain.MergeRequestMerged:
539		return e.deliverRepo(ctx, w, ev.MergeRequest.Repo, false, be, out, send)
540	case domain.MergeRequestClosed:
541		return e.deliverRepo(ctx, w, ev.MergeRequest.Repo, false, be, out, send)
542	case domain.MergeRequestAutoMergeEnabled:
543		return e.deliverRepo(ctx, w, ev.MergeRequest.Repo, false, be, out, send)
544	case domain.MergeRequestAutoMergeCancelled:
545		return e.deliverRepo(ctx, w, ev.MergeRequest.Repo, false, be, out, send)
546	case domain.MergeRequestReady:
547		return e.deliverRepo(ctx, w, ev.MergeRequest.Repo, false, be, out, send)
548	case domain.CommentAdded:
549		return e.deliverRepo(ctx, w, ev.Repo, false, be, out, send)
550	case domain.IssueReferenced:
551		return e.deliverRepo(ctx, w, ev.Repo, false, be, out, send)
552	case domain.IssueOpened:
553		return e.deliverRepo(ctx, w, ev.Issue.Repo, false, be, out, send)
554	case domain.IssueClosed:
555		return e.deliverRepo(ctx, w, ev.Issue.Repo, false, be, out, send)
556	case domain.IssueReopened:
557		return e.deliverRepo(ctx, w, ev.Issue.Repo, false, be, out, send)
558	case domain.IssueCommented:
559		return e.deliverRepo(ctx, w, ev.Repo, false, be, out, send)
560	case domain.CommentEdited:
561		return e.deliverRepo(ctx, w, ev.Repo, false, be, out, send)
562	case domain.CommentDeleted:
563		return e.deliverRepo(ctx, w, ev.Repo, false, be, out, send)
564	case domain.CommentResolved:
565		return e.deliverRepo(ctx, w, ev.Repo, false, be, out, send)
566	case domain.MergeRequestMergeability:
567		return e.deliverRepo(ctx, w, ev.Repo, false, be, out, send)
568	case domain.RunUpdated:
569		// Home shows the CI state of each repository.
570		return e.deliverRepo(ctx, w, ev.Run.Repo, false, be, out, send)
571	case domain.JobUpdated:
572		// Home gets a job when it ends only: a failed job turns the state to
573		// failing before its run ends. Its progress stays on the topic of its
574		// repository.
575		if !w.repos[ev.Job.Repo] && ev.Job.Phase != domain.CIPhaseEnded {
576			return nil
577		}
578		return e.deliverRepo(ctx, w, ev.Job.Repo, false, be, out, send)
579	}
580	return nil // an event this version does not stream
581}
582
583// deliverOwnerOnly sends an owner-topic event: never home, never a repository
584// topic, not even to an owner who watches the repository. No content travels.
585func (e *Events) deliverOwnerOnly(ctx context.Context, w *watch, name domain.RepoName, out ports.WatchEvent, send func(ports.WatchEvent) error) error {
586	if !w.owner {
587		return nil
588	}
589	repo, err := lookupRepo(ctx, e.repos.meta, name)
590	switch {
591	case errors.Is(err, domain.ErrNotFound), ctx.Err() != nil:
592		return nil
593	case err != nil:
594		return fmt.Errorf("check access to %q: %w", name, err)
595	}
596	if !repo.Settings.IssuesEnabled() {
597		return nil
598	}
599	return send(out)
600}
601
602// deliverRepo sends an event about a repository if the watcher could read the
603// repository when the event happened and can read it now, and the repository
604// is still the one the event is about. A repository that no longer exists is
605// skipped: its RepoDeleted follows or came before.
606//
607// The exception is a repository that became private: the watchers who could
608// read it before are told once, with its name and its new visibility only,
609// so that what they show can be removed.
610func (e *Events) deliverRepo(ctx context.Context, w *watch, name domain.RepoName, withRepo bool, be bufferedEvent, out ports.WatchEvent, send func(ports.WatchEvent) error) error {
611	if !w.wantsEvent(name, be.ev) || !be.known {
612		return nil
613	}
614	repo, err := lookupRepo(ctx, e.repos.meta, name)
615	switch {
616	case errors.Is(err, domain.ErrNotFound):
617		return nil
618	case ctx.Err() != nil:
619		return nil
620	case err != nil:
621		return fmt.Errorf("check access to %q: %w", name, err)
622	}
623	if repo.CreatedAt.After(be.created) {
624		return nil // the event is about a repository of this name that was deleted
625	}
626	if !canReadAs(w.p, name, be.vis) {
627		if up, ok := be.ev.(domain.RepoUpdated); ok && canReadAs(w.p, name, up.Previous) {
628			out.Repo = &ports.RepoView{Repo: domain.Repo{Name: name, Visibility: up.Visibility}}
629			return send(out)
630		}
631		return nil
632	}
633	if !canRead(w.p, repo) {
634		return nil
635	}
636	if isIssueEvent(be.ev) && !repo.Settings.IssuesEnabled() {
637		return nil // issues were turned off since: a replay must not show them
638	}
639	if withRepo {
640		view, err := e.repos.View(ctx, repo)
641		if err != nil {
642			return err
643		}
644		out.Repo = &view
645	}
646	return send(out)
647}
648
649// isIssueEvent reports whether ev is about an issue.
650func isIssueEvent(ev domain.Event) bool {
651	switch ev.(type) {
652	case domain.IssueOpened, domain.IssueClosed, domain.IssueReopened, domain.IssueCommented, domain.IssueReferenced:
653		return true
654	}
655	return false
656}
657
658// isRepoLifecycleEvent reports whether ev is a repository update or deletion:
659// the owner topic follows them, for they change what the inbox lists.
660func isRepoLifecycleEvent(ev domain.Event) bool {
661	switch ev.(type) {
662	case domain.RepoUpdated, domain.RepoDeleted:
663		return true
664	}
665	return false
666}
667
668// isItemEvent reports whether ev is about a merge request or an issue.
669func isItemEvent(ev domain.Event) bool {
670	switch ev.(type) {
671	case domain.IssueReferenced:
672		return false // back-reference refreshes do not change the inbox
673	case domain.MergeRequestOpened, domain.MergeRequestMerged, domain.MergeRequestClosed,
674		domain.MergeRequestAutoMergeEnabled, domain.MergeRequestAutoMergeCancelled,
675		domain.MergeRequestReady, domain.MergeRequestMergeability, domain.CommentAdded,
676		domain.CommentEdited, domain.CommentDeleted, domain.CommentResolved:
677		return true
678	}
679	return isIssueEvent(ev)
680}

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 2

Tags 45

↑↓ moveenter openesc close