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