1// SPDX-License-Identifier: AGPL-3.0-or-later
2
3package usecase
4
5import (
6 "context"
7 "crypto/rsa"
8 "slices"
9 "strconv"
10 "time"
11
12 "bnema.dev/ermite-actions/expr"
13 "bnema.dev/ermite-actions/template"
14 "bnema.dev/ermite-actions/workflow"
15 "bnema.dev/ermite/internal/domain"
16 "bnema.dev/ermite/internal/ports"
17)
18
19// Sweep exposes the daily sweep to the tests.
20func (c *CI) Sweep(ctx context.Context) { c.sweep(ctx) }
21
22// TouchPushedAt exposes touchPushedAt to the tests.
23func TouchPushedAt(ctx context.Context, meta ports.RepoMetaStore, name domain.RepoName, now time.Time) (domain.Repo, error) {
24 return touchPushedAt(ctx, meta, name, now)
25}
26
27// TouchActiveAt exposes touchActiveAt to the tests.
28func TouchActiveAt(ctx context.Context, meta ports.RepoMetaStore, name domain.RepoName, now time.Time) (domain.Repo, error) {
29 return touchActiveAt(ctx, meta, name, now)
30}
31
32// RunTitle gives the title of a run as startRun sets it: the evaluated
33// run-name, else commitTitle.
34func (c *CI) RunTitle(ctx context.Context, wf *workflow.Workflow, githubJSON, commitTitle string) string {
35 if name, ok := c.evalRunName(ctx, wf, githubJSON, expr.NewDictionary()); ok {
36 return name
37 }
38 return commitTitle
39}
40
41// CheckRunID exposes checkRunID to the tests.
42func CheckRunID(ctx context.Context, run domain.CIRun, index, combo int) int64 {
43 return checkRunID(ctx, run, index, combo)
44}
45
46// SecretUse is the result of SecretsUsedBy.
47type SecretUse = secretUse
48
49// SecretsUsedBy exposes secretsUsedBy to the tests.
50func SecretsUsedBy(workflowYAML, jobID string) SecretUse {
51 return secretsUsedBy(workflowYAML, jobID)
52}
53
54// SecretWalks is the number of YAML walks made so far.
55func SecretWalks() int64 { return secretWalks.Load() }
56
57// SecretUseCache is a wfCache exposed to the tests.
58type SecretUseCache struct{ c *wfCache }
59
60// NewSecretUseCache builds a cache for up to max runs.
61func NewSecretUseCache(max int) *SecretUseCache { return &SecretUseCache{newWfCache(max)} }
62
63// Use is wfCache.secretUse.
64func (s *SecretUseCache) Use(runID int64, yaml, jobKey string) SecretUse {
65 return s.c.secretUse(runID, yaml, jobKey)
66}
67
68// Drop is wfCache.drop.
69func (s *SecretUseCache) Drop(runID int64) { s.c.drop(runID) }
70
71// EvalConcurrency exposes evalConcurrency to the tests.
72func EvalConcurrency(ctx context.Context, tok template.Token, env template.Env) (domain.CIConcurrency, error) {
73 return evalConcurrency(ctx, tok, env)
74}
75
76// MatchPullRequest exposes the pull_request filter to the tests.
77func MatchPullRequest(wf *workflow.Workflow, action, base string, files []string, truncated bool) bool {
78 return matchPullRequest(wf, "pull_request", action, base, files, truncated)
79}
80
81// MatchPullRequestTarget exposes the pull_request_target filter to the tests.
82func MatchPullRequestTarget(wf *workflow.Workflow, action, base string, files []string, truncated bool) bool {
83 return matchPullRequest(wf, "pull_request_target", action, base, files, truncated)
84}
85
86// MatchWorkflowRun exposes the workflow_run filter to the tests.
87func MatchWorkflowRun(wf *workflow.Workflow, name, action, headBranch string) bool {
88 return matchWorkflowRun(wf, name, action, headBranch)
89}
90
91// ResolveDispatchInputs exposes resolveDispatchInputs to the tests.
92func ResolveDispatchInputs(defs []workflow.Input, given map[string]string) (map[string]string, error) {
93 return resolveDispatchInputs(defs, given)
94}
95
96// PullFilesLink exposes the Link header of the files endpoint to the tests.
97func PullFilesLink(base string, page, perPage, total int) string {
98 return pullFilesLink(base, page, perPage, total)
99}
100
101// FilePatch exposes the patch text of a file of the files endpoint to the tests.
102func FilePatch(f domain.FileDiff) (string, bool) { return filePatch(f) }
103
104// PullTipsTrusted exposes the trust check of an activity of a merge request to
105// the tests, on a CI that has cfg and no workers.
106func PullTipsTrusted(ctx context.Context, cfg CIConfig, repo domain.RepoName, ev ports.PullRequestEvent) (bool, domain.ObjectID) {
107 return (&CI{cfg: cfg}).pullTipsTrusted(ctx, repo, ev)
108}
109
110// Thumbprint exposes thumbprint to the tests.
111func Thumbprint(pub *rsa.PublicKey) string { return thumbprint(pub) }
112
113// IDTokenClaims gives the claims idTokenClaims builds, decoded.
114func IDTokenClaims(contextsJSON, environment, issuer, audience string, at time.Time) (map[string]any, []string, error) {
115 claims, err := idTokenClaims(contextsJSON, environment, idTokenMeta{issuer: issuer, audience: audience, jti: "jti", now: at})
116 if err != nil {
117 return nil, nil, err
118 }
119 out := make(map[string]any, len(claims))
120 keys := make([]string, 0, len(claims))
121 for _, p := range claims {
122 out[p.k] = p.v
123 keys = append(keys, p.k)
124 }
125 return out, keys, nil
126}
127
128// SignForTest signs claims (in the order of their keys) with the signing key.
129func (o *OIDC) SignForTest(claims map[string]any) (string, error) {
130 keys := make([]string, 0, len(claims))
131 for k := range claims {
132 keys = append(keys, k)
133 }
134 slices.Sort(keys)
135 out := make(ordered, 0, len(keys))
136 for _, k := range keys {
137 out = append(out, pair{k, claims[k]})
138 }
139 return o.sign(out)
140}
141
142// DifficultyFor exposes the adaptive difficulty with the production base and
143// cap to the tests.
144func DifficultyFor(perAddr, global int) int {
145 return difficultyFor(baseDifficulty, maxDifficulty, perAddr, global)
146}
147
148// Production parameters of the submission, for the tests.
149const (
150 BaseDifficulty = baseDifficulty
151 MaxDifficulty = maxDifficulty
152 MinFillTime = minFillTime
153 ChallengeTTL = challengeTTL
154)
155
156// SpentLen is the number of nonces the submission remembers as spent.
157func (s *IssueSubmissions) SpentLen() int {
158 s.mu.Lock()
159 defer s.mu.Unlock()
160 return len(s.spent)
161}
162
163// FillSpent fills the spent set with n unexpired nonces.
164func (s *IssueSubmissions) FillSpent(n int, exp time.Time) {
165 s.mu.Lock()
166 defer s.mu.Unlock()
167 for i := range n {
168 s.spent["fill"+strconv.Itoa(i)] = exp
169 }
170}
171
172// MaxSpent is the bound of the spent set.
173const MaxSpent = maxSpent
174
175// SetAfterMergeGate makes the post-merge goroutine of m run f before anything
176// else, to place a test between a merge and its side effects.
177func (m *MergeRequests) SetAfterMergeGate(f func()) { m.afterGate = f }
178
179// ScheduledRetries gives the number of retries waiting in the scheduler.
180func (s *Mergeability) ScheduledRetries() int {
181 s.retryMu.Lock()
182 defer s.retryMu.Unlock()
183 return len(s.heap)
184}
185
186// RetryAttempts gives the number of repositories whose
187// failed attempts are counted.
188func (s *Mergeability) RetryAttempts() int {
189 s.retryMu.Lock()
190 defer s.retryMu.Unlock()
191 return len(s.retries)
192}
193
194// ReconcileForTest runs a repository pass synchronously without workers.
195func (s *Mergeability) ReconcileForTest(repo domain.RepoName) bool { return s.reconcile(repo) }
196
197// RetryForTest schedules a retry of repo as a failed pass does.
198func (s *Mergeability) RetryForTest(repo domain.RepoName) { s.retry(repo) }
199
200// RetryDoneForTest forgets the retries of repo as a successful pass does.
201func (s *Mergeability) RetryDoneForTest(repo domain.RepoName) { s.retryDone(repo) }
202
203// RetryDueForTest gives the deadline of the retry scheduled for repo.
204func (s *Mergeability) RetryDueForTest(repo domain.RepoName) (time.Time, bool) {
205 s.retryMu.Lock()
206 defer s.retryMu.Unlock()
207 for _, it := range s.heap {
208 if it.key == repo {
209 return it.due, true
210 }
211 }
212 return time.Time{}, false
213}
214
215// PopDueForTest is the scheduler step taken when the timer armed for the
216// retry (repo, due) fires. It gives the repositories it released.
217func (s *Mergeability) PopDueForTest(repo domain.RepoName, due time.Time) []domain.RepoName {
218 return s.popDue(retryItem{key: repo, due: due})
219}
220
221// WindowLimits exposes windowLimits to the tests.
222var WindowLimits = windowLimits