v0.28.1 cc7ba64

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 = ports.MaxMergeRequestCommits
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	recordActivity(ctx, m.meta, repo.Name, now)
283	m.bus.Publish(ctx, domain.MergeRequestOpened{MergeRequest: mr, At: now, Visibility: repo.Visibility, CreatedAt: repo.CreatedAt})
284	if m.mergeab != nil {
285		m.mergeab.OnOpened(ctx, mr)
286	}
287	if m.pulls != nil {
288		// The commits the opening is for are the ones of now.
289		base, _ := m.branchOrZero(ctx, name, target)
290		m.pulls.OnPullRequest(ctx, name, ports.PullRequestEvent{Number: mr.Number, Action: domain.PullOpened, Head: mr.HeadID, Base: base}, p)
291	}
292	return mr, nil
293}
294
295// checkBranches validates the branches of a new request and returns them, with
296// the default branch filled in for the target.
297//
298// Only a branch that does not exist is a violation. Any other failure to read
299// Git is returned as an error, so that it is logged and masked, not shown in
300// the field violations.
301func (m *MergeRequests) checkBranches(ctx context.Context, name domain.RepoName, params ports.CreateMergeRequestParams, v *domain.Violations) (source, target string, err error) {
302	source, target = params.Source, params.Target
303	if source == "" {
304		v.Add("source_branch", "is required")
305	} else if _, err := domain.ParseBranchName(source); err != nil {
306		v.Add("source_branch", "is not a valid branch name")
307		source = ""
308	}
309	if target == "" {
310		def, exists, err := m.repos.DefaultBranch(ctx, name)
311		switch {
312		case err != nil: // includes domain.ErrNotFound: the repository is gone
313			return "", "", fmt.Errorf("read the default branch of %q: %w", name, err)
314		case !exists:
315			v.Add("target_branch", fmt.Sprintf("is empty and the default branch %q does not exist", def))
316		default:
317			target = def
318		}
319	} else if _, err := domain.ParseBranchName(target); err != nil {
320		v.Add("target_branch", "is not a valid branch name")
321		target = ""
322	}
323	if source != "" && source == target {
324		v.Add("target_branch", "must differ from source_branch")
325		return source, target, nil
326	}
327	for _, b := range []struct{ field, name string }{{"source_branch", source}, {"target_branch", target}} {
328		if b.name == "" {
329			continue
330		}
331		_, err := m.git.BranchHead(ctx, name, b.name)
332		if errors.Is(err, domain.ErrNotFound) {
333			v.Add(b.field, fmt.Sprintf("branch %q does not exist", b.name))
334		} else if err != nil {
335			return "", "", fmt.Errorf("read branch %q of %q: %w", b.name, name, err)
336		}
337	}
338	return source, target, nil
339}
340
341// List returns a page of the merge requests of a repository, highest number
342// first. The open ones carry the head of their source branch. The page token
343// names the last number of the previous page, so requests created between two
344// pages never shift the others.
345func (m *MergeRequests) List(ctx context.Context, p domain.Principal, name domain.RepoName, params ports.ListMergeRequestsParams) (ports.MergeRequestPage, error) {
346	size, err := pageSize(params.PageSize)
347	if err != nil {
348		return ports.MergeRequestPage{}, err
349	}
350	after, err := decodeMRToken(params.PageToken)
351	if err != nil {
352		return ports.MergeRequestPage{}, err
353	}
354	if _, err := m.readable(ctx, p, name); err != nil {
355		return ports.MergeRequestPage{}, err
356	}
357	all, err := m.store.List(ctx, name)
358	if err != nil {
359		return ports.MergeRequestPage{}, fmt.Errorf("list merge requests of %q: %w", name, err)
360	}
361	var page ports.MergeRequestPage
362	page.MergeRequests, page.NextPageToken = pageAfter(all, size,
363		func(mr domain.MergeRequest) bool {
364			return (params.State == "" || mr.State == params.State) && (after == 0 || mr.Number < after)
365		},
366		encodeMRToken)
367	tips := map[string]domain.ObjectID{} // one BranchHead per distinct target
368	for i, mr := range page.MergeRequests {
369		if page.MergeRequests[i], err = m.withHead(ctx, mr); err != nil {
370			return ports.MergeRequestPage{}, err
371		}
372		if m.mergeab == nil || !mr.IsOpen() {
373			continue
374		}
375		tip, ok := tips[mr.Target]
376		if !ok {
377			if tip, err = m.branchOrZero(ctx, name, mr.Target); err != nil {
378				return ports.MergeRequestPage{}, err
379			}
380			tips[mr.Target] = tip
381		}
382		if page.Mergeability == nil {
383			page.Mergeability = map[int64]domain.Mergeability{}
384		}
385		page.Mergeability[mr.Number] = m.mergeab.Read(ctx, page.MergeRequests[i], tip)
386	}
387	return page, nil
388}
389
390// MarkReady implements ports.MergeRequestService: the title of an open draft
391// loses its draft prefix, so the request can be merged. The principal needs
392// mr:write. A request that is not open, or not a draft, gives
393// domain.ErrPreconditionFailed.
394func (m *MergeRequests) MarkReady(ctx context.Context, p domain.Principal, name domain.RepoName, number int64) (domain.MergeRequest, error) {
395	repo, err := m.writable(ctx, p, name, domain.ScopeMRWrite)
396	if err != nil {
397		return domain.MergeRequest{}, err
398	}
399	unlock, err := m.lockRepo(ctx, name) // a merge sees the request as it is after
400	if err != nil {
401		return domain.MergeRequest{}, err
402	}
403	defer unlock()
404	for range maxWriteRetries {
405		mr, err := m.store.Get(ctx, name, number)
406		if err != nil {
407			return domain.MergeRequest{}, err
408		}
409		if !mr.IsOpen() {
410			return domain.MergeRequest{}, fmt.Errorf("%w: !%d is %s", domain.ErrPreconditionFailed, number, mr.State)
411		}
412		title, ok := domain.ReadyTitle(mr.Title)
413		if !ok {
414			return domain.MergeRequest{}, fmt.Errorf("%w: !%d is not a draft", domain.ErrPreconditionFailed, number)
415		}
416		mr.Title, mr.UpdatedAt = title, m.clock.Now().UTC()
417		err = m.store.Update(ctx, mr)
418		if errors.Is(err, domain.ErrConflict) {
419			continue
420		}
421		if err != nil {
422			return domain.MergeRequest{}, fmt.Errorf("mark !%d of %q ready: %w", number, name, err)
423		}
424		recordActivity(ctx, m.meta, repo.Name, mr.UpdatedAt)
425		m.bus.Publish(ctx, domain.MergeRequestReady{MergeRequest: mr, At: mr.UpdatedAt, Visibility: repo.Visibility, CreatedAt: repo.CreatedAt})
426		return m.withHead(ctx, mr)
427	}
428	return domain.MergeRequest{}, fmt.Errorf("mark !%d of %q ready: %w", number, name, domain.ErrConflict)
429}
430
431// CountOpen implements ports.MergeRequestService.
432func (m *MergeRequests) CountOpen(ctx context.Context, p domain.Principal, name domain.RepoName) (int, error) {
433	if _, err := m.readable(ctx, p, name); err != nil {
434		return 0, err
435	}
436	n, err := m.store.CountOpen(ctx, name)
437	if err != nil {
438		return 0, fmt.Errorf("count open merge requests of %q: %w", name, err)
439	}
440	return n, nil
441}
442
443// Mergeability implements ports.MergeRequestService: the mergeability of an
444// open merge request for the current tips, queued when there is no up-to-date
445// result. It is the zero value for a request that is not open, or without a
446// mergeability service.
447func (m *MergeRequests) Mergeability(ctx context.Context, p domain.Principal, name domain.RepoName, number int64) (domain.Mergeability, error) {
448	_, mr, err := m.get(ctx, p, name, number)
449	if err != nil {
450		return domain.Mergeability{}, err
451	}
452	if m.mergeab == nil || !mr.IsOpen() {
453		return domain.Mergeability{}, nil
454	}
455	if mr, err = m.withHead(ctx, mr); err != nil {
456		return domain.Mergeability{}, err
457	}
458	tip, err := m.branchOrZero(ctx, name, mr.Target)
459	if err != nil {
460		return domain.Mergeability{}, err
461	}
462	return m.mergeab.Read(ctx, mr, tip), nil
463}
464
465func encodeMRToken(last domain.MergeRequest) string {
466	return base64.RawURLEncoding.EncodeToString([]byte(mrTokenPrefix + strconv.FormatInt(last.Number, 10)))
467}
468
469// decodeMRToken returns 0 for the empty token.
470func decodeMRToken(tok string) (int64, error) {
471	if tok == "" {
472		return 0, nil
473	}
474	raw, ok := decodeToken(tok, mrTokenPrefix)
475	if ok {
476		if n, err := strconv.ParseInt(raw, 10, 64); err == nil && n > 0 {
477			return n, nil
478		}
479	}
480	return 0, fmt.Errorf("%w: merge requests", domain.ErrInvalidPageToken)
481}
482
483// get reads a merge request of a repository the principal can read.
484func (m *MergeRequests) get(ctx context.Context, p domain.Principal, name domain.RepoName, number int64) (domain.Repo, domain.MergeRequest, error) {
485	repo, err := m.readable(ctx, p, name)
486	if err != nil {
487		return domain.Repo{}, domain.MergeRequest{}, err
488	}
489	mr, err := m.store.Get(ctx, name, number)
490	if err != nil {
491		return domain.Repo{}, domain.MergeRequest{}, err
492	}
493	return repo, mr, nil
494}
495
496// Get returns a merge request with its commits, its diff, its comments and the
497// read position. The diff compares the merge base of the target and the head
498// with the head ("target...head"), within domain.DefaultDiffLimits. With
499// opts.SinceLastRead it compares the head recorded by MarkRead with the
500// current head instead, which works after a force-push as long as the recorded
501// commit still exists; when none was recorded the diff is the default one, and
502// when the recorded commit is gone too, with LastReadLost set. A merged or
503// closed request keeps the head and the base it had.
504//
505// opts.Files lists every changed file and reads the hunks of a window of them
506// only; opts.Base and opts.Head make Get fail with domain.ErrConflict when the
507// diff is no longer the one the caller shows (before any diff is read);
508// opts.DiffOnly skips the commits. An invalid window gives domain.ErrInvalid.
509func (m *MergeRequests) Get(ctx context.Context, p domain.Principal, name domain.RepoName, number int64, opts ports.GetMergeRequestOptions) (ports.MergeRequestDetail, error) {
510	limits := domain.DefaultDiffLimits()
511	if w := opts.Files; w != nil {
512		if w.From < 0 || w.To < 0 || (w.To != 0 && w.To < w.From) {
513			return ports.MergeRequestDetail{}, fmt.Errorf("%w: file window [%d, %d)", domain.ErrInvalid, w.From, w.To)
514		}
515		limits.MaxFiles, limits.From, limits.To = 0, w.From, w.To
516	}
517	_, mr, err := m.get(ctx, p, name, number)
518	if err != nil {
519		return ports.MergeRequestDetail{}, err
520	}
521	if mr, err = m.withHead(ctx, mr); err != nil {
522		return ports.MergeRequestDetail{}, err
523	}
524	if !opts.Head.IsZero() && opts.Head != mr.HeadID {
525		return ports.MergeRequestDetail{}, fmt.Errorf("%w: the head of !%d moved to %s", domain.ErrConflict, number, mr.HeadID)
526	}
527	// checkBase fails when the caller shows another diff base than base.
528	checkBase := func(base domain.ObjectID) error {
529		if !opts.Base.IsZero() && opts.Base != base {
530			return fmt.Errorf("%w: the diff base of !%d is now %s", domain.ErrConflict, number, base)
531		}
532		return nil
533	}
534	d := ports.MergeRequestDetail{MergeRequest: mr}
535	if m.mergeab != nil && mr.IsOpen() {
536		tip, err := m.branchOrZero(ctx, name, mr.Target)
537		if err != nil {
538			return ports.MergeRequestDetail{}, err
539		}
540		d.Mergeability = m.mergeab.Read(ctx, mr, tip)
541	}
542	if d.Comments, err = m.store.ListComments(ctx, name, number); err != nil {
543		return ports.MergeRequestDetail{}, fmt.Errorf("list comments of !%d in %q: %w", number, name, err)
544	}
545	d.Verdicts = domain.CurrentVerdicts(d.Comments, mr.HeadID)
546	if d.LastReadID, err = m.store.GetRead(ctx, name, number); err != nil {
547		return ports.MergeRequestDetail{}, err
548	}
549	d.HeadUnread = !mr.HeadID.IsZero() && mr.HeadID != d.LastReadID
550
551	exclude, base, err := m.rangeOf(ctx, mr)
552	if err != nil {
553		return ports.MergeRequestDetail{}, err
554	}
555	head := mr.HeadID
556	if head.IsZero() {
557		return d, checkBase(domain.ObjectID{}) // the source branch is gone: no commits, no diff
558	}
559	if !mr.IsOpen() {
560		// After a squash the reviewed commits are only reachable from the
561		// source branch; once it is deleted, gc may prune them.
562		switch ok, err := m.git.HasCommit(ctx, name, head); {
563		case err != nil:
564			return ports.MergeRequestDetail{}, err
565		case !ok:
566			// The reviewed commits are gone: no commits, no diff.
567			if err := checkBase(domain.ObjectID{}); err != nil {
568				return ports.MergeRequestDetail{}, err
569			}
570			return d, nil
571		}
572	}
573	if !opts.DiffOnly {
574		if d.Commits, d.CommitsTruncated, err = m.git.ListRange(ctx, name, exclude, head, MaxMergeRequestCommits); err != nil {
575			return ports.MergeRequestDetail{}, err
576		}
577		verifyCommits(ctx, m.verifier, name, d.Commits)
578		if !d.LastReadID.IsZero() {
579			for i, c := range d.Commits {
580				if c.ID == d.LastReadID {
581					d.NewCommits = i
582					break
583				}
584			}
585		}
586	}
587	if opts.SinceLastRead && !d.LastReadID.IsZero() {
588		switch ok, err := m.git.HasCommit(ctx, name, d.LastReadID); {
589		case err != nil:
590			return ports.MergeRequestDetail{}, err
591		case ok:
592			base = d.LastReadID
593		default:
594			d.LastReadLost = true
595		}
596	}
597	if err := checkBase(base); err != nil {
598		return ports.MergeRequestDetail{}, err
599	}
600	if base.IsZero() {
601		return d, nil
602	}
603	d.DiffBaseID = base
604	if d.Stats, d.Diff, err = m.git.DiffCommits(ctx, name, base, head, limits); err != nil {
605		return ports.MergeRequestDetail{}, err
606	}
607	return d, nil
608}
609
610// rangeOf returns what the review of a request compares: the commit whose
611// history the request's commits exclude, and the base of its diff. For an open
612// request they are the tip of the target and the merge base of the target and
613// the head; both are zero when the target is gone or shares no history with
614// the head. A merged or closed request keeps the base it stored for both.
615func (m *MergeRequests) rangeOf(ctx context.Context, mr domain.MergeRequest) (exclude, base domain.ObjectID, err error) {
616	if !mr.IsOpen() {
617		return mr.BaseID, mr.BaseID, nil
618	}
619	if mr.HeadID.IsZero() {
620		return domain.ObjectID{}, domain.ObjectID{}, nil
621	}
622	tip, err := m.branchOrZero(ctx, mr.Repo, mr.Target)
623	if err != nil || tip.IsZero() {
624		return domain.ObjectID{}, domain.ObjectID{}, err
625	}
626	base, err = m.git.MergeBase(ctx, mr.Repo, tip, mr.HeadID)
627	if errors.Is(err, domain.ErrNotFound) {
628		return tip, domain.ObjectID{}, nil
629	}
630	return tip, base, err
631}
632
633// AddComment adds a comment and publishes CommentAdded. The principal needs
634// mr:write. The text must follow the rules of ADR 0032 and not be blank unless carrying a verdict; a
635// comment on a line must name a line of the current diff of the request (see
636// domain.Diff.HasLine), else the call fails with domain.ErrInvalid. A request
637// that is not open gives domain.ErrPreconditionFailed, and one that already
638// holds MaxCommentsPerMergeRequest comments domain.ErrResourceExhausted.
639func (m *MergeRequests) AddComment(ctx context.Context, p domain.Principal, name domain.RepoName, number int64, params ports.AddCommentParams) (domain.Comment, error) {
640	repo, err := m.writable(ctx, p, name, domain.ScopeMRWrite)
641	if err != nil {
642		return domain.Comment{}, err
643	}
644	mr, err := m.store.Get(ctx, name, number)
645	if err != nil {
646		return domain.Comment{}, err
647	}
648	var v domain.Violations
649	text, err := domain.ParsePlainText(params.Text)
650	switch {
651	case err != nil:
652		v.AddErr("text", err)
653	case text.IsBlank() && params.Verdict == domain.VerdictNone:
654		v.Add("text", "is required")
655	}
656	general := params.Path == ""
657	switch {
658	case general && (params.Line != 0 || params.Side != domain.SideNone || params.StartLine != 0):
659		v.Add("path", "is required with line and side")
660	case !general && params.Line < 1:
661		v.Add("line", "must be 1 or more with a path")
662	case !general && params.Side != domain.SideOld && params.Side != domain.SideNew:
663		v.Add("side", "is required with a path")
664	}
665	if params.StartLine != 0 && (params.StartLine < 1 || params.StartLine >= params.Line) {
666		v.Add("start_line", "must be 1 or more and less than line")
667	}
668	if params.Verdict > domain.VerdictChangesRequested {
669		v.Add("verdict", "is unknown")
670	}
671	if params.ReplyTo != 0 {
672		if params.Path != "" || params.Line != 0 || params.StartLine != 0 || params.Side != domain.SideNone || params.Verdict != domain.VerdictNone {
673			v.Add("reply_to", "a reply cannot specify an anchor or verdict")
674		}
675	}
676	if err := v.Err(); err != nil {
677		return domain.Comment{}, err
678	}
679	if params.ReplyTo != 0 {
680		root, err := m.replyRoot(ctx, name, number, params.ReplyTo)
681		if err != nil {
682			return domain.Comment{}, err
683		}
684		params.Path, params.Line, params.StartLine, params.Side = root.Path, root.Line, root.StartLine, root.Side
685	}
686	if params.Verdict != domain.VerdictNone {
687		if err := scopeAccess(p, repo, domain.ScopeMRReview); err != nil {
688			return domain.Comment{}, err
689		}
690	}
691	if !mr.IsOpen() {
692		return domain.Comment{}, fmt.Errorf("%w: !%d is %s", domain.ErrPreconditionFailed, number, mr.State)
693	}
694
695	if mr, err = m.withHead(ctx, mr); err != nil {
696		return domain.Comment{}, err
697	}
698	if !general && params.ReplyTo == 0 {
699		if err := m.checkLine(ctx, mr, params); err != nil {
700			return domain.Comment{}, err
701		}
702	}
703
704	var c domain.Comment
705	for range maxWriteRetries {
706		if mr.CommentSeq >= MaxCommentsPerMergeRequest {
707			return domain.Comment{}, fmt.Errorf("%w: !%d already has %d comments", domain.ErrResourceExhausted, number, MaxCommentsPerMergeRequest)
708		}
709		c = domain.Comment{
710			ID: mr.CommentSeq + 1, Author: domain.AuthorName(p), Path: params.Path, Line: params.Line, Side: params.Side,
711			ReplyTo: params.ReplyTo, StartLine: params.StartLine, Verdict: params.Verdict, Resolved: params.Verdict == domain.VerdictApprove,
712			CommitID: mr.HeadID, Text: text, CreatedAt: m.clock.Now().UTC(),
713		}
714		mr.CommentSeq, mr.UpdatedAt = c.ID, c.CreatedAt
715		err = m.store.SaveComment(ctx, mr, c)
716		if !errors.Is(err, domain.ErrConflict) {
717			break
718		}
719		// Another write got in between: read the request again.
720		fresh, gerr := m.store.Get(ctx, name, number)
721		if gerr != nil {
722			return domain.Comment{}, gerr
723		}
724		if !fresh.IsOpen() {
725			return domain.Comment{}, fmt.Errorf("%w: !%d is %s", domain.ErrPreconditionFailed, number, fresh.State)
726		}
727		if params.ReplyTo != 0 {
728			// The root may have been deleted by the write that got in between.
729			if _, rerr := m.replyRoot(ctx, name, number, params.ReplyTo); rerr != nil {
730				return domain.Comment{}, rerr
731			}
732		}
733		fresh.HeadID = mr.HeadID
734		mr = fresh
735	}
736	if err != nil {
737		return domain.Comment{}, fmt.Errorf("save comment on !%d of %q: %w", number, name, err)
738	}
739	log := zerowrap.FromCtx(ctx)
740	log.Info().Str("repo", name.String()).Int64("number", number).Int64("comment", c.ID).
741		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")
742	recordActivity(ctx, m.meta, name, c.CreatedAt)
743	m.bus.Publish(ctx, domain.CommentAdded{
744		Repo: name, Number: number, Comment: c, At: c.CreatedAt, Visibility: repo.Visibility, CreatedAt: repo.CreatedAt,
745	})
746	return c, nil
747}
748
749// checkLine verifies that a comment designates a line of the current diff of
750// the request.
751func (m *MergeRequests) checkLine(ctx context.Context, mr domain.MergeRequest, params ports.AddCommentParams) error {
752	var v domain.Violations
753	_, base, err := m.rangeOf(ctx, mr)
754	if err != nil {
755		return err
756	}
757	if mr.HeadID.IsZero() || base.IsZero() {
758		v.Add("path", "the merge request has no diff to comment on")
759		return v.Err()
760	}
761	// A comment may be on a file past the 300th that the web view lists, so
762	// the file is looked up among all the files (MaxFiles 0). Reading every
763	// file's hunks within the default total limits would reject a comment on a
764	// file the earlier ones left no budget for. So a first read lists the files
765	// with no hunks (From past the end: cheap, git is stopped at once), and a
766	// second reads the hunks of the one file within the default per-file limit
767	// and total limits, as the web view does for a window holding it.
768	list := domain.DefaultDiffLimits()
769	list.MaxFiles, list.From = 0, math.MaxInt
770	_, diff, err := m.git.DiffCommits(ctx, mr.Repo, base, mr.HeadID, list)
771	if err != nil {
772		return err
773	}
774	idx := slices.IndexFunc(diff.Files, func(f domain.FileDiff) bool { return diffFileName(f) == params.Path })
775	if idx >= 0 {
776		one := domain.DefaultDiffLimits()
777		one.MaxFiles, one.From, one.To = 0, idx, idx+1
778		if _, diff, err = m.git.DiffCommits(ctx, mr.Repo, base, mr.HeadID, one); err != nil {
779			return err
780		}
781	}
782	if idx < 0 || !diff.HasLine(params.Path, params.Side, params.Line) {
783		v.Add("path", fmt.Sprintf("%s:%d on the %s side is not a line of the diff", params.Path, params.Line, params.Side))
784	}
785	if params.StartLine != 0 && !diff.HasLine(params.Path, params.Side, params.StartLine) {
786		v.Add("start_line", "is not a line of the diff")
787	}
788	return v.Err()
789}
790
791// diffFileName is the path a comment designates for f, as Diff.HasLine reads it.
792func diffFileName(f domain.FileDiff) string {
793	if f.Status == domain.FileDeleted {
794		return f.OldPath
795	}
796	return f.NewPath
797}
798
799// ResolveComment marks a comment resolved or unresolved. The principal needs
800// mr:write. An unknown comment gives domain.ErrNotFound and a request that is
801// not open domain.ErrPreconditionFailed. Setting the state the comment already
802// has succeeds and writes nothing.
803func (m *MergeRequests) ResolveComment(ctx context.Context, p domain.Principal, name domain.RepoName, number, commentID int64, resolved bool) (domain.Comment, error) {
804	repo, err := m.writable(ctx, p, name, domain.ScopeMRWrite)
805	if err != nil {
806		return domain.Comment{}, err
807	}
808	for range maxWriteRetries {
809		mr, err := m.store.Get(ctx, name, number)
810		if err != nil {
811			return domain.Comment{}, err
812		}
813		c, err := m.store.GetComment(ctx, name, number, commentID)
814		if err != nil {
815			return domain.Comment{}, err
816		}
817		if !mr.IsOpen() {
818			return domain.Comment{}, fmt.Errorf("%w: !%d is %s", domain.ErrPreconditionFailed, number, mr.State)
819		}
820		if c.IsReply() {
821			var v domain.Violations
822			v.Add("comment_id", fmt.Sprintf("resolve the thread on its root ^%d", c.ReplyTo))
823			return domain.Comment{}, v.Err()
824		}
825		if c.Resolved == resolved {
826			return c, nil
827		}
828		c.Resolved = resolved
829		mr.UpdatedAt = m.clock.Now().UTC()
830		err = m.store.SaveComment(ctx, mr, c)
831		if errors.Is(err, domain.ErrConflict) {
832			continue
833		}
834		if err != nil {
835			return domain.Comment{}, fmt.Errorf("resolve comment %d of !%d in %q: %w", commentID, number, name, err)
836		}
837		m.bus.Publish(ctx, domain.CommentResolved{Repo: name, Number: number, Comment: c, At: mr.UpdatedAt, Visibility: repo.Visibility, CreatedAt: repo.CreatedAt})
838		return c, nil
839	}
840	return domain.Comment{}, fmt.Errorf("resolve comment %d of !%d in %q: %w", commentID, number, name, domain.ErrConflict)
841}
842
843// Close closes an open merge request without merging it and publishes
844// MergeRequestClosed. The principal needs mr:write. A request that is not open
845// gives domain.ErrPreconditionFailed. The request keeps the head it had and
846// its merge base, so that its diff stays readable.
847func (m *MergeRequests) Close(ctx context.Context, p domain.Principal, name domain.RepoName, number int64) (domain.MergeRequest, error) {
848	repo, err := m.writable(ctx, p, name, domain.ScopeMRWrite)
849	if err != nil {
850		return domain.MergeRequest{}, err
851	}
852	unlock, err := m.lockRepo(ctx, name) // a merge and a close of one request exclude each other
853	if err != nil {
854		return domain.MergeRequest{}, err
855	}
856	defer unlock()
857	for range maxWriteRetries {
858		mr, err := m.store.Get(ctx, name, number)
859		if err != nil {
860			return domain.MergeRequest{}, err
861		}
862		if !mr.IsOpen() {
863			return domain.MergeRequest{}, fmt.Errorf("%w: !%d is %s", domain.ErrPreconditionFailed, number, mr.State)
864		}
865		if mr, err = m.withHead(ctx, mr); err != nil {
866			return domain.MergeRequest{}, err
867		}
868		_, base, err := m.rangeOf(ctx, mr)
869		if err != nil {
870			return domain.MergeRequest{}, err
871		}
872		mr.State, mr.BaseID, mr.UpdatedAt = domain.MRStateClosed, base, m.clock.Now().UTC()
873		err = m.store.Update(ctx, mr)
874		if errors.Is(err, domain.ErrConflict) {
875			continue
876		}
877		if err != nil {
878			return domain.MergeRequest{}, fmt.Errorf("close !%d of %q: %w", number, name, err)
879		}
880		log := zerowrap.FromCtx(ctx)
881		log.Info().Str("repo", name.String()).Int64("number", number).
882			Str("principal", p.Label()).Str("token_id", p.TokenID()).Msg("merge request closed")
883		recordActivity(ctx, m.meta, repo.Name, mr.UpdatedAt)
884		m.bus.Publish(ctx, domain.MergeRequestClosed{MergeRequest: mr, At: mr.UpdatedAt, Visibility: repo.Visibility, CreatedAt: repo.CreatedAt})
885		if m.pulls != nil {
886			m.pulls.OnPullRequest(ctx, name, ports.PullRequestEvent{Number: number, Action: domain.PullClosed, Head: mr.HeadID, Base: mr.BaseID}, p)
887		}
888		return mr, nil
889	}
890	return domain.MergeRequest{}, fmt.Errorf("close !%d of %q: %w", number, name, domain.ErrConflict)
891}
892
893// MarkRead records the head the reviewer has read, for the since-last-read diff
894// of Get. The principal needs mr:write. A zero head means the current head of
895// the source branch (the stored one for a merged or closed request); one that
896// is not a commit of the repository gives domain.ErrInvalid. It returns the
897// head recorded.
898func (m *MergeRequests) MarkRead(ctx context.Context, p domain.Principal, name domain.RepoName, number int64, head domain.ObjectID) (domain.ObjectID, error) {
899	if _, err := m.writable(ctx, p, name, domain.ScopeMRWrite); err != nil {
900		return domain.ObjectID{}, err
901	}
902	mr, err := m.store.Get(ctx, name, number)
903	if err != nil {
904		return domain.ObjectID{}, err
905	}
906	if head.IsZero() {
907		if mr, err = m.withHead(ctx, mr); err != nil {
908			return domain.ObjectID{}, err
909		}
910		if head = mr.HeadID; head.IsZero() {
911			return domain.ObjectID{}, fmt.Errorf("%w: the source branch %q no longer exists, give a head", domain.ErrPreconditionFailed, mr.Source)
912		}
913	} else {
914		var v domain.Violations
915		switch ok, err := m.git.HasCommit(ctx, name, head); {
916		case err != nil:
917			return domain.ObjectID{}, err
918		case !ok:
919			v.Add("head_id", fmt.Sprintf("%s is not a commit of the repository", head))
920			return domain.ObjectID{}, v.Err()
921		}
922	}
923	if err := m.store.SetRead(ctx, name, number, head); err != nil {
924		return domain.ObjectID{}, err
925	}
926	return head, nil
927}
928
929// Merge merges an open merge request, publishes MergeRequestMerged then a
930// PushEvent for the target branch, and returns the merged request. The
931// principal needs mr:merge. Merges of one repository run one at a time.
932//
933// It fails with domain.ErrInvalid for a zero head, and with
934// domain.ErrPreconditionFailed when the request is not open, the mode is not
935// allowed by the settings of the repository, the source branch no longer
936// points to the head ("branch moved, read again") or is gone, the target is
937// gone, the mode's own condition does not hold (see below), or the branch
938// brings nothing. Checks come with CI (CI-1): there are none yet, so the
939// setting that lets failing checks block the merge has nothing to act on.
940//
941// The conditions are always checked with Git, under the lock, never from the
942// stored mergeability. A fast-forward needs the target to be an ancestor of
943// the head (the author rebases and pushes again) and moves the target to the
944// head, with the old value as a precondition. A squash and a merge commit need
945// the head to merge cleanly into the target (a behind branch is fine). A squash
946// writes one commit with the merged tree, the target as parent and the author
947// and message of domain.NewSquashCommit; a merge commit has two parents (the
948// target, then the head) and the message of domain.NewMergeCommit. Both are
949// signed by the instance key and move the target the same way.
950//
951// With DeleteSource the merge is also refused, before anything changes, when
952// the source is the default branch or the source or target of another open
953// request.
954//
955// Only the merge itself runs before Merge returns, under the lock. Afterwards,
956// off the request path and without the lock: the deletion of the source branch
957// (if it still points to the head; a failure is logged and leaves the branch),
958// MergeRequestMerged then a PushEvent (which carries the deletion too), and
959// the CI and mergeability hooks. Wait waits for them. SourceDeleted therefore
960// only says that the deletion was requested.
961func (m *MergeRequests) Merge(ctx context.Context, p domain.Principal, name domain.RepoName, number int64, params ports.MergeParams) (ports.MergeResult, error) {
962	mr, err := m.merge(ctx, p, name, number, params)
963	return ports.MergeResult{MergeRequest: mr, SourceDeleted: err == nil && params.DeleteSource}, err
964}
965
966// maxConflictPathsShown is how many conflicting paths a refusal lists.
967const maxConflictPathsShown = 5
968
969// checkMode is the authoritative per-mode check of a merge, done with Git. It
970// returns the tree a squash or merge commit gets (zero for a fast-forward).
971func (m *MergeRequests) checkMode(ctx context.Context, mr domain.MergeRequest, mode domain.MergeMode, tip, head domain.ObjectID) (domain.ObjectID, error) {
972	if mode == domain.MergeModeFastForward {
973		ok, err := m.git.IsAncestor(ctx, mr.Repo, tip, head)
974		if err != nil {
975			return domain.ObjectID{}, err
976		}
977		if !ok {
978			return domain.ObjectID{}, fmt.Errorf("%w: the target has moved: rebase and push again, or merge with squash or a merge commit", domain.ErrPreconditionFailed)
979		}
980		return domain.ObjectID{}, nil
981	}
982	res, err := m.git.MergeTree(ctx, mr.Repo, tip, head)
983	if err != nil {
984		return domain.ObjectID{}, err
985	}
986	res = res.Bounded()
987	if !res.Clean {
988		what := "no common history"
989		if len(res.ConflictPaths) > 0 {
990			shown := res.ConflictPaths
991			if len(shown) > maxConflictPathsShown {
992				shown = shown[:maxConflictPathsShown]
993			}
994			what = strings.Join(shown, ", ")
995			if len(shown) < len(res.ConflictPaths) || res.Truncated {
996				what += ", ..."
997			}
998		}
999		return domain.ObjectID{}, fmt.Errorf("%w: conflicts with %s: %s: rebase and push again", domain.ErrPreconditionFailed, mr.Target, what)
1000	}
1001	return res.Tree, nil
1002}
1003
1004func (m *MergeRequests) merge(ctx context.Context, p domain.Principal, name domain.RepoName, number int64, params ports.MergeParams) (domain.MergeRequest, error) {
1005	if _, err := m.writable(ctx, p, name, domain.ScopeMRMerge); err != nil {
1006		return domain.MergeRequest{}, err
1007	}
1008	mode := params.Mode
1009	if mode == "" {
1010		mode = domain.MergeModeFastForward
1011	}
1012	var v domain.Violations
1013	if _, err := domain.ParseMergeMode(mode.String()); err != nil {
1014		v.Add("mode", "is not a merge mode")
1015	}
1016	if params.HeadID.IsZero() {
1017		v.Add("head_id", "is required")
1018	}
1019	if err := v.Err(); err != nil {
1020		return domain.MergeRequest{}, err
1021	}
1022
1023	unlock, err := m.lockRepo(ctx, name)
1024	if err != nil {
1025		return domain.MergeRequest{}, err
1026	}
1027	var once sync.Once
1028	release := func() { once.Do(unlock) }
1029	defer release()
1030
1031	mr, err := m.store.Get(ctx, name, number)
1032	if err != nil {
1033		return domain.MergeRequest{}, err
1034	}
1035	// A merge moves the target and may delete the source: a token limited to
1036	// branch prefixes may do so only within them.
1037	if !p.AllowsRef("refs/heads/" + mr.Target) {
1038		return domain.MergeRequest{}, fmt.Errorf("%w: this token may not write %s", domain.ErrForbidden, mr.Target)
1039	}
1040	if params.DeleteSource && !p.AllowsRef("refs/heads/"+mr.Source) {
1041		return domain.MergeRequest{}, fmt.Errorf("%w: this token may not write %s", domain.ErrForbidden, mr.Source)
1042	}
1043	if !mr.IsOpen() {
1044		return domain.MergeRequest{}, fmt.Errorf("%w: !%d is %s", domain.ErrPreconditionFailed, number, mr.State)
1045	}
1046	if mr.IsDraft() {
1047		return domain.MergeRequest{}, fmt.Errorf("%w: !%d is a draft: mark it ready for review first", domain.ErrPreconditionFailed, number)
1048	}
1049	// The settings are read again under the lock: a change applies at once.
1050	repo, err := m.meta.Get(ctx, name)
1051	if err != nil {
1052		if errors.Is(err, domain.ErrNotFound) {
1053			return domain.MergeRequest{}, err // deleted meanwhile
1054		}
1055		return domain.MergeRequest{}, fmt.Errorf("get repository %q: %w", name, err)
1056	}
1057	settings := repo.EffectiveSettings()
1058	if !settings.Allows(mode) {
1059		return domain.MergeRequest{}, fmt.Errorf("%w: the %s merge mode is not allowed in %s", domain.ErrPreconditionFailed, mode, name)
1060	}
1061
1062	head, err := m.branchOrZero(ctx, name, mr.Source)
1063	switch {
1064	case err != nil:
1065		return domain.MergeRequest{}, err
1066	case head.IsZero():
1067		return domain.MergeRequest{}, fmt.Errorf("%w: the source branch %q no longer exists", domain.ErrPreconditionFailed, mr.Source)
1068	case head != params.HeadID:
1069		return domain.MergeRequest{}, fmt.Errorf("%w: branch moved, read again: %q is at %s, not %s", domain.ErrPreconditionFailed, mr.Source, head, params.HeadID)
1070	}
1071	tip, err := m.branchOrZero(ctx, name, mr.Target)
1072	switch {
1073	case err != nil:
1074		return domain.MergeRequest{}, err
1075	case tip.IsZero():
1076		return domain.MergeRequest{}, fmt.Errorf("%w: the target branch %q no longer exists", domain.ErrPreconditionFailed, mr.Target)
1077	case tip == head:
1078		return domain.MergeRequest{}, fmt.Errorf("%w: nothing to merge, %q already is at %s", domain.ErrPreconditionFailed, mr.Target, head)
1079	}
1080	// A head behind the target (or at it) has nothing to merge, in any mode.
1081	if behind, err := m.git.IsAncestor(ctx, name, head, tip); err != nil {
1082		return domain.MergeRequest{}, err
1083	} else if behind {
1084		return domain.MergeRequest{}, fmt.Errorf("%w: nothing to merge, %q already contains %s", domain.ErrPreconditionFailed, mr.Target, head)
1085	}
1086	tree, err := m.checkMode(ctx, mr, mode, tip, head)
1087	if err != nil {
1088		return domain.MergeRequest{}, err
1089	}
1090	if settings.FailingChecksBlock {
1091		if err := m.checksAllow(ctx, name, head); err != nil {
1092			return domain.MergeRequest{}, err
1093		}
1094	}
1095	if params.DeleteSource {
1096		if err := m.checkDeletable(ctx, name, mr); err != nil {
1097			return domain.MergeRequest{}, err
1098		}
1099	}
1100
1101	merged, err := m.moveTarget(ctx, mr, mode, tip, head, tree, p)
1102	if err != nil {
1103		return domain.MergeRequest{}, err
1104	}
1105	m.recordPush(ctx, name) // the target moved, whatever happens next
1106	mr, err = m.markMerged(ctx, name, number, mode, tip, head, merged)
1107	if err != nil {
1108		return domain.MergeRequest{}, err
1109	}
1110	log := zerowrap.FromCtx(ctx)
1111	log.Info().Str("repo", name.String()).Int64("number", number).Str("mode", mode.String()).
1112		Str("target", mr.Target).Str("commit", merged.String()).
1113		Str("principal", p.Label()).Str("token_id", p.TokenID()).Msg("merge request merged")
1114
1115	// The merge is done and recorded. The rest runs without the lock and after
1116	// the caller got its answer.
1117	release()
1118	bg := context.WithoutCancel(ctx)
1119	m.after.Add(1)
1120	go func() {
1121		defer m.after.Done()
1122		defer func() {
1123			if r := recover(); r != nil {
1124				log := zerowrap.FromCtx(bg)
1125				log.Error().Str("repo", name.String()).Int64("number", number).
1126					Str("panic", fmt.Sprint(r)).Bytes("stack", debug.Stack()).Msg("post-merge side effects panicked")
1127			}
1128		}()
1129		if m.afterGate != nil {
1130			m.afterGate()
1131		}
1132		m.afterMerge(bg, p, repo, mr, head, tip, merged, params.DeleteSource)
1133	}()
1134	return mr, nil
1135}
1136
1137// afterMerge is what follows a merge off the request path: errors are logged,
1138// never returned. mr is the merged request, tip the old target and merged the
1139// new one.
1140func (m *MergeRequests) afterMerge(ctx context.Context, p domain.Principal, repo domain.Repo, mr domain.MergeRequest, head, tip, merged domain.ObjectID, deleteSource bool) {
1141	name := repo.Name
1142	updates := []domain.RefUpdate{{Old: tip.String(), New: merged.String(), Ref: "refs/heads/" + mr.Target}}
1143	if deleteSource && m.deleteSource(ctx, p, name, mr, head) {
1144		updates = append(updates, domain.RefUpdate{Old: head.String(), New: domain.ZeroOID, Ref: "refs/heads/" + mr.Source})
1145	}
1146	at := mr.UpdatedAt
1147	recordActivity(ctx, m.meta, repo.Name, at)
1148	m.bus.Publish(ctx, domain.MergeRequestMerged{MergeRequest: mr, At: at, Visibility: repo.Visibility, CreatedAt: repo.CreatedAt})
1149	m.bus.Publish(ctx, domain.PushEvent{
1150		Repo: name, At: at, Visibility: repo.Visibility, CreatedAt: repo.CreatedAt, Updates: updates,
1151	})
1152	if m.pulls != nil {
1153		m.pulls.OnPullRequest(ctx, name, ports.PullRequestEvent{Number: mr.Number, Action: domain.PullClosed, Head: mr.HeadID, Base: mr.BaseID, Merged: true}, p)
1154	}
1155	if m.ci != nil {
1156		// GitHub runs the "push" workflows of a merge, with the owner as actor;
1157		// the run is trusted with what the merging principal may read.
1158		m.ci.OnMerge(ctx, name, updates, p)
1159	}
1160	if m.mergeab != nil {
1161		m.mergeab.OnBranchesMoved(ctx, name, updates) // the other requests of the moved target
1162	}
1163}
1164
1165// deleteSource deletes the source branch of a merged request if it is still
1166// head and still unused, and reports whether it did. The eligibility is checked
1167// again and the branch deleted in one critical section of the merge lock: a
1168// request opened on the branch since the merge, or a push to it, keeps it. The
1169// record of who pushed the branch goes only after a deletion, and only if it
1170// still names head.
1171func (m *MergeRequests) deleteSource(ctx context.Context, p domain.Principal, name domain.RepoName, mr domain.MergeRequest, head domain.ObjectID) bool {
1172	log := zerowrap.FromCtx(ctx).With().Str("repo", name.String()).Int64("number", mr.Number).Str("branch", mr.Source).Logger()
1173	unlock, err := m.lockRepo(ctx, name)
1174	if err != nil {
1175		log.Warn().Err(err).Msg("source branch kept after the merge")
1176		return false
1177	}
1178	defer unlock()
1179	if err := m.checkDeletable(ctx, name, mr); err != nil {
1180		log.Warn().Err(err).Msg("source branch kept after the merge")
1181		return false
1182	}
1183	if err := m.git.DeleteBranch(ctx, name, mr.Source, head); err != nil {
1184		log.Warn().Err(err).Msg("source branch kept after the merge")
1185		return false
1186	}
1187	if m.tips != nil {
1188		if err := m.tips.DeleteRefTipIf(ctx, name, "refs/heads/"+mr.Source, head.String()); err != nil && !errors.Is(err, domain.ErrNotFound) {
1189			log.Warn().Err(err).Msg("the record of the source branch was kept")
1190		}
1191	}
1192	log.Info().Str("principal", p.Label()).Str("token_id", p.TokenID()).Msg("source branch deleted after the merge")
1193	return true
1194}
1195
1196// WhileOpen implements ports.PullGate: fn runs under the merge lock, so a
1197// close or a merge of the request cannot complete in the middle of it, and not
1198// at all when the request is no longer open.
1199func (m *MergeRequests) WhileOpen(ctx context.Context, name domain.RepoName, number int64, fn func() error) error {
1200	unlock, err := m.lockRepo(ctx, name)
1201	if err != nil {
1202		return err
1203	}
1204	defer unlock()
1205	mr, err := m.store.Get(ctx, name, number)
1206	if err != nil {
1207		return err
1208	}
1209	if !mr.IsOpen() {
1210		return fmt.Errorf("%w: !%d is %s", domain.ErrPreconditionFailed, number, mr.State)
1211	}
1212	return fn()
1213}
1214
1215// checksAllow is the merge rule of FailingChecksBlock: every check of the
1216// head must have ended as success, skipped or neutral. A check still queued or
1217// running blocks too (the merge could land code that then fails), and a head
1218// without any check merges.
1219func (m *MergeRequests) checksAllow(ctx context.Context, name domain.RepoName, head domain.ObjectID) error {
1220	if m.checks == nil {
1221		return nil
1222	}
1223	checks, err := m.checks.CommitChecks(ctx, name, head.String())
1224	if errors.Is(err, domain.ErrResourceExhausted) {
1225		return fmt.Errorf("%w: too many checks to tell whether they passed: %v", domain.ErrPreconditionFailed, err)
1226	}
1227	if err != nil {
1228		return fmt.Errorf("read the checks of %s: %w", head, err)
1229	}
1230	var failing, pending []string
1231	for _, c := range checks {
1232		switch {
1233		case c.Status != domain.CICompleted:
1234			pending = append(pending, c.Name)
1235		case !c.Conclusion.PassesMerge():
1236			failing = append(failing, c.Name)
1237		}
1238	}
1239	switch {
1240	case len(failing) > 0:
1241		return fmt.Errorf("%w: failing checks block the merge: %s (turn off failing_checks_block to merge anyway)", domain.ErrPreconditionFailed, strings.Join(failing, ", "))
1242	case len(pending) > 0:
1243		return fmt.Errorf("%w: checks have not finished: %s", domain.ErrPreconditionFailed, strings.Join(pending, ", "))
1244	}
1245	return nil
1246}
1247
1248// checkDeletable refuses to delete the source branch of mr when it is the
1249// default branch or the source or target of another open request. It runs
1250// under the merge lock, which Create also holds while it checks its branches
1251// and stores the request.
1252func (m *MergeRequests) checkDeletable(ctx context.Context, name domain.RepoName, mr domain.MergeRequest) error {
1253	def, _, err := m.repos.DefaultBranch(ctx, name)
1254	if err != nil {
1255		return fmt.Errorf("default branch of %q: %w", name, err)
1256	}
1257	if mr.Source == def {
1258		return fmt.Errorf("%w: %q is the default branch of %s: it cannot be deleted", domain.ErrPreconditionFailed, mr.Source, name)
1259	}
1260	all, err := m.store.List(ctx, name)
1261	if err != nil {
1262		return fmt.Errorf("list merge requests of %q: %w", name, err)
1263	}
1264	for _, o := range all {
1265		if o.Number != mr.Number && o.IsOpen() && (o.Source == mr.Source || o.Target == mr.Source) {
1266			return fmt.Errorf("%w: !%d still uses %q: it cannot be deleted", domain.ErrPreconditionFailed, o.Number, mr.Source)
1267		}
1268	}
1269	return nil
1270}
1271
1272// recordPush does for a merge what Pushes.Record does for a push, as the merge
1273// moved a branch: it sets pushed_at and queues the maintenance of the
1274// repository. The target already moved, so a failure is logged, not returned,
1275// and the caller giving up does not stop it.
1276func (m *MergeRequests) recordPush(ctx context.Context, name domain.RepoName) {
1277	ctx = context.WithoutCancel(ctx)
1278	if _, err := touchPushedAt(ctx, m.meta, name, m.clock.Now().UTC()); err != nil {
1279		log := zerowrap.FromCtx(ctx)
1280		log.Error().Err(err).Str("repo", name.String()).Msg("record pushed_at after a merge")
1281	}
1282	m.maint.Schedule(ctx, name)
1283}
1284
1285// moveTarget moves the target branch from tip to the head (fast-forward) or to
1286// a new signed squash or merge commit with the given tree, and returns the new tip.
1287func (m *MergeRequests) moveTarget(ctx context.Context, mr domain.MergeRequest, mode domain.MergeMode, tip, head, tree domain.ObjectID, p domain.Principal) (domain.ObjectID, error) {
1288	newTip := head
1289	switch mode {
1290	case domain.MergeModeMerge:
1291		commit := domain.NewMergeCommit(mr, tree, tip, head, m.committer, m.clock.Now())
1292		armored, err := m.signer.Sign(commit.Payload())
1293		if err != nil {
1294			return domain.ObjectID{}, fmt.Errorf("sign the merge commit of !%d in %q: %w", mr.Number, mr.Repo, err)
1295		}
1296		if newTip, err = m.git.WriteCommit(ctx, mr.Repo, commit.Signed(armored)); err != nil {
1297			return domain.ObjectID{}, err
1298		}
1299	case domain.MergeModeSquash:
1300		commits, more, err := m.git.ListRange(ctx, mr.Repo, tip, head, domain.MaxSquashCommits)
1301		if err != nil {
1302			return domain.ObjectID{}, err
1303		}
1304		if more {
1305			return domain.ObjectID{}, fmt.Errorf("%w: the branch has more than %d commits to squash", domain.ErrPreconditionFailed, domain.MaxSquashCommits)
1306		}
1307		commit := domain.NewSquashCommit(mr, tree, tip, commits, m.committer, m.clock.Now())
1308		armored, err := m.signer.Sign(commit.Payload())
1309		if err != nil {
1310			return domain.ObjectID{}, fmt.Errorf("sign the squash commit of !%d in %q: %w", mr.Number, mr.Repo, err)
1311		}
1312		if newTip, err = m.git.WriteCommit(ctx, mr.Repo, commit.Signed(armored)); err != nil {
1313			return domain.ObjectID{}, err
1314		}
1315	}
1316	// The target is the merger's from the moment it moves: recorded before it
1317	// does, under the merge lock (domain.CIRefTip). The run shows the owner, as a
1318	// merge's push does on GitHub.
1319	if err := recordRefTips(ctx, m.tips, mr.Repo, []domain.RefUpdate{{Old: tip.String(), New: newTip.String(), Ref: "refs/heads/" + mr.Target}},
1320		domain.AuthorName(domain.Owner()), domain.PusherOf(p), domain.TrustedActor(p)); err != nil {
1321		return domain.ObjectID{}, err
1322	}
1323	err := m.git.UpdateBranch(ctx, mr.Repo, mr.Target, tip, newTip)
1324	if errors.Is(err, domain.ErrConflict) {
1325		return domain.ObjectID{}, fmt.Errorf("%w: the target branch %q moved during the merge, try again", domain.ErrPreconditionFailed, mr.Target)
1326	}
1327	if err != nil {
1328		return domain.ObjectID{}, err
1329	}
1330	return newTip, nil
1331}
1332
1333// markMerged records the merge. The target already moved, so a write that
1334// loses a race (a comment added meanwhile) is repeated on the fresh request.
1335func (m *MergeRequests) markMerged(ctx context.Context, name domain.RepoName, number int64, mode domain.MergeMode, base, head, merged domain.ObjectID) (domain.MergeRequest, error) {
1336	// The merge must be recorded even when the caller gives up.
1337	ctx = context.WithoutCancel(ctx)
1338	for range maxWriteRetries {
1339		mr, err := m.store.Get(ctx, name, number)
1340		if err != nil {
1341			return domain.MergeRequest{}, fmt.Errorf("record the merge of !%d in %q: %w", number, name, err)
1342		}
1343		mr.State, mr.HeadID, mr.BaseID, mr.MergedCommitID, mr.MergeMode = domain.MRStateMerged, head, base, merged, mode
1344		mr.UpdatedAt = m.clock.Now().UTC()
1345		err = m.store.Update(ctx, mr)
1346		if errors.Is(err, domain.ErrConflict) {
1347			continue
1348		}
1349		if err != nil {
1350			return domain.MergeRequest{}, fmt.Errorf("record the merge of !%d in %q: %w", number, name, err)
1351		}
1352		return mr, nil
1353	}
1354	log := zerowrap.FromCtx(ctx)
1355	log.Error().Str("repo", name.String()).Int64("number", number).Str("commit", merged.String()).
1356		Msg("the target branch moved but the merge request could not be marked merged")
1357	return domain.MergeRequest{}, fmt.Errorf("record the merge of !%d in %q: %w", number, name, domain.ErrConflict)
1358}
1359
1360// EditComment changes only the author's text, preserving the immutable verdict.
1361func (m *MergeRequests) EditComment(ctx context.Context, p domain.Principal, name domain.RepoName, number, commentID int64, text string) (domain.Comment, error) {
1362	return m.changeComment(ctx, p, name, number, commentID, text, false)
1363}
1364
1365// DeleteComment removes text but retains the anchor, ID and verdict. Repeated deletion is a no-op.
1366func (m *MergeRequests) DeleteComment(ctx context.Context, p domain.Principal, name domain.RepoName, number, commentID int64) (domain.Comment, error) {
1367	return m.changeComment(ctx, p, name, number, commentID, "", true)
1368}
1369
1370func (m *MergeRequests) changeComment(ctx context.Context, p domain.Principal, name domain.RepoName, number, commentID int64, text string, remove bool) (domain.Comment, error) {
1371	repo, err := m.writable(ctx, p, name, domain.ScopeMRWrite)
1372	if err != nil {
1373		return domain.Comment{}, err
1374	}
1375	for range maxWriteRetries {
1376		mr, err := m.store.Get(ctx, name, number)
1377		if err != nil {
1378			return domain.Comment{}, err
1379		}
1380		c, err := m.store.GetComment(ctx, name, number, commentID)
1381		if err != nil {
1382			return domain.Comment{}, err
1383		}
1384		if !mr.IsOpen() {
1385			return domain.Comment{}, fmt.Errorf("%w: !%d is %s", domain.ErrPreconditionFailed, number, mr.State)
1386		}
1387		if domain.AuthorName(p) != c.Author {
1388			return domain.Comment{}, fmt.Errorf("%w: only the author of a note can edit or delete it", domain.ErrForbidden)
1389		}
1390		if c.Deleted {
1391			if remove {
1392				return c, nil
1393			}
1394			return domain.Comment{}, fmt.Errorf("%w: the note was deleted", domain.ErrPreconditionFailed)
1395		}
1396		parsed, err := domain.ParsePlainText(text)
1397		var v domain.Violations
1398		if err != nil {
1399			v.AddErr("text", err)
1400		} else if !remove && parsed.IsBlank() && c.Verdict == domain.VerdictNone {
1401			v.Add("text", "is required")
1402		}
1403		if err := v.Err(); err != nil {
1404			return domain.Comment{}, err
1405		}
1406		if !remove && parsed == c.Text {
1407			return c, nil
1408		}
1409		c.Text, c.Deleted, c.EditedAt = parsed, remove, m.clock.Now().UTC()
1410		mr.UpdatedAt = c.EditedAt
1411		if err := m.store.SaveComment(ctx, mr, c); errors.Is(err, domain.ErrConflict) {
1412			continue
1413		} else if err != nil {
1414			return domain.Comment{}, fmt.Errorf("save note %d of !%d in %q: %w", commentID, number, name, err)
1415		}
1416		log := zerowrap.FromCtx(ctx)
1417		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")
1418		if remove {
1419			m.bus.Publish(ctx, domain.CommentDeleted{Repo: name, Number: number, Comment: c, At: c.EditedAt, Visibility: repo.Visibility, CreatedAt: repo.CreatedAt})
1420		} else {
1421			m.bus.Publish(ctx, domain.CommentEdited{Repo: name, Number: number, Comment: c, At: c.EditedAt, Visibility: repo.Visibility, CreatedAt: repo.CreatedAt})
1422		}
1423		return c, nil
1424	}
1425	return domain.Comment{}, fmt.Errorf("save note %d of !%d in %q: %w", commentID, number, name, domain.ErrConflict)
1426}
1427
1428// replyRoot returns the note a reply targets, or a violation when it is
1429// missing, itself a reply, or deleted.
1430func (m *MergeRequests) replyRoot(ctx context.Context, name domain.RepoName, number, id int64) (domain.Comment, error) {
1431	root, err := m.store.GetComment(ctx, name, number, id)
1432	var v domain.Violations
1433	switch {
1434	case errors.Is(err, domain.ErrNotFound):
1435		v.Add("reply_to", fmt.Sprintf("no note ^%d", id))
1436	case err != nil:
1437		return domain.Comment{}, err
1438	case root.IsReply() || root.Deleted:
1439		v.Add("reply_to", "must name a non-deleted root note")
1440	}
1441	if err := v.Err(); err != nil {
1442		return domain.Comment{}, err
1443	}
1444	return root, nil
1445}
1446
1447// Compare lists at most ports.MaxCompareCommits source commits absent from target. Unlike bounded
1448// history intersection, ancestry remains accurate even for deep histories.
1449func (m *MergeRequests) Compare(ctx context.Context, p domain.Principal, repo domain.RepoName, target, source domain.ObjectID) (ports.CompareResult, error) {
1450	if _, err := m.readable(ctx, p, repo); err != nil {
1451		return ports.CompareResult{}, err
1452	}
1453	if target == source {
1454		return ports.CompareResult{Exact: true}, nil
1455	}
1456	ancestor, err := m.git.IsAncestor(ctx, repo, target, source)
1457	if err != nil {
1458		return ports.CompareResult{}, err
1459	}
1460	commits, more, err := m.git.ListRange(ctx, repo, target, source, ports.MaxCompareCommits)
1461	if err != nil {
1462		return ports.CompareResult{}, err
1463	}
1464	verifyCommits(ctx, m.verifier, repo, commits)
1465	return ports.CompareResult{Ahead: commits, Behind: !ancestor, Exact: !more}, nil
1466}
1467
1468// PushSummary detects rewrites by ancestry, not log ordering, and counts at
1469// most ports.MaxPushSummaryCommits new commits. More distinguishes a longer range from a rewrite.
1470func (m *MergeRequests) PushSummary(ctx context.Context, p domain.Principal, repo domain.RepoName, oldHead, newTip domain.ObjectID) (ports.PushSummary, error) {
1471	if _, err := m.readable(ctx, p, repo); err != nil {
1472		return ports.PushSummary{}, err
1473	}
1474	if oldHead == newTip {
1475		return ports.PushSummary{}, nil
1476	}
1477	ancestor, err := m.git.IsAncestor(ctx, repo, oldHead, newTip)
1478	if err != nil {
1479		return ports.PushSummary{}, err
1480	}
1481	if !ancestor {
1482		return ports.PushSummary{Rewritten: true}, nil
1483	}
1484	commits, more, err := m.git.ListRange(ctx, repo, oldHead, newTip, ports.MaxPushSummaryCommits)
1485	if err != nil {
1486		return ports.PushSummary{}, err
1487	}
1488	return ports.PushSummary{Count: len(commits), More: more}, nil
1489}

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