| 1 | package team |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "crypto/sha256" |
| 7 | "database/sql" |
| 8 | "encoding/hex" |
| 9 | "encoding/json" |
| 10 | "errors" |
| 11 | "sort" |
| 12 | "strconv" |
| 13 | "time" |
| 14 | ) |
| 15 | |
| 16 | // canonical re-encodes a JSON object with sorted keys and no insignificant |
| 17 | // whitespace, so two spellings of one payload hash alike and two payloads |
| 18 | // that differ in any value never do. |
| 19 | func canonical(raw []byte) ([]byte, string, error) { |
| 20 | if len(raw) > MaxPayloadBytes { |
| 21 | return nil, "", fail(CodeSize, "payload %d bytes", len(raw)) |
| 22 | } |
| 23 | var v any |
| 24 | dec := json.NewDecoder(bytes.NewReader(raw)) |
| 25 | dec.UseNumber() |
| 26 | if err := dec.Decode(&v); err != nil { |
| 27 | return nil, "", fail(CodeInvalid, "payload: %v", err) |
| 28 | } |
| 29 | if err := jsonEnd(dec); err != nil { |
| 30 | return nil, "", fail(CodeInvalid, "payload: %v", err) |
| 31 | } |
| 32 | if _, ok := v.(map[string]any); !ok { |
| 33 | return nil, "", fail(CodeInvalid, "payload must be a JSON object") |
| 34 | } |
| 35 | var buf bytes.Buffer |
| 36 | if err := writeCanonical(&buf, v); err != nil { |
| 37 | return nil, "", err |
| 38 | } |
| 39 | sum := sha256.Sum256(buf.Bytes()) |
| 40 | return buf.Bytes(), hex.EncodeToString(sum[:]), nil |
| 41 | } |
| 42 | |
| 43 | func writeCanonical(buf *bytes.Buffer, v any) error { |
| 44 | switch x := v.(type) { |
| 45 | case map[string]any: |
| 46 | keys := make([]string, 0, len(x)) |
| 47 | for k := range x { |
| 48 | keys = append(keys, k) |
| 49 | } |
| 50 | sort.Strings(keys) |
| 51 | buf.WriteByte('{') |
| 52 | for i, k := range keys { |
| 53 | if i > 0 { |
| 54 | buf.WriteByte(',') |
| 55 | } |
| 56 | kb, _ := json.Marshal(k) |
| 57 | buf.Write(kb) |
| 58 | buf.WriteByte(':') |
| 59 | if err := writeCanonical(buf, x[k]); err != nil { |
| 60 | return err |
| 61 | } |
| 62 | } |
| 63 | buf.WriteByte('}') |
| 64 | case []any: |
| 65 | buf.WriteByte('[') |
| 66 | for i, e := range x { |
| 67 | if i > 0 { |
| 68 | buf.WriteByte(',') |
| 69 | } |
| 70 | if err := writeCanonical(buf, e); err != nil { |
| 71 | return err |
| 72 | } |
| 73 | } |
| 74 | buf.WriteByte(']') |
| 75 | default: |
| 76 | b, err := json.Marshal(x) |
| 77 | if err != nil { |
| 78 | return fail(CodeInvalid, "payload: %v", err) |
| 79 | } |
| 80 | buf.Write(b) |
| 81 | } |
| 82 | return nil |
| 83 | } |
| 84 | |
| 85 | // hashBytes is the artifact and content hash: hex SHA-256. |
| 86 | func hashBytes(b []byte) string { |
| 87 | sum := sha256.Sum256(b) |
| 88 | return hex.EncodeToString(sum[:]) |
| 89 | } |
| 90 | |
| 91 | const actionColumns = `id, job_id, step_id, attempt_id, fence, key, operation, class, payload_hash, payload, state, reservation_id, grant_ref, grant_version, grant_epoch, admitted_at, admission_ends, receipt, last_error, created_at, updated_at, admitted_incarnation` |
| 92 | |
| 93 | func scanAction(r rowScanner) (Action, error) { |
| 94 | var a Action |
| 95 | var op, class, state, admitted, ends, receipt, created, updated string |
| 96 | if err := r.Scan(&a.ID, &a.Job, &a.Step, &a.Attempt, &a.Fence, &a.Key, &op, &class, &a.PayloadHash, &a.Payload, &state, &a.Reservation, |
| 97 | &a.Grant.Ref, &a.Grant.Version, &a.Grant.Epoch, &admitted, &ends, &receipt, &a.LastError, &created, &updated, &a.AdmittedIncarnation); err != nil { |
| 98 | return a, err |
| 99 | } |
| 100 | a.Operation, a.Class, a.State = Operation(op), ReplayClass(class), ActionState(state) |
| 101 | if !a.Operation.Valid() || !a.Class.Valid() || !a.State.Valid() { |
| 102 | return a, fail(CodeUnknownKind, "action %d stored %q/%q/%q", a.ID, op, class, state) |
| 103 | } |
| 104 | a.AdmittedAt, a.AdmissionEnds, a.CreatedAt, a.UpdatedAt = parseTS(admitted), parseTS(ends), parseTS(created), parseTS(updated) |
| 105 | if receipt != "" { |
| 106 | var rc Receipt |
| 107 | if err := strictJSON([]byte(receipt), &rc); err != nil { |
| 108 | return a, fail(CodeUnknownKind, "action %d receipt: %v", a.ID, err) |
| 109 | } |
| 110 | a.Receipt = &rc |
| 111 | } |
| 112 | return a, nil |
| 113 | } |
| 114 | |
| 115 | func loadAction(ctx context.Context, tx *sql.Tx, job JobID, id ActionID) (Action, error) { |
| 116 | a, err := scanAction(tx.QueryRowContext(ctx, `SELECT `+actionColumns+` FROM actions WHERE job_id=? AND id=?`, int64(job), int64(id))) |
| 117 | if errors.Is(err, sql.ErrNoRows) { |
| 118 | return a, fail(CodeScope, "action %d", id) |
| 119 | } |
| 120 | return a, err |
| 121 | } |
| 122 | |
| 123 | func (s *Store) adapterFor(op Operation) (Adapter, error) { |
| 124 | if !op.Valid() || !op.external() { |
| 125 | return nil, fail(CodeUnknownKind, "operation %q is not dispatchable", op) |
| 126 | } |
| 127 | ad, ok := s.adapters[op] |
| 128 | if !ok { |
| 129 | return nil, fail(CodeUnknownKind, "no adapter for %s", op) |
| 130 | } |
| 131 | return ad, nil |
| 132 | } |
| 133 | |
| 134 | // Intend persists an action intent under the attempt's current fence and |
| 135 | // reserves its budget in the same transaction. The same key with the same |
| 136 | // canonical payload returns the existing action (no second reservation); |
| 137 | // the same key with another payload is ErrConflict. An existing action |
| 138 | // still in flight is ErrUncertain: reconcile before a replacement attempt |
| 139 | // touches it. A forge publication is checked against the job's target |
| 140 | // binding and the latest candidate before anything is written. |
| 141 | func (s *Store) Intend(ctx context.Context, scope Scope, h Handle, in IntentSpec) (ActionID, error) { |
| 142 | if in.Key == "" { |
| 143 | return 0, fail(CodeInvalid, "intent needs a logical key") |
| 144 | } |
| 145 | ad, err := s.adapterFor(in.Operation) |
| 146 | if err != nil { |
| 147 | return 0, err |
| 148 | } |
| 149 | class, err := ad.Classify(in.Operation) |
| 150 | if err != nil { |
| 151 | return 0, err |
| 152 | } |
| 153 | if !class.Valid() { |
| 154 | return 0, fail(CodeUnknownKind, "replay class %q", class) |
| 155 | } |
| 156 | payload, hash, err := canonical(in.Payload) |
| 157 | if err != nil { |
| 158 | return 0, err |
| 159 | } |
| 160 | in.Reserve.Calls = 1 |
| 161 | var id ActionID |
| 162 | err = s.tx(ctx, func(tx *sql.Tx) error { |
| 163 | if err := admissionOpen(ctx, tx); err != nil { |
| 164 | return err |
| 165 | } |
| 166 | now := s.clock.Now() |
| 167 | hd, err := current(ctx, tx, scope, h, now) |
| 168 | if err != nil { |
| 169 | return err |
| 170 | } |
| 171 | if ((hd.job.Evidence.RequireBugFreeze && hd.step.Capability == CapPublish) || ((hd.job.Evidence.Predicate == PredicateSoftwareFeature || hd.job.Evidence.Predicate == PredicateRenderedChange) && (hd.step.Capability == CapPublish || hd.step.Capability == CapVerify))) && in.Operation == OpProviderCall { |
| 172 | return fail(CodeScope, "bug_publish_is_runner_only") |
| 173 | } |
| 174 | if hd.job.Target.Kind == TargetConversation && (hd.step.Capability != CapCoordinate || in.Operation != OpProviderCall) { |
| 175 | return ErrScope |
| 176 | } |
| 177 | if !operationAllowed(hd.step.Capability, in.Operation) { |
| 178 | return fail(CodeScope, "capability %s cannot perform %s", hd.step.Capability, in.Operation) |
| 179 | } |
| 180 | if in.Operation == OpForgePublish { |
| 181 | if hd.job.Policy.Version == 2 { |
| 182 | observed, err := s.observedProvenance(ctx, tx, scope, h) |
| 183 | if err != nil { |
| 184 | return err |
| 185 | } |
| 186 | var p publication |
| 187 | if err := strictJSON(payload, &p); err != nil { |
| 188 | return fail(CodeInvalid, "publication_invalid") |
| 189 | } |
| 190 | p.Isolation = observed.Isolation |
| 191 | description, err := publicationDescription(ctx, tx, hd.job, p.Isolation) |
| 192 | if err != nil { |
| 193 | return err |
| 194 | } |
| 195 | if (p.Description != "" && !publicationDescriptionContains(p.Description, description)) || (p.DescriptionHash != "" && p.DescriptionHash != hashBytes([]byte(p.Description))) { |
| 196 | return ErrEvidence |
| 197 | } |
| 198 | p.Description = description |
| 199 | p.DescriptionHash = hashBytes([]byte(description)) |
| 200 | raw, err := json.Marshal(p) |
| 201 | if err != nil { |
| 202 | return err |
| 203 | } |
| 204 | payload, hash, err = canonical(raw) |
| 205 | if err != nil { |
| 206 | return err |
| 207 | } |
| 208 | } |
| 209 | if err := s.checkPublication(ctx, tx, hd.job, payload); err != nil { |
| 210 | return err |
| 211 | } |
| 212 | } |
| 213 | existing, err := scanAction(tx.QueryRowContext(ctx, `SELECT `+actionColumns+` FROM actions WHERE job_id=? AND key=?`, int64(hd.job.ID), in.Key)) |
| 214 | switch { |
| 215 | case err == nil: |
| 216 | if existing.PayloadHash != hash || existing.Operation != in.Operation { |
| 217 | return fail(CodeConflict, "key %q already bound to another payload", in.Key) |
| 218 | } |
| 219 | if existing.State.inFlight() { |
| 220 | return fail(CodeUncertain, "action %d in flight; reconcile first", existing.ID) |
| 221 | } |
| 222 | if existing.State == ActionRevoked { |
| 223 | return fail(CodeState, "action %d revoked", existing.ID) |
| 224 | } |
| 225 | if existing.State == ActionIntent && existing.Attempt != hd.attempt.ID { |
| 226 | if _, err := tx.ExecContext(ctx, `UPDATE actions SET attempt_id=?, fence=?, step_id=?, updated_at=? WHERE id=?`, int64(hd.attempt.ID), hd.attempt.Fence, int64(hd.step.ID), ts(now), int64(existing.ID)); err != nil { |
| 227 | return fail(CodeInvalid, "rebind action: %v", err) |
| 228 | } |
| 229 | } |
| 230 | id = existing.ID |
| 231 | return nil |
| 232 | case !errors.Is(err, sql.ErrNoRows): |
| 233 | return fail(CodeInvalid, "action lookup: %v", err) |
| 234 | } |
| 235 | if hd.job.Policy.Version == 2 { |
| 236 | if err := unresolvedTurn(ctx, tx, hd.job.ID, 0); err != nil { |
| 237 | return err |
| 238 | } |
| 239 | } |
| 240 | resID, priced, err := reserve(ctx, tx, hd.job, hd.step.ID, hd.attempt.ID, in.Operation, in.Reserve, now) |
| 241 | if err != nil { |
| 242 | return err |
| 243 | } |
| 244 | res, err := tx.ExecContext(ctx, `INSERT INTO actions(job_id, step_id, attempt_id, fence, key, operation, class, payload_hash, payload, state, reservation_id, |
| 245 | grant_ref, grant_version, grant_epoch, admitted_at, admission_ends, receipt, last_error, created_at, updated_at) |
| 246 | VALUES (?,?,?,?,?,?,?,?,?,'intent',?,?,0,0,'','','','',?,?)`, |
| 247 | int64(hd.job.ID), int64(hd.step.ID), int64(hd.attempt.ID), hd.attempt.Fence, in.Key, string(in.Operation), string(class), hash, payload, int64(resID), hd.job.Grant.Ref, ts(now), ts(now)) |
| 248 | if err != nil { |
| 249 | return fail(CodeInvalid, "insert action: %v", err) |
| 250 | } |
| 251 | aid, _ := res.LastInsertId() |
| 252 | if _, err := tx.ExecContext(ctx, `UPDATE reservations SET action_id=? WHERE id=?`, aid, int64(resID)); err != nil { |
| 253 | return fail(CodeInvalid, "bind reservation: %v", err) |
| 254 | } |
| 255 | id = ActionID(aid) |
| 256 | return appendEvent(ctx, tx, scope, "action.intent", h.Runner, map[string]any{"action": aid, "key": in.Key, "operation": in.Operation, "class": class, "hash": hash, "reserved": priced}, now) |
| 257 | }) |
| 258 | return id, err |
| 259 | } |
| 260 | |
| 261 | // publication is the forge.publish_branch payload. |
| 262 | type publication = Publication |
| 263 | |
| 264 | type Publication struct { |
| 265 | Description string `json:"description,omitempty"` |
| 266 | DescriptionHash string `json:"description_hash,omitempty"` |
| 267 | CandidateHash string `json:"candidate_hash,omitempty"` |
| 268 | Isolation IsolationSnapshot `json:"isolation,omitzero"` |
| 269 | Repository string `json:"repository"` |
| 270 | Ref string `json:"ref"` |
| 271 | Head string `json:"head"` |
| 272 | } |
| 273 | |
| 274 | // checkPublication refuses a publication whose repository, ref or head is |
| 275 | // not the job's bound target and its latest candidate, and any ref equal |
| 276 | // to the protected default branch. |
| 277 | func (s *Store) checkPublication(ctx context.Context, tx *sql.Tx, j jobRow, payload []byte) error { |
| 278 | var p publication |
| 279 | if err := strictJSON(payload, &p); err != nil { |
| 280 | return fail(CodeInvalid, "publication payload: %v", err) |
| 281 | } |
| 282 | if j.Target.Kind != TargetRepository { |
| 283 | return fail(CodeState, "job %d has no repository target", j.ID) |
| 284 | } |
| 285 | if p.Repository != j.Target.Repository || p.Ref != j.Target.Ref { |
| 286 | return fail(CodeScope, "publication to %s@%s, job bound to %s@%s", p.Repository, p.Ref, j.Target.Repository, j.Target.Ref) |
| 287 | } |
| 288 | if p.Ref == j.Target.DefaultRef { |
| 289 | return fail(CodeScope, "publication to the default branch %q", p.Ref) |
| 290 | } |
| 291 | cand, err := latestArtifact(ctx, tx, j.ID, RoleCandidate) |
| 292 | if err != nil { |
| 293 | return err |
| 294 | } |
| 295 | if !publicationMatches(p, cand, j) { |
| 296 | return fail(CodeEvidence, "publication head %q is not the latest candidate", p.Head) |
| 297 | } |
| 298 | if j.Policy.Version == 2 { |
| 299 | rep, err := s.evaluateEvidence(ctx, tx, j, true) |
| 300 | if err != nil { |
| 301 | return err |
| 302 | } |
| 303 | description, err := publicationDescription(ctx, tx, j, p.Isolation) |
| 304 | if err != nil { |
| 305 | return err |
| 306 | } |
| 307 | if !publicationDescriptionContains(p.Description, description) || p.DescriptionHash != hashBytes([]byte(p.Description)) { |
| 308 | return ErrEvidence |
| 309 | } |
| 310 | if !rep.Satisfied || !isolationContains(p.Isolation, rep.Isolation) { |
| 311 | return fail(CodeEvidence, "publication_evidence_invalid") |
| 312 | } |
| 313 | } |
| 314 | return nil |
| 315 | } |
| 316 | |
| 317 | // Admit moves an intent to dispatching. The authority is introspected |
| 318 | // outside the transaction; a revocation runs the cancel path and an |
| 319 | // unavailable authority admits nothing. The transaction then compares the |
| 320 | // stored step fence and holder, the job's revision since the pre-read, its |
| 321 | // state and policy version, the stored grant snapshot against the fresh |
| 322 | // admission, the admission window, and the open reservation against the |
| 323 | // current ledger, before writing dispatching. After that write the |
| 324 | // action's effect may exist: cancellation reports it as in flight. |
| 325 | func (s *Store) Admit(ctx context.Context, scope Scope, id ActionID) (Dispatch, error) { |
| 326 | var pre Action |
| 327 | var job jobRow |
| 328 | err := s.read(ctx, func(tx *sql.Tx) error { |
| 329 | j, err := loadJob(ctx, tx, scope) |
| 330 | if err != nil { |
| 331 | return err |
| 332 | } |
| 333 | a, err := loadAction(ctx, tx, j.ID, id) |
| 334 | if err != nil { |
| 335 | return err |
| 336 | } |
| 337 | pre, job = a, j |
| 338 | return nil |
| 339 | }) |
| 340 | if err != nil { |
| 341 | return Dispatch{}, err |
| 342 | } |
| 343 | if pre.State != ActionIntent { |
| 344 | return Dispatch{}, fail(CodeState, "action %d is %s", id, pre.State) |
| 345 | } |
| 346 | adm, err := s.auth.Introspect(ctx, AdmissionRequest{Grant: job.Grant.Ref, Account: job.Account, Project: job.Project, Target: job.Target, Operation: pre.Operation}) |
| 347 | if err != nil { |
| 348 | if errors.Is(err, ErrGrantRevoked) { |
| 349 | return Dispatch{}, s.observedRevocation(ctx, scope, err) |
| 350 | } |
| 351 | return Dispatch{}, err |
| 352 | } |
| 353 | if err := s.fenceObserved(ctx, job.Grant, adm); err != nil { |
| 354 | return Dispatch{}, err |
| 355 | } |
| 356 | var d Dispatch |
| 357 | err = s.tx(ctx, func(tx *sql.Tx) error { |
| 358 | if err := admissionOpen(ctx, tx); err != nil { |
| 359 | return err |
| 360 | } |
| 361 | now := s.clock.Now() |
| 362 | j, err := loadJob(ctx, tx, scope) |
| 363 | if err != nil { |
| 364 | return err |
| 365 | } |
| 366 | if j.Revision != job.Revision { |
| 367 | return fail(CodeRevision, "job %d moved from revision %d to %d", j.ID, job.Revision, j.Revision) |
| 368 | } |
| 369 | if j.State != JobRunning { |
| 370 | return fail(CodeState, "job %d is %s", j.ID, j.State) |
| 371 | } |
| 372 | if err := checkAdmission(j, adm, now); err != nil { |
| 373 | return err |
| 374 | } |
| 375 | a, err := loadAction(ctx, tx, j.ID, id) |
| 376 | if err != nil { |
| 377 | return err |
| 378 | } |
| 379 | if a.State != ActionIntent { |
| 380 | return fail(CodeState, "action %d is %s", id, a.State) |
| 381 | } |
| 382 | att, err := loadAttempt(ctx, tx, j.ID, a.Attempt) |
| 383 | if err != nil { |
| 384 | return err |
| 385 | } |
| 386 | hd, err := current(ctx, tx, scope, Handle{Attempt: att.ID, Fence: a.Fence, Runner: att.Runner}, now) |
| 387 | if err != nil { |
| 388 | return err |
| 389 | } |
| 390 | if a.Operation == OpForgePublish { |
| 391 | if err := s.checkPublication(ctx, tx, j, a.Payload); err != nil { |
| 392 | return err |
| 393 | } |
| 394 | if j.Policy.Version == 2 { |
| 395 | observed, err := s.observedProvenance(ctx, tx, scope, Handle{Attempt: att.ID, Fence: a.Fence, Runner: att.Runner}) |
| 396 | if err != nil { |
| 397 | return err |
| 398 | } |
| 399 | var p publication |
| 400 | if strictJSON(a.Payload, &p) != nil || !isolationContains(p.Isolation, observed.Isolation) { |
| 401 | return fail(CodeEvidence, "publication_isolation_changed") |
| 402 | } |
| 403 | } |
| 404 | } |
| 405 | if j.Policy.Version == 2 { |
| 406 | if err := unresolvedTurn(ctx, tx, j.ID, a.ID); err != nil { |
| 407 | return err |
| 408 | } |
| 409 | } |
| 410 | r, err := loadReservation(ctx, tx, a.Reservation) |
| 411 | if err != nil { |
| 412 | return err |
| 413 | } |
| 414 | if r.State != ReservationOpen { |
| 415 | return fail(CodeState, "reservation %d is %s", r.ID, r.State) |
| 416 | } |
| 417 | // The reservation is already counted; re-check that the ledger still |
| 418 | // fits the limits (a policy edit or an audited settlement may have |
| 419 | // moved it). |
| 420 | if err := checkBudget(ctx, tx, hd.job, Usage{}, now); err != nil { |
| 421 | return err |
| 422 | } |
| 423 | _, err = tx.ExecContext(ctx, `UPDATE actions SET state='dispatching', grant_version=?, grant_epoch=?, admitted_at=?, admission_ends=?, updated_at=?, admitted_incarnation=? WHERE id=? AND state='intent'`, |
| 424 | adm.Version, adm.Epoch, ts(now), ts(adm.ExpiresAt), ts(now), s.incarnation, int64(a.ID)) |
| 425 | if err != nil { |
| 426 | return fail(CodeInvalid, "admit: %v", err) |
| 427 | } |
| 428 | d = Dispatch{Action: a.ID, Key: a.Key, Operation: a.Operation, Payload: a.Payload, Hash: a.PayloadHash} |
| 429 | return appendEvent(ctx, tx, scope, "action.dispatching", "broker", map[string]any{"action": a.ID, "key": a.Key, "grant_version": adm.Version, "epoch": adm.Epoch}, now) |
| 430 | }) |
| 431 | return d, err |
| 432 | } |
| 433 | |
| 434 | // Record stores an adapter receipt for a dispatching or uncertain action |
| 435 | // and settles its reservation in the same transaction. It is accepted |
| 436 | // whatever the job's state: a late receipt for a cancelled job still |
| 437 | // settles the ledger without changing the terminal outcome. A second |
| 438 | // delivery of the same receipt is a no-op; a different receipt for a |
| 439 | // finished action is ErrReceiptConflict. |
| 440 | func (s *Store) Record(ctx context.Context, scope Scope, id ActionID, rc Receipt) error { |
| 441 | return s.record(ctx, scope, id, rc, false) |
| 442 | } |
| 443 | func (s *Store) record(ctx context.Context, scope Scope, id ActionID, rc Receipt, notDispatched bool) error { |
| 444 | if err := rc.validate(); err != nil { |
| 445 | return err |
| 446 | } |
| 447 | return s.tx(ctx, func(tx *sql.Tx) error { |
| 448 | now := s.clock.Now() |
| 449 | j, err := loadJob(ctx, tx, scope) |
| 450 | if err != nil { |
| 451 | return err |
| 452 | } |
| 453 | a, err := loadAction(ctx, tx, j.ID, id) |
| 454 | if err != nil { |
| 455 | return err |
| 456 | } |
| 457 | switch a.State { |
| 458 | case ActionSucceeded, ActionFailed: |
| 459 | if a.Receipt != nil && a.Receipt.ID == rc.ID && a.Receipt.Outcome == rc.Outcome { |
| 460 | if a.Operation == OpForgePublish && j.Policy.Version == 2 { |
| 461 | saved, _ := json.Marshal(a.Receipt.Fields) |
| 462 | offered, _ := json.Marshal(rc.Fields) |
| 463 | if a.Receipt.Provider != rc.Provider || !bytes.Equal(saved, offered) { |
| 464 | return ErrReceiptConflict |
| 465 | } |
| 466 | } |
| 467 | if a.Receipt.Usage != nil && rc.Usage != nil && *a.Receipt.Usage != *rc.Usage { |
| 468 | return ErrReceiptConflict |
| 469 | } |
| 470 | if err := settle(ctx, tx, a.Reservation, rc, now); err != nil { |
| 471 | return err |
| 472 | } |
| 473 | if a.Receipt.Usage == nil && rc.Usage != nil { |
| 474 | raw, err := json.Marshal(rc) |
| 475 | if err != nil { |
| 476 | return err |
| 477 | } |
| 478 | _, err = tx.ExecContext(ctx, "UPDATE actions SET receipt=? WHERE id=?", string(raw), a.ID) |
| 479 | return err |
| 480 | } |
| 481 | return nil |
| 482 | } |
| 483 | return fail(CodeReceiptConflict, "action %d already holds receipt %q", id, a.Receipt.ID) |
| 484 | case ActionDispatching, ActionUncertain: |
| 485 | default: |
| 486 | return fail(CodeState, "action %d is %s; no dispatch to receipt", id, a.State) |
| 487 | } |
| 488 | if a.Operation == OpForgePublish && j.Policy.Version == 2 { |
| 489 | if err := ValidatePublicationReceipt(a.Payload, rc); err != nil { |
| 490 | return err |
| 491 | } |
| 492 | } |
| 493 | settlement := settle |
| 494 | if notDispatched { |
| 495 | settlement = releaseNotDispatched |
| 496 | } |
| 497 | if err := settlement(ctx, tx, a.Reservation, rc, now); err != nil { |
| 498 | return err |
| 499 | } |
| 500 | state := ActionSucceeded |
| 501 | if rc.Outcome == OutcomeFailure { |
| 502 | state = ActionFailed |
| 503 | } |
| 504 | raw, _ := json.Marshal(rc) |
| 505 | if _, err := tx.ExecContext(ctx, `UPDATE actions SET state=?, receipt=?, last_error='', updated_at=? WHERE id=?`, string(state), string(raw), ts(now), int64(a.ID)); err != nil { |
| 506 | return fail(CodeInvalid, "record: %v", err) |
| 507 | } |
| 508 | if rc.Provider != "" { |
| 509 | if _, err := tx.ExecContext(ctx, `UPDATE attempts SET provider=?, model=?, effort=? WHERE id=?`, rc.Provider, rc.Model, rc.Effort, int64(a.Attempt)); err != nil { |
| 510 | return fail(CodeInvalid, "record provider: %v", err) |
| 511 | } |
| 512 | } |
| 513 | if err := appendEvent(ctx, tx, scope, "action."+string(state), "adapter", map[string]any{"action": a.ID, "key": a.Key, "receipt": rc.ID, "usage": rc.Usage}, now); err != nil { |
| 514 | return err |
| 515 | } |
| 516 | j, err = loadJob(ctx, tx, scope) |
| 517 | if err != nil { |
| 518 | return err |
| 519 | } |
| 520 | return resumeIfResolved(ctx, tx, j, now) |
| 521 | }) |
| 522 | } |
| 523 | |
| 524 | // resumeIfResolved returns a job waiting on an uncertain outcome to |
| 525 | // running once no action of it is in flight. |
| 526 | func resumeIfResolved(ctx context.Context, tx *sql.Tx, j jobRow, now time.Time) error { |
| 527 | if j.State != JobWaiting || j.Wait != WaitUncertainOutcome { |
| 528 | return nil |
| 529 | } |
| 530 | var n int |
| 531 | if err := tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM actions WHERE job_id=? AND state IN ('dispatching','uncertain')`, int64(j.ID)).Scan(&n); err != nil { |
| 532 | return fail(CodeInvalid, "in flight: %v", err) |
| 533 | } |
| 534 | if n > 0 { |
| 535 | return nil |
| 536 | } |
| 537 | if _, err := bumpJob(ctx, tx, j, JobRunning, WaitNone, j.Outcome, now); err != nil { |
| 538 | return err |
| 539 | } |
| 540 | return appendEvent(ctx, tx, Scope{Account: j.Account, Job: j.ID}, "job.running", "broker", map[string]any{"after": "uncertain outcomes resolved"}, now) |
| 541 | } |
| 542 | |
| 543 | // Lost marks a dispatching action's reply as lost. The action becomes |
| 544 | // uncertain, its full reservation is charged and the job waits on the outcome. |
| 545 | func (s *Store) Lost(ctx context.Context, scope Scope, id ActionID, detail string) error { |
| 546 | return s.tx(ctx, func(tx *sql.Tx) error { |
| 547 | now := s.clock.Now() |
| 548 | j, err := loadJob(ctx, tx, scope) |
| 549 | if err != nil { |
| 550 | return err |
| 551 | } |
| 552 | a, err := loadAction(ctx, tx, j.ID, id) |
| 553 | if err != nil { |
| 554 | return err |
| 555 | } |
| 556 | if a.State != ActionDispatching && a.State != ActionUncertain { |
| 557 | return fail(CodeState, "action %d is %s", id, a.State) |
| 558 | } |
| 559 | if _, err := tx.ExecContext(ctx, `UPDATE actions SET state='uncertain', last_error=?, updated_at=? WHERE id=?`, detail, ts(now), int64(a.ID)); err != nil { |
| 560 | return fail(CodeInvalid, "lost: %v", err) |
| 561 | } |
| 562 | if err := settleUnknown(ctx, tx, a.Reservation, now); err != nil { |
| 563 | return err |
| 564 | } |
| 565 | if err := appendEvent(ctx, tx, scope, "action.uncertain", "broker", map[string]any{"action": a.ID, "key": a.Key, "detail": detail}, now); err != nil { |
| 566 | return err |
| 567 | } |
| 568 | if !j.State.Terminal() && !(j.State == JobWaiting && j.Wait == WaitUncertainOutcome) { |
| 569 | if _, err := bumpJob(ctx, tx, j, JobWaiting, WaitUncertainOutcome, j.Outcome, now); err != nil { |
| 570 | return err |
| 571 | } |
| 572 | } |
| 573 | return nil |
| 574 | }) |
| 575 | } |
| 576 | |
| 577 | // Dispatch is Admit, the adapter's Execute and Record or Lost in sequence. |
| 578 | // It returns the receipt on a definitive answer and ErrUncertain when the |
| 579 | // reply was lost. |
| 580 | func (s *Store) Dispatch(ctx context.Context, scope Scope, id ActionID) (Receipt, error) { |
| 581 | d, err := s.Admit(ctx, scope, id) |
| 582 | if err != nil { |
| 583 | return Receipt{}, err |
| 584 | } |
| 585 | ad, err := s.adapterFor(d.Operation) |
| 586 | if err != nil { |
| 587 | return Receipt{}, err |
| 588 | } |
| 589 | rc, execErr := ad.Execute(ctx, d) |
| 590 | notDispatched := errors.Is(execErr, ErrNotDispatched) |
| 591 | if notDispatched { |
| 592 | rc, execErr = notDispatchedReceipt(d), nil |
| 593 | } |
| 594 | if execErr != nil { |
| 595 | if err := s.Lost(context.WithoutCancel(ctx), scope, id, execErr.Error()); err != nil { |
| 596 | return Receipt{}, err |
| 597 | } |
| 598 | return Receipt{}, fail(CodeUncertain, "action %d: %v", id, execErr) |
| 599 | } |
| 600 | if err := s.record(context.WithoutCancel(ctx), scope, id, rc, notDispatched); err != nil { |
| 601 | return Receipt{}, err |
| 602 | } |
| 603 | return rc, nil |
| 604 | } |
| 605 | |
| 606 | // Reconcile recovers a receipt for an uncertain action. This prototype never |
| 607 | // automatically redispatches an admitted operation: even a missing effect |
| 608 | // does not prove that no request is still running or that no usage was billed. |
| 609 | // Unknown outcomes retain their reservation until a receipt or audited charge. |
| 610 | func (s *Store) Reconcile(ctx context.Context, scope Scope, id ActionID) (Action, error) { |
| 611 | var a Action |
| 612 | err := s.tx(ctx, func(tx *sql.Tx) error { |
| 613 | j, err := loadJob(ctx, tx, scope) |
| 614 | if err != nil { |
| 615 | return err |
| 616 | } |
| 617 | a, err = loadAction(ctx, tx, j.ID, id) |
| 618 | if err != nil { |
| 619 | return err |
| 620 | } |
| 621 | if a.State == ActionDispatching && a.AdmittedIncarnation == s.incarnation { |
| 622 | return fail(CodeState, "action %d may still be executing in this incarnation", id) |
| 623 | } |
| 624 | return nil |
| 625 | }) |
| 626 | if err != nil { |
| 627 | return a, err |
| 628 | } |
| 629 | if !a.State.inFlight() { |
| 630 | return a, fail(CodeState, "action %d is %s", id, a.State) |
| 631 | } |
| 632 | ad, err := s.adapterFor(a.Operation) |
| 633 | if err != nil { |
| 634 | return a, err |
| 635 | } |
| 636 | d := Dispatch{Action: a.ID, Key: a.Key, Operation: a.Operation, Payload: a.Payload, Hash: a.PayloadHash} |
| 637 | res, rerr := ad.Reconcile(ctx, d) |
| 638 | notDispatched := errors.Is(rerr, ErrNotDispatched) |
| 639 | if notDispatched { |
| 640 | rc := notDispatchedReceipt(d) |
| 641 | res, rerr = ReconcileResult{Receipt: &rc, Definitive: true}, nil |
| 642 | } |
| 643 | if rerr == nil && res.Receipt != nil { |
| 644 | if err := s.record(ctx, scope, id, *res.Receipt, notDispatched); err != nil { |
| 645 | return a, err |
| 646 | } |
| 647 | return s.GetAction(ctx, scope, id) |
| 648 | } |
| 649 | detail := "no receipt; automatic redispatch is not supported" |
| 650 | if rerr != nil { |
| 651 | detail = rerr.Error() |
| 652 | } |
| 653 | err = s.Lost(ctx, scope, id, detail) |
| 654 | if err != nil { |
| 655 | return a, err |
| 656 | } |
| 657 | a, err = s.GetAction(ctx, scope, id) |
| 658 | if err != nil { |
| 659 | return a, err |
| 660 | } |
| 661 | return a, fail(CodeUncertain, "action %d: %s", id, detail) |
| 662 | } |
| 663 | |
| 664 | // GetAction reads one action. |
| 665 | func (s *Store) GetAction(ctx context.Context, scope Scope, id ActionID) (Action, error) { |
| 666 | var a Action |
| 667 | err := s.read(ctx, func(tx *sql.Tx) error { |
| 668 | j, err := loadJob(ctx, tx, scope) |
| 669 | if err != nil { |
| 670 | return err |
| 671 | } |
| 672 | a, err = loadAction(ctx, tx, j.ID, id) |
| 673 | return err |
| 674 | }) |
| 675 | return a, err |
| 676 | } |
| 677 | |
| 678 | // Actions lists the job's actions. |
| 679 | func (s *Store) Actions(ctx context.Context, scope Scope) ([]Action, error) { |
| 680 | var out []Action |
| 681 | err := s.read(ctx, func(tx *sql.Tx) error { |
| 682 | if _, err := loadJob(ctx, tx, scope); err != nil { |
| 683 | return err |
| 684 | } |
| 685 | rows, err := tx.QueryContext(ctx, `SELECT `+actionColumns+` FROM actions WHERE job_id=? ORDER BY id`, int64(scope.Job)) |
| 686 | if err != nil { |
| 687 | return fail(CodeInvalid, "actions: %v", err) |
| 688 | } |
| 689 | defer rows.Close() |
| 690 | for rows.Next() { |
| 691 | a, err := scanAction(rows) |
| 692 | if err != nil { |
| 693 | return err |
| 694 | } |
| 695 | out = append(out, a) |
| 696 | } |
| 697 | return rows.Err() |
| 698 | }) |
| 699 | return out, err |
| 700 | } |
| 701 | |
| 702 | func unresolvedTurn(ctx context.Context, tx *sql.Tx, job JobID, except ActionID) error { |
| 703 | var n int |
| 704 | if err := tx.QueryRowContext(ctx, `SELECT count(*) FROM actions WHERE job_id=? AND id!=? AND state IN ('dispatching','uncertain')`, job, except).Scan(&n); err != nil { |
| 705 | return err |
| 706 | } |
| 707 | if n != 0 { |
| 708 | return fail(CodeUncertain, "prior outcome unavailable") |
| 709 | } |
| 710 | return nil |
| 711 | } |
| 712 | |
| 713 | func notDispatchedReceipt(d Dispatch) Receipt { |
| 714 | return Receipt{ID: "not-dispatched-" + strconv.FormatInt(int64(d.Action), 10) + "-" + d.Hash, Outcome: OutcomeFailure, Usage: &Usage{}} |
| 715 | } |
| 716 | |
| 717 | // ResumeContained leaves unresolved external outcomes waiting for reconciliation. |
| 718 | func (s *Store) ResumeContained(ctx context.Context, scope Scope) error { |
| 719 | return s.tx(ctx, func(tx *sql.Tx) error { |
| 720 | j, err := loadJob(ctx, tx, scope) |
| 721 | if err != nil { |
| 722 | return err |
| 723 | } |
| 724 | var pending int |
| 725 | if err = tx.QueryRowContext(ctx, "SELECT count(*) FROM attempts WHERE job_id=? AND containment='pending'", j.ID).Scan(&pending); err != nil { |
| 726 | return err |
| 727 | } |
| 728 | if pending != 0 { |
| 729 | return fail(CodeState, "containment pending") |
| 730 | } |
| 731 | return resumeIfResolved(ctx, tx, j, s.clock.Now()) |
| 732 | }) |
| 733 | } |
| 734 | |