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