budget

package
v0.6.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 17, 2026 License: MIT Imports: 10 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrBudgetExceeded = errors.New("budget exceeded")
	ErrBudgetClosed   = errors.New("budget is closed")
	ErrInvalidAmount  = errors.New("invalid amount")
)
View Source
var (
	ErrBudgetExists   = errors.New("budget already exists")
	ErrBudgetNotFound = errors.New("budget not found")
)

Functions

This section is empty.

Types

type BudgetReport

type BudgetReport struct {
	TaskID      string        `json:"taskId"`
	TotalBudget *big.Int      `json:"totalBudget"`
	TotalSpent  *big.Int      `json:"totalSpent"`
	EntryCount  int           `json:"entryCount"`
	Duration    time.Duration `json:"duration"`
	Status      BudgetStatus  `json:"status"`
}

BudgetReport is returned when a budget is closed.

type BudgetStatus

type BudgetStatus string

BudgetStatus represents the current state of a task budget.

const (
	StatusActive    BudgetStatus = "active"
	StatusExhausted BudgetStatus = "exhausted"
	StatusClosed    BudgetStatus = "closed"
)

type Engine

type Engine struct {
	// contains filtered or unexported fields
}

Engine implements the Guard interface with budget management logic.

func NewEngine

func NewEngine(store *Store, cfg config.BudgetConfig, opts ...Option) (*Engine, error)

NewEngine creates a new budget engine from config and options.

func (*Engine) Allocate

func (e *Engine) Allocate(taskID string, totalBudget *big.Int) (*TaskBudget, error)

Allocate creates a new task budget. If totalBudget is nil or zero, the default max from config is used.

func (*Engine) BurnRate

func (e *Engine) BurnRate(taskID string) (*big.Int, error)

BurnRate returns the spending rate per minute for a task. Returns zero if no time has elapsed or nothing has been spent.

func (*Engine) Check

func (e *Engine) Check(taskID string, amount *big.Int) error

Check verifies amount is within budget. If HardLimit is enabled (default), the check rejects amounts exceeding the remaining budget.

func (*Engine) Close

func (e *Engine) Close(taskID string) (*BudgetReport, error)

Close finalizes a budget and returns a report.

func (*Engine) Record

func (e *Engine) Record(taskID string, entry SpendEntry) error

Record records a spend entry, updates the budget, and checks threshold alerts.

func (*Engine) Reserve

func (e *Engine) Reserve(taskID string, amount *big.Int) (func(), error)

Reserve temporarily reserves an amount from the budget. Returns a release function that must be called to return the reserved funds.

func (*Engine) SetProgress

func (e *Engine) SetProgress(taskID string, progress float64) error

SetProgress updates task completion progress (0.0 to 1.0).

type Guard

type Guard interface {
	Check(taskID string, amount *big.Int) error
	Record(taskID string, entry SpendEntry) error
	Reserve(taskID string, amount *big.Int) (releaseFunc func(), err error)
}

Guard enforces budget constraints for task spending.

type OnChainSyncCallback

type OnChainSyncCallback func(sessionID string, spent *big.Int)

OnChainSyncCallback syncs on-chain spending data to off-chain tracking.

type OnChainTracker

type OnChainTracker struct {
	// contains filtered or unexported fields
}

OnChainTracker tracks spending from on-chain SpendingHook data.

func NewOnChainTracker

func NewOnChainTracker() *OnChainTracker

NewOnChainTracker creates a new on-chain spending tracker.

func (*OnChainTracker) GetSpent

func (t *OnChainTracker) GetSpent(sessionID string) *big.Int

GetSpent returns the cumulative amount spent for a session.

func (*OnChainTracker) Record

func (t *OnChainTracker) Record(sessionID string, amount *big.Int)

Record records a spend for a session.

func (*OnChainTracker) Reset

func (t *OnChainTracker) Reset(sessionID string)

Reset resets the tracker for a session (e.g., after on-chain sync).

func (*OnChainTracker) SetCallback

func (t *OnChainTracker) SetCallback(fn OnChainSyncCallback)

SetCallback sets the sync callback.

type Option

type Option func(*Engine)

Option configures the Engine.

func WithAlertCallback

func WithAlertCallback(fn func(taskID string, pct float64)) Option

WithAlertCallback sets the callback invoked when budget crosses a threshold. The callback receives the taskID and the threshold percentage that was crossed.

func WithRiskAssessor

func WithRiskAssessor(fn RiskAssessor) Option

WithRiskAssessor sets the risk assessor used during Check.

type RiskAssessor

type RiskAssessor func(ctx context.Context, peerDID string, amount *big.Int) error

RiskAssessor is a local interface to avoid importing the risk package directly.

type SpendEntry

type SpendEntry struct {
	ID        string    `json:"id"`
	Amount    *big.Int  `json:"amount"`
	PeerDID   string    `json:"peerDid"`
	ToolName  string    `json:"toolName"`
	Reason    string    `json:"reason"`
	Timestamp time.Time `json:"timestamp"`
}

SpendEntry records a single spend event.

type Store

type Store struct {
	// contains filtered or unexported fields
}

Store is an in-memory store for task budgets.

func NewStore

func NewStore() *Store

NewStore creates a new budget store.

func (*Store) Allocate

func (s *Store) Allocate(taskID string, total *big.Int) (*TaskBudget, error)

Allocate creates a new task budget with the given total.

func (*Store) Delete

func (s *Store) Delete(taskID string) error

Delete removes the task budget for the given task ID.

func (*Store) Get

func (s *Store) Get(taskID string) (*TaskBudget, error)

Get returns the task budget for the given task ID.

func (*Store) List

func (s *Store) List() []*TaskBudget

List returns all task budgets.

func (*Store) Update

func (s *Store) Update(budget *TaskBudget) error

Update replaces the stored budget with the provided one.

type TaskBudget

type TaskBudget struct {
	TaskID      string       `json:"taskId"`
	TotalBudget *big.Int     `json:"totalBudget"`
	Spent       *big.Int     `json:"spent"`
	Reserved    *big.Int     `json:"reserved"`
	Status      BudgetStatus `json:"status"`
	Progress    float64      `json:"progress"`
	Entries     []SpendEntry `json:"entries"`
	CreatedAt   time.Time    `json:"createdAt"`
	UpdatedAt   time.Time    `json:"updatedAt"`
}

TaskBudget tracks budget allocation and spending for a single task.

func (*TaskBudget) Remaining

func (tb *TaskBudget) Remaining() *big.Int

Remaining returns totalBudget - spent - reserved.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL