| 1 | package team |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "database/sql" |
| 7 | "encoding/json" |
| 8 | "errors" |
| 9 | "fmt" |
| 10 | "io" |
| 11 | "reflect" |
| 12 | "sort" |
| 13 | "time" |
| 14 | ) |
| 15 | |
| 16 | // JobSpec is a job creation request. GrantRef names the console grant the |
| 17 | // job runs under; Open-time Authority introspection records its current |
| 18 | // version and epoch as the job's snapshot. Parent, when set, must be a |
| 19 | // non-terminal job of the same account within the policy's depth. |
| 20 | type JobSpec struct { |
| 21 | RequestKey string |
| 22 | Project ProjectID |
| 23 | Account AccountID |
| 24 | Parent JobID |
| 25 | Requester string |
| 26 | GrantRef string |
| 27 | Target TargetBinding |
| 28 | Evidence EvidenceRequirement |
| 29 | Policy Policy |
| 30 | Steps []StepSpec |
| 31 | } |
| 32 | |
| 33 | func (js JobSpec) validate() error { |
| 34 | if js.Evidence.FrozenAcceptanceHash != "" || js.Evidence.RenderedApprovalHash != "" || len(js.Evidence.RenderedApprovals) > 0 { |
| 35 | return ErrInvalid |
| 36 | } |
| 37 | if js.Policy.Version == 2 && js.Target.Kind != TargetConversation && js.Project <= 0 && js.Parent == 0 { |
| 38 | return ErrBudget |
| 39 | } |
| 40 | if js.Target.Kind == TargetConversation && (js.Project != 0 || js.Parent != 0 || js.Target.Subject != js.Requester || len(js.Steps) != 1) { |
| 41 | return ErrInvalid |
| 42 | } |
| 43 | if js.Account == "" || js.Requester == "" || js.GrantRef == "" { |
| 44 | return fail(CodeInvalid, "job needs account, requester and grant") |
| 45 | } |
| 46 | if err := js.Target.validate(); err != nil { |
| 47 | return err |
| 48 | } |
| 49 | if err := js.Evidence.validate(js.Target.Kind); err != nil { |
| 50 | return err |
| 51 | } |
| 52 | if err := js.Policy.Validate(); err != nil { |
| 53 | return err |
| 54 | } |
| 55 | if err := validateTargetSteps(js.Target, js.Evidence, js.Policy, js.Steps); err != nil { |
| 56 | return err |
| 57 | } |
| 58 | return validateGraph(js.Steps) |
| 59 | } |
| 60 | |
| 61 | // validateGraph checks keys, capabilities, dependency references, the step |
| 62 | // cap and acyclicity (Kahn). |
| 63 | func validateGraph(steps []StepSpec) error { |
| 64 | if len(steps) == 0 || len(steps) > MaxSteps { |
| 65 | return fail(CodeInvalid, "job needs 1..%d steps", MaxSteps) |
| 66 | } |
| 67 | idx := map[string]int{} |
| 68 | for i, st := range steps { |
| 69 | if st.Key == "" { |
| 70 | return fail(CodeInvalid, "step %d without key", i) |
| 71 | } |
| 72 | if _, dup := idx[st.Key]; dup { |
| 73 | return fail(CodeConflict, "duplicate step key %q", st.Key) |
| 74 | } |
| 75 | if !st.Capability.Valid() { |
| 76 | return fail(CodeUnknownKind, "capability %q", st.Capability) |
| 77 | } |
| 78 | if st.Version <= 0 { |
| 79 | return fail(CodeInvalid, "step %q needs a positive version", st.Key) |
| 80 | } |
| 81 | idx[st.Key] = i |
| 82 | } |
| 83 | indeg := make([]int, len(steps)) |
| 84 | out := make([][]int, len(steps)) |
| 85 | for i, st := range steps { |
| 86 | for _, d := range st.DependsOn { |
| 87 | j, ok := idx[d] |
| 88 | if !ok { |
| 89 | return fail(CodeDependency, "step %q depends on unknown %q", st.Key, d) |
| 90 | } |
| 91 | if j == i { |
| 92 | return fail(CodeDependency, "step %q depends on itself", st.Key) |
| 93 | } |
| 94 | indeg[i]++ |
| 95 | out[j] = append(out[j], i) |
| 96 | } |
| 97 | } |
| 98 | var queue []int |
| 99 | for i, d := range indeg { |
| 100 | if d == 0 { |
| 101 | queue = append(queue, i) |
| 102 | } |
| 103 | } |
| 104 | seen := 0 |
| 105 | for len(queue) > 0 { |
| 106 | n := queue[0] |
| 107 | queue = queue[1:] |
| 108 | seen++ |
| 109 | for _, m := range out[n] { |
| 110 | indeg[m]-- |
| 111 | if indeg[m] == 0 { |
| 112 | queue = append(queue, m) |
| 113 | } |
| 114 | } |
| 115 | } |
| 116 | if seen != len(steps) { |
| 117 | return fail(CodeDependency, "step graph has a cycle") |
| 118 | } |
| 119 | return nil |
| 120 | } |
| 121 | |
| 122 | // CreateJob records a job and its steps. The grant is introspected online |
| 123 | // before the transaction; a revoked or uncovered grant refuses creation |
| 124 | // and an unavailable authority decides nothing. |
| 125 | func (s *Store) CreateJob(ctx context.Context, spec JobSpec) (Job, error) { |
| 126 | if err := spec.validate(); err != nil { |
| 127 | return Job{}, err |
| 128 | } |
| 129 | if spec.Parent != 0 && spec.Project == 0 { |
| 130 | parent, err := s.GetJob(ctx, Scope{spec.Account, spec.Parent}) |
| 131 | if err != nil { |
| 132 | return Job{}, err |
| 133 | } |
| 134 | spec.Project = parent.Project |
| 135 | } |
| 136 | adm, err := s.auth.Introspect(ctx, AdmissionRequest{Grant: spec.GrantRef, Account: spec.Account, Project: spec.Project, Target: spec.Target, Operation: OpJobContinue}) |
| 137 | if err != nil { |
| 138 | return Job{}, err |
| 139 | } |
| 140 | // Canonicalize graph order and empty dependencies without changing caller slices. |
| 141 | canonicalSpec := spec |
| 142 | canonicalSpec.Steps = append([]StepSpec(nil), spec.Steps...) |
| 143 | for i := range canonicalSpec.Steps { |
| 144 | deps := append([]string{}, canonicalSpec.Steps[i].DependsOn...) |
| 145 | sort.Strings(deps) |
| 146 | canonicalSpec.Steps[i].DependsOn = deps |
| 147 | } |
| 148 | sort.Slice(canonicalSpec.Steps, func(i, j int) bool { return canonicalSpec.Steps[i].Key < canonicalSpec.Steps[j].Key }) |
| 149 | input, err := json.Marshal(canonicalSpec) |
| 150 | if err != nil { |
| 151 | return Job{}, err |
| 152 | } |
| 153 | inputHash := hashBytes(input) |
| 154 | now := s.clock.Now() |
| 155 | target, _ := json.Marshal(spec.Target) |
| 156 | evidence, _ := json.Marshal(spec.Evidence) |
| 157 | policy, _ := json.Marshal(spec.Policy) |
| 158 | var job Job |
| 159 | err = s.tx(ctx, func(tx *sql.Tx) error { |
| 160 | if spec.RequestKey != "" { |
| 161 | var id JobID |
| 162 | var savedHash string |
| 163 | err := tx.QueryRowContext(ctx, `SELECT id, request_hash FROM jobs WHERE account=? AND requester=? AND request_key=?`, spec.Account, spec.Requester, spec.RequestKey).Scan(&id, &savedHash) |
| 164 | if err == nil { |
| 165 | if savedHash != inputHash { |
| 166 | return fail(CodeConflict, "job request input changed") |
| 167 | } |
| 168 | prior, err := loadJob(ctx, tx, Scope{Account: spec.Account, Job: id}) |
| 169 | job = prior.Job |
| 170 | return err |
| 171 | } |
| 172 | if !errors.Is(err, sql.ErrNoRows) { |
| 173 | return err |
| 174 | } |
| 175 | } |
| 176 | if err := admissionOpen(ctx, tx); err != nil { |
| 177 | return err |
| 178 | } |
| 179 | if err := checkGrantFence(ctx, tx, adm); err != nil { |
| 180 | return err |
| 181 | } |
| 182 | _, configuredAccount, err := loadBudgets(ctx, tx, spec.Account) |
| 183 | if err != nil { |
| 184 | return err |
| 185 | } |
| 186 | if !configuredAccount && spec.Policy.Version == 2 { |
| 187 | return ErrBudget |
| 188 | } |
| 189 | if !configuredAccount { |
| 190 | account, err := accountPolicy(ctx, tx, spec.Account) |
| 191 | if err != nil && !errors.Is(err, sql.ErrNoRows) { |
| 192 | return err |
| 193 | } |
| 194 | if err == nil && spec.Policy.Account != account.Account { |
| 195 | return fail(CodeConflict, "job cannot change the account budget") |
| 196 | } |
| 197 | if err == nil && (spec.Policy.Rates != account.Rates || spec.Policy.PerCall != account.PerCall || spec.Policy.UsageMode != account.UsageMode) { |
| 198 | return fail(CodeConflict, "job cannot change account prices or per-call ceilings") |
| 199 | } |
| 200 | } |
| 201 | depth := 0 |
| 202 | if spec.Parent != 0 { |
| 203 | parent, err := loadJob(ctx, tx, Scope{Account: spec.Account, Job: spec.Parent}) |
| 204 | if err != nil { |
| 205 | return err |
| 206 | } |
| 207 | if parent.State.Terminal() { |
| 208 | return fail(CodeState, "parent job is %s", parent.State) |
| 209 | } |
| 210 | if spec.Project != 0 && spec.Project != parent.Project { |
| 211 | return fail(CodeInvalid, "child must keep parent project") |
| 212 | } |
| 213 | spec.Project = parent.Project |
| 214 | depth = parent.depth + 1 |
| 215 | if depth > spec.Policy.MaxDepth || depth > parent.Policy.MaxDepth { |
| 216 | return fail(CodeQuota, "job depth %d exceeds policy depth %d", depth, spec.Policy.MaxDepth) |
| 217 | } |
| 218 | } |
| 219 | _, configured, err := loadBudgets(ctx, tx, spec.Account) |
| 220 | if err != nil { |
| 221 | return err |
| 222 | } |
| 223 | if spec.Target.Kind == TargetConversation { |
| 224 | if !configured { |
| 225 | return ErrBudget |
| 226 | } |
| 227 | if _, _, err := coordinatorLimit(ctx, tx, spec.Account, spec.Requester); err != nil { |
| 228 | return err |
| 229 | } |
| 230 | } else if configured { |
| 231 | if spec.Project <= 0 { |
| 232 | return fail(CodeBudget, "job needs configured project") |
| 233 | } |
| 234 | } |
| 235 | if spec.Project < 0 { |
| 236 | return fail(CodeInvalid, "negative project") |
| 237 | } |
| 238 | res, err := tx.ExecContext(ctx, `INSERT INTO jobs(request_key, request_hash, project_id, account, parent, depth, requester, target, evidence, policy_version, policy, |
| 239 | grant_ref, grant_version, grant_epoch, grant_observed_at, state, wait, revision, outcome, created_at, updated_at) |
| 240 | VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,1,'',?,?)`, |
| 241 | spec.RequestKey, inputHash, int64(spec.Project), string(spec.Account), int64(spec.Parent), depth, spec.Requester, string(target), string(evidence), spec.Policy.Version, string(policy), |
| 242 | spec.GrantRef, adm.Version, adm.Epoch, ts(now), string(JobQueued), "", ts(now), ts(now)) |
| 243 | if err != nil { |
| 244 | return fail(CodeInvalid, "insert job: %v", err) |
| 245 | } |
| 246 | id, _ := res.LastInsertId() |
| 247 | for _, st := range spec.Steps { |
| 248 | deps, _ := json.Marshal(st.DependsOn) |
| 249 | if st.DependsOn == nil { |
| 250 | deps = []byte("[]") |
| 251 | } |
| 252 | if _, err := tx.ExecContext(ctx, `INSERT INTO steps(job_id, key, capability, version, depends_on, state, fence, holder, attempts) |
| 253 | VALUES (?,?,?,?,?,?,0,0,0)`, id, st.Key, string(st.Capability), st.Version, string(deps), string(StepPending)); err != nil { |
| 254 | return fail(CodeInvalid, "insert step: %v", err) |
| 255 | } |
| 256 | } |
| 257 | scope := Scope{Account: spec.Account, Job: JobID(id)} |
| 258 | if err := appendEvent(ctx, tx, scope, "job.created", spec.Requester, map[string]any{"grant": spec.GrantRef, "grant_version": adm.Version, "steps": len(spec.Steps)}, now); err != nil { |
| 259 | return err |
| 260 | } |
| 261 | j, err := loadJob(ctx, tx, scope) |
| 262 | if err != nil { |
| 263 | return err |
| 264 | } |
| 265 | job = j.Job |
| 266 | return nil |
| 267 | }) |
| 268 | return job, err |
| 269 | } |
| 270 | |
| 271 | // The first job fixes an account's budget and concurrency ceiling for this |
| 272 | // local store. Later jobs cannot enlarge it. Account-policy administration |
| 273 | // belongs to the future owner-gated service API, not to job proposals. |
| 274 | func accountPolicy(ctx context.Context, tx *sql.Tx, account AccountID) (Policy, error) { |
| 275 | var raw []byte |
| 276 | if err := tx.QueryRowContext(ctx, `SELECT policy FROM jobs WHERE account=? ORDER BY id LIMIT 1`, string(account)).Scan(&raw); err != nil { |
| 277 | return Policy{}, err |
| 278 | } |
| 279 | return ParsePolicy(raw) |
| 280 | } |
| 281 | |
| 282 | // jobRow is a Job plus the depth column used for nesting checks. |
| 283 | type jobRow struct { |
| 284 | grantStale bool |
| 285 | Job |
| 286 | depth int |
| 287 | } |
| 288 | |
| 289 | const jobColumns = `grant_stale, id, project_id, account, parent, depth, requester, target, evidence, policy_version, policy, grant_ref, grant_version, grant_epoch, grant_observed_at, state, wait, revision, outcome, created_at, updated_at` |
| 290 | |
| 291 | type rowScanner interface { |
| 292 | Scan(dest ...any) error |
| 293 | } |
| 294 | |
| 295 | func scanJob(r rowScanner) (jobRow, error) { |
| 296 | var j jobRow |
| 297 | var target, evidence, policy, state, wait, observed, created, updated string |
| 298 | var parent int64 |
| 299 | err := r.Scan(&j.grantStale, &j.ID, &j.Project, &j.Account, &parent, &j.depth, &j.Requester, &target, &evidence, &j.PolicyVersion, &policy, |
| 300 | &j.Grant.Ref, &j.Grant.Version, &j.Grant.Epoch, &observed, &state, &wait, &j.Revision, &j.Outcome, &created, &updated) |
| 301 | if err != nil { |
| 302 | return j, err |
| 303 | } |
| 304 | j.Parent = JobID(parent) |
| 305 | j.State, j.Wait = JobState(state), WaitReason(wait) |
| 306 | if !j.State.Valid() || !j.Wait.Valid() { |
| 307 | return j, fail(CodeUnknownKind, "job %d stored state %q/%q", j.ID, state, wait) |
| 308 | } |
| 309 | if j.PolicyVersion != 1 && j.PolicyVersion != PolicyVersion { |
| 310 | return j, fail(CodeUnknownKind, "job %d policy version %d", j.ID, j.PolicyVersion) |
| 311 | } |
| 312 | if err := strictJSON([]byte(target), &j.Target); err != nil { |
| 313 | return j, fail(CodeUnknownKind, "job %d target: %v", j.ID, err) |
| 314 | } |
| 315 | if err := j.Target.validate(); err != nil { |
| 316 | return j, err |
| 317 | } |
| 318 | if err := strictJSON([]byte(evidence), &j.Evidence); err != nil { |
| 319 | return j, fail(CodeUnknownKind, "job %d evidence: %v", j.ID, err) |
| 320 | } |
| 321 | if err := j.Evidence.validate(j.Target.Kind); err != nil { |
| 322 | return j, err |
| 323 | } |
| 324 | p, err := ParsePolicy([]byte(policy)) |
| 325 | if err != nil { |
| 326 | return j, err |
| 327 | } |
| 328 | if p.Version != j.PolicyVersion { |
| 329 | return j, fail(CodeInvalid, "policy version mismatch") |
| 330 | } |
| 331 | j.Policy = p |
| 332 | j.Grant.ObservedAt = parseTS(observed) |
| 333 | j.CreatedAt, j.UpdatedAt = parseTS(created), parseTS(updated) |
| 334 | return j, nil |
| 335 | } |
| 336 | |
| 337 | // loadJob reads the job in scope. A job in another account answers ErrScope |
| 338 | // exactly like a job that does not exist. |
| 339 | func loadJob(ctx context.Context, tx *sql.Tx, scope Scope) (jobRow, error) { |
| 340 | if err := scope.validate(); err != nil { |
| 341 | return jobRow{}, err |
| 342 | } |
| 343 | j, err := scanJob(tx.QueryRowContext(ctx, `SELECT `+jobColumns+` FROM jobs WHERE id=? AND account=?`, int64(scope.Job), string(scope.Account))) |
| 344 | if errors.Is(err, sql.ErrNoRows) { |
| 345 | return jobRow{}, fail(CodeScope, "job %d", scope.Job) |
| 346 | } |
| 347 | return j, err |
| 348 | } |
| 349 | |
| 350 | // GetJob reads a job. |
| 351 | func (s *Store) GetJob(ctx context.Context, scope Scope) (Job, error) { |
| 352 | var job Job |
| 353 | err := s.read(ctx, func(tx *sql.Tx) error { |
| 354 | j, err := loadJob(ctx, tx, scope) |
| 355 | job = j.Job |
| 356 | return err |
| 357 | }) |
| 358 | return job, err |
| 359 | } |
| 360 | |
| 361 | // bumpJob advances the revision and writes the state. expected must match |
| 362 | // the stored revision (ErrRevision) so two concurrent transitions cannot |
| 363 | // both believe they moved the job. |
| 364 | func bumpJob(ctx context.Context, tx *sql.Tx, j jobRow, state JobState, wait WaitReason, outcome string, now time.Time) (jobRow, error) { |
| 365 | if !state.Valid() || !wait.Valid() { |
| 366 | return j, fail(CodeUnknownKind, "state %q/%q", state, wait) |
| 367 | } |
| 368 | if j.State.Terminal() { |
| 369 | return j, fail(CodeState, "job %d is %s", j.ID, j.State) |
| 370 | } |
| 371 | res, err := tx.ExecContext(ctx, `UPDATE jobs SET state=?, wait=?, outcome=?, revision=revision+1, updated_at=? WHERE id=? AND revision=?`, |
| 372 | string(state), string(wait), outcome, ts(now), int64(j.ID), j.Revision) |
| 373 | if err != nil { |
| 374 | return j, fail(CodeInvalid, "update job: %v", err) |
| 375 | } |
| 376 | if n, _ := res.RowsAffected(); n != 1 { |
| 377 | return j, fail(CodeRevision, "job %d moved from revision %d", j.ID, j.Revision) |
| 378 | } |
| 379 | j.State, j.Wait, j.Outcome, j.Revision, j.UpdatedAt = state, wait, outcome, j.Revision+1, now |
| 380 | return j, nil |
| 381 | } |
| 382 | |
| 383 | // appendEvent writes the next event of the job's log inside tx. |
| 384 | func appendEvent(ctx context.Context, tx *sql.Tx, scope Scope, typ, actor string, payload any, now time.Time) error { |
| 385 | if err := advanceRecovery(ctx, tx); err != nil { |
| 386 | return err |
| 387 | } |
| 388 | raw, err := json.Marshal(payload) |
| 389 | if err != nil { |
| 390 | return fail(CodeInvalid, "event payload: %v", err) |
| 391 | } |
| 392 | if len(raw) > MaxEventBytes { |
| 393 | return fail(CodeSize, "event payload %d bytes", len(raw)) |
| 394 | } |
| 395 | _, err = tx.ExecContext(ctx, `INSERT INTO events(job_id, seq, type, actor, payload, source_at) |
| 396 | SELECT ?, COALESCE(MAX(seq),0)+1, ?, ?, ?, ? FROM events WHERE job_id=?`, int64(scope.Job), typ, actor, raw, ts(now), int64(scope.Job)) |
| 397 | if err != nil { |
| 398 | return fail(CodeInvalid, "append event: %v", err) |
| 399 | } |
| 400 | return nil |
| 401 | } |
| 402 | |
| 403 | // Events returns the job's log after seq, in order. |
| 404 | func (s *Store) Events(ctx context.Context, scope Scope, after int64) ([]Event, error) { |
| 405 | var out []Event |
| 406 | err := s.read(ctx, func(tx *sql.Tx) error { |
| 407 | if _, err := loadJob(ctx, tx, scope); err != nil { |
| 408 | return err |
| 409 | } |
| 410 | rows, err := tx.QueryContext(ctx, `SELECT seq, type, actor, payload, source_at FROM events WHERE job_id=? AND seq>? ORDER BY seq`, int64(scope.Job), after) |
| 411 | if err != nil { |
| 412 | return fail(CodeInvalid, "events: %v", err) |
| 413 | } |
| 414 | defer rows.Close() |
| 415 | for rows.Next() { |
| 416 | var e Event |
| 417 | var at string |
| 418 | if err := rows.Scan(&e.Seq, &e.Type, &e.Actor, &e.Payload, &at); err != nil { |
| 419 | return fail(CodeInvalid, "events: %v", err) |
| 420 | } |
| 421 | e.Job, e.SourceAt = scope.Job, parseTS(at) |
| 422 | out = append(out, e) |
| 423 | } |
| 424 | return rows.Err() |
| 425 | }) |
| 426 | return out, err |
| 427 | } |
| 428 | |
| 429 | const stepColumns = `id, job_id, key, capability, version, depends_on, state, fence, holder, attempts` |
| 430 | |
| 431 | func scanStep(r rowScanner) (Step, error) { |
| 432 | var st Step |
| 433 | var cap, deps, state string |
| 434 | var holder int64 |
| 435 | if err := r.Scan(&st.ID, &st.Job, &st.Key, &cap, &st.Version, &deps, &state, &st.Fence, &holder, &st.Attempts); err != nil { |
| 436 | return st, err |
| 437 | } |
| 438 | st.Capability, st.State, st.Holder = Capability(cap), StepState(state), AttemptID(holder) |
| 439 | if !st.Capability.Valid() || !st.State.Valid() { |
| 440 | return st, fail(CodeUnknownKind, "step %d stored %q/%q", st.ID, cap, state) |
| 441 | } |
| 442 | if err := json.Unmarshal([]byte(deps), &st.DependsOn); err != nil { |
| 443 | return st, fail(CodeUnknownKind, "step %d depends_on: %v", st.ID, err) |
| 444 | } |
| 445 | return st, nil |
| 446 | } |
| 447 | |
| 448 | func loadSteps(ctx context.Context, tx *sql.Tx, job JobID) ([]Step, error) { |
| 449 | rows, err := tx.QueryContext(ctx, `SELECT `+stepColumns+` FROM steps WHERE job_id=? ORDER BY id`, int64(job)) |
| 450 | if err != nil { |
| 451 | return nil, fail(CodeInvalid, "steps: %v", err) |
| 452 | } |
| 453 | defer rows.Close() |
| 454 | var out []Step |
| 455 | for rows.Next() { |
| 456 | st, err := scanStep(rows) |
| 457 | if err != nil { |
| 458 | return nil, err |
| 459 | } |
| 460 | out = append(out, st) |
| 461 | } |
| 462 | return out, rows.Err() |
| 463 | } |
| 464 | |
| 465 | func loadStepByKey(ctx context.Context, tx *sql.Tx, job JobID, key string) (Step, error) { |
| 466 | st, err := scanStep(tx.QueryRowContext(ctx, `SELECT `+stepColumns+` FROM steps WHERE job_id=? AND key=?`, int64(job), key)) |
| 467 | if errors.Is(err, sql.ErrNoRows) { |
| 468 | return st, fail(CodeScope, "step %q", key) |
| 469 | } |
| 470 | return st, err |
| 471 | } |
| 472 | |
| 473 | func loadStep(ctx context.Context, tx *sql.Tx, job JobID, id StepID) (Step, error) { |
| 474 | st, err := scanStep(tx.QueryRowContext(ctx, `SELECT `+stepColumns+` FROM steps WHERE job_id=? AND id=?`, int64(job), int64(id))) |
| 475 | if errors.Is(err, sql.ErrNoRows) { |
| 476 | return st, fail(CodeScope, "step %d", id) |
| 477 | } |
| 478 | return st, err |
| 479 | } |
| 480 | |
| 481 | // Steps lists the job's steps. |
| 482 | func (s *Store) Steps(ctx context.Context, scope Scope) ([]Step, error) { |
| 483 | var out []Step |
| 484 | err := s.read(ctx, func(tx *sql.Tx) error { |
| 485 | if _, err := loadJob(ctx, tx, scope); err != nil { |
| 486 | return err |
| 487 | } |
| 488 | var err error |
| 489 | out, err = loadSteps(ctx, tx, scope.Job) |
| 490 | return err |
| 491 | }) |
| 492 | return out, err |
| 493 | } |
| 494 | |
| 495 | // Cancel ends the job. In one transaction it moves the job to cancelled, |
| 496 | // bumps every step's fence (so no live handle is current any more), |
| 497 | // records a pending stop on every live attempt, revokes actions still at |
| 498 | // intent and releases their reservations. Actions already dispatching or |
| 499 | // uncertain are reported as in flight; their reservations stay open and |
| 500 | // their receipts are still accepted later. Stops are pending until the |
| 501 | // supervisor calls Contain. |
| 502 | func (s *Store) Cancel(ctx context.Context, scope Scope, actor, reason string) (CancelReport, error) { |
| 503 | var rep CancelReport |
| 504 | err := s.tx(ctx, func(tx *sql.Tx) error { |
| 505 | j, err := loadJob(ctx, tx, scope) |
| 506 | if err != nil { |
| 507 | return err |
| 508 | } |
| 509 | r, err := terminate(ctx, tx, j, JobCancelled, actor, reason, s.clock.Now()) |
| 510 | rep = r |
| 511 | return err |
| 512 | }) |
| 513 | return rep, err |
| 514 | } |
| 515 | |
| 516 | // terminate is the shared end path for cancel, observed revocation and |
| 517 | // failure: the job becomes terminal and every live piece is fenced out. |
| 518 | func terminate(ctx context.Context, tx *sql.Tx, j jobRow, state JobState, actor, reason string, now time.Time) (CancelReport, error) { |
| 519 | if !state.Terminal() { |
| 520 | return CancelReport{}, fail(CodeInvalid, "terminate to %s", state) |
| 521 | } |
| 522 | j, err := bumpJob(ctx, tx, j, state, WaitNone, reason, now) |
| 523 | if err != nil { |
| 524 | return CancelReport{}, err |
| 525 | } |
| 526 | rep := CancelReport{Job: j.ID, Revision: j.Revision} |
| 527 | stepState := StepCancelled |
| 528 | if state == JobFailed { |
| 529 | stepState = StepFailed |
| 530 | } |
| 531 | if _, err := tx.ExecContext(ctx, `UPDATE steps SET fence=fence+1, holder=0, state=? WHERE job_id=? AND state IN ('pending','running')`, string(stepState), int64(j.ID)); err != nil { |
| 532 | return rep, fail(CodeInvalid, "fence steps: %v", err) |
| 533 | } |
| 534 | rows, err := tx.QueryContext(ctx, `SELECT id FROM attempts WHERE job_id=? AND state IN ('active','stopping','expired') AND containment='pending'`, int64(j.ID)) |
| 535 | if err != nil { |
| 536 | return rep, fail(CodeInvalid, "attempts: %v", err) |
| 537 | } |
| 538 | for rows.Next() { |
| 539 | var id int64 |
| 540 | if err := rows.Scan(&id); err != nil { |
| 541 | rows.Close() |
| 542 | return rep, fail(CodeInvalid, "attempts: %v", err) |
| 543 | } |
| 544 | rep.StopsPending = append(rep.StopsPending, AttemptID(id)) |
| 545 | } |
| 546 | rows.Close() |
| 547 | if _, err := tx.ExecContext(ctx, `UPDATE attempts SET state='stopping', stop_requested=?, updated_at=? WHERE job_id=? AND state='active'`, ts(now), ts(now), int64(j.ID)); err != nil { |
| 548 | return rep, fail(CodeInvalid, "stop attempts: %v", err) |
| 549 | } |
| 550 | // Intents never dispatched: revoke and release. |
| 551 | arows, err := tx.QueryContext(ctx, `SELECT id, state, reservation_id FROM actions WHERE job_id=? AND state IN ('intent','dispatching','uncertain')`, int64(j.ID)) |
| 552 | if err != nil { |
| 553 | return rep, fail(CodeInvalid, "actions: %v", err) |
| 554 | } |
| 555 | type pending struct { |
| 556 | id, res int64 |
| 557 | state string |
| 558 | } |
| 559 | var ps []pending |
| 560 | for arows.Next() { |
| 561 | var p pending |
| 562 | if err := arows.Scan(&p.id, &p.state, &p.res); err != nil { |
| 563 | arows.Close() |
| 564 | return rep, fail(CodeInvalid, "actions: %v", err) |
| 565 | } |
| 566 | ps = append(ps, p) |
| 567 | } |
| 568 | arows.Close() |
| 569 | for _, p := range ps { |
| 570 | if ActionState(p.state) == ActionIntent { |
| 571 | if _, err := tx.ExecContext(ctx, `UPDATE actions SET state='revoked', updated_at=? WHERE id=?`, ts(now), p.id); err != nil { |
| 572 | return rep, fail(CodeInvalid, "revoke action: %v", err) |
| 573 | } |
| 574 | if _, err := tx.ExecContext(ctx, `UPDATE reservations SET state='released', settled_at=? WHERE id=? AND state='open'`, ts(now), p.res); err != nil { |
| 575 | return rep, fail(CodeInvalid, "release reservation: %v", err) |
| 576 | } |
| 577 | rep.Revoked = append(rep.Revoked, ActionID(p.id)) |
| 578 | } else { |
| 579 | rep.InFlight = append(rep.InFlight, ActionID(p.id)) |
| 580 | } |
| 581 | } |
| 582 | sum, err := ledgerSum(ctx, tx, `job_id=?`, int64(j.ID)) |
| 583 | if err != nil { |
| 584 | return rep, err |
| 585 | } |
| 586 | rep.OpenReserved = sum.Reserved |
| 587 | if err := appendEvent(ctx, tx, Scope{Account: j.Account, Job: j.ID}, "job."+string(state), actor, |
| 588 | map[string]any{"reason": reason, "stops_pending": len(rep.StopsPending), "in_flight": len(rep.InFlight), "revoked": len(rep.Revoked)}, now); err != nil { |
| 589 | return rep, err |
| 590 | } |
| 591 | // Parent cancellation/failure revokes its delegated work in this same |
| 592 | // transaction. Keep each child's scope in the report for stop acknowledgements. |
| 593 | childRows, err := tx.QueryContext(ctx, `SELECT `+jobColumns+` FROM jobs WHERE account=? AND parent=? AND state NOT IN ('succeeded','failed','cancelled') ORDER BY id`, string(j.Account), int64(j.ID)) |
| 594 | if err != nil { |
| 595 | return rep, err |
| 596 | } |
| 597 | var children []jobRow |
| 598 | for childRows.Next() { |
| 599 | child, err := scanJob(childRows) |
| 600 | if err != nil { |
| 601 | childRows.Close() |
| 602 | return rep, err |
| 603 | } |
| 604 | children = append(children, child) |
| 605 | } |
| 606 | err = childRows.Err() |
| 607 | childRows.Close() |
| 608 | if err != nil { |
| 609 | return rep, err |
| 610 | } |
| 611 | for _, child := range children { |
| 612 | stopped, err := terminate(ctx, tx, child, JobCancelled, actor, fmt.Sprintf("parent %d terminated: %s", j.ID, reason), now) |
| 613 | if err != nil { |
| 614 | return rep, err |
| 615 | } |
| 616 | rep.Children = append(rep.Children, stopped) |
| 617 | } |
| 618 | return rep, nil |
| 619 | } |
| 620 | |
| 621 | // strictJSON decodes one JSON value refusing unknown fields and trailing |
| 622 | // data, so a stored or supplied record with a field this binary does not |
| 623 | // know fails closed. |
| 624 | func strictJSON(raw []byte, v any) error { |
| 625 | dec := json.NewDecoder(bytes.NewReader(raw)) |
| 626 | dec.DisallowUnknownFields() |
| 627 | if err := dec.Decode(v); err != nil { |
| 628 | return err |
| 629 | } |
| 630 | return jsonEnd(dec) |
| 631 | } |
| 632 | |
| 633 | func jsonEnd(dec *json.Decoder) error { |
| 634 | var extra any |
| 635 | err := dec.Decode(&extra) |
| 636 | if errors.Is(err, io.EOF) { |
| 637 | return nil |
| 638 | } |
| 639 | if err == nil { |
| 640 | return fmt.Errorf("trailing JSON value") |
| 641 | } |
| 642 | return fmt.Errorf("trailing data: %w", err) |
| 643 | } |
| 644 | |
| 645 | type PlanChange struct { |
| 646 | Append, Replace []StepSpec |
| 647 | Cancel, Order []string |
| 648 | } |
| 649 | |
| 650 | func (s *Store) EditUnstarted(ctx context.Context, scope Scope, expectedRevision int64, change PlanChange) (Job, error) { |
| 651 | var result Job |
| 652 | err := s.tx(ctx, func(tx *sql.Tx) error { |
| 653 | j, err := loadJob(ctx, tx, scope) |
| 654 | if err != nil { |
| 655 | return err |
| 656 | } |
| 657 | if expectedRevision <= 0 || j.Revision != expectedRevision { |
| 658 | return ErrRevision |
| 659 | } |
| 660 | if j.State.Terminal() { |
| 661 | return ErrState |
| 662 | } |
| 663 | adm, err := s.auth.Introspect(ctx, AdmissionRequest{Grant: j.Grant.Ref, Account: j.Account, Project: j.Project, Target: j.Target, Operation: OpJobContinue}) |
| 664 | if err != nil { |
| 665 | return err |
| 666 | } |
| 667 | if err = checkGrantFence(ctx, tx, adm); err != nil { |
| 668 | return err |
| 669 | } |
| 670 | if err = checkAdmission(j, adm, s.clock.Now()); err != nil { |
| 671 | return err |
| 672 | } |
| 673 | old, err := loadSteps(ctx, tx, j.ID) |
| 674 | if err != nil { |
| 675 | return err |
| 676 | } |
| 677 | specs := map[string]StepSpec{} |
| 678 | existing := map[string]Step{} |
| 679 | cancel := map[string]bool{} |
| 680 | var order []string |
| 681 | for _, st := range old { |
| 682 | existing[st.Key] = st |
| 683 | if st.State != StepCancelled { |
| 684 | specs[st.Key] = StepSpec{Key: st.Key, Capability: st.Capability, Version: st.Version, DependsOn: st.DependsOn} |
| 685 | order = append(order, st.Key) |
| 686 | } |
| 687 | } |
| 688 | touched := map[string]bool{} |
| 689 | for _, key := range change.Cancel { |
| 690 | st, ok := existing[key] |
| 691 | if st.Capability == CapReview || st.Capability == CapVerify || st.Capability == CapPublish { |
| 692 | return ErrDependency |
| 693 | } |
| 694 | if !ok || st.State != StepPending || st.Attempts != 0 || touched[key] { |
| 695 | return ErrState |
| 696 | } |
| 697 | touched[key] = true |
| 698 | cancel[key] = true |
| 699 | delete(specs, key) |
| 700 | } |
| 701 | for _, st := range change.Replace { |
| 702 | prior, ok := existing[st.Key] |
| 703 | if prior.Capability == CapReview || prior.Capability == CapVerify || prior.Capability == CapPublish { |
| 704 | if st.Capability != prior.Capability { |
| 705 | return ErrDependency |
| 706 | } |
| 707 | } |
| 708 | if !ok || prior.State != StepPending || prior.Attempts != 0 || touched[st.Key] { |
| 709 | return ErrState |
| 710 | } |
| 711 | touched[st.Key] = true |
| 712 | specs[st.Key] = st |
| 713 | } |
| 714 | for _, st := range change.Append { |
| 715 | if _, ok := existing[st.Key]; ok || touched[st.Key] { |
| 716 | return ErrConflict |
| 717 | } |
| 718 | touched[st.Key] = true |
| 719 | specs[st.Key] = st |
| 720 | order = append(order, st.Key) |
| 721 | } |
| 722 | if len(old)+len(change.Append) > MaxSteps { |
| 723 | return ErrQuota |
| 724 | } |
| 725 | if change.Order != nil { |
| 726 | order = change.Order |
| 727 | } |
| 728 | var graph []StepSpec |
| 729 | seen := map[string]bool{} |
| 730 | for _, key := range order { |
| 731 | if cancel[key] && change.Order == nil { |
| 732 | continue |
| 733 | } |
| 734 | st, ok := specs[key] |
| 735 | if !ok || seen[key] { |
| 736 | return ErrDependency |
| 737 | } |
| 738 | seen[key] = true |
| 739 | if change.Order != nil { |
| 740 | st.DependsOn = nil |
| 741 | if len(graph) > 0 { |
| 742 | st.DependsOn = []string{graph[len(graph)-1].Key} |
| 743 | } |
| 744 | } |
| 745 | if prior, ok := existing[key]; ok && (prior.Attempts > 0 || prior.State != StepPending) { |
| 746 | a, b := append([]string{}, prior.DependsOn...), append([]string{}, st.DependsOn...) |
| 747 | if prior.Capability != st.Capability || prior.Version != st.Version || !reflect.DeepEqual(a, b) { |
| 748 | return ErrState |
| 749 | } |
| 750 | } |
| 751 | graph = append(graph, st) |
| 752 | } |
| 753 | if len(graph) != len(specs) { |
| 754 | return ErrDependency |
| 755 | } |
| 756 | if err = validateTargetSteps(j.Target, j.Evidence, j.Policy, graph); err != nil { |
| 757 | return err |
| 758 | } |
| 759 | if err = validateGraph(graph); err != nil { |
| 760 | return err |
| 761 | } |
| 762 | if j.Target.Kind == TargetRepository { |
| 763 | if err = validatePublicationGraph(graph); err != nil { |
| 764 | return err |
| 765 | } |
| 766 | } |
| 767 | for _, st := range graph { |
| 768 | deps, _ := json.Marshal(append([]string{}, st.DependsOn...)) |
| 769 | if _, ok := existing[st.Key]; ok { |
| 770 | _, err = tx.ExecContext(ctx, `UPDATE steps SET capability=?,version=?,depends_on=? WHERE job_id=? AND key=?`, st.Capability, st.Version, string(deps), j.ID, st.Key) |
| 771 | } else { |
| 772 | _, err = tx.ExecContext(ctx, `INSERT INTO steps(job_id,key,capability,version,depends_on,state,fence,holder,attempts) VALUES(?,?,?,?,?,'pending',0,0,0)`, j.ID, st.Key, st.Capability, st.Version, string(deps)) |
| 773 | } |
| 774 | if err != nil { |
| 775 | return err |
| 776 | } |
| 777 | } |
| 778 | for key := range cancel { |
| 779 | if _, err = tx.ExecContext(ctx, `UPDATE steps SET state='cancelled',fence=fence+1 WHERE job_id=? AND key=?`, j.ID, key); err != nil { |
| 780 | return err |
| 781 | } |
| 782 | } |
| 783 | j, err = bumpJob(ctx, tx, j, j.State, j.Wait, j.Outcome, s.clock.Now()) |
| 784 | if err != nil { |
| 785 | return err |
| 786 | } |
| 787 | result = j.Job |
| 788 | return appendEvent(ctx, tx, scope, "plan.edited", j.Requester, change, s.clock.Now()) |
| 789 | }) |
| 790 | return result, err |
| 791 | } |
| 792 | |
| 793 | func validatePublicationGraph(steps []StepSpec) error { |
| 794 | byKey := map[string]StepSpec{} |
| 795 | builders := []string{} |
| 796 | review, checks, publish := "", "", "" |
| 797 | for _, st := range steps { |
| 798 | byKey[st.Key] = st |
| 799 | switch st.Capability { |
| 800 | case CapImplement: |
| 801 | builders = append(builders, st.Key) |
| 802 | case CapReview: |
| 803 | review = st.Key |
| 804 | case CapVerify: |
| 805 | checks = st.Key |
| 806 | case CapPublish: |
| 807 | publish = st.Key |
| 808 | } |
| 809 | } |
| 810 | if review == "" || checks == "" || publish == "" { |
| 811 | return ErrDependency |
| 812 | } |
| 813 | var depends func(string, string) bool |
| 814 | depends = func(key, ancestor string) bool { |
| 815 | for _, dep := range byKey[key].DependsOn { |
| 816 | if dep == ancestor || depends(dep, ancestor) { |
| 817 | return true |
| 818 | } |
| 819 | } |
| 820 | return false |
| 821 | } |
| 822 | for _, builder := range builders { |
| 823 | if !depends(review, builder) || !depends(checks, builder) { |
| 824 | return ErrDependency |
| 825 | } |
| 826 | } |
| 827 | if !depends(publish, review) || !depends(publish, checks) { |
| 828 | return ErrDependency |
| 829 | } |
| 830 | return nil |
| 831 | } |
| 832 | |