1// SPDX-License-Identifier: AGPL-3.0-or-later
2
3// Package usecase holds the use cases of ermite. It depends on the domain and on
4// the ports only.
5package usecase
6
7import (
8 "context"
9 "errors"
10 "fmt"
11
12 "github.com/bnema/zerowrap"
13
14 "bnema.dev/ermite/internal/domain"
15 "bnema.dev/ermite/internal/ports"
16)
17
18// Repos are the repository use cases.
19type Repos struct {
20 meta ports.RepoMetaStore
21 git ports.GitRepos
22 bus ports.EventBus
23 clock ports.Clock
24 ci ports.CIRunCleaner // nil: no CI logs to remove
25}
26
27var _ ports.RepoService = (*Repos)(nil)
28
29// NewRepos builds the repository use cases over their ports. Changes are
30// published on bus.
31func NewRepos(meta ports.RepoMetaStore, git ports.GitRepos, bus ports.EventBus, clock ports.Clock) *Repos {
32 return &Repos{meta: meta, git: git, bus: bus, clock: clock}
33}
34
35// WithCIRunCleaner makes Delete remove the CI logs of the repository. Call it
36// before the first request; it returns r.
37func (r *Repos) WithCIRunCleaner(c ports.CIRunCleaner) *Repos {
38 r.ci = c
39 return r
40}
41
42// Create makes a repository and publishes RepoCreated: it stages a bare repository, records the
43// metadata (which fails with domain.ErrAlreadyExists if the name is taken,
44// also when a concurrent Create wins) and publishes the directory. A failure
45// after the metadata is written removes it again and discards the staged
46// repository.
47//
48// The principal needs repo:write on the name and no branch prefixes: anonymous
49// callers get domain.ErrUnauthenticated, other callers without it (a token
50// limited to some branches included) domain.ErrForbidden.
51func (r *Repos) Create(ctx context.Context, p domain.Principal, params ports.CreateRepoParams) (domain.Repo, error) {
52 if params.Name.IsZero() {
53 return domain.Repo{}, fmt.Errorf("%w: empty name", domain.ErrInvalidName)
54 }
55 if p.IsAnonymous() {
56 return domain.Repo{}, domain.ErrUnauthenticated
57 }
58 if !canCreateRepo(p, params.Name) {
59 return domain.Repo{}, domain.ErrForbidden
60 }
61 if err := validateDescription(params.Description); err != nil {
62 return domain.Repo{}, err
63 }
64 vis := params.Visibility
65 if vis == "" {
66 vis = domain.VisibilityPrivate
67 }
68 if _, err := domain.ParseVisibility(vis.String()); err != nil {
69 return domain.Repo{}, err
70 }
71 repo := domain.Repo{
72 Name: params.Name,
73 Description: params.Description,
74 Visibility: vis,
75 CreatedAt: r.clock.Now().UTC(),
76 Settings: domain.DefaultRepoSettings(),
77 }
78
79 log := zerowrap.FromCtx(ctx)
80 // Cleanup must finish even when the caller gives up.
81 cleanup := context.WithoutCancel(ctx)
82
83 id, err := r.git.Stage(ctx)
84 if err != nil {
85 return domain.Repo{}, fmt.Errorf("stage repository %q: %w", repo.Name, err)
86 }
87 if err := r.meta.Create(ctx, repo); err != nil {
88 r.discard(cleanup, id)
89 if errors.Is(err, domain.ErrAlreadyExists) {
90 return domain.Repo{}, fmt.Errorf("repository %q: %w", repo.Name, domain.ErrAlreadyExists)
91 }
92 return domain.Repo{}, fmt.Errorf("store repository %q: %w", repo.Name, err)
93 }
94 if err := r.git.Publish(ctx, id, repo.Name); err != nil {
95 if derr := r.meta.Delete(cleanup, repo.Name); derr != nil {
96 log.Error().Err(derr).Str("repo", repo.Name.String()).Msg("remove metadata after failed publish")
97 }
98 r.discard(cleanup, id)
99 if errors.Is(err, domain.ErrAlreadyExists) {
100 return domain.Repo{}, fmt.Errorf("repository %q: directory %w", repo.Name, domain.ErrAlreadyExists)
101 }
102 return domain.Repo{}, fmt.Errorf("publish repository %q: %w", repo.Name, err)
103 }
104 log.Info().Str("repo", repo.Name.String()).Str("visibility", vis.String()).Msg("repository created")
105 r.bus.Publish(ctx, domain.RepoCreated{Repo: repo.Name, Visibility: repo.Visibility, At: repo.CreatedAt})
106 return repo, nil
107}
108
109func (r *Repos) discard(ctx context.Context, id ports.StagedID) {
110 if err := r.git.Discard(ctx, id); err != nil {
111 log := zerowrap.FromCtx(ctx)
112 log.Error().Err(err).Str("staged", string(id)).Msg("discard staged repository")
113 }
114}
115
116// lookupRepo reads the metadata of a repository: domain.ErrInvalidName for the
117// zero name, domain.ErrNotFound for a missing repository. Access rules are the
118// caller's.
119func lookupRepo(ctx context.Context, meta ports.RepoMetaStore, name domain.RepoName) (domain.Repo, error) {
120 if name.IsZero() {
121 return domain.Repo{}, fmt.Errorf("%w: empty name", domain.ErrInvalidName)
122 }
123 return meta.Get(ctx, name)
124}
125
126// Get returns a repository. A repository the principal may not read answers
127// domain.ErrNotFound, like a missing one.
128func (r *Repos) Get(ctx context.Context, p domain.Principal, name domain.RepoName) (domain.Repo, error) {
129 repo, err := lookupRepo(ctx, r.meta, name)
130 if err != nil {
131 return domain.Repo{}, err
132 }
133 if !canRead(p, repo) {
134 return domain.Repo{}, domain.ErrNotFound
135 }
136 return repo, nil
137}
138
139// List returns the repositories the principal may read, ordered by name.
140func (r *Repos) List(ctx context.Context, p domain.Principal) ([]domain.Repo, error) {
141 all, err := r.meta.List(ctx)
142 if err != nil {
143 return nil, err
144 }
145 visible := make([]domain.Repo, 0, len(all))
146 for _, repo := range all {
147 if canRead(p, repo) {
148 visible = append(visible, repo)
149 }
150 }
151 return visible, nil
152}
153
154// ReconcileReport tells what Reconcile found.
155type ReconcileReport struct {
156 // Registered are directories without metadata, now registered private.
157 Registered []domain.RepoName
158 // MissingDirs are repositories with metadata and no directory. They are
159 // left untouched.
160 MissingDirs []domain.RepoName
161 // InvalidDirs are directory entries that cannot be repositories.
162 InvalidDirs []string
163}
164
165// Reconcile aligns the repository directories with the metadata at startup:
166// it removes staging leftovers, registers a directory without metadata as
167// private, skips invalid directory names, and reports metadata without a
168// directory at error level without touching it.
169func (r *Repos) Reconcile(ctx context.Context) (ReconcileReport, error) {
170 log := zerowrap.FromCtx(ctx)
171 var rep ReconcileReport
172
173 if err := r.git.PurgeStaging(ctx); err != nil {
174 return rep, fmt.Errorf("purge staging: %w", err)
175 }
176 dirs, err := r.git.List(ctx)
177 if err != nil {
178 return rep, fmt.Errorf("list repository directories: %w", err)
179 }
180 metas, err := r.meta.List(ctx)
181 if err != nil {
182 return rep, fmt.Errorf("list repository metadata: %w", err)
183 }
184
185 for _, entry := range dirs.Invalid {
186 log.Warn().Str("entry", entry).Msg("skip directory that is not a valid repository name")
187 }
188 rep.InvalidDirs = dirs.Invalid
189
190 hasMeta := make(map[domain.RepoName]bool, len(metas))
191 for _, m := range metas {
192 hasMeta[m.Name] = true
193 }
194 hasDir := make(map[domain.RepoName]bool, len(dirs.Names))
195 for _, name := range dirs.Names {
196 hasDir[name] = true
197 }
198
199 for _, name := range dirs.Names {
200 if hasMeta[name] {
201 continue
202 }
203 repo := domain.Repo{
204 Name: name,
205 Visibility: domain.VisibilityPrivate,
206 CreatedAt: r.clock.Now().UTC(),
207 Settings: domain.DefaultRepoSettings(),
208 }
209 if err := r.meta.Create(ctx, repo); err != nil && !errors.Is(err, domain.ErrAlreadyExists) {
210 return rep, fmt.Errorf("register repository %q: %w", name, err)
211 }
212 log.Warn().Str("repo", name.String()).Msg("registered repository directory without metadata as private")
213 rep.Registered = append(rep.Registered, name)
214 }
215 for _, m := range metas {
216 if !hasDir[m.Name] {
217 log.Error().Str("repo", m.Name.String()).Msg("repository metadata without a directory, left untouched")
218 rep.MissingDirs = append(rep.MissingDirs, m.Name)
219 }
220 }
221 return rep, nil
222}