Files

87 lines
2.7 KiB
Go

package judgement
import (
"context"
"fmt"
"time"
"github.com/google/uuid"
"github.com/jmoiron/sqlx"
"github.com/samcharles93/archie-core/modules/judgement/internal/store"
)
// Budgets says how many actions one run, and the organisation in a day, may
// take.
type Budgets interface {
ActionBudgets(ctx context.Context) (perRun, perDay int, err error)
}
// ActionCounts says how many changing actions were judged for a run, and in
// the day before now, not counting the attempt named key.
type ActionCounts interface {
Actions(ctx context.Context, runID uuid.UUID, key string, now time.Time) (inRun, inDay int, err error)
}
// Spend counts the changing actions the module has judged. Refused actions
// cost nothing.
type Spend struct {
store *store.Store
orgID string
}
// NewSpend returns the action counts for orgID.
func NewSpend(db *sqlx.DB, orgID string) *Spend { return &Spend{store: store.New(db), orgID: orgID} }
// Actions counts the run's actions, and the organisation's in the 24 hours
// before now, leaving out the attempt named key so a replay isn't charged twice.
func (s *Spend) Actions(ctx context.Context, runID uuid.UUID, key string, now time.Time) (inRun, inDay int, err error) {
return s.store.CountActions(ctx, s.orgID, runID, key, now.Add(-24*time.Hour))
}
// Cost holds an action that changes something at propose and wait once its run
// or the organisation's day has used its action budget. Reading is free.
type Cost struct {
Budgets Budgets
Counts ActionCounts
// Now is the clock; nil means time.Now.
Now func() time.Time
}
// Name is the guard's name in verdicts.
func (Cost) Name() string { return "cost" }
// Advisory is false.
func (Cost) Advisory() bool { return false }
// Judge returns the cost ceiling.
func (c Cost) Judge(ctx context.Context, a Action) (Verdict, error) {
if a.Effect.ReadOnly {
return Verdict{Ceiling: ActQuietly}, nil
}
perRun, perDay, err := c.Budgets.ActionBudgets(ctx)
if err != nil {
return Verdict{}, fmt.Errorf("read budgets: %w", err)
}
now := time.Now
if c.Now != nil {
now = c.Now
}
run := runFrom(ctx)
inRun, inDay, err := c.Counts.Actions(ctx, run.RunID, run.Key, now())
if err != nil {
return Verdict{}, fmt.Errorf("count actions: %w", err)
}
var findings []Finding
if inRun >= perRun {
findings = append(findings, Finding{Text: fmt.Sprintf("this run has used its budget of %d actions", perRun)})
}
if inDay >= perDay {
findings = append(findings, Finding{Text: fmt.Sprintf("the organisation has used its budget of %d actions for the day", perDay)})
}
if len(findings) > 0 {
return Verdict{Ceiling: ProposeAndWait, Findings: findings}, nil
}
return Verdict{Ceiling: ActQuietly}, nil
}