@@ -0,0 +1,316 @@ |
| 1 | +// SPDX-License-Identifier: AGPL-3.0-or-later |
| 2 | + |
| 3 | +// Package lifecycle owns user-visible Actions run/job lifecycle mutations: |
| 4 | +// cancellation now, with re-runs and retention following in later S41g slices. |
| 5 | +package lifecycle |
| 6 | + |
| 7 | +import ( |
| 8 | + "context" |
| 9 | + "errors" |
| 10 | + "fmt" |
| 11 | + "log/slog" |
| 12 | + "strings" |
| 13 | + "time" |
| 14 | + |
| 15 | + "github.com/jackc/pgx/v5" |
| 16 | + "github.com/jackc/pgx/v5/pgtype" |
| 17 | + "github.com/jackc/pgx/v5/pgxpool" |
| 18 | + |
| 19 | + actionsdb "github.com/tenseleyFlow/shithub/internal/actions/sqlc" |
| 20 | + "github.com/tenseleyFlow/shithub/internal/checks" |
| 21 | + checksdb "github.com/tenseleyFlow/shithub/internal/checks/sqlc" |
| 22 | + "github.com/tenseleyFlow/shithub/internal/infra/metrics" |
| 23 | +) |
| 24 | + |
| 25 | +const ( |
| 26 | + CancelReasonUser = "user" |
| 27 | + CancelReasonConcurrency = "concurrency" |
| 28 | + CancelReasonTimeout = "timeout" |
| 29 | +) |
| 30 | + |
| 31 | +// Deps wires lifecycle operations to postgres and optional warning logs. |
| 32 | +type Deps struct { |
| 33 | + Pool *pgxpool.Pool |
| 34 | + Logger *slog.Logger |
| 35 | +} |
| 36 | + |
| 37 | +// CancelResult summarizes the durable state changes from a cancel request. |
| 38 | +type CancelResult struct { |
| 39 | + RunID int64 |
| 40 | + ChangedJobs []actionsdb.WorkflowJob |
| 41 | + RunCompleted bool |
| 42 | + RunConclusion actionsdb.CheckConclusion |
| 43 | +} |
| 44 | + |
| 45 | +// CancelRun requests cancellation for every queued/running job in a workflow |
| 46 | +// run. Queued jobs become terminal immediately; running jobs keep running with |
| 47 | +// cancel_requested=true so the runner's cancel-check loop can kill them. |
| 48 | +func CancelRun(ctx context.Context, deps Deps, runID int64, reason string) (CancelResult, error) { |
| 49 | + if deps.Pool == nil { |
| 50 | + return CancelResult{}, errors.New("actions lifecycle: nil Pool") |
| 51 | + } |
| 52 | + q := actionsdb.New() |
| 53 | + tx, err := deps.Pool.Begin(ctx) |
| 54 | + if err != nil { |
| 55 | + return CancelResult{}, err |
| 56 | + } |
| 57 | + committed := false |
| 58 | + defer func() { |
| 59 | + if !committed { |
| 60 | + _ = tx.Rollback(ctx) |
| 61 | + } |
| 62 | + }() |
| 63 | + |
| 64 | + if _, err := q.GetWorkflowRunByID(ctx, tx, runID); err != nil { |
| 65 | + return CancelResult{}, err |
| 66 | + } |
| 67 | + changed, err := q.RequestWorkflowRunCancel(ctx, tx, runID) |
| 68 | + if err != nil { |
| 69 | + return CancelResult{}, err |
| 70 | + } |
| 71 | + for _, job := range changed { |
| 72 | + if job.Status == actionsdb.WorkflowJobStatusCancelled { |
| 73 | + if _, err := q.CancelOpenWorkflowStepsForJob(ctx, tx, job.ID); err != nil { |
| 74 | + return CancelResult{}, err |
| 75 | + } |
| 76 | + } |
| 77 | + } |
| 78 | + var ( |
| 79 | + runCompleted bool |
| 80 | + runConclusion actionsdb.CheckConclusion |
| 81 | + ) |
| 82 | + if len(changed) > 0 { |
| 83 | + runCompleted, runConclusion, err = rollupRunAfterCancel(ctx, q, tx, runID) |
| 84 | + if err != nil { |
| 85 | + return CancelResult{}, err |
| 86 | + } |
| 87 | + } |
| 88 | + if err := tx.Commit(ctx); err != nil { |
| 89 | + return CancelResult{}, err |
| 90 | + } |
| 91 | + committed = true |
| 92 | + |
| 93 | + recordCancelledJobs(changed, reason) |
| 94 | + syncChangedJobChecks(ctx, deps, changed) |
| 95 | + return CancelResult{ |
| 96 | + RunID: runID, |
| 97 | + ChangedJobs: changed, |
| 98 | + RunCompleted: runCompleted, |
| 99 | + RunConclusion: runConclusion, |
| 100 | + }, nil |
| 101 | +} |
| 102 | + |
| 103 | +// CancelJob requests cancellation for one queued/running job. Terminal jobs are |
| 104 | +// a successful no-op so a cancel/complete race does not surface as an error. |
| 105 | +func CancelJob(ctx context.Context, deps Deps, jobID int64, reason string) (CancelResult, error) { |
| 106 | + if deps.Pool == nil { |
| 107 | + return CancelResult{}, errors.New("actions lifecycle: nil Pool") |
| 108 | + } |
| 109 | + q := actionsdb.New() |
| 110 | + tx, err := deps.Pool.Begin(ctx) |
| 111 | + if err != nil { |
| 112 | + return CancelResult{}, err |
| 113 | + } |
| 114 | + committed := false |
| 115 | + defer func() { |
| 116 | + if !committed { |
| 117 | + _ = tx.Rollback(ctx) |
| 118 | + } |
| 119 | + }() |
| 120 | + |
| 121 | + changedJob, err := q.RequestWorkflowJobCancel(ctx, tx, jobID) |
| 122 | + var changed []actionsdb.WorkflowJob |
| 123 | + var runID int64 |
| 124 | + switch { |
| 125 | + case err == nil: |
| 126 | + changed = []actionsdb.WorkflowJob{changedJob} |
| 127 | + runID = changedJob.RunID |
| 128 | + if changedJob.Status == actionsdb.WorkflowJobStatusCancelled { |
| 129 | + if _, err := q.CancelOpenWorkflowStepsForJob(ctx, tx, changedJob.ID); err != nil { |
| 130 | + return CancelResult{}, err |
| 131 | + } |
| 132 | + } |
| 133 | + case errors.Is(err, pgx.ErrNoRows): |
| 134 | + existing, getErr := q.GetWorkflowJobByID(ctx, tx, jobID) |
| 135 | + if getErr != nil { |
| 136 | + return CancelResult{}, getErr |
| 137 | + } |
| 138 | + runID = existing.RunID |
| 139 | + default: |
| 140 | + return CancelResult{}, err |
| 141 | + } |
| 142 | + |
| 143 | + var ( |
| 144 | + runCompleted bool |
| 145 | + runConclusion actionsdb.CheckConclusion |
| 146 | + ) |
| 147 | + if len(changed) > 0 { |
| 148 | + runCompleted, runConclusion, err = rollupRunAfterCancel(ctx, q, tx, runID) |
| 149 | + if err != nil { |
| 150 | + return CancelResult{}, err |
| 151 | + } |
| 152 | + } |
| 153 | + if err := tx.Commit(ctx); err != nil { |
| 154 | + return CancelResult{}, err |
| 155 | + } |
| 156 | + committed = true |
| 157 | + |
| 158 | + recordCancelledJobs(changed, reason) |
| 159 | + syncChangedJobChecks(ctx, deps, changed) |
| 160 | + return CancelResult{ |
| 161 | + RunID: runID, |
| 162 | + ChangedJobs: changed, |
| 163 | + RunCompleted: runCompleted, |
| 164 | + RunConclusion: runConclusion, |
| 165 | + }, nil |
| 166 | +} |
| 167 | + |
| 168 | +func rollupRunAfterCancel( |
| 169 | + ctx context.Context, |
| 170 | + q *actionsdb.Queries, |
| 171 | + tx pgx.Tx, |
| 172 | + runID int64, |
| 173 | +) (bool, actionsdb.CheckConclusion, error) { |
| 174 | + jobs, err := q.ListJobsForRun(ctx, tx, runID) |
| 175 | + if err != nil { |
| 176 | + return false, "", err |
| 177 | + } |
| 178 | + runConclusion, complete := deriveWorkflowRunConclusion(jobs) |
| 179 | + if complete { |
| 180 | + if _, err := q.CompleteWorkflowRun(ctx, tx, actionsdb.CompleteWorkflowRunParams{ |
| 181 | + ID: runID, |
| 182 | + Conclusion: runConclusion, |
| 183 | + }); err != nil { |
| 184 | + return false, "", err |
| 185 | + } |
| 186 | + return true, runConclusion, nil |
| 187 | + } |
| 188 | + if err := q.MarkWorkflowRunRunning(ctx, tx, runID); err != nil { |
| 189 | + return false, "", err |
| 190 | + } |
| 191 | + return false, "", nil |
| 192 | +} |
| 193 | + |
| 194 | +func deriveWorkflowRunConclusion(jobs []actionsdb.ListJobsForRunRow) (actionsdb.CheckConclusion, bool) { |
| 195 | + if len(jobs) == 0 { |
| 196 | + return actionsdb.CheckConclusionFailure, true |
| 197 | + } |
| 198 | + worst := actionsdb.CheckConclusionSuccess |
| 199 | + for _, job := range jobs { |
| 200 | + switch job.Status { |
| 201 | + case actionsdb.WorkflowJobStatusCompleted, actionsdb.WorkflowJobStatusCancelled, actionsdb.WorkflowJobStatusSkipped: |
| 202 | + default: |
| 203 | + return "", false |
| 204 | + } |
| 205 | + if job.Status == actionsdb.WorkflowJobStatusCancelled { |
| 206 | + worst = actionsdb.CheckConclusionCancelled |
| 207 | + continue |
| 208 | + } |
| 209 | + if !job.Conclusion.Valid { |
| 210 | + return actionsdb.CheckConclusionFailure, true |
| 211 | + } |
| 212 | + c := job.Conclusion.CheckConclusion |
| 213 | + if c == actionsdb.CheckConclusionFailure || |
| 214 | + c == actionsdb.CheckConclusionTimedOut || |
| 215 | + c == actionsdb.CheckConclusionActionRequired { |
| 216 | + return c, true |
| 217 | + } |
| 218 | + if c == actionsdb.CheckConclusionCancelled { |
| 219 | + worst = actionsdb.CheckConclusionCancelled |
| 220 | + } |
| 221 | + } |
| 222 | + return worst, true |
| 223 | +} |
| 224 | + |
| 225 | +func recordCancelledJobs(jobs []actionsdb.WorkflowJob, reason string) { |
| 226 | + if len(jobs) == 0 { |
| 227 | + return |
| 228 | + } |
| 229 | + metrics.ActionsJobsCancelledTotal.WithLabelValues(cancelReason(reason)).Add(float64(len(jobs))) |
| 230 | +} |
| 231 | + |
| 232 | +func cancelReason(reason string) string { |
| 233 | + switch strings.TrimSpace(reason) { |
| 234 | + case CancelReasonUser: |
| 235 | + return CancelReasonUser |
| 236 | + case CancelReasonConcurrency: |
| 237 | + return CancelReasonConcurrency |
| 238 | + case CancelReasonTimeout: |
| 239 | + return CancelReasonTimeout |
| 240 | + default: |
| 241 | + return CancelReasonUser |
| 242 | + } |
| 243 | +} |
| 244 | + |
| 245 | +func syncChangedJobChecks(ctx context.Context, deps Deps, jobs []actionsdb.WorkflowJob) { |
| 246 | + for _, job := range jobs { |
| 247 | + if job.Status != actionsdb.WorkflowJobStatusRunning && |
| 248 | + job.Status != actionsdb.WorkflowJobStatusCompleted && |
| 249 | + job.Status != actionsdb.WorkflowJobStatusCancelled { |
| 250 | + continue |
| 251 | + } |
| 252 | + if err := SyncCheckRunForJob(ctx, deps, job); err != nil && deps.Logger != nil { |
| 253 | + deps.Logger.WarnContext(ctx, "actions lifecycle: sync check_run", "job_id", job.ID, "error", err) |
| 254 | + } |
| 255 | + } |
| 256 | +} |
| 257 | + |
| 258 | +// SyncCheckRunForJob mirrors an Actions workflow_job row into its check_run |
| 259 | +// row. Missing check rows are non-fatal because check creation is already |
| 260 | +// best-effort in the trigger path and can be reconciled independently. |
| 261 | +func SyncCheckRunForJob(ctx context.Context, deps Deps, job actionsdb.WorkflowJob) error { |
| 262 | + if deps.Pool == nil { |
| 263 | + return errors.New("actions lifecycle: nil Pool") |
| 264 | + } |
| 265 | + run, err := actionsdb.New().GetWorkflowRunByID(ctx, deps.Pool, job.RunID) |
| 266 | + if err != nil { |
| 267 | + return err |
| 268 | + } |
| 269 | + name := strings.TrimSpace(job.JobName) |
| 270 | + if name == "" { |
| 271 | + name = job.JobKey |
| 272 | + } |
| 273 | + checkRun, err := checksdb.New().GetCheckRunByExternalID(ctx, deps.Pool, checksdb.GetCheckRunByExternalIDParams{ |
| 274 | + RepoID: run.RepoID, |
| 275 | + HeadSha: run.HeadSha, |
| 276 | + Name: name, |
| 277 | + ExternalID: pgtype.Text{String: fmt.Sprintf("workflow_run:%d:job:%s", job.RunID, job.JobKey), Valid: true}, |
| 278 | + }) |
| 279 | + if err != nil { |
| 280 | + if errors.Is(err, pgx.ErrNoRows) { |
| 281 | + return nil |
| 282 | + } |
| 283 | + return err |
| 284 | + } |
| 285 | + params := checks.UpdateParams{ |
| 286 | + RunID: checkRun.ID, |
| 287 | + HasStatus: true, |
| 288 | + HasStartedAt: true, |
| 289 | + StartedAt: timeFromPg(job.StartedAt), |
| 290 | + } |
| 291 | + switch job.Status { |
| 292 | + case actionsdb.WorkflowJobStatusRunning: |
| 293 | + params.Status = "in_progress" |
| 294 | + case actionsdb.WorkflowJobStatusCompleted, actionsdb.WorkflowJobStatusCancelled: |
| 295 | + params.Status = "completed" |
| 296 | + params.HasConclusion = true |
| 297 | + if job.Conclusion.Valid { |
| 298 | + params.Conclusion = string(job.Conclusion.CheckConclusion) |
| 299 | + } else if job.Status == actionsdb.WorkflowJobStatusCancelled { |
| 300 | + params.Conclusion = string(actionsdb.CheckConclusionCancelled) |
| 301 | + } |
| 302 | + params.HasCompletedAt = true |
| 303 | + params.CompletedAt = timeFromPg(job.CompletedAt) |
| 304 | + default: |
| 305 | + return nil |
| 306 | + } |
| 307 | + _, err = checks.Update(ctx, checks.Deps{Pool: deps.Pool, Logger: deps.Logger}, params) |
| 308 | + return err |
| 309 | +} |
| 310 | + |
| 311 | +func timeFromPg(ts pgtype.Timestamptz) time.Time { |
| 312 | + if !ts.Valid { |
| 313 | + return time.Time{} |
| 314 | + } |
| 315 | + return ts.Time |
| 316 | +} |