Class InMemoryCostBudgetStore

java.lang.Object
com.tnsai.quality.cost.InMemoryCostBudgetStore
All Implemented Interfaces:
CostBudgetStore

public final class InMemoryCostBudgetStore extends Object implements CostBudgetStore
Process-local CostBudgetStore (issue #82). Records each spend event individually with its timestamp; sum-over-window scans the deque on currentSpend(com.tnsai.quality.cost.CostScope, java.time.Duration). Suitable for dev / tests / single- process deployments. Production multi-process usage should swap in a Redis adapter (focused follow-up) so spend totals aggregate across instances.

Eviction

On each record(com.tnsai.quality.cost.CostScope, java.math.BigDecimal) call, entries older than maxAge are dropped from the head of the deque. The cap doubles as the maximum window any subsequent currentSpend(com.tnsai.quality.cost.CostScope, java.time.Duration) can ask about — the caller must size maxAge at least as long as the longest budget window in use.

Concurrency

Backed by a ReentrantReadWriteLock — concurrent reads, exclusive writes. ArrayDeque for O(1) head removal during eviction.
Since:
0.5.0 (issue #82)
  • Constructor Details

    • InMemoryCostBudgetStore

      public InMemoryCostBudgetStore(Duration maxAge)
      Parameters:
      maxAge - how far back to retain spend entries — must be at least as long as the longest budget window the store will be queried for. Older entries are evicted.
  • Method Details

    • record

      public void record(CostScope scope, BigDecimal amountUSD)
      Description copied from interface: CostBudgetStore
      Add amountUSD to the recorded spend at scope, dated "now". The store buckets by scope and applies eviction based on the rolling-window query.
      Specified by:
      record in interface CostBudgetStore
    • currentSpend

      public BigDecimal currentSpend(CostScope scope, Duration period)
      Description copied from interface: CostBudgetStore
      Sum of recorded spend that falls inside scope within the last period. Spend records at finer scopes (tenant + agent + capability) roll up into coarser-scoped queries (tenant only).
      Specified by:
      currentSpend in interface CostBudgetStore
    • clear

      public void clear()
      Description copied from interface: CostBudgetStore
      Drop every recorded spend entry — reset the store. Useful in tests; production callers should rely on TTL-based eviction.
      Specified by:
      clear in interface CostBudgetStore
    • size

      public int size()
      Returns:
      current entry count after eviction. For monitoring / tests.