|
| 1 | +package config |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "time" |
| 7 | + |
| 8 | + "github.com/LeanerCloud/cloud-commitments-go/pkg/ladder" |
| 9 | + "github.com/jackc/pgx/v5" |
| 10 | +) |
| 11 | + |
| 12 | +// LadderFireGrace is how late a scheduled ladder tranche may still be fired. |
| 13 | +// It is the single definition behind both sides of the boundary: in-flight |
| 14 | +// netting counts a scheduled tranche while it is still fireable, and the |
| 15 | +// overdue sweep cancels it once it is not. Keeping both on ladderGraceCutoff |
| 16 | +// guarantees every scheduled row is counted or canceled, never neither |
| 17 | +// (neither would let the next run re-plan an amount the executor can still |
| 18 | +// buy, and both would be bought) and never both. |
| 19 | +const LadderFireGrace = 24 * time.Hour |
| 20 | + |
| 21 | +// ladderGraceCutoff returns the instant at or before which a scheduled |
| 22 | +// tranche is expired: scheduled_date <= cutoff is canceled, and |
| 23 | +// scheduled_date > cutoff is still netted and claimable. |
| 24 | +func ladderGraceCutoff(asOf time.Time) time.Time { |
| 25 | + return asOf.Add(-LadderFireGrace) |
| 26 | +} |
| 27 | + |
| 28 | +// ladderTrancheEdges lists the legal tranche status transitions. completed, |
| 29 | +// failed and canceled are terminal. A fired tranche whose purchase outcome is |
| 30 | +// unknown stays fired (and keeps netting) until it is resolved to completed or |
| 31 | +// failed. |
| 32 | +var ladderTrancheEdges = map[ladder.TrancheStatus][]ladder.TrancheStatus{ |
| 33 | + ladder.TrancheStatusScheduled: {ladder.TrancheStatusFired, ladder.TrancheStatusCancelled}, |
| 34 | + ladder.TrancheStatusFired: {ladder.TrancheStatusCompleted, ladder.TrancheStatusFailed}, |
| 35 | +} |
| 36 | + |
| 37 | +func validateLadderTrancheEdge(from, to ladder.TrancheStatus) error { |
| 38 | + for _, allowed := range ladderTrancheEdges[from] { |
| 39 | + if allowed == to { |
| 40 | + return nil |
| 41 | + } |
| 42 | + } |
| 43 | + return fmt.Errorf("illegal ladder tranche transition %q -> %q", from, to) |
| 44 | +} |
| 45 | + |
| 46 | +// TransitionLadderTranche moves one tranche from `from` to `to` with a |
| 47 | +// compare-and-set UPDATE. It returns false (and no error) when the row is |
| 48 | +// missing or no longer in `from`, so a lost race is distinguishable from a DB |
| 49 | +// failure. An illegal edge is an error. scheduled -> fired is not allowed here |
| 50 | +// because a claim must create the execution in the same transaction; use |
| 51 | +// ClaimDueLadderTranches. A scheduled tranche that already has an execution |
| 52 | +// cannot be canceled. |
| 53 | +func (s *PostgresStore) TransitionLadderTranche(ctx context.Context, id string, from, to ladder.TrancheStatus) (bool, error) { |
| 54 | + if err := validateLadderTrancheEdge(from, to); err != nil { |
| 55 | + return false, err |
| 56 | + } |
| 57 | + if from == ladder.TrancheStatusScheduled && to == ladder.TrancheStatusFired { |
| 58 | + return false, fmt.Errorf("ladder tranche %s: scheduled -> fired must go through ClaimDueLadderTranches", id) |
| 59 | + } |
| 60 | + tag, err := s.db.Exec(ctx, ` |
| 61 | + UPDATE ladder_tranches |
| 62 | + SET status = $3 |
| 63 | + WHERE id = $1 |
| 64 | + AND status = $2 |
| 65 | + AND ($2 <> 'scheduled' OR execution_id IS NULL) |
| 66 | + `, id, string(from), string(to)) |
| 67 | + if err != nil { |
| 68 | + return false, fmt.Errorf("failed to transition ladder_tranche id=%s %s -> %s: %w", id, from, to, err) |
| 69 | + } |
| 70 | + return tag.RowsAffected() == 1, nil |
| 71 | +} |
| 72 | + |
| 73 | +// ClaimDueLadderTranches atomically claims up to limit tranches of configID |
| 74 | +// that are due (scheduled_date <= asOf) but not expired (scheduled_date > |
| 75 | +// asOf - LadderFireGrace). For each claimed row, in the same transaction, |
| 76 | +// create runs and must return the id of the purchase_executions row it |
| 77 | +// created; the tranche is then set to fired with that execution_id. If create |
| 78 | +// returns an error the whole transaction rolls back and nothing is claimed, so |
| 79 | +// a claim and its execution row can never disagree after a crash. Rows locked |
| 80 | +// by a concurrent claim are skipped (FOR UPDATE SKIP LOCKED), so exactly one |
| 81 | +// caller wins each tranche. |
| 82 | +func (s *PostgresStore) ClaimDueLadderTranches( |
| 83 | + ctx context.Context, |
| 84 | + configID string, |
| 85 | + asOf time.Time, |
| 86 | + limit int, |
| 87 | + create func(ctx context.Context, tx pgx.Tx, tranche LadderTrancheDB) (executionID string, err error), |
| 88 | +) ([]LadderTrancheDB, error) { |
| 89 | + if limit <= 0 { |
| 90 | + return nil, fmt.Errorf("ClaimDueLadderTranches limit must be positive, got %d", limit) |
| 91 | + } |
| 92 | + var claimed []LadderTrancheDB |
| 93 | + err := s.WithTx(ctx, func(tx pgx.Tx) error { |
| 94 | + due, err := selectDueLadderTranchesTx(ctx, tx, configID, asOf, limit) |
| 95 | + if err != nil { |
| 96 | + return err |
| 97 | + } |
| 98 | + for i := range due { |
| 99 | + execID, err := create(ctx, tx, due[i]) |
| 100 | + if err != nil { |
| 101 | + return fmt.Errorf("create execution for ladder_tranche id=%s: %w", due[i].ID, err) |
| 102 | + } |
| 103 | + if execID == "" { |
| 104 | + return fmt.Errorf("create execution for ladder_tranche id=%s returned an empty execution id", due[i].ID) |
| 105 | + } |
| 106 | + if _, err := tx.Exec(ctx, ` |
| 107 | + UPDATE ladder_tranches SET status = $2, execution_id = $3 |
| 108 | + WHERE id = $1 AND status = 'scheduled' AND execution_id IS NULL |
| 109 | + `, due[i].ID, string(ladder.TrancheStatusFired), execID); err != nil { |
| 110 | + return fmt.Errorf("failed to claim ladder_tranche id=%s: %w", due[i].ID, err) |
| 111 | + } |
| 112 | + due[i].Status = ladder.TrancheStatusFired |
| 113 | + due[i].ExecutionID = &execID |
| 114 | + } |
| 115 | + claimed = due |
| 116 | + return nil |
| 117 | + }) |
| 118 | + if err != nil { |
| 119 | + return nil, err |
| 120 | + } |
| 121 | + return claimed, nil |
| 122 | +} |
| 123 | + |
| 124 | +func selectDueLadderTranchesTx(ctx context.Context, tx pgx.Tx, configID string, asOf time.Time, limit int) ([]LadderTrancheDB, error) { |
| 125 | + rows, err := tx.Query(ctx, ` |
| 126 | + SELECT id, config_id, run_id, layer_type, amount_usd_hr, term, |
| 127 | + payment_option, scheduled_date, status, created_at |
| 128 | + FROM ladder_tranches |
| 129 | + WHERE config_id = $1 |
| 130 | + AND status = 'scheduled' |
| 131 | + AND execution_id IS NULL |
| 132 | + AND scheduled_date <= $2 |
| 133 | + AND scheduled_date > $3 |
| 134 | + ORDER BY scheduled_date, id |
| 135 | + LIMIT $4 |
| 136 | + FOR UPDATE SKIP LOCKED |
| 137 | + `, configID, asOf, ladderGraceCutoff(asOf), limit) |
| 138 | + if err != nil { |
| 139 | + return nil, fmt.Errorf("failed to select due ladder_tranches config_id=%s: %w", configID, err) |
| 140 | + } |
| 141 | + defer rows.Close() |
| 142 | + var out []LadderTrancheDB |
| 143 | + for rows.Next() { |
| 144 | + var tr LadderTrancheDB |
| 145 | + if err := rows.Scan(&tr.ID, &tr.ConfigID, &tr.RunID, &tr.LayerType, &tr.AmountUSDHr, &tr.Term, |
| 146 | + &tr.PaymentOption, &tr.ScheduledDate, &tr.Status, &tr.CreatedAt); err != nil { |
| 147 | + return nil, fmt.Errorf("failed to scan due ladder_tranche: %w", err) |
| 148 | + } |
| 149 | + out = append(out, tr) |
| 150 | + } |
| 151 | + if err := rows.Err(); err != nil { |
| 152 | + return nil, fmt.Errorf("failed to read due ladder_tranches: %w", err) |
| 153 | + } |
| 154 | + return out, nil |
| 155 | +} |
0 commit comments