1// SPDX-License-Identifier: AGPL-3.0-or-later
2
3package usecase
4
5import (
6 "context"
7 "errors"
8 "fmt"
9 "unicode"
10 "unicode/utf8"
11
12 "github.com/bnema/zerowrap"
13
14 "bnema.dev/ermite/internal/domain"
15 "bnema.dev/ermite/internal/ports"
16)
17
18// MaxDescriptionLen is the longest repository description, in bytes.
19const MaxDescriptionLen = 500
20
21// validateDescription accepts a one-line description of valid UTF-8.
22func validateDescription(s string) error {
23 if len(s) > MaxDescriptionLen {
24 return fmt.Errorf("%w: description is longer than %d bytes", domain.ErrInvalid, MaxDescriptionLen)
25 }
26 if !utf8.ValidString(s) {
27 return fmt.Errorf("%w: description is not valid UTF-8", domain.ErrInvalid)
28 }
29 for _, c := range s {
30 if unicode.IsControl(c) {
31 return fmt.Errorf("%w: description must be one line without control characters", domain.ErrInvalid)
32 }
33 }
34 return nil
35}
36
37// View adds the default branch to a repository the caller has already been
38// allowed to see. A repository without a directory has no default branch.
39func (r *Repos) View(ctx context.Context, repo domain.Repo) (ports.RepoView, error) {
40 branch, err := r.git.HeadBranch(ctx, repo.Name)
41 if err != nil && !errors.Is(err, domain.ErrNotFound) {
42 return ports.RepoView{}, fmt.Errorf("read default branch of %q: %w", repo.Name, err)
43 }
44 return ports.RepoView{Repo: repo, DefaultBranch: branch}, nil
45}
46
47// Update changes the description, the topics, the visibility, the default branch and the
48// merge settings of a repository, and publishes RepoUpdated. The principal needs repo:admin on it
49// (see adminAccess for what the others learn) and no branch prefixes. At least one field must be set,
50// else domain.ErrInvalid. A default branch that does not exist gives
51// domain.ErrPreconditionFailed; nothing is written before every check passed.
52// The metadata is written first, then HEAD, and RepoUpdated is published after
53// both. When only the HEAD move fails, RepoUpdated is still published for the
54// stored metadata and the HEAD error is returned.
55func (r *Repos) Update(ctx context.Context, p domain.Principal, name domain.RepoName, params ports.UpdateRepoParams) (domain.Repo, error) {
56 repo, err := lookupRepo(ctx, r.meta, name)
57 if err != nil {
58 return domain.Repo{}, err
59 }
60 if err := adminAccess(p, repo); err != nil {
61 return domain.Repo{}, err
62 }
63 before := repo
64 if params.Description == nil && params.Topics == nil && params.Visibility == nil && params.DefaultBranch == nil &&
65 params.AllowedMergeModes == nil && params.FailingChecksBlock == nil {
66 return domain.Repo{}, fmt.Errorf("%w: nothing to update", domain.ErrInvalid)
67 }
68 if params.AllowedMergeModes != nil {
69 modes, err := domain.NormalizeMergeModes(*params.AllowedMergeModes)
70 if err != nil {
71 return domain.Repo{}, err
72 }
73 params.AllowedMergeModes = &modes
74 }
75 if params.Description != nil {
76 if err := validateDescription(*params.Description); err != nil {
77 return domain.Repo{}, err
78 }
79 }
80 if params.Topics != nil {
81 topics, err := domain.NormalizeTopics(*params.Topics)
82 if err != nil {
83 return domain.Repo{}, err
84 }
85 params.Topics = &topics
86 }
87 if params.Visibility != nil {
88 if _, err := domain.ParseVisibility(params.Visibility.String()); err != nil {
89 return domain.Repo{}, err
90 }
91 }
92 if params.DefaultBranch != nil {
93 if *params.DefaultBranch == "" {
94 return domain.Repo{}, fmt.Errorf("%w: default branch is empty", domain.ErrInvalid)
95 }
96 ok, err := r.git.HasBranch(ctx, name, *params.DefaultBranch)
97 if err != nil {
98 return domain.Repo{}, fmt.Errorf("check branch %q of %q: %w", *params.DefaultBranch, name, err)
99 }
100 if !ok {
101 return domain.Repo{}, fmt.Errorf("%w: branch %q does not exist", domain.ErrPreconditionFailed, *params.DefaultBranch)
102 }
103 }
104
105 // Metadata first, then HEAD. The two writes are not atomic: when moving
106 // HEAD fails after the metadata was stored, the stored change is still
107 // published as RepoUpdated (a repository made private must be withdrawn
108 // from the watchers) and the call then fails with the HEAD error. The
109 // branch was checked above, so the remaining causes are a vanished
110 // repository or an I/O failure.
111 metaDone := false
112 if params.Description != nil || params.Topics != nil || params.Visibility != nil || params.AllowedMergeModes != nil || params.FailingChecksBlock != nil {
113 if repo, err = r.updateMeta(ctx, name, params); err != nil {
114 return domain.Repo{}, err
115 }
116 metaDone = true
117 }
118 var headErr error
119 if params.DefaultBranch != nil {
120 if err := r.git.SetDefaultBranch(ctx, name, *params.DefaultBranch); err != nil {
121 headErr = fmt.Errorf("set default branch of %q: %w", name, err)
122 if !metaDone {
123 return domain.Repo{}, headErr
124 }
125 }
126 }
127
128 log := zerowrap.FromCtx(ctx)
129 log.Info().
130 Str("repo", name.String()).
131 Bool("description", params.Description != nil).
132 Bool("topics", params.Topics != nil).
133 Bool("visibility", params.Visibility != nil).
134 Bool("default_branch", params.DefaultBranch != nil).
135 Bool("settings", params.AllowedMergeModes != nil || params.FailingChecksBlock != nil).
136 Str("principal", p.Label()).Str("token_id", p.TokenID()).
137 Msg("repository updated")
138 r.bus.Publish(ctx, domain.RepoUpdated{
139 Repo: name, At: r.clock.Now().UTC(),
140 Visibility: repo.Visibility, Previous: before.Visibility, CreatedAt: repo.CreatedAt,
141 })
142 if headErr != nil {
143 return domain.Repo{}, headErr
144 }
145 return repo, nil
146}
147
148// updateMeta applies the metadata fields, retrying when a write (a push
149// recording pushed_at) gets in between.
150func (r *Repos) updateMeta(ctx context.Context, name domain.RepoName, params ports.UpdateRepoParams) (domain.Repo, error) {
151 for range pushRetries {
152 repo, err := r.meta.Get(ctx, name)
153 if err != nil {
154 return domain.Repo{}, err
155 }
156 if params.Description != nil {
157 repo.Description = *params.Description
158 }
159 if params.Topics != nil {
160 repo.Topics = *params.Topics
161 }
162 if params.Visibility != nil {
163 repo.Visibility = *params.Visibility
164 }
165 if repo.Settings.IsZero() {
166 repo.Settings = domain.DefaultRepoSettings()
167 }
168 if params.AllowedMergeModes != nil {
169 repo.Settings.AllowedMergeModes = *params.AllowedMergeModes
170 }
171 if params.FailingChecksBlock != nil {
172 repo.Settings.FailingChecksBlock = *params.FailingChecksBlock
173 }
174 err = r.meta.Update(ctx, repo)
175 if errors.Is(err, domain.ErrConflict) {
176 continue
177 }
178 if err != nil {
179 return domain.Repo{}, fmt.Errorf("update repository %q: %w", name, err)
180 }
181 return repo, nil
182 }
183 return domain.Repo{}, fmt.Errorf("update repository %q: %w", name, domain.ErrConflict)
184}
185
186// Delete moves the repository directory to the trash, removes its metadata
187// and publishes RepoDeleted. The principal needs repo:admin on it (see
188// adminAccess) and no branch prefixes. A repository whose directory is already gone, left by a
189// delete that failed half way, loses its metadata.
190func (r *Repos) Delete(ctx context.Context, p domain.Principal, name domain.RepoName) error {
191 repo, err := lookupRepo(ctx, r.meta, name)
192 if err != nil {
193 return err
194 }
195 if err := adminAccess(p, repo); err != nil {
196 return err
197 }
198 log := zerowrap.FromCtx(ctx)
199 switch err := r.git.Trash(ctx, name); {
200 case errors.Is(err, domain.ErrNotFound):
201 log.Warn().Str("repo", name.String()).Msg("repository directory already gone, removing its metadata")
202 case err != nil:
203 return fmt.Errorf("trash repository %q: %w", name, err)
204 }
205 var runIDs []int64
206 if r.ci != nil {
207 // Listed before the records go: the logs are found by run id.
208 if ids, err := r.ci.RunIDs(ctx, name); err == nil {
209 runIDs = ids
210 } else {
211 log.Warn().Err(err).Str("repo", name.String()).Msg("list the CI runs of the repository; their logs are left to the sweep")
212 }
213 }
214 if err := r.meta.Delete(ctx, name); err != nil {
215 return fmt.Errorf("delete metadata of %q: %w", name, err)
216 }
217 if r.ci != nil {
218 r.ci.ForgetRepo(name)
219 }
220 if len(runIDs) > 0 {
221 if err := r.ci.RemoveLogs(context.WithoutCancel(ctx), runIDs); err != nil {
222 log.Warn().Err(err).Str("repo", name.String()).Msg("remove the CI logs of the repository; the sweep will")
223 }
224 }
225 log.Info().Str("repo", name.String()).Str("principal", p.Label()).Str("token_id", p.TokenID()).Msg("repository deleted")
226 r.bus.Publish(ctx, domain.RepoDeleted{Repo: name, Visibility: repo.Visibility, At: r.clock.Now().UTC(), CreatedAt: repo.CreatedAt})
227 return nil
228}