1// SPDX-License-Identifier: AGPL-3.0-or-later
2
3package ports
4
5import (
6 "context"
7 "errors"
8 "fmt"
9 "strconv"
10 "time"
11
12 "bnema.dev/ermite/internal/domain"
13)
14
15// CIRunDraft is what CreateRun stores: a run with its source, its jobs and
16// their checks, built once the store has chosen the ids.
17type CIRunDraft struct {
18 Run domain.CIRun
19 Source domain.CIRunSource
20 Jobs []domain.CIJob
21 Checks []domain.CICheck
22}
23
24// CIWrite is a set of records written in one atomic batch. A run or a job with
25// Version 0 must not exist yet; any other must be unchanged since it was read.
26// Checks are derived from the jobs and upserted without a precondition.
27// Apply returns domain.ErrConflict otherwise and domain.ErrNotFound when the
28// repository no longer exists.
29//
30// RepoTokens are job repository tokens created with the batch (they must not
31// exist yet), RevokeJobs the jobs whose repository tokens are deleted by it,
32// and Resolutions the action resolutions of a run attempt to keep. They are
33// written under the lock of the run that owns them.
34//
35// Annotations replace, for each (execution of a job, step) they name, all the
36// annotations stored for it (none deletes them); ClearAnnotations deletes all
37// the annotations of the executions of jobs they name, steps included. Both
38// are written with the batch, so a call is applied whole or not at all.
39type CIWrite struct {
40 Runs []domain.CIRun
41 Jobs []domain.CIJob
42 Checks []domain.CICheck
43 RepoTokens []domain.CIRepoToken
44 RevokeJobs []CIJobRef
45 Resolutions []domain.CIActionResolution
46 Annotations []CIStepAnnotations
47 ClearAnnotations []CILogRef
48}
49
50// CIConcurrencyGroup is a stored concurrency group: its repository, its key (the
51// group, canonical: ConcurrencyKey), its record and its marks.
52type CIConcurrencyGroup struct {
53 Repo domain.RepoName
54 Group string
55 State domain.CIConcurrencyGroupState
56}
57
58// CIStepAnnotations are all the annotations of one step of one execution of a
59// job, in the order the step produced them.
60type CIStepAnnotations struct {
61 Repo domain.RepoName
62 Exec CILogRef
63 Step int32
64 // Items are the annotations; none removes those of the step.
65 Items []domain.CIAnnotation
66}
67
68// CIJobRef names one execution of a job.
69type CIJobRef struct {
70 RunID int64
71 RunAttempt int32
72 JobID string
73}
74
75// CIRepoTokenStore reads the job repository tokens, for the authentication of
76// a request. They are written by CIStore.Apply. *kvstore.CI implements it.
77type CIRepoTokenStore interface {
78 // FindRepoTokenByHash returns the token whose secret has that hash, or
79 // domain.ErrNotFound.
80 FindRepoTokenByHash(ctx context.Context, hash domain.TokenHash) (domain.CIRepoToken, error)
81 // GetRepoToken returns the token with that id, or domain.ErrNotFound.
82 GetRepoToken(ctx context.Context, id string) (domain.CIRepoToken, error)
83}
84
85// CIRefTipStore keeps, per branch or tag (full ref name), who moves it to its
86// object (domain.CIRefTip). The record is written before the ref moves.
87// *kvstore.CI implements it; the records go with the repository.
88type CIRefTipStore interface {
89 // PutRefTip stores the record of a ref, replacing the earlier one. A
90 // repository that does not exist is domain.ErrNotFound.
91 PutRefTip(ctx context.Context, t domain.CIRefTip) error
92 // GetRefTip returns the record of a ref, or domain.ErrNotFound.
93 GetRefTip(ctx context.Context, repo domain.RepoName, ref string) (domain.CIRefTip, error)
94 // DeleteRefTip removes the record of a ref; a missing one is not an error.
95 DeleteRefTip(ctx context.Context, repo domain.RepoName, ref string) error
96}
97
98// CIWorkflowStore keeps, per repository, the workflow files that are disabled
99// (`ermite workflow disable`). Paths are normalized (domain.ParseWorkflowPath);
100// the file does not have to exist. The records go with the repository.
101// *kvstore.CI implements it.
102type CIWorkflowStore interface {
103 // DisableWorkflow records the path as disabled; one already disabled is
104 // left as it is. A repository that does not exist is domain.ErrNotFound.
105 DisableWorkflow(ctx context.Context, repo domain.RepoName, path string, at time.Time) error
106 // EnableWorkflow removes the record; a path that is not disabled is not an
107 // error.
108 EnableWorkflow(ctx context.Context, repo domain.RepoName, path string) error
109 // DisabledWorkflows returns the disabled paths of the repository, sorted.
110 DisabledWorkflows(ctx context.Context, repo domain.RepoName) ([]string, error)
111}
112
113// CIStore keeps CI runs, jobs and checks. The store derives its own indexes
114// (the queue of ready jobs, the active jobs, the open runs, the job tokens)
115// from the records it writes.
116type CIStore interface {
117 // CreateRun takes the next run id and the next number of the workflow in
118 // the repository (both never reused), calls build with them and stores
119 // the draft it returns, in one batch that fails with domain.ErrNotFound
120 // once the repository is deleted, and with domain.ErrWorkflowDisabled when
121 // the repository disabled workflowPath (CIWorkflowStore) when the batch
122 // applies: the state is checked in that transaction, not before it, so a
123 // disable can never be overtaken, whatever event started the run and
124 // whether the run is a failed one for an invalid file or not. The records
125 // come back with their versions.
126 CreateRun(ctx context.Context, repo domain.RepoName, workflowPath string, build func(id, number int64) CIRunDraft) (CIRunDraft, error)
127 // Apply writes the records in one batch and returns the version they all
128 // have afterwards.
129 Apply(ctx context.Context, w CIWrite) (version uint64, err error)
130 // GetRun returns the run, or domain.ErrNotFound.
131 GetRun(ctx context.Context, repo domain.RepoName, id int64) (domain.CIRun, error)
132 // GetActionResolution returns the resolution kept for the key in the run
133 // attempt, or domain.ErrNotFound.
134 GetActionResolution(ctx context.Context, runID int64, runAttempt int32, key string) (domain.CIActionResolution, error)
135 // GetRunSource returns what the run was planned from, or
136 // domain.ErrNotFound. It is how a run is found from its id alone.
137 GetRunSource(ctx context.Context, runID int64) (domain.CIRunSource, error)
138 // ListRuns returns the runs of the repository with an id below before (0
139 // for no bound), newest first, at most limit.
140 ListRuns(ctx context.Context, repo domain.RepoName, before int64, limit int) ([]domain.CIRun, error)
141 // RunIDs returns the ids of the runs of the repository.
142 RunIDs(ctx context.Context, repo domain.RepoName) ([]int64, error)
143 // ListOpenRuns returns the runs that have not completed.
144 ListOpenRuns(ctx context.Context) ([]domain.CIRun, error)
145 // JobAnnotations returns the annotations of one execution of a job
146 // (CIJob.Attempt), ordered by step then by the order the step produced
147 // them. A job without annotation gives an empty list.
148 JobAnnotations(ctx context.Context, runID int64, attempt int32, jobID string) ([]domain.CIAnnotation, error)
149 // GetJob returns a job of a run at an attempt of the run, or
150 // domain.ErrNotFound.
151 GetJob(ctx context.Context, runID int64, runAttempt int32, jobID string) (domain.CIJob, error)
152 // ListJobs returns the jobs of a run at an attempt, ordered by index then
153 // combination.
154 ListJobs(ctx context.Context, runID int64, runAttempt int32) ([]domain.CIJob, error)
155 // FindJobByToken returns the job whose current token has that hash and
156 // whose token is still valid at now, or domain.ErrNotFound.
157 FindJobByToken(ctx context.Context, hash domain.TokenHash, now time.Time) (domain.CIJob, error)
158 // ListReadyJobs returns the jobs that wait for a runner, oldest first, at
159 // most limit.
160 ListReadyJobs(ctx context.Context, limit int) ([]domain.CIJob, error)
161 // ListActiveJobs returns the jobs given to a runner and not over.
162 ListActiveJobs(ctx context.Context) ([]domain.CIJob, error)
163 // ListChecks returns the checks of a commit, at most limit; more is true
164 // when there are more.
165 ListChecks(ctx context.Context, repo domain.RepoName, sha string, limit int) (checks []domain.CICheck, more bool, err error)
166 // UpdateConcurrency reads a concurrency group of a repository (compared
167 // with domain.ConcurrencyKey) with the marks of its entries, calls fn on a
168 // copy and stores what fn leaves in it, in one batch: the record, the marks
169 // that changed and the marks that fn removed. A group left with neither
170 // record nor marks is removed. The batch carries the version precondition of
171 // the group whatever fn does, and every change of the marks rewrites the
172 // record, so no two transactions of a group both succeed on the same state:
173 // on a conflict fn is called again on the new state and must be repeatable.
174 // A deleted repository is domain.ErrNotFound.
175 UpdateConcurrency(ctx context.Context, repo domain.RepoName, group string, fn func(*domain.CIConcurrencyGroupState) error) error
176 // ListConcurrency returns every concurrency group that has an entry, for
177 // the reconciliation at startup.
178 ListConcurrency(ctx context.Context) ([]CIConcurrencyGroup, error)
179 // Sweep removes the runs completed before the time, with their jobs,
180 // checks and sources (not their numbers), and returns their ids so that
181 // the logs can go too.
182 Sweep(ctx context.Context, before time.Time) ([]int64, error)
183 // CreateRunner stores the runner and the index of its token. A name in use
184 // is domain.ErrAlreadyExists, or with replace the old runner is removed in
185 // the same batch and returned.
186 CreateRunner(ctx context.Context, r domain.CIRunner, replace bool) (removed []domain.CIRunner, err error)
187 // GetRunner returns the runner, or domain.ErrNotFound.
188 GetRunner(ctx context.Context, id string) (domain.CIRunner, error)
189 // FindRunnerByToken returns the runner whose token has that hash, or
190 // domain.ErrNotFound.
191 FindRunnerByToken(ctx context.Context, hash domain.TokenHash) (domain.CIRunner, error)
192 // ListRunners returns every runner ordered by name.
193 ListRunners(ctx context.Context) ([]domain.CIRunner, error)
194 // SetRunnerVersion records the version the runner runs now. It writes only
195 // when the stored version differs, and returns domain.ErrNotFound for a
196 // runner that is gone.
197 SetRunnerVersion(ctx context.Context, id, version string) error
198 // RemoveRunner removes the runner and its token, or returns
199 // domain.ErrNotFound.
200 RemoveRunner(ctx context.Context, id string) (domain.CIRunner, error)
201}
202
203// CIRunCleaner is what repository deletion needs from CI: the runs of the
204// repository before its records go, and the removal of their logs and
205// summaries after. *usecase.CI implements it.
206type CIRunCleaner interface {
207 RunIDs(ctx context.Context, repo domain.RepoName) ([]int64, error)
208 RemoveLogs(ctx context.Context, runIDs []int64) error
209 // ForgetRepo drops what CI keeps in memory for the deleted repository (its
210 // cached schedules).
211 ForgetRepo(repo domain.RepoName)
212}
213
214// CIChecksReader is the read side of the checks, for the merge rule and the
215// pages that show them. *usecase.CI implements it.
216type CIChecksReader interface {
217 // CommitChecks returns the checks of a commit, without access control (the
218 // caller has checked it). More than 1,000 is domain.ErrResourceExhausted,
219 // not a part of them: a rule must not decide on some of the checks.
220 CommitChecks(ctx context.Context, repo domain.RepoName, sha string) ([]domain.CICheck, error)
221}
222
223// CILogRef names one execution of a job: its log, its summaries and its
224// annotations are kept under it.
225type CILogRef struct {
226 RunID int64
227 JobID string
228 Attempt int32
229}
230
231// ErrCILogLimit is returned by CILogStore.Append when the lines do not fit in
232// the log limit; nothing was appended.
233var ErrCILogLimit = errors.New("log limit reached")
234
235// ErrCILogGap wraps domain.ErrOutOfRange when an offset is above the count.
236type ErrCILogGap struct{ Count int64 }
237
238// Error implements error.
239func (e *ErrCILogGap) Error() string {
240 return "out of range: the log holds lines up to the offset of " + strconv.FormatInt(e.Count, 10)
241}
242
243// Is makes errors.Is(err, domain.ErrOutOfRange) true.
244func (e *ErrCILogGap) Is(target error) bool { return target == domain.ErrOutOfRange }
245
246// CILogStore keeps the logs of the jobs: append-only files, one line per log
247// line, never in the metadata store. Lines are numbered from 0.
248type CILogStore interface {
249 // Append appends the lines at offset (the number of the first line), with
250 // the idempotence of AppendLog: lines already stored are skipped, a gap is
251 // an *ErrCILogGap. It returns the number of lines after the call and how
252 // many of the request were new. A log that would exceed limit bytes gets
253 // nothing and ErrCILogLimit.
254 Append(ctx context.Context, ref CILogRef, offset int64, lines []domain.CILogLine, limit int64) (next int64, added int, err error)
255 // AppendForced appends lines whatever the limit (the last line of a log
256 // that reached it).
257 AppendForced(ctx context.Context, ref CILogRef, lines []domain.CILogLine) (next int64, err error)
258 // Count returns the number of lines held, 0 for a log that does not exist.
259 Count(ctx context.Context, ref CILogRef) (int64, error)
260 // Read returns lines from the one numbered from, at most maxLines lines and
261 // about maxBytes of text. It returns domain.ErrNotFound when the log does
262 // not exist and domain.ErrOutOfRange when from is above the count.
263 Read(ctx context.Context, ref CILogRef, from int64, maxLines, maxBytes int) ([]domain.CILogLine, error)
264 // Changed returns a channel that is closed at the next append to the log.
265 Changed(ref CILogRef) <-chan struct{}
266 // Reset empties the log.
267 Reset(ctx context.Context, ref CILogRef) error
268 // RemoveRuns deletes the logs of the runs.
269 RemoveRuns(ctx context.Context, runIDs []int64) error
270 // RunIDs lists the runs that have a log directory, for the orphan sweep.
271 RunIDs(ctx context.Context) ([]int64, error)
272}
273
274// CISummaryStore keeps the job summaries (the Markdown a step wrote to
275// GITHUB_STEP_SUMMARY): one file per step of an execution of a job, never in
276// the metadata store.
277type CISummaryStore interface {
278 // Put stores the summary of a step, replacing the one it has; the file
279 // appears whole or not at all. An empty markdown removes the summary.
280 Put(ctx context.Context, ref CILogRef, step int32, markdown string) error
281 // List returns the summaries of the steps that have one, by step number,
282 // at most limit; more is true when there are others. With maxBytes above
283 // 0 the files are sized (stat) before they are read, and a summary that
284 // would take the total of the Markdown read past maxBytes is returned
285 // Omitted, unread, as are all the ones after it: a call never reads more
286 // than maxBytes.
287 List(ctx context.Context, ref CILogRef, limit int, maxBytes int64) (summaries []domain.CIStepSummary, more bool, err error)
288 // RemoveJob deletes the summaries of one execution of a job.
289 RemoveJob(ctx context.Context, ref CILogRef) error
290 // RemoveRuns deletes the summaries of the runs.
291 RemoveRuns(ctx context.Context, runIDs []int64) error
292 // RunIDs lists the runs that have a summary directory, for the orphan
293 // sweep.
294 RunIDs(ctx context.Context) ([]int64, error)
295}
296
297// DispatchParams are the arguments of RunService.DispatchWorkflow.
298type DispatchParams struct {
299 // WorkflowPath is the path of the workflow file, or its file name.
300 WorkflowPath string
301 // Ref is a branch or a tag, short or full name; empty is the default branch.
302 Ref string
303 // Inputs are the values of the inputs by name, as text.
304 Inputs map[string]string
305}
306
307// WorkflowInfo is a workflow file of a repository and whether it starts runs.
308type WorkflowInfo struct {
309 // Path is ".github/workflows/<file>".
310 Path string
311 // Name is the "name:" of the workflow at the tip of the default branch (the
312 // path when it has none); empty when that file is absent or not a workflow.
313 Name string
314 Disabled bool
315}
316
317// WorkflowTrigger starts the workflows that match pushed refs. OnPush only
318// queues the work and returns: planning happens in the background and its
319// errors never reach the push.
320type WorkflowTrigger interface {
321 OnPush(ctx context.Context, repo domain.RepoName, updates []domain.RefUpdate, pusher domain.Principal)
322 // OnMerge is OnPush for the move of a target branch by a merge. GitHub shows
323 // the owner as the actor of the push of a merge, whoever merged; but the
324 // rights the run's actions are resolved with are those of merger, the
325 // principal that merged, never the owner's.
326 OnMerge(ctx context.Context, repo domain.RepoName, updates []domain.RefUpdate, merger domain.Principal)
327}
328
329// PullRequestTrigger starts the pull_request workflows of the merge requests
330// (CI-3, D5), like WorkflowTrigger does for pushes. It only queues the work.
331// The synchronize activity needs no call here: the push of the source branch
332// reaches WorkflowTrigger.OnPush.
333type PullRequestTrigger interface {
334 // OnPullRequest queues the activity ev of a merge request. p is who caused
335 // it: its trust is the run's, whatever happens to the branches before the
336 // event is handled. A job token starts no run.
337 OnPullRequest(ctx context.Context, repo domain.RepoName, ev PullRequestEvent, p domain.Principal)
338}
339
340// PullRequestEvent is one activity of a merge request, with the commits it is
341// for fixed when it happened: it runs for exactly these, with the trust of
342// whoever caused it, even when the branches have moved on by the time it is
343// handled.
344type PullRequestEvent struct {
345 Number int64
346 // Action is domain.PullOpened or domain.PullClosed.
347 Action string
348 // Head is the head of the source branch and Base the tip of the target at
349 // that moment; either may be zero when unknown (the current one is read).
350 Head, Base domain.ObjectID
351 // Merged is set on the closing a merge makes: its runs have the merger's
352 // trust (usecase.CI checks the merge against the request).
353 Merged bool
354}
355
356// PullGate lets the CI change what depends on a merge request staying open
357// (its refs/pull refs, the runs of its opening and updates) without racing a
358// close or a merge. *usecase.MergeRequests implements it.
359type PullGate interface {
360 // WhileOpen runs fn holding the merge lock of the repository (the one
361 // Close and Merge take) when merge request number is open, and returns
362 // domain.ErrPreconditionFailed without running fn when it is not. fn must
363 // be short and must not call the merge request use cases.
364 WhileOpen(ctx context.Context, repo domain.RepoName, number int64, fn func() error) error
365}
366
367// PullGit is what the refs/pull/<n>/{head,merge} of the merge requests need
368// from Git. Every method returns domain.ErrNotFound when the repository has no
369// directory.
370type PullGit interface {
371 // TestMerge merges head into base without touching a ref (`git merge-tree
372 // --write-tree`) and returns the tree of the result. clean is false when
373 // the merge conflicts, or when the commits share no history.
374 TestMerge(ctx context.Context, repo domain.RepoName, base, head domain.ObjectID) (tree domain.ObjectID, clean bool, err error)
375 // SetPullRef points a ref of domain.IsPullRef to the commit. Any other ref
376 // name is domain.ErrInvalid.
377 SetPullRef(ctx context.Context, repo domain.RepoName, ref string, id domain.ObjectID) error
378 // PullRef returns the commit a ref of domain.IsPullRef points to, or
379 // domain.ErrNotFound.
380 PullRef(ctx context.Context, repo domain.RepoName, ref string) (domain.ObjectID, error)
381}
382
383// CIGit is what planning needs from Git beyond RepoReader and MergeGit.
384type CIGit interface {
385 // ChangedPaths returns the paths changed from base to head (a zero base
386 // means the empty tree), in the order of the diff and without renames
387 // detection, at most max; truncated is true when there were more.
388 ChangedPaths(ctx context.Context, repo domain.RepoName, base, head domain.ObjectID, max int) (paths []string, truncated bool, err error)
389 // CommitsOffBranches returns the commits reachable from head and from no
390 // branch (refs/heads/*; tags do not count), newest first, at most limit
391 // (1 to MaxCommitLimit); more is true when there are others. It is empty
392 // for a commit that a branch already has.
393 CommitsOffBranches(ctx context.Context, repo domain.RepoName, head domain.ObjectID, limit int) (commits []domain.Commit, more bool, err error)
394}
395
396// PushObjects tells where the objects of a push in progress are. Git receives a
397// push into a quarantine directory and moves the objects into the repository
398// only when pre-receive accepts it, so the objects a pre-receive check reads are
399// not in the repository yet. Both fields are what git's own environment holds
400// in the hook (GIT_OBJECT_DIRECTORY and GIT_ALTERNATE_OBJECT_DIRECTORIES). The
401// zero value is a push with nothing in quarantine.
402type PushObjects struct {
403 Dir string
404 Alternates string
405}
406
407// WorkflowGuard finds the changes of a push to the workflow files of a
408// repository.
409type WorkflowGuard interface {
410 // ChangedWorkflow returns the first path under .github/workflows/ that the
411 // updates change, "" for none. Two checks, as GitHub judges the token of a
412 // job: (1) every commit the push brings (those no ref has yet) is compared
413 // with each of its parents (a root commit with nothing) and is a change when
414 // it has workflows that differ from every parent's; (2) the workflows a ref
415 // ends with must be its old ones or none for an update, and the default
416 // branch head's or none for a new ref (none when there is no head). A
417 // workflows directory that disappears is no change, and a deleted ref changes
418 // nothing. objects are those of the push in progress; a directory that is not
419 // inside the repository is refused. A push beyond the bounds of the check
420 // (commits, parents) is an error that matches domain.ErrInvalid.
421 ChangedWorkflow(ctx context.Context, repo domain.RepoName, updates []domain.RefUpdate, objects PushObjects) (path string, err error)
422}
423
424// --- inbound ---
425
426// RegisterRunnerParams describe a runner to register.
427type RegisterRunnerParams struct {
428 Name string
429 Labels []string
430 Version string
431 Isolation domain.CIIsolation
432 Arch, OS string
433 Replace bool
434}
435
436// RegisteredRunner is a new runner with its secret, shown once.
437type RegisteredRunner struct {
438 Runner domain.CIRunner
439 Token string
440}
441
442// RunnerJob is a job given to a runner.
443type RunnerJob struct {
444 Job domain.CIJob
445 Token string
446 // GithubToken is the job repository token, the "github.token" of the job.
447 GithubToken string
448 Repo domain.RepoName
449 Sha, Ref string
450 WorkflowPath string
451 WorkflowYAML string
452 // Environment is the environment the job deploys to, "" for none.
453 Environment string
454 // Vars are the merged variables of the job (environment over repository
455 // over instance), already in its "vars" context.
456 Vars map[string]string
457 // Secrets are the secrets the job refers to, in plain text: empty when the
458 // run is not trusted, when the job refers to none and when the server has
459 // no key. They go to the runner and nowhere else: never into the run
460 // record, the github context or a log.
461 Secrets map[string]string
462 // Trusted is the trusted flag of the run: secrets were allowed.
463 Trusted bool
464 // Permissions are the permissions of GithubToken (key to level), after the
465 // trust rule: no write when the run is not trusted.
466 Permissions map[string]string
467 // Cache is the scope of the job in the runner's cache (Job.cache).
468 Cache JobCache
469 // IDTokenURL is the token endpoint of the job's OIDC ID tokens and
470 // IDTokenRequestToken its bearer (Job.id_token_url and
471 // id_token_request_token); both "" when the job may not have ID tokens.
472 IDTokenURL string
473 IDTokenRequestToken string
474}
475
476// JobCache is what a job may do in the cache the runner serves: save entries
477// under WriteRef only ("" for none) and restore those of ReadRefs, most
478// specific first. Repository is "owner/name".
479type JobCache struct {
480 Repository string
481 WriteRef string
482 ReadRefs []string
483}
484
485// String describes the job without its secrets and tokens, so that a job
486// printed by mistake leaks nothing.
487func (j RunnerJob) String() string {
488 return fmt.Sprintf("RunnerJob{job:%s run:%d repo:%s secrets:%d trusted:%t}", j.Job.ID, j.Job.RunID, j.Repo, len(j.Secrets), j.Trusted)
489}
490
491// GoString is String for %#v.
492func (j RunnerJob) GoString() string { return j.String() }
493
494// FetchJobParams selects the job a runner asks for.
495type FetchJobParams struct {
496 Labels []string
497 PollID string
498 // Version is the version of the running runner, "" from an older runner.
499 Version string
500}
501
502// FetchJobResult is the answer of a poll.
503type FetchJobResult struct {
504 Job *RunnerJob
505 // RetryAfter is how long the runner waits before polling again.
506 RetryAfter time.Duration
507}
508
509// StepUpdate is the state of one step as a runner reports it.
510type StepUpdate struct {
511 Number int32
512 Name string
513 State domain.CIStepState
514 Conclusion domain.CIConclusion
515 // Outcome is how the step ended before continue-on-error; none when the
516 // runner does not report it.
517 Outcome domain.CIConclusion
518 StartedAt time.Time
519 CompletedAt time.Time
520}
521
522// CompleteJobParams end a job.
523type CompleteJobParams struct {
524 JobID string
525 Conclusion domain.CIConclusion
526 Outputs map[string]string
527 RunnerShutdown bool
528 Steps []StepUpdate
529 // Annotations replace those of each step they name, as in UpdateJob.
530 Annotations []domain.CIAnnotation
531}
532
533// CompleteJobResult is the stored result of a job.
534type CompleteJobResult struct {
535 Conclusion domain.CIConclusion
536 Error string
537 Applied bool
538}
539
540// ResolvedAction is the resolution of one "uses" of ResolveActions: where to
541// download the action, or Error (then only Ref is set).
542type ResolvedAction struct {
543 Ref string
544 NameWithOwner string
545 Path string
546 ResolvedSHA string
547 TarballURL string
548 Token string
549 Source domain.CIActionSource
550 Error string
551}
552
553// RemoteRef is a ref of a remote repository, as `git ls-remote` lists it.
554type RemoteRef struct {
555 // Name is the full ref name ("refs/heads/main", "refs/tags/v1").
556 Name string
557 // ID is the object the ref points to (the tag object of an annotated tag).
558 ID string
559 // Peeled is the commit an annotated tag points to; empty for other refs.
560 Peeled string
561}
562
563// GitRemote lists the refs of a repository on github.com, with no
564// credentials. It returns domain.ErrNotFound for a repository that does not
565// exist or needs credentials (GitHub answers alike), and an error matching
566// domain.ErrUnavailable when it cannot tell (network, timeout, too large an
567// answer).
568type GitRemote interface {
569 ListRefs(ctx context.Context, owner, repo string) ([]RemoteRef, error)
570}
571
572// WorkflowFetcher downloads one reusable workflow file from github.com at a
573// commit that was already resolved (CI-3, D7), with no credentials. It returns
574// domain.ErrNotFound for a file or repository that does not exist or needs
575// credentials, domain.ErrResourceExhausted for a file larger than maxBytes, and
576// an error matching domain.ErrUnavailable when it cannot tell.
577type WorkflowFetcher interface {
578 FetchWorkflow(ctx context.Context, owner, repo, sha, path string, maxBytes int64) ([]byte, error)
579}
580
581// JobSignal is one message of WatchJob.
582type JobSignal struct {
583 Keepalive bool
584 // Cancel is set for a cancel request.
585 Cancel *JobCancel
586 // Ended is set when the job has ended.
587 Ended *domain.JobEndedError
588}
589
590// JobCancel is a cancel request for a running job.
591type JobCancel struct {
592 Reason domain.CICancelReason
593 Message string
594 RequestedAt time.Time
595}
596
597// RunnerService is what runners call. The secret is the bearer secret of the
598// call: the runner token for FetchJob, the job token for the other calls.
599// A bad secret is domain.ErrUnauthenticated; a job token of another job than
600// the one named is domain.ErrForbidden. *usecase.CI implements it.
601type RunnerService interface {
602 Register(ctx context.Context, p domain.Principal, params RegisterRunnerParams) (RegisteredRunner, error)
603 FetchJob(ctx context.Context, secret string, params FetchJobParams) (FetchJobResult, error)
604 // UpdateJob applies the steps and the annotations whole or not at all: for
605 // each step number present in annotations, the annotations of that step are
606 // replaced (also for a step already completed, or not in steps).
607 UpdateJob(ctx context.Context, secret, jobID string, steps []StepUpdate, annotations []domain.CIAnnotation) error
608 AppendLog(ctx context.Context, secret, jobID string, step int32, offset int64, lines []domain.CILogLine) (next int64, err error)
609 Heartbeat(ctx context.Context, secret, jobID string) error
610 // WatchJob calls ready once the job token is valid and the stream is
611 // registered, before any message: the adapter flushes the response headers
612 // then, because a client's call returns only when they arrive.
613 WatchJob(ctx context.Context, secret, jobID string, ready func(), send func(JobSignal) error) error
614 CompleteJob(ctx context.Context, secret string, params CompleteJobParams) (CompleteJobResult, error)
615 // ResolveActions resolves the "uses" of the job's steps, one answer per
616 // reference in the same order. A reference that cannot be resolved is not
617 // an error: its answer carries Error. A local ("./") or Docker
618 // ("docker://") reference, or more than 100, is domain.ErrInvalid.
619 ResolveActions(ctx context.Context, secret, jobID string, uses []string) ([]ResolvedAction, error)
620 // UploadSummary stores the summary of a step, replacing the one it has; an
621 // empty markdown removes it. More than 1 MiB, invalid UTF-8 or a step
622 // number outside 1 to 1,000 is domain.ErrInvalid.
623 UploadSummary(ctx context.Context, secret, jobID string, step int32, markdown string) error
624}
625
626// JobView is a job as owners see it.
627type JobView struct {
628 domain.CIJob
629 // Lines is the number of lines of its log now.
630 Lines int64
631 // RunnerGone is set when the runner of the job was removed since.
632 RunnerGone bool
633}
634
635// StepRanges returns where the lines of every step are in the log.
636func (v JobView) StepRanges() []domain.StepRange { return domain.StepRanges(v.Steps, v.Lines) }
637
638// ListRunsParams select a page of runs.
639type ListRunsParams struct {
640 PageSize int
641 PageToken string
642 // Workflow restricts the result to a workflow file: its path or its file
643 // name. Branch restricts it to the runs of a branch, by short name. Status
644 // restricts it to the runs of that status. Empty means no restriction.
645 Workflow string
646 Branch string
647 Status domain.CIStatus
648}
649
650// RunPage is a page of runs, newest first.
651type RunPage struct {
652 Runs []domain.CIRun
653 NextPageToken string
654}
655
656// RunDetail is a run with its jobs.
657type RunDetail struct {
658 Run domain.CIRun
659 Jobs []JobView
660 LatestAttempt int32
661}
662
663// LogBatch is a message of a log stream: consecutive lines from Offset.
664type LogBatch struct {
665 Offset int64
666 Lines []JobLogLine
667}
668
669// JobLogLine is a log line with its step.
670type JobLogLine struct {
671 Step int32
672 domain.CILogLine
673}
674
675// GetJobLogParams select the log to stream.
676type GetJobLogParams struct {
677 JobID string
678 // Attempt is the attempt of the job, 0 for the latest.
679 Attempt int32
680 Offset int64
681 Follow bool
682 // Ready, when not nil, is called once the access is checked and the
683 // stream is counted, before any batch: the adapter flushes the response
684 // headers then (a follow on a job with no line yet would keep the client's
685 // call waiting for the first one).
686 Ready func()
687 // Client identifies where the call comes from, for the limit of streams
688 // per client; empty counts against the total only.
689 Client string
690}
691
692// CheckView is a check with what owners need to read it.
693type CheckView struct {
694 domain.CICheck
695 // WaitingForRunner is set for a queued check whose job no registered
696 // runner can take (no runner has all its labels).
697 WaitingForRunner bool
698}
699
700// ChecksResult are the checks of a commit.
701type ChecksResult struct {
702 Checks []CheckView
703 Truncated bool
704}
705
706// RunnerPage is a page of runners.
707type RunnerPage struct {
708 Runners []RunnerView
709 NextPageToken string
710}
711
712// RunnerView is a runner with what is known of it now.
713type RunnerView struct {
714 domain.CIRunner
715 LastSeen time.Time
716 Busy bool
717 // Online is decided by the server's clock (see usecase.RunnerOnlineWindow).
718 Online bool
719}
720
721// JobAnnotation is an annotation with the job it belongs to.
722type JobAnnotation struct {
723 JobID string
724 Annotation domain.CIAnnotation
725}
726
727// AnnotationList are the annotations of a run, at most
728// domain.CIMaxListedAnnotations.
729type AnnotationList struct {
730 Annotations []JobAnnotation
731 Truncated bool
732}
733
734// SummaryList are the summaries of a job, at most domain.CIMaxListedSummaries.
735type SummaryList struct {
736 Summaries []domain.CIStepSummary
737 Truncated bool
738}
739
740// RunService is the owner side of CI. *usecase.CI implements it.
741type RunService interface {
742 ListRuns(ctx context.Context, p domain.Principal, repo domain.RepoName, params ListRunsParams) (RunPage, error)
743 GetRun(ctx context.Context, p domain.Principal, repo domain.RepoName, runID int64, attempt int32) (RunDetail, error)
744 GetJob(ctx context.Context, p domain.Principal, repo domain.RepoName, jobID string, attempt int32) (JobView, error)
745 GetJobLog(ctx context.Context, p domain.Principal, repo domain.RepoName, params GetJobLogParams, send func(LogBatch) error) error
746 CancelRun(ctx context.Context, p domain.Principal, repo domain.RepoName, runID int64) (domain.CIRun, error)
747 RerunRun(ctx context.Context, p domain.Principal, repo domain.RepoName, runID int64, failedOnly bool) (domain.CIRun, error)
748 // DispatchWorkflow starts a run of a workflow file by hand (workflow_dispatch).
749 // The caller needs ci:write on the repository, or is a job token with the
750 // permission actions: write. The run is returned queued.
751 DispatchWorkflow(ctx context.Context, p domain.Principal, repo domain.RepoName, params DispatchParams) (domain.CIRun, error)
752 ListChecks(ctx context.Context, p domain.Principal, repo domain.RepoName, sha string) (ChecksResult, error)
753 // ListWorkflows returns the workflow files at the tip of the default branch
754 // and the disabled ones whatever the branch holds, ordered by path. Reading
755 // the repository is enough.
756 ListWorkflows(ctx context.Context, p domain.Principal, repo domain.RepoName) ([]WorkflowInfo, error)
757 // DisabledWorkflows returns the paths of the disabled workflows, sorted,
758 // without reading any file: the cheap form of ListWorkflows for the pages.
759 DisabledWorkflows(ctx context.Context, p domain.Principal, repo domain.RepoName) ([]string, error)
760 // DisableWorkflow stops the workflow (its file name or path; it does not
761 // have to exist) from starting runs for any event. EnableWorkflow undoes it.
762 // Both need repo:admin on the repository and are idempotent.
763 DisableWorkflow(ctx context.Context, p domain.Principal, repo domain.RepoName, file string) (WorkflowInfo, error)
764 EnableWorkflow(ctx context.Context, p domain.Principal, repo domain.RepoName, file string) (WorkflowInfo, error)
765 // ListAnnotations returns the annotations of a run attempt (0 for the
766 // latest), of one job when jobID is not empty. Each job gives those of the
767 // attempt in which it executed.
768 ListAnnotations(ctx context.Context, p domain.Principal, repo domain.RepoName, runID int64, attempt int32, jobID string) (AnnotationList, error)
769 // GetStepSummaries returns the summaries of a job at an attempt (0 for the
770 // latest), by step number. maxBytes above 0 bounds the Markdown read: the
771 // summaries past it come back Omitted, without their Markdown (the API
772 // passes 0, no bound).
773 GetStepSummaries(ctx context.Context, p domain.Principal, repo domain.RepoName, jobID string, attempt int32, maxBytes int64) (SummaryList, error)
774 ListRunners(ctx context.Context, p domain.Principal, size int, token string) (RunnerPage, error)
775 RemoveRunner(ctx context.Context, p domain.Principal, id string) error
776}
777
778// ErrSecretNotOpened means a sealed secret does not open: another key, other
779// additional data (a value moved to another scope or name) or a damaged value.
780var ErrSecretNotOpened = errors.New("secret does not open")
781
782// SecretSealer encrypts the values of secrets at rest. The adapter holds the
783// master key; without one the use cases get no sealer and refuse secrets.
784type SecretSealer interface {
785 // Seal returns plaintext sealed and bound to aad. It never fails.
786 Seal(plaintext, aad []byte) []byte
787 // Open reverses Seal with the same aad, or returns ErrSecretNotOpened.
788 Open(sealed, aad []byte) ([]byte, error)
789 // KeyCheck is a value derived from the key that does not reveal it.
790 KeyCheck() []byte
791}
792
793// SealedSecret is a stored secret: its value is sealed.
794type SealedSecret struct {
795 Name string
796 Sealed []byte
797 UpdatedAt time.Time
798}
799
800// CISettingsStore keeps the secrets, variables and environments of CI (ADR
801// 0019). A scope that names a missing repository or environment is
802// domain.ErrNotFound for every write and every read of its content. Names are
803// already upper-cased (domain.ParseSettingName).
804type CISettingsStore interface {
805 // BindSecretsKey records the key check beside the secrets when none is
806 // stored, and returns domain.ErrSecretsKeyMismatch when the stored one
807 // differs.
808 BindSecretsKey(ctx context.Context, check []byte) error
809 // PutSecret creates or replaces a secret.
810 PutSecret(ctx context.Context, scope domain.SettingsScope, name string, sealed []byte, at time.Time) (domain.Secret, error)
811 // GetSealedSecret reads one secret of a scope, or domain.ErrNotFound when
812 // it, the repository or the environment does not exist.
813 GetSealedSecret(ctx context.Context, scope domain.SettingsScope, name string) (SealedSecret, error)
814 // ListSealedSecrets lists the secrets of one scope ordered by name.
815 ListSealedSecrets(ctx context.Context, scope domain.SettingsScope) ([]SealedSecret, error)
816 // DeleteSecret deletes a secret, or returns domain.ErrNotFound.
817 DeleteSecret(ctx context.Context, scope domain.SettingsScope, name string) error
818 // PutVariable creates or replaces a variable.
819 PutVariable(ctx context.Context, scope domain.SettingsScope, name, value string, at time.Time) (domain.Variable, error)
820 // GetVariable returns a variable, or domain.ErrNotFound.
821 GetVariable(ctx context.Context, scope domain.SettingsScope, name string) (domain.Variable, error)
822 // ListVariables lists the variables of one scope ordered by name.
823 ListVariables(ctx context.Context, scope domain.SettingsScope) ([]domain.Variable, error)
824 // DeleteVariable deletes a variable, or returns domain.ErrNotFound.
825 DeleteVariable(ctx context.Context, scope domain.SettingsScope, name string) error
826 // CreateEnvironment creates the environment, or returns the existing one
827 // (compared without regard to case) unchanged.
828 CreateEnvironment(ctx context.Context, repo domain.RepoName, name string, at time.Time) (domain.Environment, error)
829 // ListEnvironments lists the environments of a repository ordered by name.
830 ListEnvironments(ctx context.Context, repo domain.RepoName) ([]domain.Environment, error)
831 // DeleteEnvironment deletes the environment with its secrets and
832 // variables, or returns domain.ErrNotFound.
833 DeleteEnvironment(ctx context.Context, repo domain.RepoName, name string) error
834}
835
836// JobSettingsRequest asks for the variables, and when wanted the secrets, a job
837// sees.
838type JobSettingsRequest struct {
839 Repo domain.RepoName
840 // Environment is the environment of the job, "" for none.
841 Environment string
842 // CreateEnvironment creates the environment first when it does not exist
843 // (a job that names one creates it on first use).
844 CreateEnvironment bool
845 // WantSecrets asks for secrets at all: false for a run that is not
846 // trusted. SecretNames are the (upper-cased) names to return, or AllSecrets
847 // for every secret of the scopes.
848 WantSecrets bool
849 SecretNames []string
850 AllSecrets bool
851}
852
853// JobSettings are what a job sees: the merged variables and secrets, with the
854// environment over the repository over the instance.
855type JobSettings struct {
856 Vars map[string]string
857 Secrets map[string]string
858 // SecretsOff is set when secrets were wanted but the server has no
859 // ERMITE_SECRETS_KEY, so none can be given.
860 SecretsOff bool
861}
862
863// CIJobSettings resolves the variables and secrets of a job. *usecase.CISettings
864// implements it.
865type CIJobSettings interface {
866 Resolve(ctx context.Context, req JobSettingsRequest) (JobSettings, error)
867}