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 repo, err := m.writable(ctx, p, name, domain.ScopeMRMerge)
1006 if err != nil {
1007 return domain.MergeRequest{}, err
1008 }
1009 mode := params.Mode
1010 if mode == "" {
1011 mode = domain.MergeModeFastForward
1012 }
1013 var v domain.Violations
1014 if _, err := domain.ParseMergeMode(mode.String()); err != nil {
1015 v.Add("mode", "is not a merge mode")
1016 }
1017 if params.HeadID.IsZero() {
1018 v.Add("head_id", "is required")
1019 }
1020 if err := v.Err(); err != nil {
1021 return domain.MergeRequest{}, err
1022 }
1023
1024 unlock, err := m.lockRepo(ctx, name)
1025 if err != nil {
1026 return domain.MergeRequest{}, err
1027 }
1028 var once sync.Once
1029 release := func() { once.Do(unlock) }
1030 defer release()
1031
1032 mr, err := m.store.Get(ctx, name, number)
1033 if err != nil {
1034 return domain.MergeRequest{}, err
1035 }
1036 // A merge moves the target and may delete the source: a token limited to
1037 // branch prefixes may do so only within them.
1038 if !p.AllowsRef("refs/heads/" + mr.Target) {
1039 return domain.MergeRequest{}, fmt.Errorf("%w: this token may not write %s", domain.ErrForbidden, mr.Target)
1040 }
1041 if params.DeleteSource && !p.AllowsRef("refs/heads/"+mr.Source) {
1042 return domain.MergeRequest{}, fmt.Errorf("%w: this token may not write %s", domain.ErrForbidden, mr.Source)
1043 }
1044 if !mr.IsOpen() {
1045 return domain.MergeRequest{}, fmt.Errorf("%w: !%d is %s", domain.ErrPreconditionFailed, number, mr.State)
1046 }
1047 if mr.IsDraft() {
1048 return domain.MergeRequest{}, fmt.Errorf("%w: !%d is a draft: mark it ready for review first", domain.ErrPreconditionFailed, number)
1049 }
1050 // The settings are read again under the lock: a change applies at once.
1051 repo, err = m.meta.Get(ctx, name)
1052 if err != nil {
1053 if errors.Is(err, domain.ErrNotFound) {
1054 return domain.MergeRequest{}, err // deleted meanwhile
1055 }
1056 return domain.MergeRequest{}, fmt.Errorf("get repository %q: %w", name, err)
1057 }
1058 settings := repo.EffectiveSettings()
1059 if !settings.Allows(mode) {
1060 return domain.MergeRequest{}, fmt.Errorf("%w: the %s merge mode is not allowed in %s", domain.ErrPreconditionFailed, mode, name)
1061 }
1062
1063 head, err := m.branchOrZero(ctx, name, mr.Source)
1064 switch {
1065 case err != nil:
1066 return domain.MergeRequest{}, err
1067 case head.IsZero():
1068 return domain.MergeRequest{}, fmt.Errorf("%w: the source branch %q no longer exists", domain.ErrPreconditionFailed, mr.Source)
1069 case head != params.HeadID:
1070 return domain.MergeRequest{}, fmt.Errorf("%w: branch moved, read again: %q is at %s, not %s", domain.ErrPreconditionFailed, mr.Source, head, params.HeadID)
1071 }
1072 tip, err := m.branchOrZero(ctx, name, mr.Target)
1073 switch {
1074 case err != nil:
1075 return domain.MergeRequest{}, err
1076 case tip.IsZero():
1077 return domain.MergeRequest{}, fmt.Errorf("%w: the target branch %q no longer exists", domain.ErrPreconditionFailed, mr.Target)
1078 case tip == head:
1079 return domain.MergeRequest{}, fmt.Errorf("%w: nothing to merge, %q already is at %s", domain.ErrPreconditionFailed, mr.Target, head)
1080 }
1081 // A head behind the target (or at it) has nothing to merge, in any mode.
1082 if behind, err := m.git.IsAncestor(ctx, name, head, tip); err != nil {
1083 return domain.MergeRequest{}, err
1084 } else if behind {
1085 return domain.MergeRequest{}, fmt.Errorf("%w: nothing to merge, %q already contains %s", domain.ErrPreconditionFailed, mr.Target, head)
1086 }
1087 tree, err := m.checkMode(ctx, mr, mode, tip, head)
1088 if err != nil {
1089 return domain.MergeRequest{}, err
1090 }
1091 if settings.FailingChecksBlock {
1092 if err := m.checksAllow(ctx, name, head); err != nil {
1093 return domain.MergeRequest{}, err
1094 }
1095 }
1096 if params.DeleteSource {
1097 if err := m.checkDeletable(ctx, name, mr); err != nil {
1098 return domain.MergeRequest{}, err
1099 }
1100 }
1101
1102 merged, err := m.moveTarget(ctx, mr, mode, tip, head, tree, p)
1103 if err != nil {
1104 return domain.MergeRequest{}, err
1105 }
1106 m.recordPush(ctx, name) // the target moved, whatever happens next
1107 mr, err = m.markMerged(ctx, name, number, mode, tip, head, merged)
1108 if err != nil {
1109 return domain.MergeRequest{}, err
1110 }
1111 log := zerowrap.FromCtx(ctx)
1112 log.Info().Str("repo", name.String()).Int64("number", number).Str("mode", mode.String()).
1113 Str("target", mr.Target).Str("commit", merged.String()).
1114 Str("principal", p.Label()).Str("token_id", p.TokenID()).Msg("merge request merged")
1115
1116 // The merge is done and recorded. The rest runs without the lock and after
1117 // the caller got its answer.
1118 release()
1119 bg := context.WithoutCancel(ctx)
1120 m.after.Add(1)
1121 go func() {
1122 defer m.after.Done()
1123 defer func() {
1124 if r := recover(); r != nil {
1125 log := zerowrap.FromCtx(bg)
1126 log.Error().Str("repo", name.String()).Int64("number", number).
1127 Str("panic", fmt.Sprint(r)).Bytes("stack", debug.Stack()).Msg("post-merge side effects panicked")
1128 }
1129 }()
1130 if m.afterGate != nil {
1131 m.afterGate()
1132 }
1133 m.afterMerge(bg, p, repo, mr, head, tip, merged, params.DeleteSource)
1134 }()
1135 return mr, nil
1136}
1137
1138// afterMerge is what follows a merge off the request path: errors are logged,
1139// never returned. mr is the merged request, tip the old target and merged the
1140// new one.
1141func (m *MergeRequests) afterMerge(ctx context.Context, p domain.Principal, repo domain.Repo, mr domain.MergeRequest, head, tip, merged domain.ObjectID, deleteSource bool) {
1142 name := repo.Name
1143 updates := []domain.RefUpdate{{Old: tip.String(), New: merged.String(), Ref: "refs/heads/" + mr.Target}}
1144 if deleteSource && m.deleteSource(ctx, p, name, mr, head) {
1145 updates = append(updates, domain.RefUpdate{Old: head.String(), New: domain.ZeroOID, Ref: "refs/heads/" + mr.Source})
1146 }
1147 at := mr.UpdatedAt
1148 recordActivity(ctx, m.meta, repo.Name, at)
1149 m.bus.Publish(ctx, domain.MergeRequestMerged{MergeRequest: mr, At: at, Visibility: repo.Visibility, CreatedAt: repo.CreatedAt})
1150 m.bus.Publish(ctx, domain.PushEvent{
1151 Repo: name, At: at, Visibility: repo.Visibility, CreatedAt: repo.CreatedAt, Updates: updates,
1152 })
1153 if m.pulls != nil {
1154 m.pulls.OnPullRequest(ctx, name, ports.PullRequestEvent{Number: mr.Number, Action: domain.PullClosed, Head: mr.HeadID, Base: mr.BaseID, Merged: true}, p)
1155 }
1156 if m.ci != nil {
1157 // GitHub runs the "push" workflows of a merge, with the owner as actor;
1158 // the run is trusted with what the merging principal may read.
1159 m.ci.OnMerge(ctx, name, updates, p)
1160 }
1161 if m.mergeab != nil {
1162 m.mergeab.OnBranchesMoved(ctx, name, updates) // the other requests of the moved target
1163 }
1164}
1165
1166// deleteSource deletes the source branch of a merged request if it is still
1167// head and still unused, and reports whether it did. The eligibility is checked
1168// again and the branch deleted in one critical section of the merge lock: a
1169// request opened on the branch since the merge, or a push to it, keeps it. The
1170// record of who pushed the branch goes only after a deletion, and only if it
1171// still names head.
1172func (m *MergeRequests) deleteSource(ctx context.Context, p domain.Principal, name domain.RepoName, mr domain.MergeRequest, head domain.ObjectID) bool {
1173 log := zerowrap.FromCtx(ctx).With().Str("repo", name.String()).Int64("number", mr.Number).Str("branch", mr.Source).Logger()
1174 unlock, err := m.lockRepo(ctx, name)
1175 if err != nil {
1176 log.Warn().Err(err).Msg("source branch kept after the merge")
1177 return false
1178 }
1179 defer unlock()
1180 if err := m.checkDeletable(ctx, name, mr); err != nil {
1181 log.Warn().Err(err).Msg("source branch kept after the merge")
1182 return false
1183 }
1184 if err := m.git.DeleteBranch(ctx, name, mr.Source, head); err != nil {
1185 log.Warn().Err(err).Msg("source branch kept after the merge")
1186 return false
1187 }
1188 if m.tips != nil {
1189 if err := m.tips.DeleteRefTipIf(ctx, name, "refs/heads/"+mr.Source, head.String()); err != nil && !errors.Is(err, domain.ErrNotFound) {
1190 log.Warn().Err(err).Msg("the record of the source branch was kept")
1191 }
1192 }
1193 log.Info().Str("principal", p.Label()).Str("token_id", p.TokenID()).Msg("source branch deleted after the merge")
1194 return true
1195}
1196
1197// WhileOpen implements ports.PullGate: fn runs under the merge lock, so a
1198// close or a merge of the request cannot complete in the middle of it, and not
1199// at all when the request is no longer open.
1200func (m *MergeRequests) WhileOpen(ctx context.Context, name domain.RepoName, number int64, fn func() error) error {
1201 unlock, err := m.lockRepo(ctx, name)
1202 if err != nil {
1203 return err
1204 }
1205 defer unlock()
1206 mr, err := m.store.Get(ctx, name, number)
1207 if err != nil {
1208 return err
1209 }
1210 if !mr.IsOpen() {
1211 return fmt.Errorf("%w: !%d is %s", domain.ErrPreconditionFailed, number, mr.State)
1212 }
1213 return fn()
1214}
1215
1216// checksAllow is the merge rule of FailingChecksBlock: every check of the
1217// head must have ended as success, skipped or neutral. A check still queued or
1218// running blocks too (the merge could land code that then fails), and a head
1219// without any check merges.
1220func (m *MergeRequests) checksAllow(ctx context.Context, name domain.RepoName, head domain.ObjectID) error {
1221 if m.checks == nil {
1222 return nil
1223 }
1224 checks, err := m.checks.CommitChecks(ctx, name, head.String())
1225 if errors.Is(err, domain.ErrResourceExhausted) {
1226 return fmt.Errorf("%w: too many checks to tell whether they passed: %v", domain.ErrPreconditionFailed, err)
1227 }
1228 if err != nil {
1229 return fmt.Errorf("read the checks of %s: %w", head, err)
1230 }
1231 var failing, pending []string
1232 for _, c := range checks {
1233 switch {
1234 case c.Status != domain.CICompleted:
1235 pending = append(pending, c.Name)
1236 case !c.Conclusion.PassesMerge():
1237 failing = append(failing, c.Name)
1238 }
1239 }
1240 switch {
1241 case len(failing) > 0:
1242 return fmt.Errorf("%w: failing checks block the merge: %s (turn off failing_checks_block to merge anyway)", domain.ErrPreconditionFailed, strings.Join(failing, ", "))
1243 case len(pending) > 0:
1244 return fmt.Errorf("%w: checks have not finished: %s", domain.ErrPreconditionFailed, strings.Join(pending, ", "))
1245 }
1246 return nil
1247}
1248
1249// checkDeletable refuses to delete the source branch of mr when it is the
1250// default branch or the source or target of another open request. It runs
1251// under the merge lock, which Create also holds while it checks its branches
1252// and stores the request.
1253func (m *MergeRequests) checkDeletable(ctx context.Context, name domain.RepoName, mr domain.MergeRequest) error {
1254 def, _, err := m.repos.DefaultBranch(ctx, name)
1255 if err != nil {
1256 return fmt.Errorf("default branch of %q: %w", name, err)
1257 }
1258 if mr.Source == def {
1259 return fmt.Errorf("%w: %q is the default branch of %s: it cannot be deleted", domain.ErrPreconditionFailed, mr.Source, name)
1260 }
1261 all, err := m.store.List(ctx, name)
1262 if err != nil {
1263 return fmt.Errorf("list merge requests of %q: %w", name, err)
1264 }
1265 for _, o := range all {
1266 if o.Number != mr.Number && o.IsOpen() && (o.Source == mr.Source || o.Target == mr.Source) {
1267 return fmt.Errorf("%w: !%d still uses %q: it cannot be deleted", domain.ErrPreconditionFailed, o.Number, mr.Source)
1268 }
1269 }
1270 return nil
1271}
1272
1273// recordPush does for a merge what Pushes.Record does for a push, as the merge
1274// moved a branch: it sets pushed_at and queues the maintenance of the
1275// repository. The target already moved, so a failure is logged, not returned,
1276// and the caller giving up does not stop it.
1277func (m *MergeRequests) recordPush(ctx context.Context, name domain.RepoName) {
1278 ctx = context.WithoutCancel(ctx)
1279 if _, err := touchPushedAt(ctx, m.meta, name, m.clock.Now().UTC()); err != nil {
1280 log := zerowrap.FromCtx(ctx)
1281 log.Error().Err(err).Str("repo", name.String()).Msg("record pushed_at after a merge")
1282 }
1283 m.maint.Schedule(ctx, name)
1284}
1285
1286// moveTarget moves the target branch from tip to the head (fast-forward) or to
1287// a new signed squash or merge commit with the given tree, and returns the new tip.
1288func (m *MergeRequests) moveTarget(ctx context.Context, mr domain.MergeRequest, mode domain.MergeMode, tip, head, tree domain.ObjectID, p domain.Principal) (domain.ObjectID, error) {
1289 newTip := head
1290 switch mode {
1291 case domain.MergeModeMerge:
1292 commit := domain.NewMergeCommit(mr, tree, tip, head, m.committer, m.clock.Now())
1293 armored, err := m.signer.Sign(commit.Payload())
1294 if err != nil {
1295 return domain.ObjectID{}, fmt.Errorf("sign the merge commit of !%d in %q: %w", mr.Number, mr.Repo, err)
1296 }
1297 if newTip, err = m.git.WriteCommit(ctx, mr.Repo, commit.Signed(armored)); err != nil {
1298 return domain.ObjectID{}, err
1299 }
1300 case domain.MergeModeSquash:
1301 commits, more, err := m.git.ListRange(ctx, mr.Repo, tip, head, domain.MaxSquashCommits)
1302 if err != nil {
1303 return domain.ObjectID{}, err
1304 }
1305 if more {
1306 return domain.ObjectID{}, fmt.Errorf("%w: the branch has more than %d commits to squash", domain.ErrPreconditionFailed, domain.MaxSquashCommits)
1307 }
1308 commit := domain.NewSquashCommit(mr, tree, tip, commits, m.committer, m.clock.Now())
1309 armored, err := m.signer.Sign(commit.Payload())
1310 if err != nil {
1311 return domain.ObjectID{}, fmt.Errorf("sign the squash commit of !%d in %q: %w", mr.Number, mr.Repo, err)
1312 }
1313 if newTip, err = m.git.WriteCommit(ctx, mr.Repo, commit.Signed(armored)); err != nil {
1314 return domain.ObjectID{}, err
1315 }
1316 }
1317 // The target is the merger's from the moment it moves: recorded before it
1318 // does, under the merge lock (domain.CIRefTip). The run shows the owner, as a
1319 // merge's push does on GitHub.
1320 if err := recordRefTips(ctx, m.tips, mr.Repo, []domain.RefUpdate{{Old: tip.String(), New: newTip.String(), Ref: "refs/heads/" + mr.Target}},
1321 domain.AuthorName(domain.Owner()), domain.PusherOf(p), domain.TrustedActor(p)); err != nil {
1322 return domain.ObjectID{}, err
1323 }
1324 err := m.git.UpdateBranch(ctx, mr.Repo, mr.Target, tip, newTip)
1325 if errors.Is(err, domain.ErrConflict) {
1326 return domain.ObjectID{}, fmt.Errorf("%w: the target branch %q moved during the merge, try again", domain.ErrPreconditionFailed, mr.Target)
1327 }
1328 if err != nil {
1329 return domain.ObjectID{}, err
1330 }
1331 return newTip, nil
1332}
1333
1334// markMerged records the merge. The target already moved, so a write that
1335// loses a race (a comment added meanwhile) is repeated on the fresh request.
1336func (m *MergeRequests) markMerged(ctx context.Context, name domain.RepoName, number int64, mode domain.MergeMode, base, head, merged domain.ObjectID) (domain.MergeRequest, error) {
1337 // The merge must be recorded even when the caller gives up.
1338 ctx = context.WithoutCancel(ctx)
1339 for range maxWriteRetries {
1340 mr, err := m.store.Get(ctx, name, number)
1341 if err != nil {
1342 return domain.MergeRequest{}, fmt.Errorf("record the merge of !%d in %q: %w", number, name, err)
1343 }
1344 mr.State, mr.HeadID, mr.BaseID, mr.MergedCommitID, mr.MergeMode = domain.MRStateMerged, head, base, merged, mode
1345 mr.UpdatedAt = m.clock.Now().UTC()
1346 err = m.store.Update(ctx, mr)
1347 if errors.Is(err, domain.ErrConflict) {
1348 continue
1349 }
1350 if err != nil {
1351 return domain.MergeRequest{}, fmt.Errorf("record the merge of !%d in %q: %w", number, name, err)
1352 }
1353 return mr, nil
1354 }
1355 log := zerowrap.FromCtx(ctx)
1356 log.Error().Str("repo", name.String()).Int64("number", number).Str("commit", merged.String()).
1357 Msg("the target branch moved but the merge request could not be marked merged")
1358 return domain.MergeRequest{}, fmt.Errorf("record the merge of !%d in %q: %w", number, name, domain.ErrConflict)
1359}
1360
1361// EditComment changes only the author's text, preserving the immutable verdict.
1362func (m *MergeRequests) EditComment(ctx context.Context, p domain.Principal, name domain.RepoName, number, commentID int64, text string) (domain.Comment, error) {
1363 return m.changeComment(ctx, p, name, number, commentID, text, false)
1364}
1365
1366// DeleteComment removes text but retains the anchor, ID and verdict. Repeated deletion is a no-op.
1367func (m *MergeRequests) DeleteComment(ctx context.Context, p domain.Principal, name domain.RepoName, number, commentID int64) (domain.Comment, error) {
1368 return m.changeComment(ctx, p, name, number, commentID, "", true)
1369}
1370
1371func (m *MergeRequests) changeComment(ctx context.Context, p domain.Principal, name domain.RepoName, number, commentID int64, text string, remove bool) (domain.Comment, error) {
1372 repo, err := m.writable(ctx, p, name, domain.ScopeMRWrite)
1373 if err != nil {
1374 return domain.Comment{}, err
1375 }
1376 for range maxWriteRetries {
1377 mr, err := m.store.Get(ctx, name, number)
1378 if err != nil {
1379 return domain.Comment{}, err
1380 }
1381 c, err := m.store.GetComment(ctx, name, number, commentID)
1382 if err != nil {
1383 return domain.Comment{}, err
1384 }
1385 if !mr.IsOpen() {
1386 return domain.Comment{}, fmt.Errorf("%w: !%d is %s", domain.ErrPreconditionFailed, number, mr.State)
1387 }
1388 if domain.AuthorName(p) != c.Author {
1389 return domain.Comment{}, fmt.Errorf("%w: only the author of a note can edit or delete it", domain.ErrForbidden)
1390 }
1391 if c.Deleted {
1392 if remove {
1393 return c, nil
1394 }
1395 return domain.Comment{}, fmt.Errorf("%w: the note was deleted", domain.ErrPreconditionFailed)
1396 }
1397 parsed, err := domain.ParsePlainText(text)
1398 var v domain.Violations
1399 if err != nil {
1400 v.AddErr("text", err)
1401 } else if !remove && parsed.IsBlank() && c.Verdict == domain.VerdictNone {
1402 v.Add("text", "is required")
1403 }
1404 if err := v.Err(); err != nil {
1405 return domain.Comment{}, err
1406 }
1407 if !remove && parsed == c.Text {
1408 return c, nil
1409 }
1410 c.Text, c.Deleted, c.EditedAt = parsed, remove, m.clock.Now().UTC()
1411 mr.UpdatedAt = c.EditedAt
1412 if err := m.store.SaveComment(ctx, mr, c); errors.Is(err, domain.ErrConflict) {
1413 continue
1414 } else if err != nil {
1415 return domain.Comment{}, fmt.Errorf("save note %d of !%d in %q: %w", commentID, number, name, err)
1416 }
1417 log := zerowrap.FromCtx(ctx)
1418 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")
1419 if remove {
1420 m.bus.Publish(ctx, domain.CommentDeleted{Repo: name, Number: number, Comment: c, At: c.EditedAt, Visibility: repo.Visibility, CreatedAt: repo.CreatedAt})
1421 } else {
1422 m.bus.Publish(ctx, domain.CommentEdited{Repo: name, Number: number, Comment: c, At: c.EditedAt, Visibility: repo.Visibility, CreatedAt: repo.CreatedAt})
1423 }
1424 return c, nil
1425 }
1426 return domain.Comment{}, fmt.Errorf("save note %d of !%d in %q: %w", commentID, number, name, domain.ErrConflict)
1427}
1428
1429// replyRoot returns the note a reply targets, or a violation when it is
1430// missing, itself a reply, or deleted.
1431func (m *MergeRequests) replyRoot(ctx context.Context, name domain.RepoName, number, id int64) (domain.Comment, error) {
1432 root, err := m.store.GetComment(ctx, name, number, id)
1433 var v domain.Violations
1434 switch {
1435 case errors.Is(err, domain.ErrNotFound):
1436 v.Add("reply_to", fmt.Sprintf("no note ^%d", id))
1437 case err != nil:
1438 return domain.Comment{}, err
1439 case root.IsReply() || root.Deleted:
1440 v.Add("reply_to", "must name a non-deleted root note")
1441 }
1442 if err := v.Err(); err != nil {
1443 return domain.Comment{}, err
1444 }
1445 return root, nil
1446}
1447
1448// Compare lists at most ports.MaxCompareCommits source commits absent from target. Unlike bounded
1449// history intersection, ancestry remains accurate even for deep histories.
1450func (m *MergeRequests) Compare(ctx context.Context, p domain.Principal, repo domain.RepoName, target, source domain.ObjectID) (ports.CompareResult, error) {
1451 if _, err := m.readable(ctx, p, repo); err != nil {
1452 return ports.CompareResult{}, err
1453 }
1454 if target == source {
1455 return ports.CompareResult{Exact: true}, nil
1456 }
1457 ancestor, err := m.git.IsAncestor(ctx, repo, target, source)
1458 if err != nil {
1459 return ports.CompareResult{}, err
1460 }
1461 commits, more, err := m.git.ListRange(ctx, repo, target, source, ports.MaxCompareCommits)
1462 if err != nil {
1463 return ports.CompareResult{}, err
1464 }
1465 verifyCommits(ctx, m.verifier, repo, commits)
1466 return ports.CompareResult{Ahead: commits, Behind: !ancestor, Exact: !more}, nil
1467}
1468
1469// PushSummary detects rewrites by ancestry, not log ordering, and counts at
1470// most ports.MaxPushSummaryCommits new commits. More distinguishes a longer range from a rewrite.
1471func (m *MergeRequests) PushSummary(ctx context.Context, p domain.Principal, repo domain.RepoName, oldHead, newTip domain.ObjectID) (ports.PushSummary, error) {
1472 if _, err := m.readable(ctx, p, repo); err != nil {
1473 return ports.PushSummary{}, err
1474 }
1475 if oldHead == newTip {
1476 return ports.PushSummary{}, nil
1477 }
1478 ancestor, err := m.git.IsAncestor(ctx, repo, oldHead, newTip)
1479 if err != nil {
1480 return ports.PushSummary{}, err
1481 }
1482 if !ancestor {
1483 return ports.PushSummary{Rewritten: true}, nil
1484 }
1485 commits, more, err := m.git.ListRange(ctx, repo, oldHead, newTip, ports.MaxPushSummaryCommits)
1486 if err != nil {
1487 return ports.PushSummary{}, err
1488 }
1489 return ports.PushSummary{Count: len(commits), More: more}, nil
1490}