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