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