detached aa7340c

mergerequests.go RawHistoryFolder

1// SPDX-License-Identifier: AGPL-3.0-or-later
2
3package usecase
4
5import (
6	"context"
7	"encoding/base64"
8	"errors"
9	"fmt"
10	"math"
11	"runtime/debug"
12	"slices"
13	"strconv"
14	"strings"
15	"sync"
16
17	"github.com/bnema/zerowrap"
18
19	"bnema.dev/ermite/internal/domain"
20	"bnema.dev/ermite/internal/ports"
21)
22
23// MaxMergeRequestCommits is the most commits GetMergeRequest returns.
24const MaxMergeRequestCommits = 100
25
26// maxWriteRetries bounds the retries of a write that loses a race with another
27// write of the same merge request. Each lost race means another writer won, so
28// a writer loses at most as many times as there are other writers at once; the
29// retry is a read and a write of ermite-kv, cheap enough for a bound this high.
30const maxWriteRetries = 32
31
32// MaxCommentsPerMergeRequest is the most comments a merge request holds. Past
33// it AddComment fails with domain.ErrResourceExhausted (resource_exhausted in
34// the API). Comments are never deleted, so the limit counts the ones ever added.
35const MaxCommentsPerMergeRequest = 1000
36
37const mrTokenPrefix = "mp1:"
38
39// MergeRequests are the merge request use cases (ADR 0017): review, comment,
40// close and merge a branch. Reading needs the access of reading the
41// repository: a repository the principal may not read, a missing one and an
42// unknown number all answer domain.ErrNotFound. Writing needs mr:write, and
43// merging mr:merge, on the repository (see scopeAccess), and that scope also
44// makes a private repository visible for the action (see writable).
45type MergeRequests struct {
46	meta      ports.RepoMetaStore
47	store     ports.MergeRequestStore
48	repos     ports.GitRepos
49	git       ports.MergeGit
50	signer    ports.CommitSigner
51	committer domain.Identity
52	bus       ports.EventBus
53	clock     ports.Clock
54	maint     ports.MaintenanceScheduler
55	ci        ports.WorkflowTrigger    // nil: no CI
56	checks    ports.CIChecksReader     // nil: no CI, so no check blocks a merge
57	pulls     ports.PullRequestTrigger // nil: no pull_request workflows
58	tips      ports.CIRefTipStore      // nil: who merges is not recorded
59	verifier  ports.CommitVerifier     // nil: commits are not checked (ADR 0030)
60	mergeab   MergeabilityHook         // nil: no mergeability
61
62	mu    sync.Mutex
63	locks map[domain.RepoName]chan struct{}
64
65	// after tracks the post-merge side effects running off the request path.
66	after sync.WaitGroup
67	// afterGate, when set by a test, runs first in the post-merge goroutine.
68	afterGate func()
69}
70
71var (
72	_ ports.MergeRequestService = (*MergeRequests)(nil)
73	_ ports.PullGate            = (*MergeRequests)(nil)
74)
75
76// MergeRequestsConfig holds what the merge request use cases need. Every field
77// is required.
78type MergeRequestsConfig struct {
79	Meta  ports.RepoMetaStore
80	Store ports.MergeRequestStore
81	// Repos gives the default branch of a repository.
82	Repos ports.GitRepos
83	Git   ports.MergeGit
84	// Signer signs the squash commits.
85	Signer ports.CommitSigner
86	// Committer is recorded as the committer of the squash commits.
87	Committer domain.Identity
88	Bus       ports.EventBus
89	Clock     ports.Clock
90	// Maint queues the maintenance that follows a merge, as it does a push.
91	Maint ports.MaintenanceScheduler
92	// CI starts the workflows a merge triggers (GitHub runs "push" workflows
93	// on a merge) and Checks gives the checks the merge rule reads. Both are
94	// optional: without them there is no CI.
95	CI     ports.WorkflowTrigger
96	Checks ports.CIChecksReader
97	// PullRequests starts the pull_request workflows when a request is opened,
98	// closed or merged (the push of its source branch reaches CI instead).
99	// Optional.
100	PullRequests ports.PullRequestTrigger
101	// RefTips records who moves the target branch (and deletes the record of a
102	// deleted source branch) before the merge does, as a push does
103	// (domain.CIRefTip). Optional.
104	RefTips ports.CIRefTipStore
105	// Mergeability is queued when a request is opened, closed or merged and
106	// read by Get and List. Optional: without it Mergeability stays zero.
107	Mergeability MergeabilityHook
108}
109
110// NewMergeRequests builds the merge request use cases.
111func NewMergeRequests(cfg MergeRequestsConfig) *MergeRequests {
112	return &MergeRequests{
113		meta: cfg.Meta, store: cfg.Store, repos: cfg.Repos, git: cfg.Git, signer: cfg.Signer,
114		committer: cfg.Committer, bus: cfg.Bus, clock: cfg.Clock, maint: cfg.Maint, ci: cfg.CI, checks: cfg.Checks, pulls: cfg.PullRequests, tips: cfg.RefTips, mergeab: cfg.Mergeability,
115		locks: make(map[domain.RepoName]chan struct{}),
116	}
117}
118
119// WithVerifier makes GetMergeRequest fill the signature state of the commits
120// it lists (ADR 0030).
121func (m *MergeRequests) WithVerifier(v ports.CommitVerifier) *MergeRequests {
122	m.verifier = v
123	return m
124}
125
126// Wait waits for the post-merge side effects still running (source branch
127// deletion, events, CI and mergeability hooks), or for ctx to end. Call it
128// before closing what they use.
129func (m *MergeRequests) Wait(ctx context.Context) {
130	done := make(chan struct{})
131	go func() {
132		m.after.Wait()
133		close(done)
134	}()
135	select {
136	case <-done:
137	case <-ctx.Done():
138	}
139}
140
141// lockRepo takes the merge lock of a repository, waiting until ctx ends. The
142// merges of one repository, and the creation of its merge requests, run one at
143// a time. The returned function releases the lock.
144func (m *MergeRequests) lockRepo(ctx context.Context, name domain.RepoName) (unlock func(), err error) {
145	m.mu.Lock()
146	ch, ok := m.locks[name]
147	if !ok {
148		ch = make(chan struct{}, 1)
149		m.locks[name] = ch
150	}
151	m.mu.Unlock()
152	select {
153	case ch <- struct{}{}:
154		return func() { <-ch }, nil
155	case <-ctx.Done():
156		return nil, ctx.Err()
157	}
158}
159
160// readable looks the repository up and applies the read rule: reading merge
161// requests needs the access of reading the repository (canRead). repo:write
162// alone does not read them, as it does not fetch a private repository either.
163func (m *MergeRequests) readable(ctx context.Context, p domain.Principal, name domain.RepoName) (domain.Repo, error) {
164	repo, err := lookupRepo(ctx, m.meta, name)
165	if err != nil {
166		return domain.Repo{}, err
167	}
168	if !canRead(p, repo) {
169		return domain.Repo{}, domain.ErrNotFound
170	}
171	return repo, nil
172}
173
174// writable looks the repository up for an action that needs a merge request
175// scope. A principal whose token holds that scope on the repository sees the
176// repository for this action even without repo:read, so that the agent preset
177// (repo:write, mr:write) can open a request on the private repository it just
178// pushed. A principal with neither repo:read nor the scope, and an unknown
179// repository, still get domain.ErrNotFound; one that can read the repository
180// but lacks the scope gets the error of scopeAccess.
181func (m *MergeRequests) writable(ctx context.Context, p domain.Principal, name domain.RepoName, scope domain.Scope) (domain.Repo, error) {
182	repo, err := lookupRepo(ctx, m.meta, name)
183	if err != nil {
184		return domain.Repo{}, err
185	}
186	if !canRead(p, repo) && !p.Allows(scope, name) {
187		return domain.Repo{}, domain.ErrNotFound
188	}
189	if err := scopeAccess(p, repo, scope); err != nil {
190		return domain.Repo{}, err
191	}
192	return repo, nil
193}
194
195// withHead fills HeadID of an open request from its source branch: zero when
196// the branch is gone. Merged and closed requests keep the head they stored.
197func (m *MergeRequests) withHead(ctx context.Context, mr domain.MergeRequest) (domain.MergeRequest, error) {
198	if !mr.IsOpen() {
199		return mr, nil
200	}
201	head, err := m.git.BranchHead(ctx, mr.Repo, mr.Source)
202	switch {
203	case errors.Is(err, domain.ErrNotFound):
204		mr.HeadID = domain.ObjectID{}
205	case err != nil:
206		return domain.MergeRequest{}, err
207	default:
208		mr.HeadID = head
209	}
210	return mr, nil
211}
212
213// branchOrZero returns the head of a branch, the zero id when it is gone.
214func (m *MergeRequests) branchOrZero(ctx context.Context, repo domain.RepoName, branch string) (domain.ObjectID, error) {
215	id, err := m.git.BranchHead(ctx, repo, branch)
216	if errors.Is(err, domain.ErrNotFound) {
217		return domain.ObjectID{}, nil
218	}
219	return id, err
220}
221
222// Create opens a merge request and publishes MergeRequestOpened. The principal
223// needs mr:write. A request that breaks a rule of ADR 0017 (the texts, a
224// branch that does not exist, source and target the same) is rejected whole
225// with an *domain.InvalidFieldsError naming the fields. An open request with
226// the same source and target gives domain.ErrAlreadyExists.
227func (m *MergeRequests) Create(ctx context.Context, p domain.Principal, name domain.RepoName, params ports.CreateMergeRequestParams) (domain.MergeRequest, error) {
228	repo, err := m.writable(ctx, p, name, domain.ScopeMRWrite)
229	if err != nil {
230		return domain.MergeRequest{}, err
231	}
232	var v domain.Violations
233	title, err := domain.ParseMRTitle(params.Title)
234	if err != nil {
235		v.AddErr("title", err)
236	}
237	desc, err := domain.ParsePlainText(params.Description)
238	if err != nil {
239		v.AddErr("description", err)
240	}
241	// Under the lock, so that two requests for the same pair cannot both pass
242	// the check for an existing one, and a merge that deletes its source
243	// cannot remove a branch between its check here and the creation.
244	unlock, err := m.lockRepo(ctx, name)
245	if err != nil {
246		return domain.MergeRequest{}, err
247	}
248	defer unlock()
249	source, target, err := m.checkBranches(ctx, name, params, &v)
250	if err != nil {
251		return domain.MergeRequest{}, err
252	}
253	if err := v.Err(); err != nil {
254		return domain.MergeRequest{}, err
255	}
256	existing, err := m.store.List(ctx, name)
257	if err != nil {
258		return domain.MergeRequest{}, fmt.Errorf("list merge requests of %q: %w", name, err)
259	}
260	for _, e := range existing {
261		if e.IsOpen() && e.Source == source && e.Target == target {
262			return domain.MergeRequest{}, fmt.Errorf("%w: !%d already merges %s into %s", domain.ErrAlreadyExists, e.Number, source, target)
263		}
264	}
265
266	now := m.clock.Now().UTC()
267	mr, err := m.store.Create(ctx, domain.MergeRequest{
268		Repo: name, Title: title, Description: desc, Source: source, Target: target,
269		State: domain.MRStateOpen, Author: domain.AuthorName(p), CreatedAt: now, UpdatedAt: now,
270	})
271	if err != nil {
272		return domain.MergeRequest{}, fmt.Errorf("create merge request of %q: %w", name, err)
273	}
274	log := zerowrap.FromCtx(ctx)
275	log.Info().Str("repo", name.String()).Int64("number", mr.Number).
276		Str("source", source).Str("target", target).
277		Str("principal", p.Label()).Str("token_id", p.TokenID()).Msg("merge request opened")
278	mr, err = m.withHead(ctx, mr)
279	if err != nil {
280		return domain.MergeRequest{}, err
281	}
282	m.bus.Publish(ctx, domain.MergeRequestOpened{MergeRequest: mr, At: now, Visibility: repo.Visibility, CreatedAt: repo.CreatedAt})
283	if m.mergeab != nil {
284		m.mergeab.OnOpened(ctx, mr)
285	}
286	if m.pulls != nil {
287		// The commits the opening is for are the ones of now.
288		base, _ := m.branchOrZero(ctx, name, target)
289		m.pulls.OnPullRequest(ctx, name, ports.PullRequestEvent{Number: mr.Number, Action: domain.PullOpened, Head: mr.HeadID, Base: base}, p)
290	}
291	return mr, nil
292}
293
294// checkBranches validates the branches of a new request and returns them, with
295// the default branch filled in for the target.
296//
297// Only a branch that does not exist is a violation. Any other failure to read
298// Git is returned as an error, so that it is logged and masked, not shown in
299// the field violations.
300func (m *MergeRequests) checkBranches(ctx context.Context, name domain.RepoName, params ports.CreateMergeRequestParams, v *domain.Violations) (source, target string, err error) {
301	source, target = params.Source, params.Target
302	if source == "" {
303		v.Add("source_branch", "is required")
304	} else if _, err := domain.ParseBranchName(source); err != nil {
305		v.Add("source_branch", "is not a valid branch name")
306		source = ""
307	}
308	if target == "" {
309		def, exists, err := m.repos.DefaultBranch(ctx, name)
310		switch {
311		case err != nil: // includes domain.ErrNotFound: the repository is gone
312			return "", "", fmt.Errorf("read the default branch of %q: %w", name, err)
313		case !exists:
314			v.Add("target_branch", fmt.Sprintf("is empty and the default branch %q does not exist", def))
315		default:
316			target = def
317		}
318	} else if _, err := domain.ParseBranchName(target); err != nil {
319		v.Add("target_branch", "is not a valid branch name")
320		target = ""
321	}
322	if source != "" && source == target {
323		v.Add("target_branch", "must differ from source_branch")
324		return source, target, nil
325	}
326	for _, b := range []struct{ field, name string }{{"source_branch", source}, {"target_branch", target}} {
327		if b.name == "" {
328			continue
329		}
330		_, err := m.git.BranchHead(ctx, name, b.name)
331		if errors.Is(err, domain.ErrNotFound) {
332			v.Add(b.field, fmt.Sprintf("branch %q does not exist", b.name))
333		} else if err != nil {
334			return "", "", fmt.Errorf("read branch %q of %q: %w", b.name, name, err)
335		}
336	}
337	return source, target, nil
338}
339
340// List returns a page of the merge requests of a repository, highest number
341// first. The open ones carry the head of their source branch. The page token
342// names the last number of the previous page, so requests created between two
343// pages never shift the others.
344func (m *MergeRequests) List(ctx context.Context, p domain.Principal, name domain.RepoName, params ports.ListMergeRequestsParams) (ports.MergeRequestPage, error) {
345	size, err := pageSize(params.PageSize)
346	if err != nil {
347		return ports.MergeRequestPage{}, err
348	}
349	after, err := decodeMRToken(params.PageToken)
350	if err != nil {
351		return ports.MergeRequestPage{}, err
352	}
353	if _, err := m.readable(ctx, p, name); err != nil {
354		return ports.MergeRequestPage{}, err
355	}
356	all, err := m.store.List(ctx, name)
357	if err != nil {
358		return ports.MergeRequestPage{}, fmt.Errorf("list merge requests of %q: %w", name, err)
359	}
360	var page ports.MergeRequestPage
361	page.MergeRequests, page.NextPageToken = pageAfter(all, size,
362		func(mr domain.MergeRequest) bool {
363			return (params.State == "" || mr.State == params.State) && (after == 0 || mr.Number < after)
364		},
365		encodeMRToken)
366	tips := map[string]domain.ObjectID{} // one BranchHead per distinct target
367	for i, mr := range page.MergeRequests {
368		if page.MergeRequests[i], err = m.withHead(ctx, mr); err != nil {
369			return ports.MergeRequestPage{}, err
370		}
371		if m.mergeab == nil || !mr.IsOpen() {
372			continue
373		}
374		tip, ok := tips[mr.Target]
375		if !ok {
376			if tip, err = m.branchOrZero(ctx, name, mr.Target); err != nil {
377				return ports.MergeRequestPage{}, err
378			}
379			tips[mr.Target] = tip
380		}
381		if page.Mergeability == nil {
382			page.Mergeability = map[int64]domain.Mergeability{}
383		}
384		page.Mergeability[mr.Number] = m.mergeab.Read(ctx, page.MergeRequests[i], tip)
385	}
386	return page, nil
387}
388
389// MarkReady implements ports.MergeRequestService: the title of an open draft
390// loses its draft prefix, so the request can be merged. The principal needs
391// mr:write. A request that is not open, or not a draft, gives
392// domain.ErrPreconditionFailed.
393func (m *MergeRequests) MarkReady(ctx context.Context, p domain.Principal, name domain.RepoName, number int64) (domain.MergeRequest, error) {
394	repo, err := m.writable(ctx, p, name, domain.ScopeMRWrite)
395	if err != nil {
396		return domain.MergeRequest{}, err
397	}
398	unlock, err := m.lockRepo(ctx, name) // a merge sees the request as it is after
399	if err != nil {
400		return domain.MergeRequest{}, err
401	}
402	defer unlock()
403	for range maxWriteRetries {
404		mr, err := m.store.Get(ctx, name, number)
405		if err != nil {
406			return domain.MergeRequest{}, err
407		}
408		if !mr.IsOpen() {
409			return domain.MergeRequest{}, fmt.Errorf("%w: !%d is %s", domain.ErrPreconditionFailed, number, mr.State)
410		}
411		title, ok := domain.ReadyTitle(mr.Title)
412		if !ok {
413			return domain.MergeRequest{}, fmt.Errorf("%w: !%d is not a draft", domain.ErrPreconditionFailed, number)
414		}
415		mr.Title, mr.UpdatedAt = title, m.clock.Now().UTC()
416		err = m.store.Update(ctx, mr)
417		if errors.Is(err, domain.ErrConflict) {
418			continue
419		}
420		if err != nil {
421			return domain.MergeRequest{}, fmt.Errorf("mark !%d of %q ready: %w", number, name, err)
422		}
423		m.bus.Publish(ctx, domain.MergeRequestReady{MergeRequest: mr, At: mr.UpdatedAt, Visibility: repo.Visibility, CreatedAt: repo.CreatedAt})
424		return m.withHead(ctx, mr)
425	}
426	return domain.MergeRequest{}, fmt.Errorf("mark !%d of %q ready: %w", number, name, domain.ErrConflict)
427}
428
429// CountOpen implements ports.MergeRequestService.
430func (m *MergeRequests) CountOpen(ctx context.Context, p domain.Principal, name domain.RepoName) (int, error) {
431	if _, err := m.readable(ctx, p, name); err != nil {
432		return 0, err
433	}
434	n, err := m.store.CountOpen(ctx, name)
435	if err != nil {
436		return 0, fmt.Errorf("count open merge requests of %q: %w", name, err)
437	}
438	return n, nil
439}
440
441// Mergeability implements ports.MergeRequestService: the mergeability of an
442// open merge request for the current tips, queued when there is no up-to-date
443// result. It is the zero value for a request that is not open, or without a
444// mergeability service.
445func (m *MergeRequests) Mergeability(ctx context.Context, p domain.Principal, name domain.RepoName, number int64) (domain.Mergeability, error) {
446	_, mr, err := m.get(ctx, p, name, number)
447	if err != nil {
448		return domain.Mergeability{}, err
449	}
450	if m.mergeab == nil || !mr.IsOpen() {
451		return domain.Mergeability{}, nil
452	}
453	if mr, err = m.withHead(ctx, mr); err != nil {
454		return domain.Mergeability{}, err
455	}
456	tip, err := m.branchOrZero(ctx, name, mr.Target)
457	if err != nil {
458		return domain.Mergeability{}, err
459	}
460	return m.mergeab.Read(ctx, mr, tip), nil
461}
462
463func encodeMRToken(last domain.MergeRequest) string {
464	return base64.RawURLEncoding.EncodeToString([]byte(mrTokenPrefix + strconv.FormatInt(last.Number, 10)))
465}
466
467// decodeMRToken returns 0 for the empty token.
468func decodeMRToken(tok string) (int64, error) {
469	if tok == "" {
470		return 0, nil
471	}
472	raw, ok := decodeToken(tok, mrTokenPrefix)
473	if ok {
474		if n, err := strconv.ParseInt(raw, 10, 64); err == nil && n > 0 {
475			return n, nil
476		}
477	}
478	return 0, fmt.Errorf("%w: merge requests", domain.ErrInvalidPageToken)
479}
480
481// get reads a merge request of a repository the principal can read.
482func (m *MergeRequests) get(ctx context.Context, p domain.Principal, name domain.RepoName, number int64) (domain.Repo, domain.MergeRequest, error) {
483	repo, err := m.readable(ctx, p, name)
484	if err != nil {
485		return domain.Repo{}, domain.MergeRequest{}, err
486	}
487	mr, err := m.store.Get(ctx, name, number)
488	if err != nil {
489		return domain.Repo{}, domain.MergeRequest{}, err
490	}
491	return repo, mr, nil
492}
493
494// Get returns a merge request with its commits, its diff, its comments and the
495// read position. The diff compares the merge base of the target and the head
496// with the head ("target...head"), within domain.DefaultDiffLimits. With
497// opts.SinceLastRead it compares the head recorded by MarkRead with the
498// current head instead, which works after a force-push as long as the recorded
499// commit still exists; when none was recorded the diff is the default one, and
500// when the recorded commit is gone too, with LastReadLost set. A merged or
501// closed request keeps the head and the base it had.
502//
503// opts.Files lists every changed file and reads the hunks of a window of them
504// only; opts.Base and opts.Head make Get fail with domain.ErrConflict when the
505// diff is no longer the one the caller shows (before any diff is read);
506// opts.DiffOnly skips the commits. An invalid window gives domain.ErrInvalid.
507func (m *MergeRequests) Get(ctx context.Context, p domain.Principal, name domain.RepoName, number int64, opts ports.GetMergeRequestOptions) (ports.MergeRequestDetail, error) {
508	limits := domain.DefaultDiffLimits()
509	if w := opts.Files; w != nil {
510		if w.From < 0 || w.To < 0 || (w.To != 0 && w.To < w.From) {
511			return ports.MergeRequestDetail{}, fmt.Errorf("%w: file window [%d, %d)", domain.ErrInvalid, w.From, w.To)
512		}
513		limits.MaxFiles, limits.From, limits.To = 0, w.From, w.To
514	}
515	_, mr, err := m.get(ctx, p, name, number)
516	if err != nil {
517		return ports.MergeRequestDetail{}, err
518	}
519	if mr, err = m.withHead(ctx, mr); err != nil {
520		return ports.MergeRequestDetail{}, err
521	}
522	if !opts.Head.IsZero() && opts.Head != mr.HeadID {
523		return ports.MergeRequestDetail{}, fmt.Errorf("%w: the head of !%d moved to %s", domain.ErrConflict, number, mr.HeadID)
524	}
525	// checkBase fails when the caller shows another diff base than base.
526	checkBase := func(base domain.ObjectID) error {
527		if !opts.Base.IsZero() && opts.Base != base {
528			return fmt.Errorf("%w: the diff base of !%d is now %s", domain.ErrConflict, number, base)
529		}
530		return nil
531	}
532	d := ports.MergeRequestDetail{MergeRequest: mr}
533	if m.mergeab != nil && mr.IsOpen() {
534		tip, err := m.branchOrZero(ctx, name, mr.Target)
535		if err != nil {
536			return ports.MergeRequestDetail{}, err
537		}
538		d.Mergeability = m.mergeab.Read(ctx, mr, tip)
539	}
540	if d.Comments, err = m.store.ListComments(ctx, name, number); err != nil {
541		return ports.MergeRequestDetail{}, fmt.Errorf("list comments of !%d in %q: %w", number, name, err)
542	}
543	d.Verdicts = domain.CurrentVerdicts(d.Comments, mr.HeadID)
544	if d.LastReadID, err = m.store.GetRead(ctx, name, number); err != nil {
545		return ports.MergeRequestDetail{}, err
546	}
547
548	exclude, base, err := m.rangeOf(ctx, mr)
549	if err != nil {
550		return ports.MergeRequestDetail{}, err
551	}
552	head := mr.HeadID
553	if head.IsZero() {
554		return d, checkBase(domain.ObjectID{}) // the source branch is gone: no commits, no diff
555	}
556	if !mr.IsOpen() {
557		// After a squash the reviewed commits are only reachable from the
558		// source branch; once it is deleted, gc may prune them.
559		switch ok, err := m.git.HasCommit(ctx, name, head); {
560		case err != nil:
561			return ports.MergeRequestDetail{}, err
562		case !ok:
563			// The reviewed commits are gone: no commits, no diff.
564			if err := checkBase(domain.ObjectID{}); err != nil {
565				return ports.MergeRequestDetail{}, err
566			}
567			return d, nil
568		}
569	}
570	if !opts.DiffOnly {
571		if d.Commits, d.CommitsTruncated, err = m.git.ListRange(ctx, name, exclude, head, MaxMergeRequestCommits); err != nil {
572			return ports.MergeRequestDetail{}, err
573		}
574		verifyCommits(ctx, m.verifier, name, d.Commits)
575	}
576	if opts.SinceLastRead && !d.LastReadID.IsZero() {
577		switch ok, err := m.git.HasCommit(ctx, name, d.LastReadID); {
578		case err != nil:
579			return ports.MergeRequestDetail{}, err
580		case ok:
581			base = d.LastReadID
582		default:
583			d.LastReadLost = true
584		}
585	}
586	if err := checkBase(base); err != nil {
587		return ports.MergeRequestDetail{}, err
588	}
589	if base.IsZero() {
590		return d, nil
591	}
592	d.DiffBaseID = base
593	if d.Stats, d.Diff, err = m.git.DiffCommits(ctx, name, base, head, limits); err != nil {
594		return ports.MergeRequestDetail{}, err
595	}
596	return d, nil
597}
598
599// rangeOf returns what the review of a request compares: the commit whose
600// history the request's commits exclude, and the base of its diff. For an open
601// request they are the tip of the target and the merge base of the target and
602// the head; both are zero when the target is gone or shares no history with
603// the head. A merged or closed request keeps the base it stored for both.
604func (m *MergeRequests) rangeOf(ctx context.Context, mr domain.MergeRequest) (exclude, base domain.ObjectID, err error) {
605	if !mr.IsOpen() {
606		return mr.BaseID, mr.BaseID, nil
607	}
608	if mr.HeadID.IsZero() {
609		return domain.ObjectID{}, domain.ObjectID{}, nil
610	}
611	tip, err := m.branchOrZero(ctx, mr.Repo, mr.Target)
612	if err != nil || tip.IsZero() {
613		return domain.ObjectID{}, domain.ObjectID{}, err
614	}
615	base, err = m.git.MergeBase(ctx, mr.Repo, tip, mr.HeadID)
616	if errors.Is(err, domain.ErrNotFound) {
617		return tip, domain.ObjectID{}, nil
618	}
619	return tip, base, err
620}
621
622// AddComment adds a comment and publishes CommentAdded. The principal needs
623// mr:write. The text must follow the rules of ADR 0032 and not be blank unless carrying a verdict; a
624// comment on a line must name a line of the current diff of the request (see
625// domain.Diff.HasLine), else the call fails with domain.ErrInvalid. A request
626// that is not open gives domain.ErrPreconditionFailed, and one that already
627// holds MaxCommentsPerMergeRequest comments domain.ErrResourceExhausted.
628func (m *MergeRequests) AddComment(ctx context.Context, p domain.Principal, name domain.RepoName, number int64, params ports.AddCommentParams) (domain.Comment, error) {
629	repo, err := m.writable(ctx, p, name, domain.ScopeMRWrite)
630	if err != nil {
631		return domain.Comment{}, err
632	}
633	mr, err := m.store.Get(ctx, name, number)
634	if err != nil {
635		return domain.Comment{}, err
636	}
637	var v domain.Violations
638	text, err := domain.ParsePlainText(params.Text)
639	switch {
640	case err != nil:
641		v.AddErr("text", err)
642	case text.IsBlank() && params.Verdict == domain.VerdictNone:
643		v.Add("text", "is required")
644	}
645	general := params.Path == ""
646	switch {
647	case general && (params.Line != 0 || params.Side != domain.SideNone || params.StartLine != 0):
648		v.Add("path", "is required with line and side")
649	case !general && params.Line < 1:
650		v.Add("line", "must be 1 or more with a path")
651	case !general && params.Side != domain.SideOld && params.Side != domain.SideNew:
652		v.Add("side", "is required with a path")
653	}
654	if params.StartLine != 0 && (params.StartLine < 1 || params.StartLine >= params.Line) {
655		v.Add("start_line", "must be 1 or more and less than line")
656	}
657	if params.Verdict > domain.VerdictChangesRequested {
658		v.Add("verdict", "is unknown")
659	}
660	if params.ReplyTo != 0 {
661		if params.Path != "" || params.Line != 0 || params.StartLine != 0 || params.Side != domain.SideNone || params.Verdict != domain.VerdictNone {
662			v.Add("reply_to", "a reply cannot specify an anchor or verdict")
663		}
664	}
665	if err := v.Err(); err != nil {
666		return domain.Comment{}, err
667	}
668	if params.ReplyTo != 0 {
669		root, err := m.replyRoot(ctx, name, number, params.ReplyTo)
670		if err != nil {
671			return domain.Comment{}, err
672		}
673		params.Path, params.Line, params.StartLine, params.Side = root.Path, root.Line, root.StartLine, root.Side
674	}
675	if params.Verdict != domain.VerdictNone {
676		if err := scopeAccess(p, repo, domain.ScopeMRReview); err != nil {
677			return domain.Comment{}, err
678		}
679	}
680	if !mr.IsOpen() {
681		return domain.Comment{}, fmt.Errorf("%w: !%d is %s", domain.ErrPreconditionFailed, number, mr.State)
682	}
683
684	if mr, err = m.withHead(ctx, mr); err != nil {
685		return domain.Comment{}, err
686	}
687	if !general && params.ReplyTo == 0 {
688		if err := m.checkLine(ctx, mr, params); err != nil {
689			return domain.Comment{}, err
690		}
691	}
692
693	var c domain.Comment
694	for range maxWriteRetries {
695		if mr.CommentSeq >= MaxCommentsPerMergeRequest {
696			return domain.Comment{}, fmt.Errorf("%w: !%d already has %d comments", domain.ErrResourceExhausted, number, MaxCommentsPerMergeRequest)
697		}
698		c = domain.Comment{
699			ID: mr.CommentSeq + 1, Author: domain.AuthorName(p), Path: params.Path, Line: params.Line, Side: params.Side,
700			ReplyTo: params.ReplyTo, StartLine: params.StartLine, Verdict: params.Verdict, Resolved: params.Verdict == domain.VerdictApprove,
701			CommitID: mr.HeadID, Text: text, CreatedAt: m.clock.Now().UTC(),
702		}
703		mr.CommentSeq, mr.UpdatedAt = c.ID, c.CreatedAt
704		err = m.store.SaveComment(ctx, mr, c)
705		if !errors.Is(err, domain.ErrConflict) {
706			break
707		}
708		// Another write got in between: read the request again.
709		fresh, gerr := m.store.Get(ctx, name, number)
710		if gerr != nil {
711			return domain.Comment{}, gerr
712		}
713		if !fresh.IsOpen() {
714			return domain.Comment{}, fmt.Errorf("%w: !%d is %s", domain.ErrPreconditionFailed, number, fresh.State)
715		}
716		if params.ReplyTo != 0 {
717			// The root may have been deleted by the write that got in between.
718			if _, rerr := m.replyRoot(ctx, name, number, params.ReplyTo); rerr != nil {
719				return domain.Comment{}, rerr
720			}
721		}
722		fresh.HeadID = mr.HeadID
723		mr = fresh
724	}
725	if err != nil {
726		return domain.Comment{}, fmt.Errorf("save comment on !%d of %q: %w", number, name, err)
727	}
728	log := zerowrap.FromCtx(ctx)
729	log.Info().Str("repo", name.String()).Int64("number", number).Int64("comment", c.ID).
730		Int64("reply_to", c.ReplyTo).Str("verdict", c.Verdict.String()).Bool("on_line", !general).Str("principal", p.Label()).Str("token_id", p.TokenID()).Msg("comment added")
731	m.bus.Publish(ctx, domain.CommentAdded{
732		Repo: name, Number: number, Comment: c, At: c.CreatedAt, Visibility: repo.Visibility, CreatedAt: repo.CreatedAt,
733	})
734	return c, nil
735}
736
737// checkLine verifies that a comment designates a line of the current diff of
738// the request.
739func (m *MergeRequests) checkLine(ctx context.Context, mr domain.MergeRequest, params ports.AddCommentParams) error {
740	var v domain.Violations
741	_, base, err := m.rangeOf(ctx, mr)
742	if err != nil {
743		return err
744	}
745	if mr.HeadID.IsZero() || base.IsZero() {
746		v.Add("path", "the merge request has no diff to comment on")
747		return v.Err()
748	}
749	// A comment may be on a file past the 300th that the web view lists, so
750	// the file is looked up among all the files (MaxFiles 0). Reading every
751	// file's hunks within the default total limits would reject a comment on a
752	// file the earlier ones left no budget for. So a first read lists the files
753	// with no hunks (From past the end: cheap, git is stopped at once), and a
754	// second reads the hunks of the one file within the default per-file limit
755	// and total limits, as the web view does for a window holding it.
756	list := domain.DefaultDiffLimits()
757	list.MaxFiles, list.From = 0, math.MaxInt
758	_, diff, err := m.git.DiffCommits(ctx, mr.Repo, base, mr.HeadID, list)
759	if err != nil {
760		return err
761	}
762	idx := slices.IndexFunc(diff.Files, func(f domain.FileDiff) bool { return diffFileName(f) == params.Path })
763	if idx >= 0 {
764		one := domain.DefaultDiffLimits()
765		one.MaxFiles, one.From, one.To = 0, idx, idx+1
766		if _, diff, err = m.git.DiffCommits(ctx, mr.Repo, base, mr.HeadID, one); err != nil {
767			return err
768		}
769	}
770	if idx < 0 || !diff.HasLine(params.Path, params.Side, params.Line) {
771		v.Add("path", fmt.Sprintf("%s:%d on the %s side is not a line of the diff", params.Path, params.Line, params.Side))
772	}
773	if params.StartLine != 0 && !diff.HasLine(params.Path, params.Side, params.StartLine) {
774		v.Add("start_line", "is not a line of the diff")
775	}
776	return v.Err()
777}
778
779// diffFileName is the path a comment designates for f, as Diff.HasLine reads it.
780func diffFileName(f domain.FileDiff) string {
781	if f.Status == domain.FileDeleted {
782		return f.OldPath
783	}
784	return f.NewPath
785}
786
787// ResolveComment marks a comment resolved or unresolved. The principal needs
788// mr:write. An unknown comment gives domain.ErrNotFound and a request that is
789// not open domain.ErrPreconditionFailed. Setting the state the comment already
790// has succeeds and writes nothing.
791func (m *MergeRequests) ResolveComment(ctx context.Context, p domain.Principal, name domain.RepoName, number, commentID int64, resolved bool) (domain.Comment, error) {
792	repo, err := m.writable(ctx, p, name, domain.ScopeMRWrite)
793	if err != nil {
794		return domain.Comment{}, err
795	}
796	for range maxWriteRetries {
797		mr, err := m.store.Get(ctx, name, number)
798		if err != nil {
799			return domain.Comment{}, err
800		}
801		c, err := m.store.GetComment(ctx, name, number, commentID)
802		if err != nil {
803			return domain.Comment{}, err
804		}
805		if !mr.IsOpen() {
806			return domain.Comment{}, fmt.Errorf("%w: !%d is %s", domain.ErrPreconditionFailed, number, mr.State)
807		}
808		if c.IsReply() {
809			var v domain.Violations
810			v.Add("comment_id", fmt.Sprintf("resolve the thread on its root ^%d", c.ReplyTo))
811			return domain.Comment{}, v.Err()
812		}
813		if c.Resolved == resolved {
814			return c, nil
815		}
816		c.Resolved = resolved
817		mr.UpdatedAt = m.clock.Now().UTC()
818		err = m.store.SaveComment(ctx, mr, c)
819		if errors.Is(err, domain.ErrConflict) {
820			continue
821		}
822		if err != nil {
823			return domain.Comment{}, fmt.Errorf("resolve comment %d of !%d in %q: %w", commentID, number, name, err)
824		}
825		m.bus.Publish(ctx, domain.CommentResolved{Repo: name, Number: number, Comment: c, At: mr.UpdatedAt, Visibility: repo.Visibility, CreatedAt: repo.CreatedAt})
826		return c, nil
827	}
828	return domain.Comment{}, fmt.Errorf("resolve comment %d of !%d in %q: %w", commentID, number, name, domain.ErrConflict)
829}
830
831// Close closes an open merge request without merging it and publishes
832// MergeRequestClosed. The principal needs mr:write. A request that is not open
833// gives domain.ErrPreconditionFailed. The request keeps the head it had and
834// its merge base, so that its diff stays readable.
835func (m *MergeRequests) Close(ctx context.Context, p domain.Principal, name domain.RepoName, number int64) (domain.MergeRequest, error) {
836	repo, err := m.writable(ctx, p, name, domain.ScopeMRWrite)
837	if err != nil {
838		return domain.MergeRequest{}, err
839	}
840	unlock, err := m.lockRepo(ctx, name) // a merge and a close of one request exclude each other
841	if err != nil {
842		return domain.MergeRequest{}, err
843	}
844	defer unlock()
845	for range maxWriteRetries {
846		mr, err := m.store.Get(ctx, name, number)
847		if err != nil {
848			return domain.MergeRequest{}, err
849		}
850		if !mr.IsOpen() {
851			return domain.MergeRequest{}, fmt.Errorf("%w: !%d is %s", domain.ErrPreconditionFailed, number, mr.State)
852		}
853		if mr, err = m.withHead(ctx, mr); err != nil {
854			return domain.MergeRequest{}, err
855		}
856		_, base, err := m.rangeOf(ctx, mr)
857		if err != nil {
858			return domain.MergeRequest{}, err
859		}
860		mr.State, mr.BaseID, mr.UpdatedAt = domain.MRStateClosed, base, m.clock.Now().UTC()
861		err = m.store.Update(ctx, mr)
862		if errors.Is(err, domain.ErrConflict) {
863			continue
864		}
865		if err != nil {
866			return domain.MergeRequest{}, fmt.Errorf("close !%d of %q: %w", number, name, err)
867		}
868		log := zerowrap.FromCtx(ctx)
869		log.Info().Str("repo", name.String()).Int64("number", number).
870			Str("principal", p.Label()).Str("token_id", p.TokenID()).Msg("merge request closed")
871		m.bus.Publish(ctx, domain.MergeRequestClosed{MergeRequest: mr, At: mr.UpdatedAt, Visibility: repo.Visibility, CreatedAt: repo.CreatedAt})
872		if m.pulls != nil {
873			m.pulls.OnPullRequest(ctx, name, ports.PullRequestEvent{Number: number, Action: domain.PullClosed, Head: mr.HeadID, Base: mr.BaseID}, p)
874		}
875		return mr, nil
876	}
877	return domain.MergeRequest{}, fmt.Errorf("close !%d of %q: %w", number, name, domain.ErrConflict)
878}
879
880// MarkRead records the head the reviewer has read, for the since-last-read diff
881// of Get. The principal needs mr:write. A zero head means the current head of
882// the source branch (the stored one for a merged or closed request); one that
883// is not a commit of the repository gives domain.ErrInvalid. It returns the
884// head recorded.
885func (m *MergeRequests) MarkRead(ctx context.Context, p domain.Principal, name domain.RepoName, number int64, head domain.ObjectID) (domain.ObjectID, error) {
886	if _, err := m.writable(ctx, p, name, domain.ScopeMRWrite); err != nil {
887		return domain.ObjectID{}, err
888	}
889	mr, err := m.store.Get(ctx, name, number)
890	if err != nil {
891		return domain.ObjectID{}, err
892	}
893	if head.IsZero() {
894		if mr, err = m.withHead(ctx, mr); err != nil {
895			return domain.ObjectID{}, err
896		}
897		if head = mr.HeadID; head.IsZero() {
898			return domain.ObjectID{}, fmt.Errorf("%w: the source branch %q no longer exists, give a head", domain.ErrPreconditionFailed, mr.Source)
899		}
900	} else {
901		var v domain.Violations
902		switch ok, err := m.git.HasCommit(ctx, name, head); {
903		case err != nil:
904			return domain.ObjectID{}, err
905		case !ok:
906			v.Add("head_id", fmt.Sprintf("%s is not a commit of the repository", head))
907			return domain.ObjectID{}, v.Err()
908		}
909	}
910	if err := m.store.SetRead(ctx, name, number, head); err != nil {
911		return domain.ObjectID{}, err
912	}
913	return head, nil
914}
915
916// Merge merges an open merge request, publishes MergeRequestMerged then a
917// PushEvent for the target branch, and returns the merged request. The
918// principal needs mr:merge. Merges of one repository run one at a time.
919//
920// It fails with domain.ErrInvalid for a zero head, and with
921// domain.ErrPreconditionFailed when the request is not open, the mode is not
922// allowed by the settings of the repository, the source branch no longer
923// points to the head ("branch moved, read again") or is gone, the target is
924// gone, the mode's own condition does not hold (see below), or the branch
925// brings nothing. Checks come with CI (CI-1): there are none yet, so the
926// setting that lets failing checks block the merge has nothing to act on.
927//
928// The conditions are always checked with Git, under the lock, never from the
929// stored mergeability. A fast-forward needs the target to be an ancestor of
930// the head (the author rebases and pushes again) and moves the target to the
931// head, with the old value as a precondition. A squash and a merge commit need
932// the head to merge cleanly into the target (a behind branch is fine). A squash
933// writes one commit with the merged tree, the target as parent and the author
934// and message of domain.NewSquashCommit; a merge commit has two parents (the
935// target, then the head) and the message of domain.NewMergeCommit. Both are
936// signed by the instance key and move the target the same way.
937//
938// With DeleteSource the merge is also refused, before anything changes, when
939// the source is the default branch or the source or target of another open
940// request.
941//
942// Only the merge itself runs before Merge returns, under the lock. Afterwards,
943// off the request path and without the lock: the deletion of the source branch
944// (if it still points to the head; a failure is logged and leaves the branch),
945// MergeRequestMerged then a PushEvent (which carries the deletion too), and
946// the CI and mergeability hooks. Wait waits for them. SourceDeleted therefore
947// only says that the deletion was requested.
948func (m *MergeRequests) Merge(ctx context.Context, p domain.Principal, name domain.RepoName, number int64, params ports.MergeParams) (ports.MergeResult, error) {
949	mr, err := m.merge(ctx, p, name, number, params)
950	return ports.MergeResult{MergeRequest: mr, SourceDeleted: err == nil && params.DeleteSource}, err
951}
952
953// maxConflictPathsShown is how many conflicting paths a refusal lists.
954const maxConflictPathsShown = 5
955
956// checkMode is the authoritative per-mode check of a merge, done with Git. It
957// returns the tree a squash or merge commit gets (zero for a fast-forward).
958func (m *MergeRequests) checkMode(ctx context.Context, mr domain.MergeRequest, mode domain.MergeMode, tip, head domain.ObjectID) (domain.ObjectID, error) {
959	if mode == domain.MergeModeFastForward {
960		ok, err := m.git.IsAncestor(ctx, mr.Repo, tip, head)
961		if err != nil {
962			return domain.ObjectID{}, err
963		}
964		if !ok {
965			return domain.ObjectID{}, fmt.Errorf("%w: the target has moved: rebase and push again, or merge with squash or a merge commit", domain.ErrPreconditionFailed)
966		}
967		return domain.ObjectID{}, nil
968	}
969	res, err := m.git.MergeTree(ctx, mr.Repo, tip, head)
970	if err != nil {
971		return domain.ObjectID{}, err
972	}
973	res = res.Bounded()
974	if !res.Clean {
975		what := "no common history"
976		if len(res.ConflictPaths) > 0 {
977			shown := res.ConflictPaths
978			if len(shown) > maxConflictPathsShown {
979				shown = shown[:maxConflictPathsShown]
980			}
981			what = strings.Join(shown, ", ")
982			if len(shown) < len(res.ConflictPaths) || res.Truncated {
983				what += ", ..."
984			}
985		}
986		return domain.ObjectID{}, fmt.Errorf("%w: conflicts with %s: %s: rebase and push again", domain.ErrPreconditionFailed, mr.Target, what)
987	}
988	return res.Tree, nil
989}
990
991func (m *MergeRequests) merge(ctx context.Context, p domain.Principal, name domain.RepoName, number int64, params ports.MergeParams) (domain.MergeRequest, error) {
992	repo, err := m.writable(ctx, p, name, domain.ScopeMRMerge)
993	if err != nil {
994		return domain.MergeRequest{}, err
995	}
996	mode := params.Mode
997	if mode == "" {
998		mode = domain.MergeModeFastForward
999	}
1000	var v domain.Violations
1001	if _, err := domain.ParseMergeMode(mode.String()); err != nil {
1002		v.Add("mode", "is not a merge mode")
1003	}
1004	if params.HeadID.IsZero() {
1005		v.Add("head_id", "is required")
1006	}
1007	if err := v.Err(); err != nil {
1008		return domain.MergeRequest{}, err
1009	}
1010
1011	unlock, err := m.lockRepo(ctx, name)
1012	if err != nil {
1013		return domain.MergeRequest{}, err
1014	}
1015	var once sync.Once
1016	release := func() { once.Do(unlock) }
1017	defer release()
1018
1019	mr, err := m.store.Get(ctx, name, number)
1020	if err != nil {
1021		return domain.MergeRequest{}, err
1022	}
1023	// A merge moves the target and may delete the source: a token limited to
1024	// branch prefixes may do so only within them.
1025	if !p.AllowsRef("refs/heads/" + mr.Target) {
1026		return domain.MergeRequest{}, fmt.Errorf("%w: this token may not write %s", domain.ErrForbidden, mr.Target)
1027	}
1028	if params.DeleteSource && !p.AllowsRef("refs/heads/"+mr.Source) {
1029		return domain.MergeRequest{}, fmt.Errorf("%w: this token may not write %s", domain.ErrForbidden, mr.Source)
1030	}
1031	if !mr.IsOpen() {
1032		return domain.MergeRequest{}, fmt.Errorf("%w: !%d is %s", domain.ErrPreconditionFailed, number, mr.State)
1033	}
1034	if mr.IsDraft() {
1035		return domain.MergeRequest{}, fmt.Errorf("%w: !%d is a draft: mark it ready for review first", domain.ErrPreconditionFailed, number)
1036	}
1037	// The settings are read again under the lock: a change applies at once.
1038	repo, err = m.meta.Get(ctx, name)
1039	if err != nil {
1040		if errors.Is(err, domain.ErrNotFound) {
1041			return domain.MergeRequest{}, err // deleted meanwhile
1042		}
1043		return domain.MergeRequest{}, fmt.Errorf("get repository %q: %w", name, err)
1044	}
1045	settings := repo.Settings
1046	if settings.IsZero() {
1047		settings = domain.DefaultRepoSettings()
1048	}
1049	if !settings.Allows(mode) {
1050		return domain.MergeRequest{}, fmt.Errorf("%w: the %s merge mode is not allowed in %s", domain.ErrPreconditionFailed, mode, name)
1051	}
1052
1053	head, err := m.branchOrZero(ctx, name, mr.Source)
1054	switch {
1055	case err != nil:
1056		return domain.MergeRequest{}, err
1057	case head.IsZero():
1058		return domain.MergeRequest{}, fmt.Errorf("%w: the source branch %q no longer exists", domain.ErrPreconditionFailed, mr.Source)
1059	case head != params.HeadID:
1060		return domain.MergeRequest{}, fmt.Errorf("%w: branch moved, read again: %q is at %s, not %s", domain.ErrPreconditionFailed, mr.Source, head, params.HeadID)
1061	}
1062	tip, err := m.branchOrZero(ctx, name, mr.Target)
1063	switch {
1064	case err != nil:
1065		return domain.MergeRequest{}, err
1066	case tip.IsZero():
1067		return domain.MergeRequest{}, fmt.Errorf("%w: the target branch %q no longer exists", domain.ErrPreconditionFailed, mr.Target)
1068	case tip == head:
1069		return domain.MergeRequest{}, fmt.Errorf("%w: nothing to merge, %q already is at %s", domain.ErrPreconditionFailed, mr.Target, head)
1070	}
1071	// A head behind the target (or at it) has nothing to merge, in any mode.
1072	if behind, err := m.git.IsAncestor(ctx, name, head, tip); err != nil {
1073		return domain.MergeRequest{}, err
1074	} else if behind {
1075		return domain.MergeRequest{}, fmt.Errorf("%w: nothing to merge, %q already contains %s", domain.ErrPreconditionFailed, mr.Target, head)
1076	}
1077	tree, err := m.checkMode(ctx, mr, mode, tip, head)
1078	if err != nil {
1079		return domain.MergeRequest{}, err
1080	}
1081	if settings.FailingChecksBlock {
1082		if err := m.checksAllow(ctx, name, head); err != nil {
1083			return domain.MergeRequest{}, err
1084		}
1085	}
1086	if params.DeleteSource {
1087		if err := m.checkDeletable(ctx, name, mr); err != nil {
1088			return domain.MergeRequest{}, err
1089		}
1090	}
1091
1092	merged, err := m.moveTarget(ctx, mr, mode, tip, head, tree, p)
1093	if err != nil {
1094		return domain.MergeRequest{}, err
1095	}
1096	m.recordPush(ctx, name) // the target moved, whatever happens next
1097	mr, err = m.markMerged(ctx, name, number, mode, tip, head, merged)
1098	if err != nil {
1099		return domain.MergeRequest{}, err
1100	}
1101	log := zerowrap.FromCtx(ctx)
1102	log.Info().Str("repo", name.String()).Int64("number", number).Str("mode", mode.String()).
1103		Str("target", mr.Target).Str("commit", merged.String()).
1104		Str("principal", p.Label()).Str("token_id", p.TokenID()).Msg("merge request merged")
1105
1106	// The merge is done and recorded. The rest runs without the lock and after
1107	// the caller got its answer.
1108	release()
1109	bg := context.WithoutCancel(ctx)
1110	m.after.Add(1)
1111	go func() {
1112		defer m.after.Done()
1113		defer func() {
1114			if r := recover(); r != nil {
1115				log := zerowrap.FromCtx(bg)
1116				log.Error().Str("repo", name.String()).Int64("number", number).
1117					Str("panic", fmt.Sprint(r)).Bytes("stack", debug.Stack()).Msg("post-merge side effects panicked")
1118			}
1119		}()
1120		if m.afterGate != nil {
1121			m.afterGate()
1122		}
1123		m.afterMerge(bg, p, repo, mr, head, tip, merged, params.DeleteSource)
1124	}()
1125	return mr, nil
1126}
1127
1128// afterMerge is what follows a merge off the request path: errors are logged,
1129// never returned. mr is the merged request, tip the old target and merged the
1130// new one.
1131func (m *MergeRequests) afterMerge(ctx context.Context, p domain.Principal, repo domain.Repo, mr domain.MergeRequest, head, tip, merged domain.ObjectID, deleteSource bool) {
1132	name := repo.Name
1133	updates := []domain.RefUpdate{{Old: tip.String(), New: merged.String(), Ref: "refs/heads/" + mr.Target}}
1134	if deleteSource && m.deleteSource(ctx, p, name, mr, head) {
1135		updates = append(updates, domain.RefUpdate{Old: head.String(), New: domain.ZeroOID, Ref: "refs/heads/" + mr.Source})
1136	}
1137	at := mr.UpdatedAt
1138	m.bus.Publish(ctx, domain.MergeRequestMerged{MergeRequest: mr, At: at, Visibility: repo.Visibility, CreatedAt: repo.CreatedAt})
1139	m.bus.Publish(ctx, domain.PushEvent{
1140		Repo: name, At: at, Visibility: repo.Visibility, CreatedAt: repo.CreatedAt, Updates: updates,
1141	})
1142	if m.pulls != nil {
1143		m.pulls.OnPullRequest(ctx, name, ports.PullRequestEvent{Number: mr.Number, Action: domain.PullClosed, Head: mr.HeadID, Base: mr.BaseID, Merged: true}, p)
1144	}
1145	if m.ci != nil {
1146		// GitHub runs the "push" workflows of a merge, with the owner as actor;
1147		// the run is trusted with what the merging principal may read.
1148		m.ci.OnMerge(ctx, name, updates, p)
1149	}
1150	if m.mergeab != nil {
1151		m.mergeab.OnBranchesMoved(ctx, name, updates) // the other requests of the moved target
1152	}
1153}
1154
1155// deleteSource deletes the source branch of a merged request if it is still
1156// head and still unused, and reports whether it did. The eligibility is checked
1157// again and the branch deleted in one critical section of the merge lock: a
1158// request opened on the branch since the merge, or a push to it, keeps it. The
1159// record of who pushed the branch goes only after a deletion, and only if it
1160// still names head.
1161func (m *MergeRequests) deleteSource(ctx context.Context, p domain.Principal, name domain.RepoName, mr domain.MergeRequest, head domain.ObjectID) bool {
1162	log := zerowrap.FromCtx(ctx).With().Str("repo", name.String()).Int64("number", mr.Number).Str("branch", mr.Source).Logger()
1163	unlock, err := m.lockRepo(ctx, name)
1164	if err != nil {
1165		log.Warn().Err(err).Msg("source branch kept after the merge")
1166		return false
1167	}
1168	defer unlock()
1169	if err := m.checkDeletable(ctx, name, mr); err != nil {
1170		log.Warn().Err(err).Msg("source branch kept after the merge")
1171		return false
1172	}
1173	if err := m.git.DeleteBranch(ctx, name, mr.Source, head); err != nil {
1174		log.Warn().Err(err).Msg("source branch kept after the merge")
1175		return false
1176	}
1177	if m.tips != nil {
1178		if err := m.tips.DeleteRefTipIf(ctx, name, "refs/heads/"+mr.Source, head.String()); err != nil && !errors.Is(err, domain.ErrNotFound) {
1179			log.Warn().Err(err).Msg("the record of the source branch was kept")
1180		}
1181	}
1182	log.Info().Str("principal", p.Label()).Str("token_id", p.TokenID()).Msg("source branch deleted after the merge")
1183	return true
1184}
1185
1186// WhileOpen implements ports.PullGate: fn runs under the merge lock, so a
1187// close or a merge of the request cannot complete in the middle of it, and not
1188// at all when the request is no longer open.
1189func (m *MergeRequests) WhileOpen(ctx context.Context, name domain.RepoName, number int64, fn func() error) error {
1190	unlock, err := m.lockRepo(ctx, name)
1191	if err != nil {
1192		return err
1193	}
1194	defer unlock()
1195	mr, err := m.store.Get(ctx, name, number)
1196	if err != nil {
1197		return err
1198	}
1199	if !mr.IsOpen() {
1200		return fmt.Errorf("%w: !%d is %s", domain.ErrPreconditionFailed, number, mr.State)
1201	}
1202	return fn()
1203}
1204
1205// checksAllow is the merge rule of FailingChecksBlock: every check of the
1206// head must have ended as success, skipped or neutral. A check still queued or
1207// running blocks too (the merge could land code that then fails), and a head
1208// without any check merges.
1209func (m *MergeRequests) checksAllow(ctx context.Context, name domain.RepoName, head domain.ObjectID) error {
1210	if m.checks == nil {
1211		return nil
1212	}
1213	checks, err := m.checks.CommitChecks(ctx, name, head.String())
1214	if errors.Is(err, domain.ErrResourceExhausted) {
1215		return fmt.Errorf("%w: too many checks to tell whether they passed: %v", domain.ErrPreconditionFailed, err)
1216	}
1217	if err != nil {
1218		return fmt.Errorf("read the checks of %s: %w", head, err)
1219	}
1220	var failing, pending []string
1221	for _, c := range checks {
1222		switch {
1223		case c.Status != domain.CICompleted:
1224			pending = append(pending, c.Name)
1225		case !c.Conclusion.PassesMerge():
1226			failing = append(failing, c.Name)
1227		}
1228	}
1229	switch {
1230	case len(failing) > 0:
1231		return fmt.Errorf("%w: failing checks block the merge: %s (turn off failing_checks_block to merge anyway)", domain.ErrPreconditionFailed, strings.Join(failing, ", "))
1232	case len(pending) > 0:
1233		return fmt.Errorf("%w: checks have not finished: %s", domain.ErrPreconditionFailed, strings.Join(pending, ", "))
1234	}
1235	return nil
1236}
1237
1238// checkDeletable refuses to delete the source branch of mr when it is the
1239// default branch or the source or target of another open request. It runs
1240// under the merge lock, which Create also holds while it checks its branches
1241// and stores the request.
1242func (m *MergeRequests) checkDeletable(ctx context.Context, name domain.RepoName, mr domain.MergeRequest) error {
1243	def, _, err := m.repos.DefaultBranch(ctx, name)
1244	if err != nil {
1245		return fmt.Errorf("default branch of %q: %w", name, err)
1246	}
1247	if mr.Source == def {
1248		return fmt.Errorf("%w: %q is the default branch of %s: it cannot be deleted", domain.ErrPreconditionFailed, mr.Source, name)
1249	}
1250	all, err := m.store.List(ctx, name)
1251	if err != nil {
1252		return fmt.Errorf("list merge requests of %q: %w", name, err)
1253	}
1254	for _, o := range all {
1255		if o.Number != mr.Number && o.IsOpen() && (o.Source == mr.Source || o.Target == mr.Source) {
1256			return fmt.Errorf("%w: !%d still uses %q: it cannot be deleted", domain.ErrPreconditionFailed, o.Number, mr.Source)
1257		}
1258	}
1259	return nil
1260}
1261
1262// recordPush does for a merge what Pushes.Record does for a push, as the merge
1263// moved a branch: it sets pushed_at and queues the maintenance of the
1264// repository. The target already moved, so a failure is logged, not returned,
1265// and the caller giving up does not stop it.
1266func (m *MergeRequests) recordPush(ctx context.Context, name domain.RepoName) {
1267	ctx = context.WithoutCancel(ctx)
1268	if _, err := touchPushedAt(ctx, m.meta, name, m.clock.Now().UTC()); err != nil {
1269		log := zerowrap.FromCtx(ctx)
1270		log.Error().Err(err).Str("repo", name.String()).Msg("record pushed_at after a merge")
1271	}
1272	m.maint.Schedule(ctx, name)
1273}
1274
1275// moveTarget moves the target branch from tip to the head (fast-forward) or to
1276// a new signed squash or merge commit with the given tree, and returns the new tip.
1277func (m *MergeRequests) moveTarget(ctx context.Context, mr domain.MergeRequest, mode domain.MergeMode, tip, head, tree domain.ObjectID, p domain.Principal) (domain.ObjectID, error) {
1278	newTip := head
1279	switch mode {
1280	case domain.MergeModeMerge:
1281		commit := domain.NewMergeCommit(mr, tree, tip, head, m.committer, m.clock.Now())
1282		armored, err := m.signer.Sign(commit.Payload())
1283		if err != nil {
1284			return domain.ObjectID{}, fmt.Errorf("sign the merge commit of !%d in %q: %w", mr.Number, mr.Repo, err)
1285		}
1286		if newTip, err = m.git.WriteCommit(ctx, mr.Repo, commit.Signed(armored)); err != nil {
1287			return domain.ObjectID{}, err
1288		}
1289	case domain.MergeModeSquash:
1290		commits, more, err := m.git.ListRange(ctx, mr.Repo, tip, head, domain.MaxSquashCommits)
1291		if err != nil {
1292			return domain.ObjectID{}, err
1293		}
1294		if more {
1295			return domain.ObjectID{}, fmt.Errorf("%w: the branch has more than %d commits to squash", domain.ErrPreconditionFailed, domain.MaxSquashCommits)
1296		}
1297		commit := domain.NewSquashCommit(mr, tree, tip, commits, m.committer, m.clock.Now())
1298		armored, err := m.signer.Sign(commit.Payload())
1299		if err != nil {
1300			return domain.ObjectID{}, fmt.Errorf("sign the squash commit of !%d in %q: %w", mr.Number, mr.Repo, err)
1301		}
1302		if newTip, err = m.git.WriteCommit(ctx, mr.Repo, commit.Signed(armored)); err != nil {
1303			return domain.ObjectID{}, err
1304		}
1305	}
1306	// The target is the merger's from the moment it moves: recorded before it
1307	// does, under the merge lock (domain.CIRefTip). The run shows the owner, as a
1308	// merge's push does on GitHub.
1309	if err := recordRefTips(ctx, m.tips, mr.Repo, []domain.RefUpdate{{Old: tip.String(), New: newTip.String(), Ref: "refs/heads/" + mr.Target}},
1310		domain.AuthorName(domain.Owner()), domain.PusherOf(p), domain.TrustedActor(p)); err != nil {
1311		return domain.ObjectID{}, err
1312	}
1313	err := m.git.UpdateBranch(ctx, mr.Repo, mr.Target, tip, newTip)
1314	if errors.Is(err, domain.ErrConflict) {
1315		return domain.ObjectID{}, fmt.Errorf("%w: the target branch %q moved during the merge, try again", domain.ErrPreconditionFailed, mr.Target)
1316	}
1317	if err != nil {
1318		return domain.ObjectID{}, err
1319	}
1320	return newTip, nil
1321}
1322
1323// markMerged records the merge. The target already moved, so a write that
1324// loses a race (a comment added meanwhile) is repeated on the fresh request.
1325func (m *MergeRequests) markMerged(ctx context.Context, name domain.RepoName, number int64, mode domain.MergeMode, base, head, merged domain.ObjectID) (domain.MergeRequest, error) {
1326	// The merge must be recorded even when the caller gives up.
1327	ctx = context.WithoutCancel(ctx)
1328	for range maxWriteRetries {
1329		mr, err := m.store.Get(ctx, name, number)
1330		if err != nil {
1331			return domain.MergeRequest{}, fmt.Errorf("record the merge of !%d in %q: %w", number, name, err)
1332		}
1333		mr.State, mr.HeadID, mr.BaseID, mr.MergedCommitID, mr.MergeMode = domain.MRStateMerged, head, base, merged, mode
1334		mr.UpdatedAt = m.clock.Now().UTC()
1335		err = m.store.Update(ctx, mr)
1336		if errors.Is(err, domain.ErrConflict) {
1337			continue
1338		}
1339		if err != nil {
1340			return domain.MergeRequest{}, fmt.Errorf("record the merge of !%d in %q: %w", number, name, err)
1341		}
1342		return mr, nil
1343	}
1344	log := zerowrap.FromCtx(ctx)
1345	log.Error().Str("repo", name.String()).Int64("number", number).Str("commit", merged.String()).
1346		Msg("the target branch moved but the merge request could not be marked merged")
1347	return domain.MergeRequest{}, fmt.Errorf("record the merge of !%d in %q: %w", number, name, domain.ErrConflict)
1348}
1349
1350// EditComment changes only the author's text, preserving the immutable verdict.
1351func (m *MergeRequests) EditComment(ctx context.Context, p domain.Principal, name domain.RepoName, number, commentID int64, text string) (domain.Comment, error) {
1352	return m.changeComment(ctx, p, name, number, commentID, text, false)
1353}
1354
1355// DeleteComment removes text but retains the anchor, ID and verdict. Repeated deletion is a no-op.
1356func (m *MergeRequests) DeleteComment(ctx context.Context, p domain.Principal, name domain.RepoName, number, commentID int64) (domain.Comment, error) {
1357	return m.changeComment(ctx, p, name, number, commentID, "", true)
1358}
1359
1360func (m *MergeRequests) changeComment(ctx context.Context, p domain.Principal, name domain.RepoName, number, commentID int64, text string, remove bool) (domain.Comment, error) {
1361	repo, err := m.writable(ctx, p, name, domain.ScopeMRWrite)
1362	if err != nil {
1363		return domain.Comment{}, err
1364	}
1365	for range maxWriteRetries {
1366		mr, err := m.store.Get(ctx, name, number)
1367		if err != nil {
1368			return domain.Comment{}, err
1369		}
1370		c, err := m.store.GetComment(ctx, name, number, commentID)
1371		if err != nil {
1372			return domain.Comment{}, err
1373		}
1374		if !mr.IsOpen() {
1375			return domain.Comment{}, fmt.Errorf("%w: !%d is %s", domain.ErrPreconditionFailed, number, mr.State)
1376		}
1377		if domain.AuthorName(p) != c.Author {
1378			return domain.Comment{}, fmt.Errorf("%w: only the author of a note can edit or delete it", domain.ErrForbidden)
1379		}
1380		if c.Deleted {
1381			if remove {
1382				return c, nil
1383			}
1384			return domain.Comment{}, fmt.Errorf("%w: the note was deleted", domain.ErrPreconditionFailed)
1385		}
1386		parsed, err := domain.ParsePlainText(text)
1387		var v domain.Violations
1388		if err != nil {
1389			v.AddErr("text", err)
1390		} else if !remove && parsed.IsBlank() && c.Verdict == domain.VerdictNone {
1391			v.Add("text", "is required")
1392		}
1393		if err := v.Err(); err != nil {
1394			return domain.Comment{}, err
1395		}
1396		if !remove && parsed == c.Text {
1397			return c, nil
1398		}
1399		c.Text, c.Deleted, c.EditedAt = parsed, remove, m.clock.Now().UTC()
1400		mr.UpdatedAt = c.EditedAt
1401		if err := m.store.SaveComment(ctx, mr, c); errors.Is(err, domain.ErrConflict) {
1402			continue
1403		} else if err != nil {
1404			return domain.Comment{}, fmt.Errorf("save note %d of !%d in %q: %w", commentID, number, name, err)
1405		}
1406		log := zerowrap.FromCtx(ctx)
1407		log.Info().Str("repo", name.String()).Int64("number", number).Int64("comment", c.ID).Bool("deleted", remove).Str("principal", p.Label()).Str("token_id", p.TokenID()).Msg("comment changed")
1408		if remove {
1409			m.bus.Publish(ctx, domain.CommentDeleted{Repo: name, Number: number, Comment: c, At: c.EditedAt, Visibility: repo.Visibility, CreatedAt: repo.CreatedAt})
1410		} else {
1411			m.bus.Publish(ctx, domain.CommentEdited{Repo: name, Number: number, Comment: c, At: c.EditedAt, Visibility: repo.Visibility, CreatedAt: repo.CreatedAt})
1412		}
1413		return c, nil
1414	}
1415	return domain.Comment{}, fmt.Errorf("save note %d of !%d in %q: %w", commentID, number, name, domain.ErrConflict)
1416}
1417
1418// replyRoot returns the note a reply targets, or a violation when it is
1419// missing, itself a reply, or deleted.
1420func (m *MergeRequests) replyRoot(ctx context.Context, name domain.RepoName, number, id int64) (domain.Comment, error) {
1421	root, err := m.store.GetComment(ctx, name, number, id)
1422	var v domain.Violations
1423	switch {
1424	case errors.Is(err, domain.ErrNotFound):
1425		v.Add("reply_to", fmt.Sprintf("no note ^%d", id))
1426	case err != nil:
1427		return domain.Comment{}, err
1428	case root.IsReply() || root.Deleted:
1429		v.Add("reply_to", "must name a non-deleted root note")
1430	}
1431	if err := v.Err(); err != nil {
1432		return domain.Comment{}, err
1433	}
1434	return root, nil
1435}

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