Compare commits
No commits in common. "dev" and "v0.1.3" have entirely different histories.
24 changed files with 760 additions and 3375 deletions
|
|
@ -1,24 +0,0 @@
|
|||
version: 1
|
||||
|
||||
project:
|
||||
name: go-ratelimit
|
||||
description: Rate limiting
|
||||
binary: ""
|
||||
|
||||
build:
|
||||
cgo: false
|
||||
flags:
|
||||
- -trimpath
|
||||
ldflags:
|
||||
- -s
|
||||
- -w
|
||||
|
||||
targets:
|
||||
- os: linux
|
||||
arch: amd64
|
||||
- os: linux
|
||||
arch: arm64
|
||||
- os: darwin
|
||||
arch: arm64
|
||||
- os: windows
|
||||
arch: amd64
|
||||
|
|
@ -1,20 +0,0 @@
|
|||
version: 1
|
||||
|
||||
project:
|
||||
name: go-ratelimit
|
||||
repository: core/go-ratelimit
|
||||
|
||||
publishers: []
|
||||
|
||||
changelog:
|
||||
include:
|
||||
- feat
|
||||
- fix
|
||||
- perf
|
||||
- refactor
|
||||
exclude:
|
||||
- chore
|
||||
- docs
|
||||
- style
|
||||
- test
|
||||
- ci
|
||||
54
.github/workflows/ci.yml
vendored
54
.github/workflows/ci.yml
vendored
|
|
@ -1,54 +0,0 @@
|
|||
name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main, dev]
|
||||
pull_request:
|
||||
branches: [main]
|
||||
pull_request_review:
|
||||
types: [submitted]
|
||||
|
||||
jobs:
|
||||
test:
|
||||
if: github.event_name != 'pull_request_review'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: dAppCore/build/actions/build/core@dev
|
||||
with:
|
||||
go-version: "1.26"
|
||||
run-vet: "true"
|
||||
|
||||
auto-fix:
|
||||
if: >
|
||||
github.event_name == 'pull_request_review' &&
|
||||
github.event.review.user.login == 'coderabbitai' &&
|
||||
github.event.review.state == 'changes_requested'
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
pull-requests: write
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ github.event.pull_request.head.ref }}
|
||||
fetch-depth: 0
|
||||
- uses: dAppCore/build/actions/fix@dev
|
||||
with:
|
||||
go-version: "1.26"
|
||||
|
||||
auto-merge:
|
||||
if: >
|
||||
github.event_name == 'pull_request_review' &&
|
||||
github.event.review.user.login == 'coderabbitai' &&
|
||||
github.event.review.state == 'approved'
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
pull-requests: write
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Merge PR
|
||||
run: gh pr merge ${{ github.event.pull_request.number }} --merge --delete-branch
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
2
.gitignore
vendored
2
.gitignore
vendored
|
|
@ -1,2 +0,0 @@
|
|||
.core/
|
||||
.idea/
|
||||
72
CLAUDE.md
72
CLAUDE.md
|
|
@ -1,76 +1,28 @@
|
|||
<!-- SPDX-License-Identifier: EUPL-1.2 -->
|
||||
|
||||
# CLAUDE.md
|
||||
|
||||
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
|
||||
Token counting, model quotas, and sliding window rate limiter.
|
||||
|
||||
## Overview
|
||||
|
||||
Provider-agnostic sliding window rate limiter for LLM API calls. Single Go package (no sub-packages) with two persistence backends: YAML (single-process, default) and SQLite (multi-process, WAL mode). Enforces RPM, TPM, and RPD quotas per model. Ships default profiles for Gemini, OpenAI, Anthropic, and Local providers.
|
||||
|
||||
Module: `dappco.re/go/core/go-ratelimit` — Go 1.26, no CGO required.
|
||||
Module: `forge.lthn.ai/core/go-ratelimit`
|
||||
|
||||
## Commands
|
||||
|
||||
```bash
|
||||
go test ./... # run all tests
|
||||
go test -race ./... # race detector (required before commit)
|
||||
go test -v -run TestCanSend ./... # single test
|
||||
go test -v -run "TestCanSend/RPM_at_exact_limit" ./... # single subtest
|
||||
go test -bench=. -benchmem ./... # benchmarks
|
||||
go vet ./... # vet check
|
||||
golangci-lint run ./... # lint
|
||||
go test ./... # run all tests
|
||||
go test -race ./... # race detector (required before commit)
|
||||
go test -v -run Name ./... # single test
|
||||
go vet ./... # vet check
|
||||
```
|
||||
|
||||
Pre-commit gate: `go test -race ./...` and `go vet ./...` must both pass.
|
||||
|
||||
## Standards
|
||||
|
||||
- **UK English** everywhere: colour, organisation, serialise, initialise, behaviour
|
||||
- **Conventional commits**: `type(scope): description` — scopes: `ratelimit`, `sqlite`, `persist`, `config`
|
||||
- **Co-Author line** on every commit: `Co-Authored-By: Virgil <virgil@lethean.io>`
|
||||
- **Coverage** must not drop below 95%
|
||||
- **Error format**: `core.E("ratelimit.FunctionName", "what", err)` via `dappco.re/go/core` — lowercase, no trailing punctuation
|
||||
- **No `init()` functions**, no global mutable state
|
||||
- **Mutex discipline**: lock at the top of public methods, never inside helpers. Helpers that need the lock document "Caller must hold the lock". `prune()` mutates state, so even "read-only" methods that call it take the write lock. Never call a public method from another public method while holding the lock.
|
||||
|
||||
## Architecture
|
||||
|
||||
All code lives in the root package. Key files:
|
||||
|
||||
- `ratelimit.go` — core types (`RateLimiter`, `ModelQuota`, `UsageStats`, `Config`, `Provider`), sliding window logic (`prune`, `CanSend`, `RecordUsage`), YAML persistence, `CountTokens` (Gemini-specific), iterators (`Models`, `Iter`)
|
||||
- `sqlite.go` — `sqliteStore` internal type, schema creation, load/save for quotas and state
|
||||
|
||||
Constructor matrix: `New()` / `NewWithConfig()` for YAML, `NewWithSQLite()` / `NewWithSQLiteConfig()` for SQLite. Always `defer rl.Close()` with SQLite.
|
||||
|
||||
### Sliding window
|
||||
|
||||
1-minute window pruned on every `CanSend`/`Stats`/`RecordUsage` call. Daily counter is a rolling 24h window from first request, not a calendar boundary. Empty state entries are garbage-collected by `prune()` to prevent memory leaks.
|
||||
|
||||
## Test Organisation
|
||||
|
||||
White-box tests (`package ratelimit`), all assertions via `testify` (`require` for fatal, `assert` for non-fatal). Do not use `t.Error`/`t.Fatal` directly.
|
||||
|
||||
| File | Scope |
|
||||
|------|-------|
|
||||
| `ratelimit_test.go` | Core logic, provider profiles, concurrency, benchmarks |
|
||||
| `sqlite_test.go` | SQLite backend, migration, concurrent persistence |
|
||||
| `error_test.go` | Error paths for SQLite and YAML |
|
||||
| `iter_test.go` | Iterators, `CountTokens` edge cases |
|
||||
|
||||
SQLite tests use `_Good`/`_Bad`/`_Ugly` suffixes (happy path / expected errors / edge cases). Core tests use plain descriptive names with table-driven subtests. Use `t.TempDir()` for all file paths.
|
||||
|
||||
## Dependencies
|
||||
|
||||
Four direct dependencies — do not add more without justification:
|
||||
|
||||
- `dappco.re/go/core` — file I/O helpers, structured errors, JSON helpers, path/environment utilities
|
||||
- `gopkg.in/yaml.v3` — YAML backend
|
||||
- `modernc.org/sqlite` — pure Go SQLite (no CGO)
|
||||
- `github.com/stretchr/testify` — test-only
|
||||
- UK English
|
||||
- `go test -race ./...` and `go vet ./...` must pass before commit
|
||||
- Conventional commits: `type(scope): description`
|
||||
- Co-Author: `Co-Authored-By: Virgil <virgil@lethean.io>`
|
||||
- Coverage must not drop below 95%
|
||||
|
||||
## Docs
|
||||
|
||||
- `docs/architecture.md` — sliding window algorithm, provider quotas, YAML/SQLite backends, concurrency model
|
||||
- `docs/architecture.md` — sliding window algorithm, provider quotas, YAML/SQLite backends
|
||||
- `docs/development.md` — prerequisites, test patterns, coding standards
|
||||
- `docs/history.md` — completed phases with commit hashes, known limitations
|
||||
|
|
|
|||
|
|
@ -1,21 +1,15 @@
|
|||
<!-- SPDX-License-Identifier: EUPL-1.2 -->
|
||||
|
||||
# Contributing
|
||||
|
||||
Thank you for your interest in contributing!
|
||||
|
||||
## Requirements
|
||||
- **Go Version**: 1.26 or higher is required.
|
||||
- **Tools**: `golangci-lint` is recommended.
|
||||
- **Tools**: `golangci-lint` and `task` (Taskfile.dev) are recommended.
|
||||
|
||||
## Development Workflow
|
||||
1. **Testing**: Ensure all tests pass before submitting changes.
|
||||
```bash
|
||||
go build ./...
|
||||
go test ./...
|
||||
go test -race ./...
|
||||
go test -cover ./...
|
||||
go mod tidy
|
||||
```
|
||||
2. **Code Style**: All code must follow standard Go formatting.
|
||||
```bash
|
||||
|
|
@ -28,22 +22,14 @@ Thank you for your interest in contributing!
|
|||
```
|
||||
|
||||
## Commit Message Format
|
||||
We follow the [Conventional Commits](https://www.conventionalcommits.org/) specification using the repository format `type(scope): description`:
|
||||
We follow the [Conventional Commits](https://www.conventionalcommits.org/) specification:
|
||||
- `feat`: A new feature
|
||||
- `fix`: A bug fix
|
||||
- `docs`: Documentation changes
|
||||
- `refactor`: A code change that neither fixes a bug nor adds a feature
|
||||
- `chore`: Changes to the build process or auxiliary tools and libraries
|
||||
|
||||
Common scopes: `ratelimit`, `sqlite`, `persist`, `config`
|
||||
Example: `feat: add new endpoint for health check`
|
||||
|
||||
Example:
|
||||
|
||||
```text
|
||||
fix(ratelimit): align module metadata with dappco.re
|
||||
|
||||
Co-Authored-By: Virgil <virgil@lethean.io>
|
||||
```
|
||||
|
||||
## Licence
|
||||
## License
|
||||
By contributing to this project, you agree that your contributions will be licensed under the **European Union Public Licence (EUPL-1.2)**.
|
||||
|
|
|
|||
44
README.md
44
README.md
|
|
@ -1,50 +1,30 @@
|
|||
<!-- SPDX-License-Identifier: EUPL-1.2 -->
|
||||
|
||||
[](https://pkg.go.dev/dappco.re/go/core/go-ratelimit)
|
||||

|
||||
[](https://pkg.go.dev/forge.lthn.ai/core/go-ratelimit)
|
||||
[](LICENSE.md)
|
||||
[](go.mod)
|
||||
|
||||
# go-ratelimit
|
||||
|
||||
Provider-agnostic sliding window rate limiter for LLM API calls. Enforces requests per minute (RPM), tokens per minute (TPM), and requests per day (RPD) quotas per model using an in-memory sliding window. Ships with default quota profiles for Gemini, OpenAI, Anthropic, and a local inference provider. State persists across process restarts via YAML (single-process) or SQLite (multi-process, WAL mode). Includes a Gemini-specific token counting helper and a YAML-to-SQLite migration path.
|
||||
|
||||
**Module**: `dappco.re/go/core/go-ratelimit`
|
||||
**Module**: `forge.lthn.ai/core/go-ratelimit`
|
||||
**Licence**: EUPL-1.2
|
||||
**Language**: Go 1.26
|
||||
**Language**: Go 1.25
|
||||
|
||||
## Quick Start
|
||||
|
||||
```go
|
||||
import "dappco.re/go/core/go-ratelimit"
|
||||
import "forge.lthn.ai/core/go-ratelimit"
|
||||
|
||||
// YAML backend (default, single-process)
|
||||
rl, err := ratelimit.New()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
// SQLite backend (multi-process)
|
||||
rl, err = ratelimit.NewWithSQLite("/tmp/ratelimits.db")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
rl, err := ratelimit.NewWithSQLite("~/.core/ratelimits.db")
|
||||
defer rl.Close()
|
||||
|
||||
if rl.CanSend("gemini-2.0-flash", 1500) {
|
||||
rl.RecordUsage("gemini-2.0-flash", 1000, 500)
|
||||
}
|
||||
|
||||
if err := rl.Persist(); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
```
|
||||
|
||||
For agent workflows, `Decide` returns a structured verdict with retry guidance:
|
||||
|
||||
```go
|
||||
decision := rl.Decide("gemini-2.0-flash", 1500)
|
||||
if !decision.Allowed {
|
||||
log.Printf("throttled (%s); retry after %s", decision.Code, decision.RetryAfter)
|
||||
ok, reason := rl.CanSend("gemini-2.0-flash", 1500)
|
||||
if ok {
|
||||
rl.RecordUsage("gemini-2.0-flash", 1500)
|
||||
}
|
||||
```
|
||||
|
||||
|
|
@ -57,14 +37,12 @@ if !decision.Allowed {
|
|||
## Build & Test
|
||||
|
||||
```bash
|
||||
go build ./...
|
||||
go test ./...
|
||||
go test -race ./...
|
||||
go vet ./...
|
||||
go test -cover ./...
|
||||
go mod tidy
|
||||
go build ./...
|
||||
```
|
||||
|
||||
## Licence
|
||||
|
||||
European Union Public Licence 1.2.
|
||||
European Union Public Licence 1.2 — see [LICENCE](LICENCE) for details.
|
||||
|
|
|
|||
46
Taskfile.yml
Normal file
46
Taskfile.yml
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
version: '3'
|
||||
|
||||
tasks:
|
||||
test:
|
||||
desc: Run all tests
|
||||
cmds:
|
||||
- go test ./...
|
||||
|
||||
lint:
|
||||
desc: Run golangci-lint
|
||||
cmds:
|
||||
- golangci-lint run ./...
|
||||
|
||||
fmt:
|
||||
desc: Format all Go files
|
||||
cmds:
|
||||
- gofmt -w .
|
||||
|
||||
vet:
|
||||
desc: Run go vet
|
||||
cmds:
|
||||
- go vet ./...
|
||||
|
||||
build:
|
||||
desc: Build all Go packages
|
||||
cmds:
|
||||
- go build ./...
|
||||
|
||||
cov:
|
||||
desc: Run tests with coverage and open HTML report
|
||||
cmds:
|
||||
- go test -coverprofile=coverage.out ./...
|
||||
- go tool cover -html=coverage.out
|
||||
|
||||
tidy:
|
||||
desc: Tidy go.mod
|
||||
cmds:
|
||||
- go mod tidy
|
||||
|
||||
check:
|
||||
desc: Run fmt, vet, lint, and test in sequence
|
||||
cmds:
|
||||
- task: fmt
|
||||
- task: vet
|
||||
- task: lint
|
||||
- task: test
|
||||
|
|
@ -1,40 +0,0 @@
|
|||
<!-- SPDX-License-Identifier: EUPL-1.2 -->
|
||||
|
||||
# API Contract
|
||||
|
||||
Test coverage is marked `yes` when the symbol is exercised by the existing test suite in `ratelimit_test.go`, `sqlite_test.go`, `error_test.go`, or `iter_test.go`.
|
||||
|
||||
| Kind | Name | Signature | Description | Test coverage |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| Type | `Provider` | `type Provider string` | Identifies an LLM provider used to select default quota profiles. | yes |
|
||||
| Type | `ModelQuota` | `type ModelQuota struct { MaxRPM int; MaxTPM int; MaxRPD int }` | Declares per-model RPM, TPM, and RPD limits; `0` means unlimited. | yes |
|
||||
| Type | `ProviderProfile` | `type ProviderProfile struct { Provider Provider; Models map[string]ModelQuota }` | Bundles a provider identifier with its default model quota map. | yes |
|
||||
| Type | `Config` | `type Config struct { FilePath string; Backend string; Quotas map[string]ModelQuota; Providers []Provider }` | Configures limiter initialisation, persistence settings, explicit quotas, and provider defaults. | yes |
|
||||
| Type | `TokenEntry` | `type TokenEntry struct { Time time.Time; Count int }` | Records a timestamped token-usage event. | yes |
|
||||
| Type | `UsageStats` | `type UsageStats struct { Requests []time.Time; Tokens []TokenEntry; DayStart time.Time; DayCount int }` | Stores per-model sliding-window request and token history plus rolling daily usage state. | yes |
|
||||
| Type | `RateLimiter` | `type RateLimiter struct { Quotas map[string]ModelQuota; State map[string]*UsageStats }` | Manages quotas, usage state, persistence, and concurrency across models. | yes |
|
||||
| Type | `ModelStats` | `type ModelStats struct { RPM int; MaxRPM int; TPM int; MaxTPM int; RPD int; MaxRPD int; DayStart time.Time }` | Represents a snapshot of current usage and configured limits for a model. | yes |
|
||||
| Type | `DecisionCode` | `type DecisionCode string` | Machine-readable allow/deny codes returned by `Decide` (e.g., `ok`, `rpm_exceeded`). | yes |
|
||||
| Type | `Decision` | `type Decision struct { Allowed bool; Code DecisionCode; Reason string; RetryAfter time.Duration; Stats ModelStats }` | Structured decision result with a code, human-readable reason, optional retry guidance, and a stats snapshot. | yes |
|
||||
| Function | `DefaultProfiles` | `func DefaultProfiles() map[Provider]ProviderProfile` | Returns the built-in quota profiles for the supported providers. | yes |
|
||||
| Function | `New` | `func New() (*RateLimiter, error)` | Creates a new limiter with Gemini defaults for backward-compatible YAML-backed usage. | yes |
|
||||
| Function | `NewWithConfig` | `func NewWithConfig(cfg Config) (*RateLimiter, error)` | Creates a YAML-backed limiter from explicit configuration, defaulting to Gemini when config is empty. | yes |
|
||||
| Function | `NewWithSQLite` | `func NewWithSQLite(dbPath string) (*RateLimiter, error)` | Creates a SQLite-backed limiter with Gemini defaults and opens or creates the database. | yes |
|
||||
| Function | `NewWithSQLiteConfig` | `func NewWithSQLiteConfig(dbPath string, cfg Config) (*RateLimiter, error)` | Creates a SQLite-backed limiter from explicit configuration and always uses SQLite persistence. | yes |
|
||||
| Function | `MigrateYAMLToSQLite` | `func MigrateYAMLToSQLite(yamlPath, sqlitePath string) error` | Migrates quotas and usage state from a YAML state file into a SQLite database. | yes |
|
||||
| Function | `CountTokens` | `func CountTokens(ctx context.Context, apiKey, model, text string) (int, error)` | Calls the Gemini `countTokens` API for a prompt and returns the reported token count. | yes |
|
||||
| Method | `SetQuota` | `func (rl *RateLimiter) SetQuota(model string, quota ModelQuota)` | Sets or replaces a model quota at runtime. | yes |
|
||||
| Method | `AddProvider` | `func (rl *RateLimiter) AddProvider(provider Provider)` | Loads a built-in provider profile and overwrites any matching model quotas. | yes |
|
||||
| Method | `Load` | `func (rl *RateLimiter) Load() error` | Loads quotas and usage state from YAML or SQLite into memory. | yes |
|
||||
| Method | `Persist` | `func (rl *RateLimiter) Persist() error` | Persists a snapshot of quotas and usage state to YAML or SQLite. | yes |
|
||||
| Method | `BackgroundPrune` | `func (rl *RateLimiter) BackgroundPrune(interval time.Duration) func()` | Starts periodic pruning of expired usage state and returns a stop function. | yes |
|
||||
| Method | `CanSend` | `func (rl *RateLimiter) CanSend(model string, estimatedTokens int) bool` | Reports whether a request with the estimated token count fits within current limits. | yes |
|
||||
| Method | `Decide` | `func (rl *RateLimiter) Decide(model string, estimatedTokens int) Decision` | Returns structured allow/deny information including code, reason, retry guidance, and stats snapshot without recording usage. | yes |
|
||||
| Method | `RecordUsage` | `func (rl *RateLimiter) RecordUsage(model string, promptTokens, outputTokens int)` | Records a successful request into the sliding-window and daily counters. | yes |
|
||||
| Method | `WaitForCapacity` | `func (rl *RateLimiter) WaitForCapacity(ctx context.Context, model string, tokens int) error` | Blocks until `Decide` allows the request, sleeping according to `RetryAfter` hints or one-second polls. | yes |
|
||||
| Method | `Reset` | `func (rl *RateLimiter) Reset(model string)` | Clears usage state for one model or for all models when `model` is empty. | yes |
|
||||
| Method | `Models` | `func (rl *RateLimiter) Models() iter.Seq[string]` | Returns a sorted iterator of all model names known from quotas or state. | yes |
|
||||
| Method | `Iter` | `func (rl *RateLimiter) Iter() iter.Seq2[string, ModelStats]` | Returns a sorted iterator of model names paired with current stats snapshots. | yes |
|
||||
| Method | `Stats` | `func (rl *RateLimiter) Stats(model string) ModelStats` | Returns current stats for a single model after pruning expired usage. | yes |
|
||||
| Method | `AllStats` | `func (rl *RateLimiter) AllStats() map[string]ModelStats` | Returns stats snapshots for every tracked model. | yes |
|
||||
| Method | `Close` | `func (rl *RateLimiter) Close() error` | Closes SQLite resources for SQLite-backed limiters and is a no-op for YAML-backed limiters. | yes |
|
||||
|
|
@ -1,74 +1,81 @@
|
|||
<!-- SPDX-License-Identifier: EUPL-1.2 -->
|
||||
|
||||
---
|
||||
title: Architecture
|
||||
description: Internals of go-ratelimit -- sliding window algorithm, provider quota system, persistence backends, and concurrency model.
|
||||
---
|
||||
|
||||
# Architecture
|
||||
|
||||
go-ratelimit is a provider-agnostic rate limiter for LLM API calls. It enforces
|
||||
three independent quota dimensions per model -- requests per minute (RPM), tokens
|
||||
per minute (TPM), and requests per day (RPD) -- using an in-memory sliding window
|
||||
three independent quota dimensions per model — requests per minute (RPM), tokens
|
||||
per minute (TPM), and requests per day (RPD) — using an in-memory sliding window
|
||||
that can be persisted across process restarts via YAML or SQLite.
|
||||
|
||||
Module path: `dappco.re/go/core/go-ratelimit`
|
||||
Module path: `forge.lthn.ai/core/go-ratelimit`
|
||||
|
||||
---
|
||||
|
||||
## Key Types
|
||||
## Sliding Window Algorithm
|
||||
|
||||
### RateLimiter
|
||||
|
||||
The central struct. Holds the quota definitions, current usage state, a mutex for
|
||||
thread safety, and an optional SQLite backend reference.
|
||||
|
||||
```go
|
||||
type RateLimiter struct {
|
||||
mu sync.RWMutex
|
||||
Quotas map[string]ModelQuota // per-model quota definitions
|
||||
State map[string]*UsageStats // per-model sliding window state
|
||||
filePath string // YAML file path (ignored when SQLite is active)
|
||||
sqlite *sqliteStore // non-nil when using SQLite backend
|
||||
}
|
||||
```
|
||||
|
||||
### ModelQuota
|
||||
|
||||
Defines the rate limits for a single model. A zero value in any field means that
|
||||
dimension is unlimited.
|
||||
|
||||
```go
|
||||
type ModelQuota struct {
|
||||
MaxRPM int `yaml:"max_rpm"` // Requests per minute (0 = unlimited)
|
||||
MaxTPM int `yaml:"max_tpm"` // Tokens per minute (0 = unlimited)
|
||||
MaxRPD int `yaml:"max_rpd"` // Requests per day (0 = unlimited)
|
||||
}
|
||||
```
|
||||
|
||||
### UsageStats
|
||||
|
||||
Tracks the sliding window state for a single model.
|
||||
The limiter maintains per-model `UsageStats` structs in memory:
|
||||
|
||||
```go
|
||||
type UsageStats struct {
|
||||
Requests []time.Time // timestamps of recent requests (1-minute window)
|
||||
Tokens []TokenEntry // token counts with timestamps (1-minute window)
|
||||
DayStart time.Time // when the current 24-hour window started
|
||||
DayCount int // total requests since DayStart
|
||||
}
|
||||
|
||||
type TokenEntry struct {
|
||||
Time time.Time
|
||||
Count int // prompt + output tokens for this request
|
||||
DayStart time.Time // when the current daily window started
|
||||
DayCount int // total requests recorded since DayStart
|
||||
}
|
||||
```
|
||||
|
||||
### Config
|
||||
|
||||
Controls `RateLimiter` initialisation.
|
||||
Every call to `CanSend()` or `Stats()` first calls `prune()`, which scans both
|
||||
slices and discards entries older than `now - 1 minute`. Pruning is done
|
||||
in-place to avoid allocation on the hot path:
|
||||
|
||||
```go
|
||||
validReqs := 0
|
||||
for _, t := range stats.Requests {
|
||||
if t.After(window) {
|
||||
stats.Requests[validReqs] = t
|
||||
validReqs++
|
||||
}
|
||||
}
|
||||
stats.Requests = stats.Requests[:validReqs]
|
||||
```
|
||||
|
||||
The same loop runs for token entries. After pruning, `CanSend()` checks each
|
||||
quota dimension in priority order: RPD first (cheapest check), then RPM, then
|
||||
TPM. A zero value for any dimension means that dimension is unlimited. If all
|
||||
three are zero the model is treated as fully unlimited and the check short-circuits
|
||||
before touching any state.
|
||||
|
||||
### Daily Reset
|
||||
|
||||
The daily counter resets automatically inside `prune()`. When
|
||||
`now - stats.DayStart >= 24h`, `DayCount` is set to zero and `DayStart` is set
|
||||
to the current time. This means the daily window is a rolling 24-hour period
|
||||
anchored to the first request of the day, not a calendar boundary.
|
||||
|
||||
### Concurrency
|
||||
|
||||
All reads and writes are protected by a single `sync.RWMutex`. Methods that
|
||||
write state — `CanSend()`, `RecordUsage()`, `Reset()`, `Load()` — acquire a
|
||||
full write lock. `Persist()`, `Stats()`, and `AllStats()` acquire a read lock
|
||||
where possible. The `CanSend()` method acquires a write lock because it calls
|
||||
`prune()`, which mutates the state slices.
|
||||
|
||||
`go test -race ./...` passes clean with 20 goroutines performing concurrent
|
||||
`CanSend()`, `RecordUsage()`, and `Stats()` calls.
|
||||
|
||||
---
|
||||
|
||||
## Provider and Quota Configuration
|
||||
|
||||
### Types
|
||||
|
||||
```go
|
||||
type Provider string // "gemini", "openai", "anthropic", "local"
|
||||
|
||||
type ModelQuota struct {
|
||||
MaxRPM int `yaml:"max_rpm"` // 0 = unlimited
|
||||
MaxTPM int `yaml:"max_tpm"`
|
||||
MaxRPD int `yaml:"max_rpd"`
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
FilePath string // default: ~/.core/ratelimits.yaml
|
||||
Backend string // "yaml" (default) or "sqlite"
|
||||
|
|
@ -77,116 +84,32 @@ type Config struct {
|
|||
}
|
||||
```
|
||||
|
||||
### Provider
|
||||
### Quota Resolution
|
||||
|
||||
A string type identifying an LLM provider. Four constants are defined:
|
||||
|
||||
```go
|
||||
type Provider string
|
||||
|
||||
const (
|
||||
ProviderGemini Provider = "gemini"
|
||||
ProviderOpenAI Provider = "openai"
|
||||
ProviderAnthropic Provider = "anthropic"
|
||||
ProviderLocal Provider = "local"
|
||||
)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Sliding Window Algorithm
|
||||
|
||||
Every call to `CanSend()` or `Stats()` first calls `prune()`, which removes
|
||||
entries older than one minute from the `Requests` and `Tokens` slices. Pruning
|
||||
is done in-place using `slices.DeleteFunc` to minimise allocations:
|
||||
|
||||
```go
|
||||
window := now.Add(-1 * time.Minute)
|
||||
|
||||
stats.Requests = slices.DeleteFunc(stats.Requests, func(t time.Time) bool {
|
||||
return t.Before(window)
|
||||
})
|
||||
stats.Tokens = slices.DeleteFunc(stats.Tokens, func(t TokenEntry) bool {
|
||||
return t.Time.Before(window)
|
||||
})
|
||||
```
|
||||
|
||||
After pruning, `CanSend()` checks each quota dimension. If all three limits
|
||||
(RPM, TPM, RPD) are zero, the model is treated as fully unlimited and the
|
||||
check short-circuits before touching any state.
|
||||
|
||||
The check order is: RPD, then RPM, then TPM. RPD is checked first because it
|
||||
is the cheapest comparison (a single integer). TPM is checked last because it
|
||||
requires summing the token counts in the sliding window.
|
||||
|
||||
`Decide()` follows the same path as `CanSend()` but returns a structured
|
||||
`Decision` containing a machine-readable code, reason, `RetryAfter` guidance,
|
||||
and a `ModelStats` snapshot. It is agent-facing and does not record usage;
|
||||
`WaitForCapacity()` consumes its `RetryAfter` hint to avoid unnecessary
|
||||
one-second polling when limits are saturated.
|
||||
|
||||
### Daily Reset
|
||||
|
||||
The daily counter resets automatically inside `prune()`. When
|
||||
`now - stats.DayStart >= 24h`, `DayCount` is set to zero and `DayStart` is
|
||||
updated to the current time. The daily window is a rolling 24-hour period
|
||||
anchored to the first request of the day, not a calendar boundary.
|
||||
|
||||
### Background Pruning
|
||||
|
||||
`BackgroundPrune(interval)` starts a goroutine that periodically prunes all
|
||||
model states on a configurable interval. It returns a cancel function to stop
|
||||
the pruner:
|
||||
|
||||
```go
|
||||
stop := rl.BackgroundPrune(30 * time.Second)
|
||||
defer stop()
|
||||
```
|
||||
|
||||
This prevents memory growth in long-running processes where some models may
|
||||
accumulate stale entries between calls to `CanSend()`.
|
||||
|
||||
### Memory Cleanup
|
||||
|
||||
When `prune()` empties both the `Requests` and `Tokens` slices for a model,
|
||||
and `DayCount` is also zero, the entire `UsageStats` entry is deleted from
|
||||
the `State` map. This prevents memory leaks from models that were used once
|
||||
and never again.
|
||||
|
||||
---
|
||||
|
||||
## Provider and Quota Configuration
|
||||
|
||||
### Quota Resolution Order
|
||||
|
||||
1. Provider profiles are loaded first from `DefaultProfiles()`.
|
||||
2. Explicit `Config.Quotas` are merged on top using `maps.Copy`, overriding any
|
||||
matching model.
|
||||
1. Provider profiles are loaded first (from `DefaultProfiles()`).
|
||||
2. Explicit `Config.Quotas` are merged on top, overriding any matching model.
|
||||
3. If neither `Providers` nor `Quotas` are specified, Gemini defaults are used.
|
||||
|
||||
`SetQuota()` and `AddProvider()` allow runtime modification. Both acquire the
|
||||
write lock. `AddProvider()` is additive -- it does not remove existing quotas for
|
||||
models outside the new provider's profile.
|
||||
`SetQuota()` and `AddProvider()` allow runtime modification; both are
|
||||
mutex-protected. `AddProvider()` is additive — it does not remove existing
|
||||
quotas for models outside the new provider's profile.
|
||||
|
||||
### Default Quotas (as of February 2026)
|
||||
|
||||
| Provider | Model | MaxRPM | MaxTPM | MaxRPD |
|
||||
|-----------|------------------------|-----------|-------------|-----------|
|
||||
| Gemini | gemini-3-pro-preview | 150 | 1,000,000 | 1,000 |
|
||||
| Gemini | gemini-3-flash-preview | 150 | 1,000,000 | 1,000 |
|
||||
| Gemini | gemini-2.5-pro | 150 | 1,000,000 | 1,000 |
|
||||
| Gemini | gemini-2.0-flash | 150 | 1,000,000 | unlimited |
|
||||
| Gemini | gemini-2.0-flash-lite | unlimited | unlimited | unlimited |
|
||||
| OpenAI | gpt-4o | 500 | 30,000 | unlimited |
|
||||
| OpenAI | gpt-4o-mini | 500 | 200,000 | unlimited |
|
||||
| OpenAI | gpt-4-turbo | 500 | 30,000 | unlimited |
|
||||
| OpenAI | o1 | 500 | 30,000 | unlimited |
|
||||
| OpenAI | o1-mini | 500 | 200,000 | unlimited |
|
||||
| OpenAI | o3-mini | 500 | 200,000 | unlimited |
|
||||
| Anthropic | claude-opus-4 | 50 | 40,000 | unlimited |
|
||||
| Anthropic | claude-sonnet-4 | 50 | 40,000 | unlimited |
|
||||
| Anthropic | claude-haiku-3.5 | 50 | 50,000 | unlimited |
|
||||
| Local | (none by default) | user-defined |
|
||||
| Provider | Model | MaxRPM | MaxTPM | MaxRPD |
|
||||
|-----------|------------------------|-----------|-----------|-----------|
|
||||
| Gemini | gemini-3-pro-preview | 150 | 1,000,000 | 1,000 |
|
||||
| Gemini | gemini-3-flash-preview | 150 | 1,000,000 | 1,000 |
|
||||
| Gemini | gemini-2.5-pro | 150 | 1,000,000 | 1,000 |
|
||||
| Gemini | gemini-2.0-flash | 150 | 1,000,000 | unlimited |
|
||||
| Gemini | gemini-2.0-flash-lite | unlimited | unlimited | unlimited |
|
||||
| OpenAI | gpt-4o, gpt-4-turbo | 500 | 30,000 | unlimited |
|
||||
| OpenAI | gpt-4o-mini, o1-mini | 500 | 200,000 | unlimited |
|
||||
| OpenAI | o1, o3-mini | 500 | varies | unlimited |
|
||||
| Anthropic | claude-opus-4 | 50 | 40,000 | unlimited |
|
||||
| Anthropic | claude-sonnet-4 | 50 | 40,000 | unlimited |
|
||||
| Anthropic | claude-haiku-3.5 | 50 | 50,000 | unlimited |
|
||||
| Local | (none by default) | user-defined |
|
||||
|
||||
The Local provider exists for local inference backends (Ollama, MLX, llama.cpp)
|
||||
where the throttle limit is hardware rather than an API quota. No defaults are
|
||||
|
|
@ -194,54 +117,10 @@ provided; callers add per-model limits via `Config.Quotas` or `SetQuota()`.
|
|||
|
||||
---
|
||||
|
||||
## Constructors
|
||||
## YAML Persistence (Legacy)
|
||||
|
||||
| Function | Backend | Default Provider |
|
||||
|----------|---------|------------------|
|
||||
| `New()` | YAML | Gemini |
|
||||
| `NewWithConfig(cfg)` | YAML | Configurable (Gemini if empty) |
|
||||
| `NewWithSQLite(dbPath)` | SQLite | Gemini |
|
||||
| `NewWithSQLiteConfig(dbPath, cfg)` | SQLite | Configurable (Gemini if empty) |
|
||||
|
||||
`Close()` releases the database connection for SQLite-backed limiters. It is a
|
||||
no-op on YAML-backed limiters. Always call `Close()` (or `defer rl.Close()`)
|
||||
when using the SQLite backend.
|
||||
|
||||
---
|
||||
|
||||
## Data Flow
|
||||
|
||||
A typical request lifecycle:
|
||||
|
||||
```
|
||||
1. CanSend(model, estimatedTokens)
|
||||
|-- acquires write lock
|
||||
|-- looks up ModelQuota for the model
|
||||
|-- if unknown model or all-zero quota: returns true (allowed)
|
||||
|-- calls prune(model) to discard stale entries
|
||||
|-- checks RPD, RPM, TPM against the pruned state
|
||||
'-- returns true/false
|
||||
|
||||
2. (caller makes the API call)
|
||||
|
||||
3. RecordUsage(model, promptTokens, outputTokens)
|
||||
|-- acquires write lock
|
||||
|-- calls prune(model)
|
||||
|-- appends to Requests and Tokens slices
|
||||
'-- increments DayCount
|
||||
|
||||
4. Persist()
|
||||
|-- acquires write lock, clones state, releases lock
|
||||
|-- YAML: marshals to file
|
||||
'-- SQLite: saves quotas and state in transactions
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## YAML Persistence
|
||||
|
||||
The default backend serialises both the `Quotas` map and the `State` map to a
|
||||
YAML file at `~/.core/ratelimits.yaml` (configurable via `Config.FilePath`).
|
||||
The default backend serialises the entire `RateLimiter` struct — both the
|
||||
`Quotas` map and the `State` map — to a YAML file at `~/.core/ratelimits.yaml`.
|
||||
|
||||
```yaml
|
||||
quotas:
|
||||
|
|
@ -260,34 +139,39 @@ state:
|
|||
day_count: 42
|
||||
```
|
||||
|
||||
`Persist()` creates parent directories with the `core.Fs` helper before writing.
|
||||
`Persist()` creates parent directories with `os.MkdirAll` before writing.
|
||||
`Load()` treats a missing file as an empty state (no error). Corrupt or
|
||||
unreadable files return an error.
|
||||
|
||||
**Limitations of the YAML backend:**
|
||||
|
||||
**Limitations of YAML backend:**
|
||||
- Single-process only. Concurrent writes from multiple processes corrupt the
|
||||
file because the write is not atomic at the OS level.
|
||||
- The entire state is serialised on every `Persist()` call.
|
||||
- Timestamps are serialised as RFC 3339 strings.
|
||||
- The entire state is serialised on every `Persist()` call, which grows linearly
|
||||
with the number of tracked models and entries.
|
||||
- Timestamps are serialised as RFC3339 strings; sub-nanosecond precision is
|
||||
preserved by Go's time marshaller but depends on the YAML library.
|
||||
|
||||
---
|
||||
|
||||
## SQLite Backend
|
||||
|
||||
The SQLite backend supports multi-process scenarios. It uses `modernc.org/sqlite`,
|
||||
a pure Go port of SQLite that compiles without CGO.
|
||||
The SQLite backend was added in Phase 2 to support multi-process scenarios and
|
||||
provide a more robust persistence layer. It uses `modernc.org/sqlite` — a pure
|
||||
Go port of SQLite that compiles without CGO.
|
||||
|
||||
### Connection Settings
|
||||
|
||||
```go
|
||||
db.SetMaxOpenConns(1) // single connection for PRAGMA consistency
|
||||
db.Exec("PRAGMA journal_mode=WAL") // concurrent readers alongside a single writer
|
||||
db.Exec("PRAGMA busy_timeout=5000") // 5-second wait on lock contention
|
||||
db.SetMaxOpenConns(1) // single connection for PRAGMA consistency
|
||||
db.Exec("PRAGMA journal_mode=WAL") // WAL mode for concurrent readers
|
||||
db.Exec("PRAGMA busy_timeout=5000") // 5-second busy timeout
|
||||
```
|
||||
|
||||
WAL mode allows one writer and multiple concurrent readers. The 5-second busy
|
||||
timeout prevents immediate failure when a second process is mid-commit.
|
||||
timeout prevents immediate failure when a second process is mid-commit. A single
|
||||
`sql.DB` connection is used because SQLite's WAL mode handles reader concurrency
|
||||
at the file level; multiple Go connections to the same file through a single
|
||||
process would not add throughput but would complicate locking.
|
||||
|
||||
### Schema
|
||||
|
||||
|
|
@ -312,7 +196,7 @@ CREATE TABLE IF NOT EXISTS tokens (
|
|||
|
||||
CREATE TABLE IF NOT EXISTS daily (
|
||||
model TEXT PRIMARY KEY,
|
||||
day_start INTEGER NOT NULL, -- UnixNano
|
||||
day_start INTEGER NOT NULL, -- UnixNano
|
||||
day_count INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
|
||||
|
|
@ -321,22 +205,51 @@ CREATE INDEX IF NOT EXISTS idx_tokens_model_ts ON tokens(model, ts);
|
|||
```
|
||||
|
||||
Timestamps are stored as `INTEGER` UnixNano values. This preserves nanosecond
|
||||
precision and allows efficient range queries using the composite indices.
|
||||
precision without relying on SQLite's text date format, and allows efficient
|
||||
range queries using the composite indices.
|
||||
|
||||
### Save Strategy
|
||||
|
||||
- **Quotas**: full snapshot replace inside a single transaction. `saveQuotas()`
|
||||
clears the table and reinserts the current quota map.
|
||||
- **State**: Delete-then-insert inside a single transaction. All three state
|
||||
tables (`requests`, `tokens`, `daily`) are truncated and rewritten atomically.
|
||||
`saveState()` uses a delete-then-insert pattern inside a single transaction.
|
||||
All three state tables are truncated and rewritten atomically:
|
||||
|
||||
```go
|
||||
tx.Exec("DELETE FROM requests")
|
||||
tx.Exec("DELETE FROM tokens")
|
||||
tx.Exec("DELETE FROM daily")
|
||||
// then INSERT for every model in state
|
||||
tx.Commit()
|
||||
```
|
||||
|
||||
`saveQuotas()` uses `INSERT ... ON CONFLICT(model) DO UPDATE` (upsert) so
|
||||
existing quota rows are updated in place without deleting unrelated models.
|
||||
|
||||
### Constructors
|
||||
|
||||
```go
|
||||
// YAML backend (default)
|
||||
rl, err := ratelimit.New()
|
||||
rl, err := ratelimit.NewWithConfig(cfg)
|
||||
|
||||
// SQLite backend
|
||||
rl, err := ratelimit.NewWithSQLite(dbPath)
|
||||
rl, err := ratelimit.NewWithSQLiteConfig(dbPath, cfg)
|
||||
|
||||
defer rl.Close() // releases the database connection
|
||||
```
|
||||
|
||||
`Close()` is a no-op on YAML-backed limiters.
|
||||
|
||||
---
|
||||
|
||||
## Migration Path
|
||||
|
||||
`MigrateYAMLToSQLite(yamlPath, sqlitePath)` reads an existing YAML state file
|
||||
and writes all quotas and usage state to a new SQLite database. The function is
|
||||
idempotent -- running it again overwrites the SQLite database state.
|
||||
`MigrateYAMLToSQLite(yamlPath, sqlitePath string) error` reads an existing YAML
|
||||
state file and writes all quotas and usage state to a new SQLite database. The
|
||||
function is idempotent — running it again on the same YAML file overwrites the
|
||||
SQLite database state.
|
||||
|
||||
Typical one-time migration:
|
||||
|
||||
```go
|
||||
err := ratelimit.MigrateYAMLToSQLite(
|
||||
|
|
@ -345,59 +258,29 @@ err := ratelimit.MigrateYAMLToSQLite(
|
|||
)
|
||||
```
|
||||
|
||||
After migration, switch the constructor from `New()` to `NewWithSQLite()`. The
|
||||
YAML file can be kept as a backup; the two backends do not share state.
|
||||
|
||||
---
|
||||
|
||||
## Iterators
|
||||
|
||||
Two Go 1.26+ iterators are provided for inspecting the limiter state:
|
||||
|
||||
- `Models() iter.Seq[string]` -- returns a sorted sequence of all model names
|
||||
(from both `Quotas` and `State` maps, deduplicated).
|
||||
- `Iter() iter.Seq2[string, ModelStats]` -- returns sorted model names paired
|
||||
with their current `ModelStats` snapshot.
|
||||
After migration, switch the constructor:
|
||||
|
||||
```go
|
||||
for model, stats := range rl.Iter() {
|
||||
fmt.Printf("%s: %d/%d RPM, %d/%d TPM\n",
|
||||
model, stats.RPM, stats.MaxRPM, stats.TPM, stats.MaxTPM)
|
||||
}
|
||||
// Before
|
||||
rl, _ := ratelimit.New()
|
||||
|
||||
// After
|
||||
rl, _ := ratelimit.NewWithSQLite(filepath.Join(home, ".core", "ratelimits.db"))
|
||||
defer rl.Close()
|
||||
```
|
||||
|
||||
The YAML file can be kept as a backup; the two backends do not share state.
|
||||
|
||||
---
|
||||
|
||||
## CountTokens
|
||||
|
||||
`CountTokens(ctx, apiKey, model, text)` calls the Google Generative Language API
|
||||
to obtain an exact token count for a prompt string. It is Gemini-specific and
|
||||
hardcodes the `generativelanguage.googleapis.com` endpoint.
|
||||
`CountTokens(apiKey, model, text string) (int, error)` calls the Google
|
||||
Generative Language API to obtain an exact token count for a prompt string. It
|
||||
is Gemini-specific and hardcodes the `generativelanguage.googleapis.com`
|
||||
endpoint. The URL is not configurable, which prevents unit testing of the
|
||||
success path without network access.
|
||||
|
||||
For other providers, callers must supply `estimatedTokens` directly to
|
||||
`CanSend()`. Accurate token counts are typically available in API response
|
||||
metadata after a call completes.
|
||||
|
||||
---
|
||||
|
||||
## Concurrency Model
|
||||
|
||||
All reads and writes are protected by a single `sync.RWMutex` on the
|
||||
`RateLimiter` struct.
|
||||
|
||||
| Method | Lock type | Reason |
|
||||
|--------|-----------|--------|
|
||||
| `CanSend()` | Write | Calls `prune()`, which mutates state slices |
|
||||
| `RecordUsage()` | Write | Appends to state slices |
|
||||
| `Reset()` | Write | Deletes state entries |
|
||||
| `Load()` | Write | Replaces in-memory state |
|
||||
| `SetQuota()` | Write | Modifies quota map |
|
||||
| `AddProvider()` | Write | Modifies quota map |
|
||||
| `Persist()` | Write (brief) | Clones state, then releases lock before I/O |
|
||||
| `Stats()` | Write | Calls `prune()` |
|
||||
| `AllStats()` | Write | Prunes inline |
|
||||
| `Models()` | Read | Reads keys only |
|
||||
|
||||
`Persist()` minimises lock contention by cloning the state under a write lock,
|
||||
then performing I/O after releasing the lock. The test suite passes clean under
|
||||
`go test -race ./...` with 20 goroutines performing concurrent operations.
|
||||
`CanSend()` and `RecordUsage()`. Accurate token counts are typically available
|
||||
in API response metadata after a call completes.
|
||||
|
|
|
|||
|
|
@ -1,75 +0,0 @@
|
|||
<!-- SPDX-License-Identifier: EUPL-1.2 -->
|
||||
|
||||
# Convention Drift Check
|
||||
|
||||
Date: 2026-03-23
|
||||
|
||||
`CODEX.md` was not present anywhere under `/workspace`, so this check used
|
||||
`CLAUDE.md`, `docs/development.md`, and the current tree.
|
||||
|
||||
## stdlib -> core.*
|
||||
|
||||
- `CLAUDE.md:65` still documents `forge.lthn.ai/core/go-io`, while the direct
|
||||
dependency in `go.mod:6` is `dappco.re/go/core/io`.
|
||||
- `CLAUDE.md:66` still documents `forge.lthn.ai/core/go-log`, while the direct
|
||||
dependency in `go.mod:7` is `dappco.re/go/core/log`.
|
||||
- `docs/development.md:175` still mandates `fmt.Errorf("ratelimit.Function: what: %w", err)`,
|
||||
but the implementation and repo guidance use `coreerr.E(...)`
|
||||
(`ratelimit.go:19`, `sqlite.go:8`, `CLAUDE.md:31`).
|
||||
- `docs/development.md:195` omits the `core.*` direct dependencies entirely;
|
||||
`go.mod:6-7` now declares both `dappco.re/go/core/io` and
|
||||
`dappco.re/go/core/log`.
|
||||
- `docs/index.md:102` likewise omits the `core.*` direct dependencies that are
|
||||
present in `go.mod:6-7`.
|
||||
|
||||
## UK English
|
||||
|
||||
- `README.md:2` uses `License` in the badge alt text.
|
||||
- `CONTRIBUTING.md:34` uses `License` as the section heading.
|
||||
|
||||
## Missing Tests
|
||||
|
||||
- `docs/development.md:150` says current coverage is `95.1%` and the floor is
|
||||
`95%`, but `go test -coverprofile=/tmp/convention-cover.out ./...` currently
|
||||
reports `94.4%`.
|
||||
- `docs/history.md:28` still records coverage as `95.1%`; the current tree is
|
||||
below that figure at `94.4%`.
|
||||
- `docs/history.md:66` and `docs/development.md:157` say the
|
||||
`os.UserHomeDir()` branch in `NewWithConfig()` is untestable, but
|
||||
`error_test.go:648` now exercises that path.
|
||||
- `ratelimit.go:202` (`Load`) is only `90.0%` covered.
|
||||
- `ratelimit.go:242` (`Persist`) is only `90.0%` covered.
|
||||
- `ratelimit.go:650` (`CountTokens`) is only `71.4%` covered.
|
||||
- `sqlite.go:20` (`newSQLiteStore`) is only `64.3%` covered.
|
||||
- `sqlite.go:110` (`loadQuotas`) is only `92.9%` covered.
|
||||
- `sqlite.go:194` (`loadState`) is only `88.6%` covered.
|
||||
- `ratelimit_test.go:746` starts a mock server for `CountTokens`, but the test
|
||||
contains no assertion that exercises the success path.
|
||||
- `iter_test.go:108` starts a second mock server for `CountTokens`, but again
|
||||
does not exercise the mocked path.
|
||||
- `error_test.go:42` defines `TestSQLiteInitErrors`, but the `WAL pragma failure`
|
||||
subtest is still an empty placeholder.
|
||||
|
||||
## SPDX Headers
|
||||
|
||||
- `CLAUDE.md:1` is missing an SPDX header.
|
||||
- `CONTRIBUTING.md:1` is missing an SPDX header.
|
||||
- `README.md:1` is missing an SPDX header.
|
||||
- `docs/architecture.md:1` is missing an SPDX header.
|
||||
- `docs/development.md:1` is missing an SPDX header.
|
||||
- `docs/history.md:1` is missing an SPDX header.
|
||||
- `docs/index.md:1` is missing an SPDX header.
|
||||
- `error_test.go:1` is missing an SPDX header.
|
||||
- `go.mod:1` is missing an SPDX header.
|
||||
- `iter_test.go:1` is missing an SPDX header.
|
||||
- `ratelimit.go:1` is missing an SPDX header.
|
||||
- `ratelimit_test.go:1` is missing an SPDX header.
|
||||
- `sqlite.go:1` is missing an SPDX header.
|
||||
- `sqlite_test.go:1` is missing an SPDX header.
|
||||
|
||||
## Verification
|
||||
|
||||
- `go test ./...`
|
||||
- `go test -coverprofile=/tmp/convention-cover.out ./...`
|
||||
- `go test -race ./...`
|
||||
- `go vet ./...`
|
||||
|
|
@ -1,16 +1,9 @@
|
|||
<!-- SPDX-License-Identifier: EUPL-1.2 -->
|
||||
|
||||
---
|
||||
title: Development Guide
|
||||
description: How to build, test, and contribute to go-ratelimit -- prerequisites, test patterns, coding standards, and commit conventions.
|
||||
---
|
||||
|
||||
# Development Guide
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- **Go 1.26** or later (the module declares `go 1.26.0`)
|
||||
- No CGO required -- `modernc.org/sqlite` is a pure Go port
|
||||
- Go 1.25 or later (the module declares `go 1.25.5`)
|
||||
- No CGO required — `modernc.org/sqlite` is a pure Go port
|
||||
|
||||
No C toolchain, no system SQLite library, no external build tools. A plain
|
||||
`go build ./...` is sufficient.
|
||||
|
|
@ -20,9 +13,6 @@ No C toolchain, no system SQLite library, no external build tools. A plain
|
|||
## Build and Test
|
||||
|
||||
```bash
|
||||
# Compile all packages
|
||||
go build ./...
|
||||
|
||||
# Run all tests
|
||||
go test ./...
|
||||
|
||||
|
|
@ -44,51 +34,40 @@ go test -bench=BenchmarkCanSend -benchmem ./...
|
|||
# Check for vet issues
|
||||
go vet ./...
|
||||
|
||||
# Lint (requires golangci-lint)
|
||||
golangci-lint run ./...
|
||||
|
||||
# Coverage check
|
||||
go test -cover ./...
|
||||
|
||||
# Tidy dependencies
|
||||
go mod tidy
|
||||
```
|
||||
|
||||
Before a commit is pushed, `go build ./...`, `go test -race ./...`,
|
||||
`go vet ./...`, `go test -cover ./...`, and `go mod tidy` must all pass
|
||||
without errors, and coverage must remain at or above 95%.
|
||||
All three commands (`go test -race ./...`, `go vet ./...`, and `go mod tidy`)
|
||||
must produce no errors or warnings before a commit is pushed.
|
||||
|
||||
---
|
||||
|
||||
## Test Organisation
|
||||
## Test Patterns
|
||||
|
||||
### File Layout
|
||||
### File Organisation
|
||||
|
||||
| File | Scope |
|
||||
|------|-------|
|
||||
| `ratelimit_test.go` | Core sliding window logic, provider profiles, concurrency, benchmarks |
|
||||
| `sqlite_test.go` | SQLite backend, migration, concurrent persistence |
|
||||
| `error_test.go` | SQLite and YAML error paths |
|
||||
| `iter_test.go` | `Models()` and `Iter()` iterators, `CountTokens` edge cases |
|
||||
- `ratelimit_test.go` — Phase 0 (core logic) and Phase 1 (provider profiles)
|
||||
- `sqlite_test.go` — Phase 2 (SQLite backend)
|
||||
|
||||
All test files are in `package ratelimit` (white-box tests), giving access to
|
||||
Both files are in `package ratelimit` (white-box tests) so they can access
|
||||
unexported fields and methods such as `prune()`, `filePath`, and `sqlite`.
|
||||
|
||||
### Naming Convention
|
||||
|
||||
SQLite tests follow the `_Good`, `_Bad`, `_Ugly` suffix pattern:
|
||||
|
||||
- `_Good` -- happy path
|
||||
- `_Bad` -- expected error conditions (invalid paths, corrupt input)
|
||||
- `_Ugly` -- panic-adjacent edge cases (corrupt database files, truncated files)
|
||||
- `_Good` — happy path
|
||||
- `_Bad` — expected error conditions (invalid paths, corrupt input)
|
||||
- `_Ugly` — panic-adjacent edge cases (corrupt DB files, truncated files)
|
||||
|
||||
Core logic tests use plain descriptive names without suffixes, grouped by method
|
||||
with table-driven subtests.
|
||||
Core logic tests use plain descriptive names without suffixes, grouped by
|
||||
method with table-driven subtests.
|
||||
|
||||
### Test Helper
|
||||
### Test Helpers
|
||||
|
||||
`newTestLimiter(t)` creates a `RateLimiter` with Gemini defaults and redirects
|
||||
the YAML file path into `t.TempDir()`:
|
||||
`newTestLimiter(t *testing.T)` creates a `RateLimiter` with Gemini defaults and
|
||||
redirects the YAML file path into `t.TempDir()`:
|
||||
|
||||
```go
|
||||
func newTestLimiter(t *testing.T) *RateLimiter {
|
||||
|
|
@ -107,57 +86,45 @@ after each test completes.
|
|||
|
||||
Tests use `github.com/stretchr/testify` exclusively:
|
||||
|
||||
- `require.NoError(t, err)` -- fail immediately on setup errors
|
||||
- `assert.NoError(t, err)` -- record failure but continue
|
||||
- `assert.Equal(t, expected, actual, "message")` -- prefer over raw comparisons
|
||||
- `assert.True` / `assert.False` -- for boolean checks
|
||||
- `assert.Empty` / `assert.Len` -- for slice length checks
|
||||
- `assert.ErrorIs(t, err, target)` -- for sentinel errors
|
||||
- `require.NoError(t, err)` — fail immediately on setup errors
|
||||
- `assert.NoError(t, err)` — record failure but continue
|
||||
- `assert.Equal(t, expected, actual, "message")` — prefer over raw comparisons
|
||||
- `assert.True / assert.False` — for boolean checks
|
||||
- `assert.Empty / assert.Len` — for slice length checks
|
||||
- `assert.ErrorIs(t, err, context.DeadlineExceeded)` — for sentinel errors
|
||||
|
||||
Do not use `t.Error`, `t.Fatal`, or `t.Log` directly.
|
||||
|
||||
### Concurrency Tests
|
||||
### Race Tests
|
||||
|
||||
Race tests spin up goroutines and use `sync.WaitGroup`. Some assert specific
|
||||
outcomes (e.g., correct RPD count after concurrent recordings), while others
|
||||
rely solely on the race detector to catch data races:
|
||||
Concurrency tests spin up goroutines and use `sync.WaitGroup`. They do not
|
||||
assert anything beyond absence of data races (the race detector does the work):
|
||||
|
||||
```go
|
||||
var wg sync.WaitGroup
|
||||
for range 20 {
|
||||
wg.Go(func() {
|
||||
for range 50 {
|
||||
rl.CanSend(model, 10)
|
||||
rl.RecordUsage(model, 5, 5)
|
||||
rl.Stats(model)
|
||||
}
|
||||
})
|
||||
for i := range 20 {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
// concurrent operations
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
```
|
||||
|
||||
Always run concurrency tests with `-race`.
|
||||
|
||||
### Benchmarks
|
||||
|
||||
The following benchmarks are included:
|
||||
|
||||
| Benchmark | What it measures |
|
||||
|-----------|------------------|
|
||||
| `BenchmarkCanSend` | CanSend with a 1,000-entry sliding window |
|
||||
| `BenchmarkRecordUsage` | Recording usage on a single model |
|
||||
| `BenchmarkCanSendConcurrent` | Parallel CanSend across goroutines |
|
||||
| `BenchmarkCanSendWithPrune` | CanSend with 500 old + 500 new entries |
|
||||
| `BenchmarkStats` | Stats retrieval with a 1,000-entry window |
|
||||
| `BenchmarkAllStats` | AllStats across 5 models x 200 entries each |
|
||||
| `BenchmarkPersist` | YAML persistence I/O |
|
||||
| `BenchmarkSQLitePersist` | SQLite persistence I/O |
|
||||
| `BenchmarkSQLiteLoad` | SQLite state loading |
|
||||
Run every concurrency test with `-race`. The CI baseline is `go test -race ./...`
|
||||
clean.
|
||||
|
||||
### Coverage
|
||||
|
||||
Maintain at least 95% statement coverage. Verify it with `go test -cover ./...`
|
||||
and document any justified exception in the commit or PR that introduces it.
|
||||
Current coverage: 95.1%. The remaining 5% consists of three paths that cannot
|
||||
be covered in unit tests without modifying the production code:
|
||||
|
||||
1. `CountTokens` success path — hardcoded Google API URL requires network access
|
||||
2. `yaml.Marshal` error path in `Persist()` — cannot be triggered with valid Go structs
|
||||
3. `os.UserHomeDir()` error path in `NewWithConfig()` — requires unsetting `$HOME`
|
||||
|
||||
Do not lower coverage below 95% without a documented reason.
|
||||
|
||||
---
|
||||
|
||||
|
|
@ -170,25 +137,26 @@ Do not use American spellings in identifiers, comments, or documentation.
|
|||
|
||||
### Go Style
|
||||
|
||||
- All exported types, functions, and fields must have doc comments.
|
||||
- Error strings must be lowercase and not end with punctuation (Go convention).
|
||||
- Contextual errors use `core.E("ratelimit.Function", "what", err)` so errors
|
||||
identify their origin clearly.
|
||||
- No `init()` functions.
|
||||
- No global mutable state. `DefaultProfiles()` returns a fresh map on each call.
|
||||
- All exported types, functions, and fields must have doc comments
|
||||
- Error strings must be lowercase and not end with punctuation (Go convention)
|
||||
- Contextual errors use `fmt.Errorf("package.Function: what: %w", err)` — the
|
||||
prefix `ratelimit.` is included so errors identify their origin clearly
|
||||
- No `init()` functions
|
||||
- No global mutable state outside of `DefaultProfiles()` (which returns a fresh
|
||||
map on each call)
|
||||
|
||||
### Mutex Discipline
|
||||
|
||||
The `RateLimiter.mu` mutex is the only synchronisation primitive. Rules:
|
||||
|
||||
- Methods that call `prune()` always acquire the write lock (`mu.Lock()`), even
|
||||
if they appear read-only, because `prune()` mutates state slices.
|
||||
- `Persist()` acquires the write lock briefly to clone state, then releases it
|
||||
before performing I/O.
|
||||
- Methods that call `prune()` always acquire the write lock (`mu.Lock()`),
|
||||
even if they appear read-only, because `prune()` mutates slices
|
||||
- `Persist()` acquires only the read lock (`mu.RLock()`) because it reads a
|
||||
snapshot of state
|
||||
- Lock acquisition always happens at the top of the public method, never inside
|
||||
a helper. Helpers document "Caller must hold the lock".
|
||||
- Never call a public method from inside another public method while holding the
|
||||
lock (deadlock risk).
|
||||
a helper — helpers document "Caller must hold the lock"
|
||||
- Never call a public method from inside another public method while holding
|
||||
the lock (deadlock risk)
|
||||
|
||||
### Dependencies
|
||||
|
||||
|
|
@ -196,7 +164,6 @@ Direct dependencies are intentionally minimal:
|
|||
|
||||
| Dependency | Purpose |
|
||||
|------------|---------|
|
||||
| `dappco.re/go/core` | File I/O helpers, structured errors, JSON helpers, path/environment utilities |
|
||||
| `gopkg.in/yaml.v3` | YAML serialisation for legacy backend |
|
||||
| `modernc.org/sqlite` | Pure Go SQLite for persistent backend |
|
||||
| `github.com/stretchr/testify` | Test assertions (test-only) |
|
||||
|
|
@ -208,8 +175,9 @@ client libraries; the existing `CountTokens` function uses the standard library.
|
|||
|
||||
## Licence
|
||||
|
||||
EUPL-1.2. Confirm with the project lead before adding files under a different
|
||||
licence.
|
||||
EUPL-1.2. Every new source file must carry the standard header if the project
|
||||
adopts per-file headers in future. Confirm with the project lead before adding
|
||||
files under a different licence.
|
||||
|
||||
---
|
||||
|
||||
|
|
@ -237,17 +205,3 @@ Co-Authored-By: Virgil <virgil@lethean.io>
|
|||
|
||||
Commits must not be pushed unless `go test -race ./...` and `go vet ./...` both
|
||||
pass. `go mod tidy` must produce no changes.
|
||||
|
||||
---
|
||||
|
||||
## Linting
|
||||
|
||||
The project uses `golangci-lint` with the following enabled linters (see
|
||||
`.golangci.yml`):
|
||||
|
||||
- `govet`, `errcheck`, `staticcheck`, `unused`, `gosimple`
|
||||
- `ineffassign`, `typecheck`, `gocritic`, `gofmt`
|
||||
|
||||
Disabled linters: `exhaustive`, `wrapcheck`.
|
||||
|
||||
Run `golangci-lint run ./...` to check before committing.
|
||||
|
|
|
|||
|
|
@ -1,13 +1,10 @@
|
|||
<!-- SPDX-License-Identifier: EUPL-1.2 -->
|
||||
|
||||
# Project History
|
||||
|
||||
## Origin
|
||||
|
||||
go-ratelimit was extracted from the `pkg/ratelimit` package inside
|
||||
`forge.lthn.ai/core/go` on 19 February 2026. The package now lives at
|
||||
`dappco.re/go/core/go-ratelimit`, with its own repository and independent
|
||||
development cadence.
|
||||
`forge.lthn.ai/core/go` on 19 February 2026. The extraction gave the package
|
||||
its own module path, repository, and independent development cadence.
|
||||
|
||||
Initial commit: `fa1a6fc` — `feat: extract go-ratelimit from core/go pkg/ratelimit`
|
||||
|
||||
|
|
@ -28,7 +25,7 @@ Commit: `3c63b10` — `feat(ratelimit): generalise beyond Gemini with provider p
|
|||
|
||||
Supplementary commit: `db958f2` — `test: expand race coverage and benchmarks`
|
||||
|
||||
Coverage increased from 77.1% to above the 95% floor. The test suite was rewritten using
|
||||
Coverage increased from 77.1% to 95.1%. The test suite was rewritten using
|
||||
testify with table-driven subtests throughout.
|
||||
|
||||
### Tests added
|
||||
|
|
@ -61,6 +58,18 @@ testify with table-driven subtests throughout.
|
|||
- `BenchmarkAllStats` — 5 models x 200 entries
|
||||
- `BenchmarkPersist` — YAML I/O
|
||||
|
||||
### Remaining uncovered paths (5%)
|
||||
|
||||
These three paths are structurally impossible to cover in unit tests without
|
||||
modifying production code:
|
||||
|
||||
1. `CountTokens` success path — the Google API URL is hardcoded; unit tests
|
||||
cannot intercept the HTTP call without URL injection support
|
||||
2. `yaml.Marshal` error path in `Persist()` — `yaml.Marshal` does not fail on
|
||||
valid Go structs; the error branch exists for correctness only
|
||||
3. `os.UserHomeDir()` error path in `NewWithConfig()` — triggered only when
|
||||
`$HOME` is unset, which test infrastructure prevents
|
||||
|
||||
`go test -race ./...` passed clean. `go vet ./...` produced no warnings.
|
||||
|
||||
---
|
||||
|
|
@ -130,7 +139,7 @@ established elsewhere in the ecosystem.
|
|||
|
||||
- `TestNewSQLiteStore_Good / _Bad` — creation and invalid path handling
|
||||
- `TestSQLiteQuotasRoundTrip_Good` — save/load round-trip
|
||||
- `TestSQLite_QuotasOverwrite_Good` — the latest quota snapshot replaces previous rows
|
||||
- `TestSQLiteQuotasUpsert_Good` — upsert replaces existing rows
|
||||
- `TestSQLiteStateRoundTrip_Good` — multi-model state with nanosecond precision
|
||||
- `TestSQLiteStateOverwrite_Good` — delete-then-insert atomicity
|
||||
- `TestSQLiteEmptyState_Good` — fresh database returns empty maps
|
||||
|
|
@ -159,10 +168,11 @@ Not yet implemented. Intended downstream integrations:
|
|||
|
||||
## Known Limitations
|
||||
|
||||
**CountTokens URL is hardcoded.** The exported `CountTokens` helper calls
|
||||
`generativelanguage.googleapis.com` directly. Callers cannot redirect it to
|
||||
Gemini-compatible proxies or alternate endpoints without going through an
|
||||
internal helper or refactoring the API to accept a base URL or `http.Client`.
|
||||
**CountTokens URL is hardcoded.** The `CountTokens` helper calls
|
||||
`generativelanguage.googleapis.com` directly. There is no way to override the
|
||||
base URL, which prevents testing the success path in unit tests and prevents
|
||||
use with Gemini-compatible proxies. A future refactor would accept a base URL
|
||||
parameter or an `http.Client`.
|
||||
|
||||
**saveState is a full table replace.** On every `Persist()` call, the `requests`,
|
||||
`tokens`, and `daily` tables are truncated and rewritten. For a limiter tracking
|
||||
|
|
@ -176,10 +186,10 @@ SQLite on `Persist()`. The database does not grow unboundedly between persist
|
|||
cycles because `saveState` replaces all rows, but if `Persist()` is called
|
||||
frequently the WAL file can grow transiently.
|
||||
|
||||
**WaitForCapacity now sleeps using `Decide`’s `RetryAfter` hint** (with a
|
||||
one-second fallback when no hint exists). This reduces busy looping on long
|
||||
windows but remains coarse for sub-second smoothing; callers that need
|
||||
sub-second pacing should implement their own loop.
|
||||
**WaitForCapacity polling interval is fixed at 1 second.** This is appropriate
|
||||
for RPM-scale limits but is coarse for sub-second limits. If a caller needs
|
||||
finer-grained waiting (e.g., smoothing requests within a minute), they must
|
||||
implement their own loop.
|
||||
|
||||
**No automatic persistence.** `Persist()` must be called explicitly. If a
|
||||
process exits without calling `Persist()`, any usage recorded since the last
|
||||
|
|
|
|||
122
docs/index.md
122
docs/index.md
|
|
@ -1,122 +0,0 @@
|
|||
<!-- SPDX-License-Identifier: EUPL-1.2 -->
|
||||
|
||||
---
|
||||
title: go-ratelimit
|
||||
description: Provider-agnostic sliding window rate limiter for LLM API calls, with YAML and SQLite persistence backends.
|
||||
---
|
||||
|
||||
# go-ratelimit
|
||||
|
||||
**Module**: `dappco.re/go/core/go-ratelimit`
|
||||
**Licence**: EUPL-1.2
|
||||
**Go version**: 1.26+
|
||||
|
||||
go-ratelimit enforces requests-per-minute (RPM), tokens-per-minute (TPM), and
|
||||
requests-per-day (RPD) quotas on a per-model basis using an in-memory sliding
|
||||
window. It ships with default quota profiles for Gemini, OpenAI, Anthropic, and
|
||||
a local inference provider. State persists across process restarts via YAML
|
||||
(single-process) or SQLite with WAL mode (multi-process). A YAML-to-SQLite
|
||||
migration helper is included.
|
||||
|
||||
## Quick Start
|
||||
|
||||
```go
|
||||
import "dappco.re/go/core/go-ratelimit"
|
||||
|
||||
// Create a limiter with Gemini defaults (YAML backend).
|
||||
rl, err := ratelimit.New()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
// Check capacity before sending.
|
||||
if rl.CanSend("gemini-2.0-flash", 1500) {
|
||||
// Make the API call...
|
||||
rl.RecordUsage("gemini-2.0-flash", 1000, 500) // promptTokens, outputTokens
|
||||
}
|
||||
|
||||
// Persist state to disk for recovery across restarts.
|
||||
if err := rl.Persist(); err != nil {
|
||||
log.Printf("persist failed: %v", err)
|
||||
}
|
||||
```
|
||||
|
||||
### Multi-provider configuration
|
||||
|
||||
```go
|
||||
rl, err := ratelimit.NewWithConfig(ratelimit.Config{
|
||||
Providers: []ratelimit.Provider{
|
||||
ratelimit.ProviderGemini,
|
||||
ratelimit.ProviderAnthropic,
|
||||
},
|
||||
Quotas: map[string]ratelimit.ModelQuota{
|
||||
// Override a specific model's limits.
|
||||
"gemini-3-pro-preview": {MaxRPM: 50, MaxTPM: 500000, MaxRPD: 200},
|
||||
// Add a custom model not in any profile.
|
||||
"llama-3.3-70b": {MaxRPM: 5, MaxTPM: 50000, MaxRPD: 0},
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
### SQLite backend (multi-process safe)
|
||||
|
||||
```go
|
||||
rl, err := ratelimit.NewWithSQLite("~/.core/ratelimits.db")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
defer rl.Close()
|
||||
|
||||
// Load persisted state.
|
||||
if err := rl.Load(); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
// Use exactly as the YAML backend -- CanSend, RecordUsage, Persist, etc.
|
||||
```
|
||||
|
||||
### Blocking until capacity is available
|
||||
|
||||
```go
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
|
||||
if err := rl.WaitForCapacity(ctx, "claude-opus-4", 2000); err != nil {
|
||||
log.Printf("timed out waiting for capacity: %v", err)
|
||||
return
|
||||
}
|
||||
// Capacity is available; proceed with the API call.
|
||||
|
||||
// WaitForCapacity uses Decide's RetryAfter hint to avoid tight polling.
|
||||
```
|
||||
|
||||
## Package Layout
|
||||
|
||||
The module is a single package with no sub-packages.
|
||||
|
||||
| File | Purpose |
|
||||
|------|---------|
|
||||
| `ratelimit.go` | Core types (`RateLimiter`, `ModelQuota`, `Config`, `Provider`), sliding window logic, provider profiles, YAML persistence, `CountTokens` helper |
|
||||
| `sqlite.go` | SQLite persistence backend (`sqliteStore`), schema creation, load/save operations |
|
||||
| `ratelimit_test.go` | Tests for core logic, provider profiles, concurrency, and benchmarks |
|
||||
| `sqlite_test.go` | Tests for SQLite backend, migration, and error recovery |
|
||||
| `error_test.go` | Tests for SQLite and YAML error paths |
|
||||
| `iter_test.go` | Tests for `Models()` and `Iter()` iterators, plus `CountTokens` edge cases |
|
||||
|
||||
## Dependencies
|
||||
|
||||
| Dependency | Purpose | Category |
|
||||
|------------|---------|----------|
|
||||
| `dappco.re/go/core` | File I/O helpers, structured errors, JSON helpers, path/environment utilities | Direct |
|
||||
| `gopkg.in/yaml.v3` | YAML serialisation for the legacy persistence backend | Direct |
|
||||
| `modernc.org/sqlite` | Pure Go SQLite driver (no CGO required) | Direct |
|
||||
| `github.com/stretchr/testify` | Test assertions (`assert`, `require`) | Test only |
|
||||
|
||||
All indirect dependencies are pulled in by `modernc.org/sqlite`. No C toolchain
|
||||
or system SQLite library is needed.
|
||||
|
||||
## Further Reading
|
||||
|
||||
- [Architecture](architecture.md) -- sliding window algorithm, provider quotas, YAML and SQLite backends, concurrency model
|
||||
- [Development](development.md) -- build commands, test patterns, coding standards, commit conventions
|
||||
- [History](history.md) -- completed phases with commit hashes, known limitations
|
||||
|
|
@ -1,46 +0,0 @@
|
|||
<!-- SPDX-License-Identifier: EUPL-1.2 -->
|
||||
|
||||
# Security Attack Vector Mapping
|
||||
|
||||
Scope: external inputs that cross into this package from callers, persisted storage, or the network. This is a mapping only; it does not propose or apply fixes.
|
||||
|
||||
Note: `CODEX.md` was not present anywhere under `/workspace` during this scan, so conventions were taken from `CLAUDE.md` and the existing repository layout.
|
||||
|
||||
## Caller-Controlled API Inputs
|
||||
|
||||
| Function | File:Line | Input Source | What It Flows Into | Current Validation | Potential Attack Vector |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| `NewWithConfig(cfg Config)` | `ratelimit.go:145` | Caller-controlled `cfg.FilePath`, `cfg.Providers`, `cfg.Quotas` | `cfg.FilePath` is stored in `rl.filePath` and later used by `Load()` / `Persist()`; `cfg.Providers` selects built-in profiles; `cfg.Quotas` is copied straight into `rl.Quotas` | Empty `FilePath` defaults to `~/.core/ratelimits.yaml`; unknown providers are ignored; `cfg.Backend` is not read here; quota values and model keys are copied verbatim | Untrusted `FilePath` can later steer YAML reads and writes to arbitrary local paths because the package uses unsandboxed `coreio.Local`; negative quota values act like "unlimited" because enforcement only checks `> 0`; very large maps or model strings can drive memory and disk growth |
|
||||
| `(*RateLimiter).SetQuota(model string, quota ModelQuota)` | `ratelimit.go:183` | Caller-controlled `model` and `quota` | Direct write to `rl.Quotas[model]`; later consumed by `CanSend()`, `Stats()`, `Persist()`, and SQLite/YAML persistence | None beyond Go type checking | Negative quota fields disable enforcement for that dimension; extreme values can skew blocking behaviour; arbitrary model names expand the in-memory and persisted keyspace |
|
||||
| `(*RateLimiter).AddProvider(provider Provider)` | `ratelimit.go:191` | Caller-controlled `provider` selector | Looks up `DefaultProfiles()[provider]` and overwrites matching entries in `rl.Quotas` via `maps.Copy` | Unknown providers are silently ignored; no authorisation or policy guard in this package | If a higher-level service exposes this call, an attacker can overwrite stricter runtime quotas for a provider's models with the shipped defaults and relax the intended rate-limit policy |
|
||||
| `(*RateLimiter).BackgroundPrune(interval time.Duration)` | `ratelimit.go:328` | Caller-controlled `interval` | Passed to `time.NewTicker(interval)` and drives a background goroutine that repeatedly locks and prunes state | None | `interval <= 0` causes a panic; very small intervals can create CPU and lock-contention DoS; repeated calls without using the returned cancel function leak goroutines |
|
||||
| `(*RateLimiter).CanSend(model string, estimatedTokens int)` | `ratelimit.go:350` | Caller-controlled `model` and `estimatedTokens` | `model` indexes `rl.Quotas` / `rl.State`; `estimatedTokens` is added to the current token total before the TPM comparison | Unknown models are allowed immediately; no non-negative or range checks on `estimatedTokens` | Passing an unconfigured model name bypasses throttling entirely; negative or overflowed token values can undercount the TPM check and permit oversend |
|
||||
| `(*RateLimiter).RecordUsage(model string, promptTokens, outputTokens int)` | `ratelimit.go:396` | Caller-controlled `model`, `promptTokens`, `outputTokens` | Creates or updates `rl.State[model]`; stores `promptTokens + outputTokens` in the token window and increments `DayCount` | None | Arbitrary model names create unbounded state that will later persist to YAML/SQLite; negative or overflowed token totals poison accounting and can reduce future TPM totals below the real usage |
|
||||
| `(*RateLimiter).WaitForCapacity(ctx context.Context, model string, tokens int)` | `ratelimit.go:429` | Caller-controlled `ctx`, `model`, `tokens` | Calls `Decide(model, tokens)` in a loop and sleeps for the returned `RetryAfter` (or 1s fallback) until allowed or `ctx.Done()` fires | No direct validation beyond negative-token guard; relies on downstream `Decide()` and caller-supplied context cancellation | Long `RetryAfter` values can delay rechecks; repeated calls with long-lived contexts can still accumulate goroutines and lock pressure |
|
||||
| `(*RateLimiter).Reset(model string)` | `ratelimit.go:433` | Caller-controlled `model` | `model == ""` replaces the entire `rl.State` map; otherwise `delete(rl.State, model)` | Empty string is treated as a wildcard reset | If reachable by an untrusted actor, an empty string clears all rate-limit history and targeted resets erase throttling state for chosen models |
|
||||
| `(*RateLimiter).Stats(model string)` | `ratelimit.go:484` | Caller-controlled `model` | Prunes `rl.State[model]`, reads `rl.Quotas[model]`, and returns a usage snapshot | None | If exposed through a service boundary, it discloses per-model quota ceilings and live usage counts that can help an attacker tune evasion or timing |
|
||||
| `NewWithSQLite(dbPath string)` | `ratelimit.go:567` | Caller-controlled `dbPath` | Thin wrapper that forwards `dbPath` into `NewWithSQLiteConfig()` and then `newSQLiteStore()` | No additional validation in the wrapper | Untrusted `dbPath` can steer database creation/opening to unintended local filesystem locations, including companion `-wal` and `-shm` files |
|
||||
| `NewWithSQLiteConfig(dbPath string, cfg Config)` | `ratelimit.go:576` | Caller-controlled `dbPath`, `cfg.Providers`, `cfg.Quotas` | `dbPath` goes straight to `newSQLiteStore()`; provider and quota inputs are copied into `rl.Quotas` exactly as in `NewWithConfig()` | `cfg.Backend` is ignored; unknown providers are ignored; no path, range, or size checks | Combines arbitrary database-path selection with the same quota poisoning risks as `NewWithConfig()` and `SetQuota()` |
|
||||
|
||||
## Filesystem And YAML Inputs
|
||||
|
||||
| Function | File:Line | Input Source | What It Flows Into | Current Validation | Potential Attack Vector |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| `(*RateLimiter).Load()` (YAML backend) | `ratelimit.go:210` | File bytes read from `rl.filePath` | `coreio.Local.Read(rl.filePath)` feeds `yaml.Unmarshal(..., rl)`, which overwrites `rl.Quotas` and `rl.State` | Missing file is ignored; YAML syntax and type mismatches return an error; no semantic checks on counts, limits, model names, or slice sizes | A malicious YAML file can inject negative quotas or counters to bypass enforcement, preload very large maps/slices for memory DoS, or replace the in-memory policy/state with attacker-chosen values |
|
||||
| `MigrateYAMLToSQLite(yamlPath, sqlitePath string)` | `ratelimit.go:617` | Caller-controlled `yamlPath` and `sqlitePath`, plus YAML file bytes from `yamlPath` | Reads YAML with `coreio.Local.Read(yamlPath)`, unmarshals into a temporary `RateLimiter`, then opens `sqlitePath` and writes the imported quotas/state into SQLite | Read/open errors and YAML syntax/type errors are surfaced; no path restrictions and no semantic validation of imported quotas/state | Untrusted paths enable arbitrary local file reads and database creation/clobbering; attacker-controlled YAML can permanently seed the SQLite backend with quota-bypass values or oversized state |
|
||||
|
||||
## SQLite Inputs
|
||||
|
||||
| Function | File:Line | Input Source | What It Flows Into | Current Validation | Potential Attack Vector |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| `newSQLiteStore(dbPath string)` | `sqlite.go:20` | Caller-controlled database path passed from `NewWithSQLite*()` or `MigrateYAMLToSQLite()` | `sql.Open("sqlite", dbPath)` opens or creates the database, then applies PRAGMAs and creates tables and indexes | Only driver/open/PRAGMA/schema errors are checked; there is no allowlist, path normalisation, or sandboxing in this package | An attacker-chosen `dbPath` can redirect state into unintended files or directories and create matching SQLite sidecar files, which is useful for tampering, data placement, or storage-exhaustion attacks |
|
||||
| `(*RateLimiter).Load()` (SQLite backend via `loadSQLite()`) | `ratelimit.go:223` | SQLite content reachable through the already-open `rl.sqlite` handle | `loadQuotas()` and `loadState()` results are copied into `rl.Quotas` and `rl.State`; loaded quotas override in-memory defaults | Only lower-level scan/query errors are checked; no semantic validation after load | A tampered SQLite database can override intended quotas/state, including negative limits and poisoned counters, before any enforcement call runs |
|
||||
| `(*sqliteStore).loadQuotas()` | `sqlite.go:110` | Rows from the `quotas` table (`model`, `max_rpm`, `max_tpm`, `max_rpd`) | Scanned into `map[string]ModelQuota`, then copied into `rl.Quotas` by `loadSQLite()` | SQL scan and row iteration errors only; no range or length checks | Negative or extreme values disable or destabilise later quota enforcement; a large number of rows or large model strings can cause memory growth |
|
||||
| `(*sqliteStore).loadState()` | `sqlite.go:194` | Rows from the `daily`, `requests`, and `tokens` tables | Scanned into `UsageStats` maps/slices and then copied into `rl.State` by `loadSQLite()` | SQL scan and row iteration errors only; no bounds, ordering, or semantic checks on timestamps and counts | Crafted counts or timestamps can poison later `CanSend()` / `Stats()` results; oversized tables can drive memory and CPU exhaustion during load |
|
||||
|
||||
## Network Inputs
|
||||
|
||||
| Function | File:Line | Input Source | What It Flows Into | Current Validation | Potential Attack Vector |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| `CountTokens(ctx, apiKey, model, text)` (request construction) | `ratelimit.go:650` | Caller-controlled `ctx`, `apiKey`, `model`, `text` | `model` is interpolated directly into the Google API URL path; `text` is marshalled into JSON request body; `apiKey` goes into `x-goog-api-key`; `ctx` governs request lifetime | JSON marshalling must succeed; `http.NewRequestWithContext()` rejects some malformed URLs; there is no path escaping, length check, or output-size cap on the request body | Untrusted prompt text is exfiltrated to a remote API; very large text can consume memory/bandwidth; unescaped model strings can alter the path or query on the fixed Google host; repeated calls burn external quota |
|
||||
| `CountTokens(ctx, apiKey, model, text)` (response handling) | `ratelimit.go:681` | Remote HTTP status, response body, and JSON `totalTokens` value from `generativelanguage.googleapis.com` | Non-200 bodies are read fully with `io.ReadAll()` and embedded into the returned error; 200 responses are decoded into `result.TotalTokens` and returned to the caller | Checks for HTTP 200 and JSON decode errors only; no response-body size limit and no sanity check on `TotalTokens` | A very large error body can cause memory pressure and log/telemetry pollution; a negative or extreme `totalTokens` value would be returned unchanged and could poison downstream rate-limit accounting if the caller trusts it |
|
||||
693
error_test.go
693
error_test.go
|
|
@ -1,693 +0,0 @@
|
|||
// SPDX-License-Identifier: EUPL-1.2
|
||||
|
||||
package ratelimit
|
||||
|
||||
import (
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestError_SQLiteErrorPaths_Bad(t *testing.T) {
|
||||
dbPath := testPath(t.TempDir(), "error.db")
|
||||
rl, err := NewWithSQLite(dbPath)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Close the underlying DB to trigger errors.
|
||||
rl.sqlite.close()
|
||||
|
||||
t.Run("loadQuotas error", func(t *testing.T) {
|
||||
_, err := rl.sqlite.loadQuotas()
|
||||
assert.Error(t, err)
|
||||
})
|
||||
|
||||
t.Run("saveQuotas error", func(t *testing.T) {
|
||||
err := rl.sqlite.saveQuotas(map[string]ModelQuota{"test": {}})
|
||||
assert.Error(t, err)
|
||||
})
|
||||
|
||||
t.Run("saveState error", func(t *testing.T) {
|
||||
err := rl.sqlite.saveState(map[string]*UsageStats{"test": {}})
|
||||
assert.Error(t, err)
|
||||
})
|
||||
|
||||
t.Run("loadState error", func(t *testing.T) {
|
||||
_, err := rl.sqlite.loadState()
|
||||
assert.Error(t, err)
|
||||
})
|
||||
}
|
||||
|
||||
func TestError_SQLiteInitErrors_Bad(t *testing.T) {
|
||||
t.Run("WAL pragma failure", func(t *testing.T) {
|
||||
// This is hard to trigger without mocking sql.DB, but we can try an invalid connection string
|
||||
// modernc.org/sqlite doesn't support all DSN options that might cause PRAGMA to fail but connection to succeed.
|
||||
})
|
||||
}
|
||||
|
||||
func TestError_PersistYAML_Good(t *testing.T) {
|
||||
t.Run("successful YAML persist and load", func(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
path := testPath(tmpDir, "ratelimits.yaml")
|
||||
rl, _ := New()
|
||||
rl.filePath = path
|
||||
rl.Quotas["test"] = ModelQuota{MaxRPM: 1}
|
||||
rl.RecordUsage("test", 1, 1)
|
||||
|
||||
require.NoError(t, rl.Persist())
|
||||
|
||||
rl2, _ := New()
|
||||
rl2.filePath = path
|
||||
require.NoError(t, rl2.Load())
|
||||
assert.Equal(t, 1, rl2.Quotas["test"].MaxRPM)
|
||||
assert.Equal(t, 1, rl2.State["test"].DayCount)
|
||||
})
|
||||
}
|
||||
|
||||
func TestError_SQLiteLoadViaLimiter_Bad(t *testing.T) {
|
||||
t.Run("Load returns error when SQLite DB is closed", func(t *testing.T) {
|
||||
dbPath := testPath(t.TempDir(), "load-err.db")
|
||||
rl, err := NewWithSQLite(dbPath)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Close the underlying DB to trigger errors on Load.
|
||||
rl.sqlite.close()
|
||||
|
||||
err = rl.Load()
|
||||
assert.Error(t, err, "Load should fail with closed DB")
|
||||
})
|
||||
|
||||
t.Run("Load returns error when loadState fails", func(t *testing.T) {
|
||||
dbPath := testPath(t.TempDir(), "load-state-err.db")
|
||||
rl, err := NewWithSQLite(dbPath)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Save some quotas so loadQuotas succeeds, then corrupt the state tables.
|
||||
require.NoError(t, rl.Persist())
|
||||
|
||||
// Drop the daily table to cause loadState to fail.
|
||||
_, execErr := rl.sqlite.db.Exec("DROP TABLE daily")
|
||||
require.NoError(t, execErr)
|
||||
|
||||
err = rl.Load()
|
||||
assert.Error(t, err, "Load should fail when loadState fails")
|
||||
rl.Close()
|
||||
})
|
||||
}
|
||||
|
||||
func TestError_SQLitePersistViaLimiter_Bad(t *testing.T) {
|
||||
t.Run("Persist returns error when SQLite saveQuotas fails", func(t *testing.T) {
|
||||
dbPath := testPath(t.TempDir(), "persist-err.db")
|
||||
rl, err := NewWithSQLite(dbPath)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Drop the quotas table to cause saveQuotas to fail.
|
||||
_, execErr := rl.sqlite.db.Exec("DROP TABLE quotas")
|
||||
require.NoError(t, execErr)
|
||||
|
||||
err = rl.Persist()
|
||||
assert.Error(t, err, "Persist should fail when saveQuotas fails")
|
||||
assert.Contains(t, err.Error(), "ratelimit.Persist")
|
||||
rl.Close()
|
||||
})
|
||||
|
||||
t.Run("Persist returns error when SQLite saveState fails", func(t *testing.T) {
|
||||
dbPath := testPath(t.TempDir(), "persist-state-err.db")
|
||||
rl, err := NewWithSQLite(dbPath)
|
||||
require.NoError(t, err)
|
||||
|
||||
rl.RecordUsage("test-model", 10, 10)
|
||||
|
||||
// Drop a state table to cause saveState to fail.
|
||||
_, execErr := rl.sqlite.db.Exec("DROP TABLE requests")
|
||||
require.NoError(t, execErr)
|
||||
|
||||
err = rl.Persist()
|
||||
assert.Error(t, err, "Persist should fail when saveState fails")
|
||||
assert.Contains(t, err.Error(), "ratelimit.Persist")
|
||||
rl.Close()
|
||||
})
|
||||
}
|
||||
|
||||
func TestError_NewWithSQLite_Bad(t *testing.T) {
|
||||
t.Run("NewWithSQLite with invalid path", func(t *testing.T) {
|
||||
_, err := NewWithSQLite("/nonexistent/deep/nested/dir/test.db")
|
||||
assert.Error(t, err, "should fail with invalid path")
|
||||
})
|
||||
|
||||
t.Run("NewWithSQLiteConfig with invalid path", func(t *testing.T) {
|
||||
_, err := NewWithSQLiteConfig("/nonexistent/deep/nested/dir/test.db", Config{
|
||||
Providers: []Provider{ProviderGemini},
|
||||
})
|
||||
assert.Error(t, err, "should fail with invalid path")
|
||||
})
|
||||
}
|
||||
|
||||
func TestError_SQLiteSaveState_Bad(t *testing.T) {
|
||||
t.Run("saveState fails when tokens table is dropped", func(t *testing.T) {
|
||||
dbPath := testPath(t.TempDir(), "tokens-err.db")
|
||||
store, err := newSQLiteStore(dbPath)
|
||||
require.NoError(t, err)
|
||||
defer store.close()
|
||||
|
||||
_, execErr := store.db.Exec("DROP TABLE tokens")
|
||||
require.NoError(t, execErr)
|
||||
|
||||
state := map[string]*UsageStats{
|
||||
"model": {
|
||||
Tokens: []TokenEntry{{Time: time.Now(), Count: 100}},
|
||||
DayStart: time.Now(),
|
||||
DayCount: 1,
|
||||
},
|
||||
}
|
||||
err = store.saveState(state)
|
||||
assert.Error(t, err, "saveState should fail when tokens table is missing")
|
||||
})
|
||||
|
||||
t.Run("saveState fails when daily table is dropped", func(t *testing.T) {
|
||||
dbPath := testPath(t.TempDir(), "daily-err.db")
|
||||
store, err := newSQLiteStore(dbPath)
|
||||
require.NoError(t, err)
|
||||
defer store.close()
|
||||
|
||||
_, execErr := store.db.Exec("DROP TABLE daily")
|
||||
require.NoError(t, execErr)
|
||||
|
||||
state := map[string]*UsageStats{
|
||||
"model": {
|
||||
DayStart: time.Now(),
|
||||
DayCount: 1,
|
||||
},
|
||||
}
|
||||
err = store.saveState(state)
|
||||
assert.Error(t, err, "saveState should fail when daily table is missing")
|
||||
})
|
||||
|
||||
t.Run("saveState fails on request insert with renamed column", func(t *testing.T) {
|
||||
dbPath := testPath(t.TempDir(), "req-insert-err.db")
|
||||
store, err := newSQLiteStore(dbPath)
|
||||
require.NoError(t, err)
|
||||
defer store.close()
|
||||
|
||||
// Rename the ts column so INSERT INTO requests (model, ts) fails.
|
||||
_, execErr := store.db.Exec("ALTER TABLE requests RENAME COLUMN ts TO timestamp")
|
||||
require.NoError(t, execErr)
|
||||
|
||||
state := map[string]*UsageStats{
|
||||
"model": {
|
||||
Requests: []time.Time{time.Now()},
|
||||
DayStart: time.Now(),
|
||||
DayCount: 1,
|
||||
},
|
||||
}
|
||||
err = store.saveState(state)
|
||||
assert.Error(t, err, "saveState should fail on request insert with renamed column")
|
||||
})
|
||||
|
||||
t.Run("saveState fails on token insert with renamed column", func(t *testing.T) {
|
||||
dbPath := testPath(t.TempDir(), "tok-insert-err.db")
|
||||
store, err := newSQLiteStore(dbPath)
|
||||
require.NoError(t, err)
|
||||
defer store.close()
|
||||
|
||||
// Rename the count column so INSERT INTO tokens (model, ts, count) fails.
|
||||
_, execErr := store.db.Exec("ALTER TABLE tokens RENAME COLUMN count TO amount")
|
||||
require.NoError(t, execErr)
|
||||
|
||||
state := map[string]*UsageStats{
|
||||
"model": {
|
||||
Tokens: []TokenEntry{{Time: time.Now(), Count: 100}},
|
||||
DayStart: time.Now(),
|
||||
DayCount: 1,
|
||||
},
|
||||
}
|
||||
err = store.saveState(state)
|
||||
assert.Error(t, err, "saveState should fail on token insert with renamed column")
|
||||
})
|
||||
|
||||
t.Run("saveState fails on daily insert with renamed column", func(t *testing.T) {
|
||||
dbPath := testPath(t.TempDir(), "day-insert-err.db")
|
||||
store, err := newSQLiteStore(dbPath)
|
||||
require.NoError(t, err)
|
||||
defer store.close()
|
||||
|
||||
// Rename day_count column so INSERT INTO daily fails.
|
||||
_, execErr := store.db.Exec("ALTER TABLE daily RENAME COLUMN day_count TO total")
|
||||
require.NoError(t, execErr)
|
||||
|
||||
state := map[string]*UsageStats{
|
||||
"model": {
|
||||
DayStart: time.Now(),
|
||||
DayCount: 1,
|
||||
},
|
||||
}
|
||||
err = store.saveState(state)
|
||||
assert.Error(t, err, "saveState should fail on daily insert with renamed column")
|
||||
})
|
||||
}
|
||||
|
||||
func TestError_SQLiteLoadState_Bad(t *testing.T) {
|
||||
t.Run("loadState fails when requests table is dropped", func(t *testing.T) {
|
||||
dbPath := testPath(t.TempDir(), "req-err.db")
|
||||
store, err := newSQLiteStore(dbPath)
|
||||
require.NoError(t, err)
|
||||
defer store.close()
|
||||
|
||||
state := map[string]*UsageStats{
|
||||
"model": {
|
||||
Requests: []time.Time{time.Now()},
|
||||
DayStart: time.Now(),
|
||||
DayCount: 1,
|
||||
},
|
||||
}
|
||||
require.NoError(t, store.saveState(state))
|
||||
|
||||
_, execErr := store.db.Exec("DROP TABLE requests")
|
||||
require.NoError(t, execErr)
|
||||
|
||||
_, err = store.loadState()
|
||||
assert.Error(t, err, "loadState should fail when requests table is missing")
|
||||
})
|
||||
|
||||
t.Run("loadState fails when tokens table is dropped", func(t *testing.T) {
|
||||
dbPath := testPath(t.TempDir(), "tok-err.db")
|
||||
store, err := newSQLiteStore(dbPath)
|
||||
require.NoError(t, err)
|
||||
defer store.close()
|
||||
|
||||
state := map[string]*UsageStats{
|
||||
"model": {
|
||||
Tokens: []TokenEntry{{Time: time.Now(), Count: 100}},
|
||||
DayStart: time.Now(),
|
||||
DayCount: 1,
|
||||
},
|
||||
}
|
||||
require.NoError(t, store.saveState(state))
|
||||
|
||||
_, execErr := store.db.Exec("DROP TABLE tokens")
|
||||
require.NoError(t, execErr)
|
||||
|
||||
_, err = store.loadState()
|
||||
assert.Error(t, err, "loadState should fail when tokens table is missing")
|
||||
})
|
||||
|
||||
t.Run("loadState fails when daily table is dropped", func(t *testing.T) {
|
||||
dbPath := testPath(t.TempDir(), "daily-load-err.db")
|
||||
store, err := newSQLiteStore(dbPath)
|
||||
require.NoError(t, err)
|
||||
defer store.close()
|
||||
|
||||
state := map[string]*UsageStats{
|
||||
"model": {
|
||||
DayStart: time.Now(),
|
||||
DayCount: 1,
|
||||
},
|
||||
}
|
||||
require.NoError(t, store.saveState(state))
|
||||
|
||||
_, execErr := store.db.Exec("DROP TABLE daily")
|
||||
require.NoError(t, execErr)
|
||||
|
||||
_, err = store.loadState()
|
||||
assert.Error(t, err, "loadState should fail when daily table is missing")
|
||||
})
|
||||
}
|
||||
|
||||
func TestError_SQLiteSaveQuotasExec_Bad(t *testing.T) {
|
||||
t.Run("saveQuotas fails with renamed column at prepare", func(t *testing.T) {
|
||||
dbPath := testPath(t.TempDir(), "quota-exec-err.db")
|
||||
store, err := newSQLiteStore(dbPath)
|
||||
require.NoError(t, err)
|
||||
defer store.close()
|
||||
|
||||
// Rename column so INSERT fails at prepare.
|
||||
_, execErr := store.db.Exec("ALTER TABLE quotas RENAME COLUMN max_rpm TO rpm")
|
||||
require.NoError(t, execErr)
|
||||
|
||||
err = store.saveQuotas(map[string]ModelQuota{
|
||||
"test": {MaxRPM: 10, MaxTPM: 100, MaxRPD: 50},
|
||||
})
|
||||
assert.Error(t, err, "saveQuotas should fail with renamed column")
|
||||
})
|
||||
|
||||
t.Run("saveQuotas fails at exec via trigger", func(t *testing.T) {
|
||||
dbPath := testPath(t.TempDir(), "quota-trigger.db")
|
||||
store, err := newSQLiteStore(dbPath)
|
||||
require.NoError(t, err)
|
||||
defer store.close()
|
||||
|
||||
// Add trigger to abort INSERT.
|
||||
_, execErr := store.db.Exec(`CREATE TRIGGER fail_quota BEFORE INSERT ON quotas
|
||||
BEGIN SELECT RAISE(ABORT, 'forced quota insert failure'); END`)
|
||||
require.NoError(t, execErr)
|
||||
|
||||
err = store.saveQuotas(map[string]ModelQuota{
|
||||
"test": {MaxRPM: 10, MaxTPM: 100, MaxRPD: 50},
|
||||
})
|
||||
assert.Error(t, err, "saveQuotas should fail when trigger fires")
|
||||
assert.Contains(t, err.Error(), "exec test")
|
||||
})
|
||||
}
|
||||
|
||||
func TestError_SQLiteSaveStateExec_Bad(t *testing.T) {
|
||||
t.Run("request insert exec fails via trigger", func(t *testing.T) {
|
||||
dbPath := testPath(t.TempDir(), "trigger-req.db")
|
||||
store, err := newSQLiteStore(dbPath)
|
||||
require.NoError(t, err)
|
||||
defer store.close()
|
||||
|
||||
// Add a trigger that aborts INSERT on requests.
|
||||
_, execErr := store.db.Exec(`CREATE TRIGGER fail_req_insert BEFORE INSERT ON requests
|
||||
BEGIN SELECT RAISE(ABORT, 'forced request insert failure'); END`)
|
||||
require.NoError(t, execErr)
|
||||
|
||||
state := map[string]*UsageStats{
|
||||
"model": {
|
||||
Requests: []time.Time{time.Now()},
|
||||
DayStart: time.Now(),
|
||||
DayCount: 1,
|
||||
},
|
||||
}
|
||||
err = store.saveState(state)
|
||||
assert.Error(t, err, "saveState should fail when request insert trigger fires")
|
||||
assert.Contains(t, err.Error(), "insert request")
|
||||
})
|
||||
|
||||
t.Run("token insert exec fails via trigger", func(t *testing.T) {
|
||||
dbPath := testPath(t.TempDir(), "trigger-tok.db")
|
||||
store, err := newSQLiteStore(dbPath)
|
||||
require.NoError(t, err)
|
||||
defer store.close()
|
||||
|
||||
// Add a trigger that aborts INSERT on tokens.
|
||||
_, execErr := store.db.Exec(`CREATE TRIGGER fail_tok_insert BEFORE INSERT ON tokens
|
||||
BEGIN SELECT RAISE(ABORT, 'forced token insert failure'); END`)
|
||||
require.NoError(t, execErr)
|
||||
|
||||
state := map[string]*UsageStats{
|
||||
"model": {
|
||||
Tokens: []TokenEntry{{Time: time.Now(), Count: 100}},
|
||||
DayStart: time.Now(),
|
||||
DayCount: 1,
|
||||
},
|
||||
}
|
||||
err = store.saveState(state)
|
||||
assert.Error(t, err, "saveState should fail when token insert trigger fires")
|
||||
assert.Contains(t, err.Error(), "insert token")
|
||||
})
|
||||
|
||||
t.Run("daily insert exec fails via trigger", func(t *testing.T) {
|
||||
dbPath := testPath(t.TempDir(), "trigger-day.db")
|
||||
store, err := newSQLiteStore(dbPath)
|
||||
require.NoError(t, err)
|
||||
defer store.close()
|
||||
|
||||
// Add a trigger that aborts INSERT on daily.
|
||||
_, execErr := store.db.Exec(`CREATE TRIGGER fail_day_insert BEFORE INSERT ON daily
|
||||
BEGIN SELECT RAISE(ABORT, 'forced daily insert failure'); END`)
|
||||
require.NoError(t, execErr)
|
||||
|
||||
state := map[string]*UsageStats{
|
||||
"model": {
|
||||
DayStart: time.Now(),
|
||||
DayCount: 1,
|
||||
},
|
||||
}
|
||||
err = store.saveState(state)
|
||||
assert.Error(t, err, "saveState should fail when daily insert trigger fires")
|
||||
assert.Contains(t, err.Error(), "insert daily")
|
||||
})
|
||||
}
|
||||
|
||||
func TestError_SQLiteLoadQuotasScan_Bad(t *testing.T) {
|
||||
t.Run("loadQuotas fails with renamed column", func(t *testing.T) {
|
||||
dbPath := testPath(t.TempDir(), "quota-scan-err.db")
|
||||
store, err := newSQLiteStore(dbPath)
|
||||
require.NoError(t, err)
|
||||
defer store.close()
|
||||
|
||||
// Save valid quotas first.
|
||||
require.NoError(t, store.saveQuotas(map[string]ModelQuota{
|
||||
"test": {MaxRPM: 10},
|
||||
}))
|
||||
|
||||
// Rename column so SELECT ... FROM quotas fails.
|
||||
_, execErr := store.db.Exec("ALTER TABLE quotas RENAME COLUMN max_rpm TO rpm")
|
||||
require.NoError(t, execErr)
|
||||
|
||||
_, err = store.loadQuotas()
|
||||
assert.Error(t, err, "loadQuotas should fail with renamed column")
|
||||
})
|
||||
}
|
||||
|
||||
func TestError_NewSQLiteStoreInReadOnlyDir_Bad(t *testing.T) {
|
||||
if isRootUser() {
|
||||
t.Skip("chmod restrictions do not apply to root")
|
||||
}
|
||||
|
||||
t.Run("fails when parent directory is read-only", func(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
readonlyDir := testPath(tmpDir, "readonly")
|
||||
ensureTestDir(t, readonlyDir)
|
||||
setPathMode(t, readonlyDir, 0o555)
|
||||
defer func() {
|
||||
_ = syscall.Chmod(readonlyDir, 0o755)
|
||||
}()
|
||||
|
||||
dbPath := testPath(readonlyDir, "test.db")
|
||||
_, err := newSQLiteStore(dbPath)
|
||||
assert.Error(t, err, "should fail when directory is read-only")
|
||||
})
|
||||
}
|
||||
|
||||
func TestError_SQLiteCreateSchema_Bad(t *testing.T) {
|
||||
t.Run("createSchema fails on closed DB", func(t *testing.T) {
|
||||
dbPath := testPath(t.TempDir(), "schema-err.db")
|
||||
store, err := newSQLiteStore(dbPath)
|
||||
require.NoError(t, err)
|
||||
|
||||
db := store.db
|
||||
store.close()
|
||||
|
||||
err = createSchema(db)
|
||||
assert.Error(t, err, "createSchema should fail on closed DB")
|
||||
assert.Contains(t, err.Error(), "ratelimit.createSchema")
|
||||
})
|
||||
}
|
||||
|
||||
func TestError_SQLiteLoadStateScan_Bad(t *testing.T) {
|
||||
t.Run("scan daily fails with NULL values", func(t *testing.T) {
|
||||
dbPath := testPath(t.TempDir(), "scan-daily.db")
|
||||
store, err := newSQLiteStore(dbPath)
|
||||
require.NoError(t, err)
|
||||
defer store.close()
|
||||
|
||||
// Recreate daily without NOT NULL constraints so we can insert NULLs.
|
||||
_, _ = store.db.Exec("DROP TABLE daily")
|
||||
_, execErr := store.db.Exec("CREATE TABLE daily (model TEXT PRIMARY KEY, day_start INTEGER, day_count INTEGER)")
|
||||
require.NoError(t, execErr)
|
||||
// Insert a NULL day_start; scanning NULL into int64 returns an error.
|
||||
_, execErr = store.db.Exec("INSERT INTO daily VALUES ('test', NULL, NULL)")
|
||||
require.NoError(t, execErr)
|
||||
|
||||
_, err = store.loadState()
|
||||
if err != nil {
|
||||
assert.Contains(t, err.Error(), "ratelimit.loadState")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("scan requests fails with NULL ts", func(t *testing.T) {
|
||||
dbPath := testPath(t.TempDir(), "scan-req.db")
|
||||
store, err := newSQLiteStore(dbPath)
|
||||
require.NoError(t, err)
|
||||
defer store.close()
|
||||
|
||||
// Insert a valid daily entry so loadState gets past the daily phase.
|
||||
_, execErr := store.db.Exec("INSERT INTO daily VALUES ('test', 0, 1)")
|
||||
require.NoError(t, execErr)
|
||||
|
||||
// Recreate requests without NOT NULL, insert NULL ts.
|
||||
_, _ = store.db.Exec("DROP TABLE requests")
|
||||
_, execErr = store.db.Exec("CREATE TABLE requests (model TEXT, ts INTEGER)")
|
||||
require.NoError(t, execErr)
|
||||
_, execErr = store.db.Exec("CREATE INDEX IF NOT EXISTS idx_requests_model_ts ON requests(model, ts)")
|
||||
require.NoError(t, execErr)
|
||||
_, execErr = store.db.Exec("INSERT INTO requests VALUES ('test', NULL)")
|
||||
require.NoError(t, execErr)
|
||||
|
||||
_, err = store.loadState()
|
||||
if err != nil {
|
||||
assert.Contains(t, err.Error(), "ratelimit.loadState")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("scan tokens fails with NULL values", func(t *testing.T) {
|
||||
dbPath := testPath(t.TempDir(), "scan-tok.db")
|
||||
store, err := newSQLiteStore(dbPath)
|
||||
require.NoError(t, err)
|
||||
defer store.close()
|
||||
|
||||
// Insert valid daily entry.
|
||||
_, execErr := store.db.Exec("INSERT INTO daily VALUES ('test', 0, 1)")
|
||||
require.NoError(t, execErr)
|
||||
|
||||
// Recreate tokens without NOT NULL, insert NULL values.
|
||||
_, _ = store.db.Exec("DROP TABLE tokens")
|
||||
_, execErr = store.db.Exec("CREATE TABLE tokens (model TEXT, ts INTEGER, count INTEGER)")
|
||||
require.NoError(t, execErr)
|
||||
_, execErr = store.db.Exec("CREATE INDEX IF NOT EXISTS idx_tokens_model_ts ON tokens(model, ts)")
|
||||
require.NoError(t, execErr)
|
||||
_, execErr = store.db.Exec("INSERT INTO tokens VALUES ('test', NULL, NULL)")
|
||||
require.NoError(t, execErr)
|
||||
|
||||
_, err = store.loadState()
|
||||
if err != nil {
|
||||
assert.Contains(t, err.Error(), "ratelimit.loadState")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestError_SQLiteLoadQuotasScanWithBadSchema_Bad(t *testing.T) {
|
||||
t.Run("scan fails with NULL quota values", func(t *testing.T) {
|
||||
dbPath := testPath(t.TempDir(), "scan-quota.db")
|
||||
store, err := newSQLiteStore(dbPath)
|
||||
require.NoError(t, err)
|
||||
defer store.close()
|
||||
|
||||
// Recreate quotas without NOT NULL constraints.
|
||||
_, _ = store.db.Exec("DROP TABLE quotas")
|
||||
_, execErr := store.db.Exec("CREATE TABLE quotas (model TEXT PRIMARY KEY, max_rpm INTEGER, max_tpm INTEGER, max_rpd INTEGER)")
|
||||
require.NoError(t, execErr)
|
||||
_, execErr = store.db.Exec("INSERT INTO quotas VALUES ('test', NULL, NULL, NULL)")
|
||||
require.NoError(t, execErr)
|
||||
|
||||
_, err = store.loadQuotas()
|
||||
if err != nil {
|
||||
assert.Contains(t, err.Error(), "ratelimit.loadQuotas")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestError_MigrateYAMLToSQLiteWithSaveErrors_Bad(t *testing.T) {
|
||||
t.Run("saveQuotas failure during migration via trigger", func(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
yamlPath := testPath(tmpDir, "with-quotas.yaml")
|
||||
sqlitePath := testPath(tmpDir, "migrate-quota-err.db")
|
||||
|
||||
// Write a YAML file with quotas.
|
||||
yamlData := `quotas:
|
||||
test-model:
|
||||
max_rpm: 10
|
||||
max_tpm: 100
|
||||
max_rpd: 50
|
||||
`
|
||||
writeTestFile(t, yamlPath, yamlData)
|
||||
|
||||
// Pre-create DB with a trigger that aborts quota inserts.
|
||||
store, err := newSQLiteStore(sqlitePath)
|
||||
require.NoError(t, err)
|
||||
_, execErr := store.db.Exec(`CREATE TRIGGER fail_quota_migrate BEFORE INSERT ON quotas
|
||||
BEGIN SELECT RAISE(ABORT, 'forced quota failure'); END`)
|
||||
require.NoError(t, execErr)
|
||||
store.close()
|
||||
|
||||
// Migration re-opens the DB; tables already exist, trigger persists.
|
||||
err = MigrateYAMLToSQLite(yamlPath, sqlitePath)
|
||||
assert.Error(t, err, "migration should fail when saveQuotas fails")
|
||||
})
|
||||
|
||||
t.Run("saveState failure during migration via trigger", func(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
yamlPath := testPath(tmpDir, "with-state.yaml")
|
||||
sqlitePath := testPath(tmpDir, "migrate-state-err.db")
|
||||
|
||||
// Write YAML with state.
|
||||
yamlData := `state:
|
||||
test-model:
|
||||
requests:
|
||||
- time: 2026-01-01T00:00:00Z
|
||||
day_start: 2026-01-01T00:00:00Z
|
||||
day_count: 1
|
||||
`
|
||||
writeTestFile(t, yamlPath, yamlData)
|
||||
|
||||
// Pre-create DB with a trigger that aborts daily inserts.
|
||||
store, err := newSQLiteStore(sqlitePath)
|
||||
require.NoError(t, err)
|
||||
_, execErr := store.db.Exec(`CREATE TRIGGER fail_daily_migrate BEFORE INSERT ON daily
|
||||
BEGIN SELECT RAISE(ABORT, 'forced daily failure'); END`)
|
||||
require.NoError(t, execErr)
|
||||
store.close()
|
||||
|
||||
err = MigrateYAMLToSQLite(yamlPath, sqlitePath)
|
||||
assert.Error(t, err, "migration should fail when saveState fails")
|
||||
})
|
||||
}
|
||||
|
||||
func TestError_MigrateYAMLToSQLiteNilQuotasAndState_Good(t *testing.T) {
|
||||
t.Run("YAML with empty quotas and state migrates cleanly", func(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
yamlPath := testPath(tmpDir, "empty.yaml")
|
||||
writeTestFile(t, yamlPath, "{}")
|
||||
|
||||
sqlitePath := testPath(tmpDir, "empty.db")
|
||||
require.NoError(t, MigrateYAMLToSQLite(yamlPath, sqlitePath))
|
||||
|
||||
store, err := newSQLiteStore(sqlitePath)
|
||||
require.NoError(t, err)
|
||||
defer store.close()
|
||||
|
||||
quotas, err := store.loadQuotas()
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, quotas)
|
||||
|
||||
state, err := store.loadState()
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, state)
|
||||
})
|
||||
}
|
||||
|
||||
func TestError_NewWithConfigHomeUnavailable_Bad(t *testing.T) {
|
||||
// Clear all supported home env vars so defaultStatePath cannot resolve a home directory.
|
||||
t.Setenv("CORE_HOME", "")
|
||||
t.Setenv("HOME", "")
|
||||
t.Setenv("home", "")
|
||||
t.Setenv("USERPROFILE", "")
|
||||
|
||||
_, err := NewWithConfig(Config{})
|
||||
assert.Error(t, err, "should fail when HOME is unset")
|
||||
}
|
||||
|
||||
func TestError_PersistMarshal_Good(t *testing.T) {
|
||||
// yaml.Marshal on a struct with map[string]ModelQuota and map[string]*UsageStats
|
||||
// should not fail in practice. We test the error path by using a type that
|
||||
// yaml.Marshal cannot handle: a channel.
|
||||
// Since we cannot inject a channel into the typed struct, this path is
|
||||
// unreachable in production. Instead, exercise the Persist YAML path
|
||||
// with valid data to confirm coverage of the non-error path.
|
||||
rl := newTestLimiter(t)
|
||||
rl.RecordUsage("test", 1, 1)
|
||||
assert.NoError(t, rl.Persist(), "valid persist should succeed")
|
||||
}
|
||||
|
||||
func TestError_MigrateErrorsExtended_Bad(t *testing.T) {
|
||||
t.Run("unmarshal failure", func(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
path := testPath(tmpDir, "bad.yaml")
|
||||
writeTestFile(t, path, "invalid: yaml: [")
|
||||
err := MigrateYAMLToSQLite(path, testPath(tmpDir, "out.db"))
|
||||
assert.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "ratelimit.MigrateYAMLToSQLite: unmarshal")
|
||||
})
|
||||
|
||||
t.Run("sqlite open failure", func(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
yamlPath := testPath(tmpDir, "ok.yaml")
|
||||
writeTestFile(t, yamlPath, "quotas: {}")
|
||||
// Use an invalid sqlite path (dir where file should be)
|
||||
err := MigrateYAMLToSQLite(yamlPath, "/dev/null/not-a-db")
|
||||
assert.Error(t, err)
|
||||
})
|
||||
}
|
||||
17
go.mod
17
go.mod
|
|
@ -1,25 +1,24 @@
|
|||
// SPDX-License-Identifier: EUPL-1.2
|
||||
|
||||
module dappco.re/go/core/go-ratelimit
|
||||
module forge.lthn.ai/core/go-ratelimit
|
||||
|
||||
go 1.26.0
|
||||
|
||||
require (
|
||||
dappco.re/go/core v0.8.0-alpha.1
|
||||
gopkg.in/yaml.v3 v3.0.1
|
||||
modernc.org/sqlite v1.47.0
|
||||
modernc.org/sqlite v1.46.1
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/kr/text v0.2.0 // indirect
|
||||
github.com/kr/pretty v0.3.1 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/ncruces/go-strftime v1.0.0 // indirect
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||
golang.org/x/sys v0.42.0 // indirect
|
||||
golang.org/x/tools v0.43.0 // indirect
|
||||
modernc.org/libc v1.70.0 // indirect
|
||||
github.com/rogpeppe/go-internal v1.14.1 // indirect
|
||||
golang.org/x/exp v0.0.0-20260218203240-3dfff04db8fa // indirect
|
||||
golang.org/x/sys v0.41.0 // indirect
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect
|
||||
modernc.org/libc v1.68.0 // indirect
|
||||
modernc.org/mathutil v1.7.1 // indirect
|
||||
modernc.org/memory v1.11.0 // indirect
|
||||
)
|
||||
|
|
|
|||
41
go.sum
41
go.sum
|
|
@ -1,5 +1,3 @@
|
|||
dappco.re/go/core v0.8.0-alpha.1 h1:gj7+Scv+L63Z7wMxbJYHhaRFkHJo2u4MMPuUSv/Dhtk=
|
||||
dappco.re/go/core v0.8.0-alpha.1/go.mod h1:f2/tBZ3+3IqDrg2F5F598llv0nmb/4gJVCFzM5geE4A=
|
||||
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
|
|
@ -11,31 +9,38 @@ github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
|||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
|
||||
github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
|
||||
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
|
||||
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
|
||||
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
|
||||
github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
|
||||
github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA=
|
||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
|
||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
||||
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
|
||||
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
|
||||
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
golang.org/x/mod v0.34.0 h1:xIHgNUUnW6sYkcM5Jleh05DvLOtwc6RitGHbDk4akRI=
|
||||
golang.org/x/mod v0.34.0/go.mod h1:ykgH52iCZe79kzLLMhyCUzhMci+nQj+0XkbXpNYtVjY=
|
||||
golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
|
||||
golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/exp v0.0.0-20260218203240-3dfff04db8fa h1:Zt3DZoOFFYkKhDT3v7Lm9FDMEV06GpzjG2jrqW+QTE0=
|
||||
golang.org/x/exp v0.0.0-20260218203240-3dfff04db8fa/go.mod h1:K79w1Vqn7PoiZn+TkNpx3BUWUQksGO3JcVX6qIjytmA=
|
||||
golang.org/x/mod v0.33.0 h1:tHFzIWbBifEmbwtGz65eaWyGiGZatSrT9prnU8DbVL8=
|
||||
golang.org/x/mod v0.33.0/go.mod h1:swjeQEj+6r7fODbD2cqrnje9PnziFuw4bmLbBZFrQ5w=
|
||||
golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4=
|
||||
golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=
|
||||
golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/tools v0.43.0 h1:12BdW9CeB3Z+J/I/wj34VMl8X+fEXBxVR90JeMX5E7s=
|
||||
golang.org/x/tools v0.43.0/go.mod h1:uHkMso649BX2cZK6+RpuIPXS3ho2hZo4FVwfoy1vIk0=
|
||||
golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=
|
||||
golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||
golang.org/x/tools v0.42.0 h1:uNgphsn75Tdz5Ji2q36v/nsFSfR/9BRFvqhGBaJGd5k=
|
||||
golang.org/x/tools v0.42.0/go.mod h1:Ma6lCIwGZvHK6XtgbswSoWroEkhugApmsXyrUmBhfr0=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||
|
|
@ -43,18 +48,18 @@ gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
|||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
modernc.org/cc/v4 v4.27.1 h1:9W30zRlYrefrDV2JE2O8VDtJ1yPGownxciz5rrbQZis=
|
||||
modernc.org/cc/v4 v4.27.1/go.mod h1:uVtb5OGqUKpoLWhqwNQo/8LwvoiEBLvZXIQ/SmO6mL0=
|
||||
modernc.org/ccgo/v4 v4.32.0 h1:hjG66bI/kqIPX1b2yT6fr/jt+QedtP2fqojG2VrFuVw=
|
||||
modernc.org/ccgo/v4 v4.32.0/go.mod h1:6F08EBCx5uQc38kMGl+0Nm0oWczoo1c7cgpzEry7Uc0=
|
||||
modernc.org/fileutil v1.4.0 h1:j6ZzNTftVS054gi281TyLjHPp6CPHr2KCxEXjEbD6SM=
|
||||
modernc.org/fileutil v1.4.0/go.mod h1:EqdKFDxiByqxLk8ozOxObDSfcVOv/54xDs/DUHdvCUU=
|
||||
modernc.org/ccgo/v4 v4.30.2 h1:4yPaaq9dXYXZ2V8s1UgrC3KIj580l2N4ClrLwnbv2so=
|
||||
modernc.org/ccgo/v4 v4.30.2/go.mod h1:yZMnhWEdW0qw3EtCndG1+ldRrVGS+bIwyWmAWzS0XEw=
|
||||
modernc.org/fileutil v1.3.40 h1:ZGMswMNc9JOCrcrakF1HrvmergNLAmxOPjizirpfqBA=
|
||||
modernc.org/fileutil v1.3.40/go.mod h1:HxmghZSZVAz/LXcMNwZPA/DRrQZEVP9VX0V4LQGQFOc=
|
||||
modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI=
|
||||
modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito=
|
||||
modernc.org/gc/v3 v3.1.2 h1:ZtDCnhonXSZexk/AYsegNRV1lJGgaNZJuKjJSWKyEqo=
|
||||
modernc.org/gc/v3 v3.1.2/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY=
|
||||
modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks=
|
||||
modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI=
|
||||
modernc.org/libc v1.70.0 h1:U58NawXqXbgpZ/dcdS9kMshu08aiA6b7gusEusqzNkw=
|
||||
modernc.org/libc v1.70.0/go.mod h1:OVmxFGP1CI/Z4L3E0Q3Mf1PDE0BucwMkcXjjLntvHJo=
|
||||
modernc.org/libc v1.68.0 h1:PJ5ikFOV5pwpW+VqCK1hKJuEWsonkIJhhIXyuF/91pQ=
|
||||
modernc.org/libc v1.68.0/go.mod h1:NnKCYeoYgsEqnY3PgvNgAeaJnso968ygU8Z0DxjoEc0=
|
||||
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
|
||||
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
|
||||
modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI=
|
||||
|
|
@ -63,8 +68,8 @@ modernc.org/opt v0.1.4 h1:2kNGMRiUjrp4LcaPuLY2PzUfqM/w9N23quVwhKt5Qm8=
|
|||
modernc.org/opt v0.1.4/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns=
|
||||
modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w=
|
||||
modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE=
|
||||
modernc.org/sqlite v1.47.0 h1:R1XyaNpoW4Et9yly+I2EeX7pBza/w+pmYee/0HJDyKk=
|
||||
modernc.org/sqlite v1.47.0/go.mod h1:hWjRO6Tj/5Ik8ieqxQybiEOUXy0NJFNp2tpvVpKlvig=
|
||||
modernc.org/sqlite v1.46.1 h1:eFJ2ShBLIEnUWlLy12raN0Z1plqmFX9Qe3rjQTKt6sU=
|
||||
modernc.org/sqlite v1.46.1/go.mod h1:CzbrU2lSB1DKUusvwGz7rqEKIq+NUd8GWuBBZDs9/nA=
|
||||
modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=
|
||||
modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=
|
||||
modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
|
||||
|
|
|
|||
140
iter_test.go
140
iter_test.go
|
|
@ -1,140 +0,0 @@
|
|||
// SPDX-License-Identifier: EUPL-1.2
|
||||
|
||||
package ratelimit
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestIter_Iterators_Good(t *testing.T) {
|
||||
rl, err := NewWithConfig(Config{
|
||||
Quotas: map[string]ModelQuota{
|
||||
"model-c": {MaxRPM: 10},
|
||||
"model-a": {MaxRPM: 10},
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
rl.RecordUsage("model-b", 1, 1)
|
||||
|
||||
t.Run("Models iterator is sorted", func(t *testing.T) {
|
||||
var models []string
|
||||
for m := range rl.Models() {
|
||||
models = append(models, m)
|
||||
}
|
||||
// Should include Gemini defaults (from NewWithConfig's default) + custom models
|
||||
// and be sorted.
|
||||
assert.Contains(t, models, "model-a")
|
||||
assert.Contains(t, models, "model-b")
|
||||
assert.Contains(t, models, "model-c")
|
||||
|
||||
// Check sorting of our specific models
|
||||
foundA, foundB, foundC := -1, -1, -1
|
||||
for i, m := range models {
|
||||
if m == "model-a" {
|
||||
foundA = i
|
||||
}
|
||||
if m == "model-b" {
|
||||
foundB = i
|
||||
}
|
||||
if m == "model-c" {
|
||||
foundC = i
|
||||
}
|
||||
}
|
||||
assert.True(t, foundA < foundB && foundB < foundC, "models should be sorted: a < b < c")
|
||||
})
|
||||
|
||||
t.Run("Iter iterator is sorted", func(t *testing.T) {
|
||||
var models []string
|
||||
for m, stats := range rl.Iter() {
|
||||
models = append(models, m)
|
||||
if m == "model-a" {
|
||||
assert.Equal(t, 10, stats.MaxRPM)
|
||||
}
|
||||
}
|
||||
assert.Contains(t, models, "model-a")
|
||||
assert.Contains(t, models, "model-b")
|
||||
assert.Contains(t, models, "model-c")
|
||||
|
||||
// Check sorting
|
||||
foundA, foundB, foundC := -1, -1, -1
|
||||
for i, m := range models {
|
||||
if m == "model-a" {
|
||||
foundA = i
|
||||
}
|
||||
if m == "model-b" {
|
||||
foundB = i
|
||||
}
|
||||
if m == "model-c" {
|
||||
foundC = i
|
||||
}
|
||||
}
|
||||
assert.True(t, foundA < foundB && foundB < foundC, "iter should be sorted: a < b < c")
|
||||
})
|
||||
}
|
||||
|
||||
func TestIter_IterEarlyBreak_Good(t *testing.T) {
|
||||
rl, err := NewWithConfig(Config{
|
||||
Quotas: map[string]ModelQuota{
|
||||
"model-a": {MaxRPM: 10},
|
||||
"model-b": {MaxRPM: 20},
|
||||
"model-c": {MaxRPM: 30},
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
t.Run("Iter breaks early", func(t *testing.T) {
|
||||
var count int
|
||||
for range rl.Iter() {
|
||||
count++
|
||||
if count == 1 {
|
||||
break
|
||||
}
|
||||
}
|
||||
assert.Equal(t, 1, count, "should stop after first iteration")
|
||||
})
|
||||
|
||||
t.Run("Models early break via manual iteration", func(t *testing.T) {
|
||||
var count int
|
||||
for range rl.Models() {
|
||||
count++
|
||||
if count == 2 {
|
||||
break
|
||||
}
|
||||
}
|
||||
assert.Equal(t, 2, count, "should stop after two models")
|
||||
})
|
||||
}
|
||||
|
||||
func TestIter_CountTokensFull_Ugly(t *testing.T) {
|
||||
t.Run("empty model is rejected", func(t *testing.T) {
|
||||
_, err := CountTokens(context.Background(), "key", "", "text")
|
||||
assert.Error(t, err)
|
||||
})
|
||||
|
||||
t.Run("API error non-200", func(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
w.Write([]byte("bad request"))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
_, err := countTokensWithClient(context.Background(), server.Client(), server.URL, "key", "model", "text")
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "status 400")
|
||||
})
|
||||
|
||||
t.Run("context cancelled", func(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
_, err := countTokensWithClient(ctx, http.DefaultClient, "https://generativelanguage.googleapis.com", "key", "model", "text")
|
||||
assert.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "do request")
|
||||
})
|
||||
}
|
||||
848
ratelimit.go
848
ratelimit.go
File diff suppressed because it is too large
Load diff
|
|
@ -1,113 +1,33 @@
|
|||
// SPDX-License-Identifier: EUPL-1.2
|
||||
|
||||
package ratelimit
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
core "dappco.re/go/core"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func testPath(parts ...string) string {
|
||||
return core.Path(parts...)
|
||||
}
|
||||
|
||||
func pathExists(path string) bool {
|
||||
var fs core.Fs
|
||||
return fs.Exists(path)
|
||||
}
|
||||
|
||||
func writeTestFile(tb testing.TB, path, content string) {
|
||||
tb.Helper()
|
||||
require.NoError(tb, writeLocalFile(path, content))
|
||||
}
|
||||
|
||||
func ensureTestDir(tb testing.TB, path string) {
|
||||
tb.Helper()
|
||||
require.NoError(tb, ensureDir(path))
|
||||
}
|
||||
|
||||
func setPathMode(tb testing.TB, path string, mode uint32) {
|
||||
tb.Helper()
|
||||
require.NoError(tb, syscall.Chmod(path, mode))
|
||||
}
|
||||
|
||||
func overwriteTestFile(tb testing.TB, path, content string) {
|
||||
tb.Helper()
|
||||
|
||||
var fs core.Fs
|
||||
writer := fs.Create(path)
|
||||
require.NoError(tb, resultError(writer))
|
||||
require.NoError(tb, resultError(core.WriteAll(writer.Value, content)))
|
||||
}
|
||||
|
||||
func isRootUser() bool {
|
||||
return syscall.Geteuid() == 0
|
||||
}
|
||||
|
||||
func repeatString(part string, count int) string {
|
||||
builder := core.NewBuilder()
|
||||
for i := 0; i < count; i++ {
|
||||
builder.WriteString(part)
|
||||
}
|
||||
return builder.String()
|
||||
}
|
||||
|
||||
func substringCount(s, substr string) int {
|
||||
if substr == "" {
|
||||
return 0
|
||||
}
|
||||
return len(core.Split(s, substr)) - 1
|
||||
}
|
||||
|
||||
func decodeJSONBody(tb testing.TB, r io.Reader, target any) {
|
||||
tb.Helper()
|
||||
|
||||
data, err := io.ReadAll(r)
|
||||
require.NoError(tb, err)
|
||||
require.NoError(tb, resultError(core.JSONUnmarshal(data, target)))
|
||||
}
|
||||
|
||||
func writeJSONBody(tb testing.TB, w io.Writer, value any) {
|
||||
tb.Helper()
|
||||
|
||||
_, err := io.WriteString(w, core.JSONMarshalString(value))
|
||||
require.NoError(tb, err)
|
||||
}
|
||||
|
||||
// newTestLimiter returns a RateLimiter with file path set to a temp directory.
|
||||
func newTestLimiter(t *testing.T) *RateLimiter {
|
||||
t.Helper()
|
||||
rl, err := New()
|
||||
require.NoError(t, err)
|
||||
rl.filePath = testPath(t.TempDir(), "ratelimits.yaml")
|
||||
rl.filePath = filepath.Join(t.TempDir(), "ratelimits.yaml")
|
||||
return rl
|
||||
}
|
||||
|
||||
type roundTripFunc func(*http.Request) (*http.Response, error)
|
||||
|
||||
func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
|
||||
return f(req)
|
||||
}
|
||||
|
||||
type errReader struct{}
|
||||
|
||||
func (errReader) Read([]byte) (int, error) {
|
||||
return 0, io.ErrUnexpectedEOF
|
||||
}
|
||||
|
||||
// --- Phase 0: CanSend boundary conditions ---
|
||||
|
||||
func TestRatelimit_CanSend_Good(t *testing.T) {
|
||||
func TestCanSend(t *testing.T) {
|
||||
t.Run("fresh state allows send", func(t *testing.T) {
|
||||
rl := newTestLimiter(t)
|
||||
model := "test-model"
|
||||
|
|
@ -242,144 +162,11 @@ func TestRatelimit_CanSend_Good(t *testing.T) {
|
|||
rl.RecordUsage(model, 50, 50) // exactly 100 tokens
|
||||
assert.True(t, rl.CanSend(model, 0), "zero estimated tokens should fit even at limit")
|
||||
})
|
||||
|
||||
t.Run("negative estimated tokens are rejected", func(t *testing.T) {
|
||||
rl := newTestLimiter(t)
|
||||
model := "negative-est"
|
||||
rl.Quotas[model] = ModelQuota{MaxRPM: 100, MaxTPM: 100, MaxRPD: 100}
|
||||
rl.RecordUsage(model, 50, 50)
|
||||
|
||||
assert.False(t, rl.CanSend(model, -1), "negative estimated tokens should not bypass TPM limits")
|
||||
})
|
||||
}
|
||||
|
||||
// --- Phase 0: Decide surface area ---
|
||||
|
||||
func TestRatelimit_Decide_Good(t *testing.T) {
|
||||
t.Run("unknown model remains allowed with unknown code", func(t *testing.T) {
|
||||
rl := newTestLimiter(t)
|
||||
|
||||
decision := rl.Decide("unknown-model", 50)
|
||||
|
||||
assert.True(t, decision.Allowed)
|
||||
assert.Equal(t, DecisionUnknownModel, decision.Code)
|
||||
assert.Zero(t, decision.RetryAfter)
|
||||
})
|
||||
|
||||
t.Run("unlimited quota reports unlimited decision", func(t *testing.T) {
|
||||
rl := newTestLimiter(t)
|
||||
model := "unlimited"
|
||||
rl.Quotas[model] = ModelQuota{}
|
||||
|
||||
decision := rl.Decide(model, 100)
|
||||
|
||||
assert.True(t, decision.Allowed)
|
||||
assert.Equal(t, DecisionUnlimited, decision.Code)
|
||||
assert.Equal(t, 0, decision.Stats.MaxRPM)
|
||||
assert.Equal(t, 0, decision.Stats.MaxTPM)
|
||||
assert.Equal(t, 0, decision.Stats.MaxRPD)
|
||||
})
|
||||
|
||||
t.Run("rpd limit returns retry window", func(t *testing.T) {
|
||||
rl := newTestLimiter(t)
|
||||
model := "rpd-limit"
|
||||
now := time.Now()
|
||||
rl.Quotas[model] = ModelQuota{MaxRPM: 10, MaxTPM: 1000, MaxRPD: 2}
|
||||
rl.State[model] = &UsageStats{DayStart: now.Add(-23 * time.Hour), DayCount: 2}
|
||||
|
||||
decision := rl.Decide(model, 10)
|
||||
|
||||
assert.False(t, decision.Allowed)
|
||||
assert.Equal(t, DecisionRPDLimit, decision.Code)
|
||||
assert.InDelta(t, time.Hour.Seconds(), decision.RetryAfter.Seconds(), 2)
|
||||
assert.Equal(t, 2, decision.Stats.MaxRPD)
|
||||
assert.Equal(t, 2, decision.Stats.RPD)
|
||||
})
|
||||
|
||||
t.Run("rpm limit includes retry-after estimate", func(t *testing.T) {
|
||||
rl := newTestLimiter(t)
|
||||
model := "rpm-limit"
|
||||
now := time.Now()
|
||||
rl.Quotas[model] = ModelQuota{MaxRPM: 1, MaxTPM: 1000, MaxRPD: 5}
|
||||
rl.State[model] = &UsageStats{
|
||||
Requests: []time.Time{now.Add(-10 * time.Second)},
|
||||
Tokens: []TokenEntry{{Time: now.Add(-10 * time.Second), Count: 10}},
|
||||
DayStart: now,
|
||||
DayCount: 1,
|
||||
}
|
||||
|
||||
decision := rl.Decide(model, 5)
|
||||
|
||||
assert.False(t, decision.Allowed)
|
||||
assert.Equal(t, DecisionRPMLimit, decision.Code)
|
||||
assert.InDelta(t, 50, decision.RetryAfter.Seconds(), 1)
|
||||
})
|
||||
|
||||
t.Run("tpm limit surfaces earliest expiry", func(t *testing.T) {
|
||||
rl := newTestLimiter(t)
|
||||
model := "tpm-limit"
|
||||
now := time.Now()
|
||||
rl.Quotas[model] = ModelQuota{MaxRPM: 10, MaxTPM: 100, MaxRPD: 10}
|
||||
rl.State[model] = &UsageStats{
|
||||
Requests: []time.Time{now.Add(-30 * time.Second)},
|
||||
Tokens: []TokenEntry{
|
||||
{Time: now.Add(-50 * time.Second), Count: 70},
|
||||
{Time: now.Add(-10 * time.Second), Count: 20},
|
||||
},
|
||||
DayStart: now,
|
||||
DayCount: 2,
|
||||
}
|
||||
|
||||
decision := rl.Decide(model, 20)
|
||||
|
||||
assert.False(t, decision.Allowed)
|
||||
assert.Equal(t, DecisionTPMLimit, decision.Code)
|
||||
assert.InDelta(t, 10, decision.RetryAfter.Seconds(), 1)
|
||||
})
|
||||
|
||||
t.Run("allowed decision carries stats snapshot", func(t *testing.T) {
|
||||
rl := newTestLimiter(t)
|
||||
model := "decide-allowed"
|
||||
rl.Quotas[model] = ModelQuota{MaxRPM: 5, MaxTPM: 200, MaxRPD: 3}
|
||||
now := time.Now()
|
||||
rl.State[model] = &UsageStats{
|
||||
Requests: []time.Time{now.Add(-5 * time.Second)},
|
||||
Tokens: []TokenEntry{{Time: now.Add(-5 * time.Second), Count: 30}},
|
||||
DayStart: now,
|
||||
DayCount: 1,
|
||||
}
|
||||
|
||||
decision := rl.Decide(model, 20)
|
||||
|
||||
assert.True(t, decision.Allowed)
|
||||
assert.Equal(t, DecisionAllowed, decision.Code)
|
||||
assert.Equal(t, 1, decision.Stats.RPM)
|
||||
assert.Equal(t, 30, decision.Stats.TPM)
|
||||
assert.Equal(t, 1, decision.Stats.RPD)
|
||||
assert.Equal(t, 5, decision.Stats.MaxRPM)
|
||||
assert.Equal(t, 200, decision.Stats.MaxTPM)
|
||||
assert.Equal(t, 3, decision.Stats.MaxRPD)
|
||||
})
|
||||
|
||||
t.Run("negative estimate returns invalid decision", func(t *testing.T) {
|
||||
rl := newTestLimiter(t)
|
||||
model := "neg"
|
||||
rl.Quotas[model] = ModelQuota{MaxRPM: 5, MaxTPM: 50, MaxRPD: 5}
|
||||
|
||||
decision := rl.Decide(model, -5)
|
||||
|
||||
assert.False(t, decision.Allowed)
|
||||
assert.Equal(t, DecisionInvalidTokens, decision.Code)
|
||||
assert.Zero(t, decision.RetryAfter)
|
||||
require.Contains(t, rl.State, model)
|
||||
require.NotNil(t, rl.State[model])
|
||||
assert.Equal(t, 0, rl.State[model].DayCount)
|
||||
})
|
||||
}
|
||||
|
||||
// --- Phase 0: Sliding window / prune tests ---
|
||||
|
||||
func TestRatelimit_Prune_Good(t *testing.T) {
|
||||
func TestPrune(t *testing.T) {
|
||||
t.Run("removes old entries", func(t *testing.T) {
|
||||
rl := newTestLimiter(t)
|
||||
model := "test-prune"
|
||||
|
|
@ -494,7 +281,7 @@ func TestRatelimit_Prune_Good(t *testing.T) {
|
|||
|
||||
// --- Phase 0: RecordUsage ---
|
||||
|
||||
func TestRatelimit_RecordUsage_Good(t *testing.T) {
|
||||
func TestRecordUsage(t *testing.T) {
|
||||
t.Run("records into fresh state", func(t *testing.T) {
|
||||
rl := newTestLimiter(t)
|
||||
model := "record-fresh"
|
||||
|
|
@ -548,24 +335,11 @@ func TestRatelimit_RecordUsage_Good(t *testing.T) {
|
|||
assert.Len(t, stats.Tokens, 2)
|
||||
assert.Equal(t, 6, stats.DayCount)
|
||||
})
|
||||
|
||||
t.Run("negative token inputs are clamped to zero", func(t *testing.T) {
|
||||
rl := newTestLimiter(t)
|
||||
model := "record-negative"
|
||||
|
||||
rl.RecordUsage(model, -100, 25)
|
||||
|
||||
stats := rl.State[model]
|
||||
require.NotNil(t, stats)
|
||||
assert.Len(t, stats.Requests, 1)
|
||||
assert.Len(t, stats.Tokens, 1)
|
||||
assert.Equal(t, 25, stats.Tokens[0].Count)
|
||||
})
|
||||
}
|
||||
|
||||
// --- Phase 0: Reset ---
|
||||
|
||||
func TestRatelimit_Reset_Good(t *testing.T) {
|
||||
func TestReset(t *testing.T) {
|
||||
t.Run("reset single model", func(t *testing.T) {
|
||||
rl := newTestLimiter(t)
|
||||
rl.RecordUsage("model-a", 10, 10)
|
||||
|
|
@ -599,7 +373,7 @@ func TestRatelimit_Reset_Good(t *testing.T) {
|
|||
|
||||
// --- Phase 0: WaitForCapacity ---
|
||||
|
||||
func TestRatelimit_WaitForCapacity_Good(t *testing.T) {
|
||||
func TestWaitForCapacity(t *testing.T) {
|
||||
t.Run("context cancelled returns error", func(t *testing.T) {
|
||||
rl := newTestLimiter(t)
|
||||
model := "wait-cancel"
|
||||
|
|
@ -648,63 +422,11 @@ func TestRatelimit_WaitForCapacity_Good(t *testing.T) {
|
|||
err := rl.WaitForCapacity(ctx, model, 10)
|
||||
assert.Error(t, err, "should return error for already-cancelled context")
|
||||
})
|
||||
|
||||
t.Run("negative tokens return error", func(t *testing.T) {
|
||||
rl := newTestLimiter(t)
|
||||
err := rl.WaitForCapacity(context.Background(), "wait-negative", -1)
|
||||
assert.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "negative tokens")
|
||||
})
|
||||
}
|
||||
|
||||
func TestRatelimit_NilUsageStats_Ugly(t *testing.T) {
|
||||
t.Run("CanSend replaces nil state without panicking", func(t *testing.T) {
|
||||
rl := newTestLimiter(t)
|
||||
model := "nil-cansend"
|
||||
rl.Quotas[model] = ModelQuota{MaxRPM: 10, MaxTPM: 100, MaxRPD: 10}
|
||||
rl.State[model] = nil
|
||||
|
||||
assert.NotPanics(t, func() {
|
||||
assert.True(t, rl.CanSend(model, 10))
|
||||
})
|
||||
assert.NotNil(t, rl.State[model])
|
||||
})
|
||||
|
||||
t.Run("RecordUsage replaces nil state without panicking", func(t *testing.T) {
|
||||
rl := newTestLimiter(t)
|
||||
model := "nil-record"
|
||||
rl.State[model] = nil
|
||||
|
||||
assert.NotPanics(t, func() {
|
||||
rl.RecordUsage(model, 10, 10)
|
||||
})
|
||||
require.NotNil(t, rl.State[model])
|
||||
assert.Equal(t, 1, rl.State[model].DayCount)
|
||||
})
|
||||
|
||||
t.Run("Stats and AllStats tolerate nil state entries", func(t *testing.T) {
|
||||
rl := newTestLimiter(t)
|
||||
rl.Quotas["nil-stats"] = ModelQuota{MaxRPM: 1, MaxTPM: 2, MaxRPD: 3}
|
||||
rl.State["nil-stats"] = nil
|
||||
rl.State["nil-all-stats"] = nil
|
||||
|
||||
assert.NotPanics(t, func() {
|
||||
stats := rl.Stats("nil-stats")
|
||||
assert.Equal(t, 1, stats.MaxRPM)
|
||||
assert.Equal(t, 0, stats.TPM)
|
||||
})
|
||||
|
||||
assert.NotPanics(t, func() {
|
||||
all := rl.AllStats()
|
||||
assert.Contains(t, all, "nil-stats")
|
||||
assert.Contains(t, all, "nil-all-stats")
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// --- Phase 0: Stats ---
|
||||
|
||||
func TestRatelimit_Stats_Good(t *testing.T) {
|
||||
func TestStats(t *testing.T) {
|
||||
t.Run("returns stats for known model with usage", func(t *testing.T) {
|
||||
rl := newTestLimiter(t)
|
||||
model := "stats-test"
|
||||
|
|
@ -744,7 +466,7 @@ func TestRatelimit_Stats_Good(t *testing.T) {
|
|||
|
||||
// --- Phase 0: AllStats ---
|
||||
|
||||
func TestRatelimit_AllStats_Good(t *testing.T) {
|
||||
func TestAllStats(t *testing.T) {
|
||||
t.Run("includes all default quotas plus state-only models", func(t *testing.T) {
|
||||
rl := newTestLimiter(t)
|
||||
rl.RecordUsage("gemini-3-pro-preview", 1000, 500)
|
||||
|
|
@ -802,10 +524,10 @@ func TestRatelimit_AllStats_Good(t *testing.T) {
|
|||
|
||||
// --- Phase 0: Persist and Load ---
|
||||
|
||||
func TestRatelimit_PersistAndLoad_Ugly(t *testing.T) {
|
||||
func TestPersistAndLoad(t *testing.T) {
|
||||
t.Run("round-trip preserves state", func(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
path := testPath(tmpDir, "ratelimits.yaml")
|
||||
path := filepath.Join(tmpDir, "ratelimits.yaml")
|
||||
|
||||
rl1, err := New()
|
||||
require.NoError(t, err)
|
||||
|
|
@ -828,7 +550,7 @@ func TestRatelimit_PersistAndLoad_Ugly(t *testing.T) {
|
|||
|
||||
t.Run("load from non-existent file is not an error", func(t *testing.T) {
|
||||
rl := newTestLimiter(t)
|
||||
rl.filePath = testPath(t.TempDir(), "does-not-exist.yaml")
|
||||
rl.filePath = filepath.Join(t.TempDir(), "does-not-exist.yaml")
|
||||
|
||||
err := rl.Load()
|
||||
assert.NoError(t, err, "loading non-existent file should not error")
|
||||
|
|
@ -836,8 +558,8 @@ func TestRatelimit_PersistAndLoad_Ugly(t *testing.T) {
|
|||
|
||||
t.Run("load from corrupt YAML returns error", func(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
path := testPath(tmpDir, "corrupt.yaml")
|
||||
writeTestFile(t, path, "{{{{invalid yaml!!!!")
|
||||
path := filepath.Join(tmpDir, "corrupt.yaml")
|
||||
require.NoError(t, os.WriteFile(path, []byte("{{{{invalid yaml!!!!"), 0644))
|
||||
|
||||
rl := newTestLimiter(t)
|
||||
rl.filePath = path
|
||||
|
|
@ -847,13 +569,13 @@ func TestRatelimit_PersistAndLoad_Ugly(t *testing.T) {
|
|||
})
|
||||
|
||||
t.Run("load from unreadable file returns error", func(t *testing.T) {
|
||||
if isRootUser() {
|
||||
if os.Getuid() == 0 {
|
||||
t.Skip("chmod 000 does not restrict root")
|
||||
}
|
||||
tmpDir := t.TempDir()
|
||||
path := testPath(tmpDir, "unreadable.yaml")
|
||||
writeTestFile(t, path, "quotas: {}")
|
||||
setPathMode(t, path, 0o000)
|
||||
path := filepath.Join(tmpDir, "unreadable.yaml")
|
||||
require.NoError(t, os.WriteFile(path, []byte("quotas: {}"), 0644))
|
||||
require.NoError(t, os.Chmod(path, 0000))
|
||||
|
||||
rl := newTestLimiter(t)
|
||||
rl.filePath = path
|
||||
|
|
@ -862,12 +584,12 @@ func TestRatelimit_PersistAndLoad_Ugly(t *testing.T) {
|
|||
assert.Error(t, err, "unreadable file should produce an error")
|
||||
|
||||
// Clean up permissions for temp dir cleanup
|
||||
_ = syscall.Chmod(path, 0o644)
|
||||
_ = os.Chmod(path, 0644)
|
||||
})
|
||||
|
||||
t.Run("persist to nested non-existent directory creates it", func(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
path := testPath(tmpDir, "nested", "deep", "ratelimits.yaml")
|
||||
path := filepath.Join(tmpDir, "nested", "deep", "ratelimits.yaml")
|
||||
|
||||
rl := newTestLimiter(t)
|
||||
rl.filePath = path
|
||||
|
|
@ -876,32 +598,32 @@ func TestRatelimit_PersistAndLoad_Ugly(t *testing.T) {
|
|||
err := rl.Persist()
|
||||
assert.NoError(t, err, "should create nested directories")
|
||||
|
||||
assert.True(t, pathExists(path), "file should exist")
|
||||
_, statErr := os.Stat(path)
|
||||
assert.NoError(t, statErr, "file should exist")
|
||||
})
|
||||
|
||||
t.Run("persist to unwritable directory returns error", func(t *testing.T) {
|
||||
if isRootUser() {
|
||||
if os.Getuid() == 0 {
|
||||
t.Skip("chmod 0555 does not restrict root")
|
||||
}
|
||||
tmpDir := t.TempDir()
|
||||
unwritable := testPath(tmpDir, "readonly")
|
||||
ensureTestDir(t, unwritable)
|
||||
setPathMode(t, unwritable, 0o555)
|
||||
unwritable := filepath.Join(tmpDir, "readonly")
|
||||
require.NoError(t, os.MkdirAll(unwritable, 0555))
|
||||
|
||||
rl := newTestLimiter(t)
|
||||
rl.filePath = testPath(unwritable, "sub", "ratelimits.yaml")
|
||||
rl.filePath = filepath.Join(unwritable, "sub", "ratelimits.yaml")
|
||||
|
||||
err := rl.Persist()
|
||||
assert.Error(t, err, "should fail when directory is unwritable")
|
||||
|
||||
// Clean up
|
||||
_ = syscall.Chmod(unwritable, 0o755)
|
||||
_ = os.Chmod(unwritable, 0755)
|
||||
})
|
||||
}
|
||||
|
||||
// --- Phase 0: Default quotas ---
|
||||
|
||||
func TestRatelimit_DefaultQuotas_Good(t *testing.T) {
|
||||
func TestDefaultQuotas(t *testing.T) {
|
||||
rl := newTestLimiter(t)
|
||||
|
||||
tests := []struct {
|
||||
|
|
@ -930,7 +652,7 @@ func TestRatelimit_DefaultQuotas_Good(t *testing.T) {
|
|||
|
||||
// --- Phase 0: Concurrent access (race test) ---
|
||||
|
||||
func TestRatelimit_ConcurrentAccess_Good(t *testing.T) {
|
||||
func TestConcurrentAccess(t *testing.T) {
|
||||
rl := newTestLimiter(t)
|
||||
model := "concurrent-test"
|
||||
rl.Quotas[model] = ModelQuota{MaxRPM: 1000, MaxTPM: 10000000, MaxRPD: 10000}
|
||||
|
|
@ -956,7 +678,7 @@ func TestRatelimit_ConcurrentAccess_Good(t *testing.T) {
|
|||
assert.Equal(t, expected, stats.RPD, "all recordings should be counted")
|
||||
}
|
||||
|
||||
func TestRatelimit_ConcurrentResetAndRecord_Ugly(t *testing.T) {
|
||||
func TestConcurrentResetAndRecord(t *testing.T) {
|
||||
rl := newTestLimiter(t)
|
||||
model := "concurrent-reset"
|
||||
rl.Quotas[model] = ModelQuota{MaxRPM: 10000, MaxTPM: 100000000, MaxRPD: 100000}
|
||||
|
|
@ -994,194 +716,38 @@ func TestRatelimit_ConcurrentResetAndRecord_Ugly(t *testing.T) {
|
|||
// No assertion needed -- if we get here without -race flagging, mutex is sound
|
||||
}
|
||||
|
||||
func TestRatelimit_BackgroundPrune_Good(t *testing.T) {
|
||||
rl := newTestLimiter(t)
|
||||
model := "prune-me"
|
||||
rl.Quotas[model] = ModelQuota{MaxRPM: 100}
|
||||
|
||||
// Set state with old usage.
|
||||
old := time.Now().Add(-2 * time.Minute)
|
||||
rl.State[model] = &UsageStats{
|
||||
Requests: []time.Time{old},
|
||||
Tokens: []TokenEntry{{Time: old, Count: 100}},
|
||||
}
|
||||
|
||||
stop := rl.BackgroundPrune(10 * time.Millisecond)
|
||||
defer stop()
|
||||
|
||||
// Wait for pruner to run.
|
||||
assert.Eventually(t, func() bool {
|
||||
rl.mu.Lock()
|
||||
defer rl.mu.Unlock()
|
||||
_, exists := rl.State[model]
|
||||
return !exists
|
||||
}, 1*time.Second, 20*time.Millisecond, "old empty state should be pruned")
|
||||
|
||||
t.Run("non-positive interval is a safe no-op", func(t *testing.T) {
|
||||
rl := newTestLimiter(t)
|
||||
rl.State["still-here"] = &UsageStats{
|
||||
Requests: []time.Time{time.Now().Add(-2 * time.Minute)},
|
||||
}
|
||||
|
||||
assert.NotPanics(t, func() {
|
||||
stop := rl.BackgroundPrune(0)
|
||||
stop()
|
||||
})
|
||||
assert.Contains(t, rl.State, "still-here")
|
||||
})
|
||||
}
|
||||
|
||||
// --- Phase 0: CountTokens (with mock HTTP server) ---
|
||||
|
||||
func TestRatelimit_CountTokens_Ugly(t *testing.T) {
|
||||
func TestCountTokens(t *testing.T) {
|
||||
t.Run("successful token count", func(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
assert.Equal(t, http.MethodPost, r.Method)
|
||||
assert.Equal(t, "application/json", r.Header.Get("Content-Type"))
|
||||
assert.Equal(t, "test-api-key", r.Header.Get("x-goog-api-key"))
|
||||
assert.Equal(t, "/v1beta/models/test-model:countTokens", r.URL.EscapedPath())
|
||||
|
||||
var body struct {
|
||||
Contents []struct {
|
||||
Parts []struct {
|
||||
Text string `json:"text"`
|
||||
} `json:"parts"`
|
||||
} `json:"contents"`
|
||||
}
|
||||
decodeJSONBody(t, r.Body, &body)
|
||||
require.Len(t, body.Contents, 1)
|
||||
require.Len(t, body.Contents[0].Parts, 1)
|
||||
assert.Equal(t, "hello", body.Contents[0].Parts[0].Text)
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
writeJSONBody(t, w, map[string]int{"totalTokens": 42})
|
||||
json.NewEncoder(w).Encode(map[string]int{"totalTokens": 42})
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
tokens, err := countTokensWithClient(context.Background(), server.Client(), server.URL, "test-api-key", "test-model", "hello")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 42, tokens)
|
||||
// We need to override the URL. Since CountTokens hardcodes the Google API URL,
|
||||
// we test it via the exported function with a test server.
|
||||
// For proper unit testing, we would need to make the base URL configurable.
|
||||
// For now, test the error paths that don't require a real API.
|
||||
})
|
||||
|
||||
t.Run("model name is path escaped", func(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
assert.Equal(t, "/v1beta/models/folder%2Fmodel%3Fdebug=1:countTokens", r.URL.EscapedPath())
|
||||
assert.Empty(t, r.URL.RawQuery)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
writeJSONBody(t, w, map[string]int{"totalTokens": 7})
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
tokens, err := countTokensWithClient(context.Background(), server.Client(), server.URL, "test-api-key", "folder/model?debug=1", "hello")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 7, tokens)
|
||||
})
|
||||
|
||||
t.Run("API error body is truncated", func(t *testing.T) {
|
||||
largeBody := repeatString("x", countTokensErrorBodyLimit+256)
|
||||
t.Run("API error returns error", func(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
_, err := io.WriteString(w, largeBody)
|
||||
require.NoError(t, err)
|
||||
fmt.Fprint(w, `{"error": "invalid API key"}`)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
_, err := countTokensWithClient(context.Background(), server.Client(), server.URL, "fake-key", "test-model", "hello")
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "api error status 401")
|
||||
assert.True(t, substringCount(err.Error(), "x") < len(largeBody), "error body should be bounded")
|
||||
assert.Contains(t, err.Error(), "...")
|
||||
// Can't test directly due to hardcoded URL, but we can verify error
|
||||
// handling with an unreachable endpoint
|
||||
_, err := CountTokens("fake-key", "test-model", "hello")
|
||||
assert.Error(t, err, "should fail with invalid API endpoint")
|
||||
})
|
||||
|
||||
t.Run("empty model is rejected before request", func(t *testing.T) {
|
||||
_, err := CountTokens(context.Background(), "fake-key", "", "hello")
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "build url")
|
||||
})
|
||||
|
||||
t.Run("invalid base URL returns error", func(t *testing.T) {
|
||||
_, err := countTokensWithClient(context.Background(), http.DefaultClient, "://bad-url", "fake-key", "test-model", "hello")
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "build url")
|
||||
})
|
||||
|
||||
t.Run("base URL without host returns error", func(t *testing.T) {
|
||||
_, err := countTokensWithClient(context.Background(), http.DefaultClient, "/relative", "fake-key", "test-model", "hello")
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "build url")
|
||||
})
|
||||
|
||||
t.Run("invalid JSON response returns error", func(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, err := w.Write([]byte(`{"totalTokens":`))
|
||||
require.NoError(t, err)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
_, err := countTokensWithClient(context.Background(), server.Client(), server.URL, "fake-key", "test-model", "hello")
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "decode response")
|
||||
})
|
||||
|
||||
t.Run("error body read failures are returned", func(t *testing.T) {
|
||||
client := &http.Client{
|
||||
Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusBadGateway,
|
||||
Body: io.NopCloser(errReader{}),
|
||||
Header: make(http.Header),
|
||||
}, nil
|
||||
}),
|
||||
}
|
||||
|
||||
_, err := countTokensWithClient(context.Background(), client, "https://generativelanguage.googleapis.com", "fake-key", "test-model", "hello")
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "read error body")
|
||||
})
|
||||
|
||||
t.Run("nil client falls back to http.DefaultClient", func(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
writeJSONBody(t, w, map[string]int{"totalTokens": 11})
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
originalClient := http.DefaultClient
|
||||
http.DefaultClient = server.Client()
|
||||
defer func() {
|
||||
http.DefaultClient = originalClient
|
||||
}()
|
||||
|
||||
tokens, err := countTokensWithClient(context.Background(), nil, server.URL, "fake-key", "test-model", "hello")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 11, tokens)
|
||||
})
|
||||
}
|
||||
|
||||
func TestRatelimit_PersistSkipsNilState_Good(t *testing.T) {
|
||||
path := testPath(t.TempDir(), "nil-state.yaml")
|
||||
|
||||
rl, err := New()
|
||||
require.NoError(t, err)
|
||||
rl.filePath = path
|
||||
rl.State["nil-model"] = nil
|
||||
|
||||
require.NoError(t, rl.Persist())
|
||||
|
||||
rl2, err := New()
|
||||
require.NoError(t, err)
|
||||
rl2.filePath = path
|
||||
require.NoError(t, rl2.Load())
|
||||
assert.NotContains(t, rl2.State, "nil-model")
|
||||
}
|
||||
|
||||
func TestRatelimit_TokenTotals_Good(t *testing.T) {
|
||||
maxInt := int(^uint(0) >> 1)
|
||||
|
||||
assert.Equal(t, 25, safeTokenSum(-100, 25))
|
||||
assert.Equal(t, maxInt, safeTokenSum(maxInt, 1))
|
||||
assert.Equal(t, 10, totalTokenCount([]TokenEntry{{Count: -5}, {Count: 10}}))
|
||||
}
|
||||
|
||||
// --- Phase 0: Benchmarks ---
|
||||
|
|
@ -1246,7 +812,7 @@ func BenchmarkCanSendConcurrent(b *testing.B) {
|
|||
|
||||
// --- Phase 1: Provider profiles and NewWithConfig ---
|
||||
|
||||
func TestRatelimit_DefaultProfiles_Good(t *testing.T) {
|
||||
func TestDefaultProfiles(t *testing.T) {
|
||||
profiles := DefaultProfiles()
|
||||
|
||||
t.Run("contains all four providers", func(t *testing.T) {
|
||||
|
|
@ -1287,10 +853,10 @@ func TestRatelimit_DefaultProfiles_Good(t *testing.T) {
|
|||
})
|
||||
}
|
||||
|
||||
func TestRatelimit_NewWithConfig_Ugly(t *testing.T) {
|
||||
func TestNewWithConfig(t *testing.T) {
|
||||
t.Run("empty config defaults to Gemini", func(t *testing.T) {
|
||||
rl, err := NewWithConfig(Config{
|
||||
FilePath: testPath(t.TempDir(), "test.yaml"),
|
||||
FilePath: filepath.Join(t.TempDir(), "test.yaml"),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
|
|
@ -1300,7 +866,7 @@ func TestRatelimit_NewWithConfig_Ugly(t *testing.T) {
|
|||
|
||||
t.Run("single provider loads only its models", func(t *testing.T) {
|
||||
rl, err := NewWithConfig(Config{
|
||||
FilePath: testPath(t.TempDir(), "test.yaml"),
|
||||
FilePath: filepath.Join(t.TempDir(), "test.yaml"),
|
||||
Providers: []Provider{ProviderOpenAI},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
|
@ -1314,7 +880,7 @@ func TestRatelimit_NewWithConfig_Ugly(t *testing.T) {
|
|||
|
||||
t.Run("multiple providers merge models", func(t *testing.T) {
|
||||
rl, err := NewWithConfig(Config{
|
||||
FilePath: testPath(t.TempDir(), "test.yaml"),
|
||||
FilePath: filepath.Join(t.TempDir(), "test.yaml"),
|
||||
Providers: []Provider{ProviderGemini, ProviderAnthropic},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
|
@ -1330,7 +896,7 @@ func TestRatelimit_NewWithConfig_Ugly(t *testing.T) {
|
|||
|
||||
t.Run("explicit quotas override provider defaults", func(t *testing.T) {
|
||||
rl, err := NewWithConfig(Config{
|
||||
FilePath: testPath(t.TempDir(), "test.yaml"),
|
||||
FilePath: filepath.Join(t.TempDir(), "test.yaml"),
|
||||
Providers: []Provider{ProviderGemini},
|
||||
Quotas: map[string]ModelQuota{
|
||||
"gemini-3-pro-preview": {MaxRPM: 999, MaxTPM: 888, MaxRPD: 777},
|
||||
|
|
@ -1346,7 +912,7 @@ func TestRatelimit_NewWithConfig_Ugly(t *testing.T) {
|
|||
|
||||
t.Run("explicit quotas without providers", func(t *testing.T) {
|
||||
rl, err := NewWithConfig(Config{
|
||||
FilePath: testPath(t.TempDir(), "test.yaml"),
|
||||
FilePath: filepath.Join(t.TempDir(), "test.yaml"),
|
||||
Quotas: map[string]ModelQuota{
|
||||
"my-custom-model": {MaxRPM: 10, MaxTPM: 1000, MaxRPD: 50},
|
||||
},
|
||||
|
|
@ -1359,7 +925,7 @@ func TestRatelimit_NewWithConfig_Ugly(t *testing.T) {
|
|||
})
|
||||
|
||||
t.Run("custom file path is respected", func(t *testing.T) {
|
||||
customPath := testPath(t.TempDir(), "custom", "limits.yaml")
|
||||
customPath := filepath.Join(t.TempDir(), "custom", "limits.yaml")
|
||||
rl, err := NewWithConfig(Config{
|
||||
FilePath: customPath,
|
||||
Providers: []Provider{ProviderLocal},
|
||||
|
|
@ -1369,12 +935,13 @@ func TestRatelimit_NewWithConfig_Ugly(t *testing.T) {
|
|||
rl.RecordUsage("test", 1, 1)
|
||||
require.NoError(t, rl.Persist())
|
||||
|
||||
assert.True(t, pathExists(customPath), "file should be created at custom path")
|
||||
_, statErr := os.Stat(customPath)
|
||||
assert.NoError(t, statErr, "file should be created at custom path")
|
||||
})
|
||||
|
||||
t.Run("unknown provider is silently skipped", func(t *testing.T) {
|
||||
rl, err := NewWithConfig(Config{
|
||||
FilePath: testPath(t.TempDir(), "test.yaml"),
|
||||
FilePath: filepath.Join(t.TempDir(), "test.yaml"),
|
||||
Providers: []Provider{"nonexistent-provider"},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
|
@ -1383,7 +950,7 @@ func TestRatelimit_NewWithConfig_Ugly(t *testing.T) {
|
|||
|
||||
t.Run("local provider with custom quotas", func(t *testing.T) {
|
||||
rl, err := NewWithConfig(Config{
|
||||
FilePath: testPath(t.TempDir(), "test.yaml"),
|
||||
FilePath: filepath.Join(t.TempDir(), "test.yaml"),
|
||||
Providers: []Provider{ProviderLocal},
|
||||
Quotas: map[string]ModelQuota{
|
||||
"llama-3.3-70b": {MaxRPM: 5, MaxTPM: 50000, MaxRPD: 0},
|
||||
|
|
@ -1396,28 +963,9 @@ func TestRatelimit_NewWithConfig_Ugly(t *testing.T) {
|
|||
assert.Equal(t, 5, q.MaxRPM)
|
||||
assert.Equal(t, 50000, q.MaxTPM)
|
||||
})
|
||||
|
||||
t.Run("invalid backend returns error", func(t *testing.T) {
|
||||
_, err := NewWithConfig(Config{
|
||||
Backend: "bogus",
|
||||
})
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "unknown backend")
|
||||
})
|
||||
|
||||
t.Run("default YAML path uses home directory", func(t *testing.T) {
|
||||
home := t.TempDir()
|
||||
t.Setenv("HOME", home)
|
||||
t.Setenv("USERPROFILE", "")
|
||||
t.Setenv("home", "")
|
||||
|
||||
rl, err := NewWithConfig(Config{})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, testPath(home, defaultStateDirName, defaultYAMLStateFile), rl.filePath)
|
||||
})
|
||||
}
|
||||
|
||||
func TestRatelimit_NewBackwardCompatibility_Good(t *testing.T) {
|
||||
func TestNewBackwardCompatibility(t *testing.T) {
|
||||
// New() should produce the exact same result as before Phase 1
|
||||
rl, err := New()
|
||||
require.NoError(t, err)
|
||||
|
|
@ -1440,7 +988,7 @@ func TestRatelimit_NewBackwardCompatibility_Good(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
func TestRatelimit_SetQuota_Good(t *testing.T) {
|
||||
func TestSetQuota(t *testing.T) {
|
||||
t.Run("adds new model quota", func(t *testing.T) {
|
||||
rl := newTestLimiter(t)
|
||||
rl.SetQuota("custom-model", ModelQuota{MaxRPM: 42, MaxTPM: 9999, MaxRPD: 100})
|
||||
|
|
@ -1468,7 +1016,7 @@ func TestRatelimit_SetQuota_Good(t *testing.T) {
|
|||
wg.Add(1)
|
||||
go func(n int) {
|
||||
defer wg.Done()
|
||||
model := core.Sprintf("model-%d", n)
|
||||
model := fmt.Sprintf("model-%d", n)
|
||||
rl.SetQuota(model, ModelQuota{MaxRPM: n, MaxTPM: n * 100, MaxRPD: n * 10})
|
||||
}(i)
|
||||
}
|
||||
|
|
@ -1478,7 +1026,7 @@ func TestRatelimit_SetQuota_Good(t *testing.T) {
|
|||
})
|
||||
}
|
||||
|
||||
func TestRatelimit_AddProvider_Good(t *testing.T) {
|
||||
func TestAddProvider(t *testing.T) {
|
||||
t.Run("adds OpenAI models to existing limiter", func(t *testing.T) {
|
||||
rl := newTestLimiter(t) // starts with Gemini defaults
|
||||
geminiCount := len(rl.Quotas)
|
||||
|
|
@ -1540,7 +1088,7 @@ func TestRatelimit_AddProvider_Good(t *testing.T) {
|
|||
})
|
||||
}
|
||||
|
||||
func TestRatelimit_ProviderConstants_Good(t *testing.T) {
|
||||
func TestProviderConstants(t *testing.T) {
|
||||
// Verify the string values are stable (they may be used in YAML configs)
|
||||
assert.Equal(t, Provider("gemini"), ProviderGemini)
|
||||
assert.Equal(t, Provider("openai"), ProviderOpenAI)
|
||||
|
|
@ -1550,7 +1098,7 @@ func TestRatelimit_ProviderConstants_Good(t *testing.T) {
|
|||
|
||||
// --- Phase 0 addendum: Additional concurrent and multi-model race tests ---
|
||||
|
||||
func TestRatelimit_ConcurrentMultipleModels_Good(t *testing.T) {
|
||||
func TestConcurrentMultipleModels(t *testing.T) {
|
||||
rl := newTestLimiter(t)
|
||||
models := []string{"model-a", "model-b", "model-c", "model-d", "model-e"}
|
||||
for _, m := range models {
|
||||
|
|
@ -1580,9 +1128,9 @@ func TestRatelimit_ConcurrentMultipleModels_Good(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
func TestRatelimit_ConcurrentPersistAndLoad_Ugly(t *testing.T) {
|
||||
func TestConcurrentPersistAndLoad(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
path := testPath(tmpDir, "concurrent.yaml")
|
||||
path := filepath.Join(tmpDir, "concurrent.yaml")
|
||||
|
||||
rl := newTestLimiter(t)
|
||||
rl.filePath = path
|
||||
|
|
@ -1614,7 +1162,7 @@ func TestRatelimit_ConcurrentPersistAndLoad_Ugly(t *testing.T) {
|
|||
// No panics or data races = pass
|
||||
}
|
||||
|
||||
func TestRatelimit_ConcurrentAllStatsAndRecordUsage_Good(t *testing.T) {
|
||||
func TestConcurrentAllStatsAndRecordUsage(t *testing.T) {
|
||||
rl := newTestLimiter(t)
|
||||
models := []string{"stats-a", "stats-b", "stats-c"}
|
||||
for _, m := range models {
|
||||
|
|
@ -1645,7 +1193,7 @@ func TestRatelimit_ConcurrentAllStatsAndRecordUsage_Good(t *testing.T) {
|
|||
wg.Wait()
|
||||
}
|
||||
|
||||
func TestRatelimit_ConcurrentWaitForCapacityAndRecordUsage_Good(t *testing.T) {
|
||||
func TestConcurrentWaitForCapacityAndRecordUsage(t *testing.T) {
|
||||
rl := newTestLimiter(t)
|
||||
model := "race-wait"
|
||||
rl.Quotas[model] = ModelQuota{MaxRPM: 100, MaxTPM: 10000000, MaxRPD: 10000}
|
||||
|
|
@ -1742,7 +1290,7 @@ func BenchmarkAllStats(b *testing.B) {
|
|||
|
||||
func BenchmarkPersist(b *testing.B) {
|
||||
tmpDir := b.TempDir()
|
||||
path := testPath(tmpDir, "bench.yaml")
|
||||
path := filepath.Join(tmpDir, "bench.yaml")
|
||||
|
||||
rl, _ := New()
|
||||
rl.filePath = path
|
||||
|
|
@ -1763,10 +1311,10 @@ func BenchmarkPersist(b *testing.B) {
|
|||
}
|
||||
}
|
||||
|
||||
func TestRatelimit_EndToEndMultiProvider_Good(t *testing.T) {
|
||||
func TestEndToEndMultiProvider(t *testing.T) {
|
||||
// Simulate a real-world scenario: limiter for both Gemini and Anthropic
|
||||
rl, err := NewWithConfig(Config{
|
||||
FilePath: testPath(t.TempDir(), "multi.yaml"),
|
||||
FilePath: filepath.Join(t.TempDir(), "multi.yaml"),
|
||||
Providers: []Provider{ProviderGemini, ProviderAnthropic},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
|
|
|||
154
specs/RFC.md
154
specs/RFC.md
|
|
@ -1,154 +0,0 @@
|
|||
# ratelimit
|
||||
**Import:** `dappco.re/go/core/go-ratelimit`
|
||||
**Files:** 2
|
||||
|
||||
## Types
|
||||
|
||||
### `Provider`
|
||||
`type Provider string`
|
||||
|
||||
`Provider` identifies an LLM provider used to select built-in quota profiles. The package defines four exported provider values: `ProviderGemini`, `ProviderOpenAI`, `ProviderAnthropic`, and `ProviderLocal`.
|
||||
|
||||
### `ModelQuota`
|
||||
`type ModelQuota struct`
|
||||
|
||||
`ModelQuota` defines the rate limits for a single model. A value of `0` means the corresponding limit is unlimited.
|
||||
|
||||
- `MaxRPM int`: requests per minute.
|
||||
- `MaxTPM int`: tokens per minute.
|
||||
- `MaxRPD int`: requests per rolling 24-hour window.
|
||||
|
||||
### `ProviderProfile`
|
||||
`type ProviderProfile struct`
|
||||
|
||||
`ProviderProfile` bundles a provider identifier with the default quota table for that provider.
|
||||
|
||||
- `Provider Provider`: the provider that owns the profile.
|
||||
- `Models map[string]ModelQuota`: built-in quotas keyed by model name.
|
||||
|
||||
### `Config`
|
||||
`type Config struct`
|
||||
|
||||
`Config` controls `RateLimiter` initialisation, backend selection, and default quotas.
|
||||
|
||||
- `FilePath string`: overrides the default persistence path. When empty, `NewWithConfig` resolves a default path under `~/.core`, using `ratelimits.yaml` for the YAML backend and `ratelimits.db` for the SQLite backend.
|
||||
- `Backend string`: selects the persistence backend. `NewWithConfig` accepts `""` or `"yaml"` for YAML and `"sqlite"` for SQLite. `NewWithSQLiteConfig` ignores this field and always uses SQLite.
|
||||
- `Quotas map[string]ModelQuota`: explicit per-model quotas. These are merged on top of any provider defaults loaded from `Providers`.
|
||||
- `Providers []Provider`: provider profiles to load from `DefaultProfiles`. If both `Providers` and `Quotas` are empty, Gemini defaults are used.
|
||||
|
||||
### `TokenEntry`
|
||||
`type TokenEntry struct`
|
||||
|
||||
`TokenEntry` records a single token-usage event.
|
||||
|
||||
- `Time time.Time`: when the token event was recorded.
|
||||
- `Count int`: how many tokens were counted for that event.
|
||||
|
||||
### `UsageStats`
|
||||
`type UsageStats struct`
|
||||
|
||||
`UsageStats` stores the in-memory usage history for one model.
|
||||
|
||||
- `Requests []time.Time`: request timestamps inside the sliding one-minute window.
|
||||
- `Tokens []TokenEntry`: token usage entries inside the sliding one-minute window.
|
||||
- `DayStart time.Time`: the start of the current rolling 24-hour window.
|
||||
- `DayCount int`: the number of requests recorded in the current rolling 24-hour window.
|
||||
|
||||
### `RateLimiter`
|
||||
`type RateLimiter struct`
|
||||
|
||||
`RateLimiter` is the package’s main concurrency-safe limiter. It stores quotas, tracks usage state per model, supports YAML or SQLite persistence, and prunes expired state as part of normal operations.
|
||||
|
||||
- `Quotas map[string]ModelQuota`: configured per-model limits. If a model has no quota entry, `CanSend` allows it.
|
||||
- `State map[string]*UsageStats`: tracked usage windows keyed by model name.
|
||||
|
||||
### `ModelStats`
|
||||
`type ModelStats struct`
|
||||
|
||||
`ModelStats` is the read-only snapshot returned by `Stats`, `AllStats`, and `Iter`.
|
||||
|
||||
- `RPM int`: current requests counted in the one-minute window.
|
||||
- `MaxRPM int`: configured requests-per-minute limit.
|
||||
- `TPM int`: current tokens counted in the one-minute window.
|
||||
- `MaxTPM int`: configured tokens-per-minute limit.
|
||||
- `RPD int`: current requests counted in the rolling 24-hour window.
|
||||
- `MaxRPD int`: configured requests-per-day limit.
|
||||
- `DayStart time.Time`: start of the current rolling 24-hour window. This is zero if the model has no recorded state.
|
||||
|
||||
### `DecisionCode`
|
||||
`type DecisionCode string`
|
||||
|
||||
`DecisionCode` enumerates machine-readable allow/deny codes returned by `Decide`. Defined values: `ok`, `unknown_model`, `unlimited`, `invalid_tokens`, `rpd_exceeded`, `rpm_exceeded`, and `tpm_exceeded`.
|
||||
|
||||
### `Decision`
|
||||
`type Decision struct`
|
||||
|
||||
`Decision` bundles the outcome from `Decide`, including whether the request is allowed, a `DecisionCode`, a human-readable `Reason`, an optional `RetryAfter` duration when throttled, and a `ModelStats` snapshot at the time of evaluation.
|
||||
|
||||
## Functions
|
||||
|
||||
### `DefaultProfiles() map[Provider]ProviderProfile`
|
||||
Returns a fresh map of built-in quota profiles for the supported providers. The returned map currently contains Gemini, OpenAI, Anthropic, and Local profiles. Because a new map is built on each call, callers can modify the result without mutating shared package state.
|
||||
|
||||
### `New() (*RateLimiter, error)`
|
||||
Creates a new YAML-backed `RateLimiter` with Gemini defaults. This is equivalent to calling `NewWithConfig(Config{Providers: []Provider{ProviderGemini}})`. It initialises in-memory state only; it does not automatically restore persisted data, so callers that want previous state must call `Load()`.
|
||||
|
||||
### `NewWithConfig(cfg Config) (*RateLimiter, error)`
|
||||
Creates a `RateLimiter` from explicit configuration. If `cfg.Backend` is empty it uses the YAML backend for backward compatibility. If both `cfg.Providers` and `cfg.Quotas` are empty, Gemini defaults are loaded. When `cfg.FilePath` is empty, the constructor resolves a default path under `~/.core`; for the implicit SQLite path it also ensures the parent directory exists. Like `New`, it does not call `Load()` automatically.
|
||||
|
||||
### `func (rl *RateLimiter) SetQuota(model string, quota ModelQuota)`
|
||||
Adds or replaces the quota for `model` in memory. This change affects later `CanSend`, `Stats`, and related calls immediately, but it is not persisted until `Persist()` is called.
|
||||
|
||||
### `func (rl *RateLimiter) AddProvider(provider Provider)`
|
||||
Loads the built-in quota profile for `provider` and copies its model quotas into `rl.Quotas`. Any existing quota entries for matching model names are overwritten. Unknown provider values are ignored.
|
||||
|
||||
### `func (rl *RateLimiter) Load() error`
|
||||
Loads persisted state into the limiter. For the YAML backend, it reads the configured file and unmarshals the stored quotas and state; a missing file is treated as an empty state and returns `nil`. For the SQLite backend, it loads persisted quotas and usage state from the database. If the database has stored quotas, those quotas replace the in-memory configuration; if no stored quotas exist, the current in-memory quotas are retained. In both cases, the loaded usage state replaces the current in-memory state.
|
||||
|
||||
### `func (rl *RateLimiter) Persist() error`
|
||||
Writes the current quotas and usage state to the configured backend. The method clones the in-memory snapshot while holding the lock, then performs I/O after releasing it. YAML persistence serialises the quota and state maps into the state file. SQLite persistence writes a full snapshot transactionally so quotas and usage move together.
|
||||
|
||||
### `func (rl *RateLimiter) BackgroundPrune(interval time.Duration) func()`
|
||||
Starts a background goroutine that prunes expired entries from every tracked model on the supplied interval and returns a stop function. If `interval <= 0`, it returns a no-op stop function and does not start a goroutine.
|
||||
|
||||
### `func (rl *RateLimiter) CanSend(model string, estimatedTokens int) bool`
|
||||
Reports whether a request for `model` can be sent without violating the configured limits. Negative token estimates are rejected. Models with no configured quota are allowed. If all three limits for a known model are `0`, the model is treated as unlimited. Before evaluating the request, the limiter prunes entries older than one minute and resets the rolling daily counter when its 24-hour window has elapsed. The method then checks requests-per-day, requests-per-minute, and tokens-per-minute against the estimated token count.
|
||||
|
||||
### `func (rl *RateLimiter) Decide(model string, estimatedTokens int) Decision`
|
||||
Returns a structured allow/deny decision for the estimated request. The result includes a `DecisionCode`, a human-readable `Reason`, optional `RetryAfter` guidance when throttled, and a `ModelStats` snapshot. It prunes expired state, initialises empty state for configured models, but does not record usage.
|
||||
|
||||
### `func (rl *RateLimiter) RecordUsage(model string, promptTokens, outputTokens int)`
|
||||
Records a successful request for `model`. The limiter prunes stale entries first, creates state for the model if needed, appends the current timestamp to the request window, appends a token entry containing the combined prompt and output token count, and increments the rolling daily counter. Negative token values are ignored by the internal token summation logic rather than reducing the recorded total.
|
||||
|
||||
### `func (rl *RateLimiter) WaitForCapacity(ctx context.Context, model string, tokens int) error`
|
||||
Blocks until `Decide(model, tokens)` allows the request or `ctx` is cancelled. The method uses the `RetryAfter` hint from `Decide` to sleep between checks, falling back to one-second polling when no hint is available. If `tokens` is negative, it returns an error immediately.
|
||||
|
||||
### `func (rl *RateLimiter) Reset(model string)`
|
||||
Clears usage state without changing quotas. If `model` is empty, it drops all tracked state. Otherwise it removes state only for the named model.
|
||||
|
||||
### `func (rl *RateLimiter) Models() iter.Seq[string]`
|
||||
Returns a sorted iterator of all model names currently known to the limiter. The result is the union of model names present in `rl.Quotas` and `rl.State`, so it includes models that only have stored state as well as models that only have configured quotas.
|
||||
|
||||
### `func (rl *RateLimiter) Iter() iter.Seq2[string, ModelStats]`
|
||||
Returns a sorted iterator of model names paired with their current `ModelStats` snapshots. Internally it builds the snapshot via `AllStats()` and yields entries in lexical model-name order.
|
||||
|
||||
### `func (rl *RateLimiter) Stats(model string) ModelStats`
|
||||
Returns the current snapshot for a single model after pruning expired entries. The result includes both current usage and configured maxima. If the model has no configured quota, the maximum fields are zero. If the model has no recorded state, the usage counters are zero and `DayStart` is the zero time.
|
||||
|
||||
### `func (rl *RateLimiter) AllStats() map[string]ModelStats`
|
||||
Returns a snapshot for every tracked model. The returned map includes model names found in either `rl.Quotas` or `rl.State`. Each model is pruned before its snapshot is computed, so expired one-minute entries are removed and stale daily windows are reset as part of the call.
|
||||
|
||||
### `NewWithSQLite(dbPath string) (*RateLimiter, error)`
|
||||
Creates a SQLite-backed `RateLimiter` with Gemini defaults and opens or creates the database at `dbPath`. Like the YAML constructors, it initialises in-memory configuration but does not automatically call `Load()`. Callers should `defer rl.Close()` when they are done with the limiter.
|
||||
|
||||
### `NewWithSQLiteConfig(dbPath string, cfg Config) (*RateLimiter, error)`
|
||||
Creates a SQLite-backed `RateLimiter` using `cfg` for provider and quota configuration. The `Backend` field in `cfg` is ignored because this constructor always uses SQLite. The database is opened or created at `dbPath`, and callers should `defer rl.Close()` to release the connection. Existing persisted data is not loaded until `Load()` is called.
|
||||
|
||||
### `func (rl *RateLimiter) Close() error`
|
||||
Releases resources held by the limiter. For YAML-backed limiters this is a no-op that returns `nil`. For SQLite-backed limiters it closes the underlying database connection.
|
||||
|
||||
### `MigrateYAMLToSQLite(yamlPath, sqlitePath string) error`
|
||||
Reads a YAML state file into a temporary `RateLimiter` and writes its quotas and usage state into a SQLite database. The SQLite database is created if it does not exist. The migration writes a complete snapshot, so any existing SQLite snapshot tables are replaced by the imported data.
|
||||
|
||||
### `CountTokens(ctx context.Context, apiKey, model, text string) (int, error)`
|
||||
Calls Google’s Gemini `countTokens` API for `model` and returns the `totalTokens` value from the response. The function uses `http.DefaultClient`, posts to the Generative Language API base URL, and sends the API key through the `x-goog-api-key` header. It validates that `model` is non-empty, truncates oversized response bodies when building error messages, and wraps transport, request-building, and decoding failures with package-scoped errors.
|
||||
155
sqlite.go
155
sqlite.go
|
|
@ -1,12 +1,10 @@
|
|||
// SPDX-License-Identifier: EUPL-1.2
|
||||
|
||||
package ratelimit
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
core "dappco.re/go/core"
|
||||
_ "modernc.org/sqlite"
|
||||
)
|
||||
|
||||
|
|
@ -21,7 +19,7 @@ type sqliteStore struct {
|
|||
func newSQLiteStore(dbPath string) (*sqliteStore, error) {
|
||||
db, err := sql.Open("sqlite", dbPath)
|
||||
if err != nil {
|
||||
return nil, core.E("ratelimit.newSQLiteStore", "open", err)
|
||||
return nil, fmt.Errorf("ratelimit.newSQLiteStore: open: %w", err)
|
||||
}
|
||||
|
||||
// Single connection for PRAGMA consistency.
|
||||
|
|
@ -29,11 +27,11 @@ func newSQLiteStore(dbPath string) (*sqliteStore, error) {
|
|||
|
||||
if _, err := db.Exec("PRAGMA journal_mode=WAL"); err != nil {
|
||||
db.Close()
|
||||
return nil, core.E("ratelimit.newSQLiteStore", "WAL", err)
|
||||
return nil, fmt.Errorf("ratelimit.newSQLiteStore: WAL: %w", err)
|
||||
}
|
||||
if _, err := db.Exec("PRAGMA busy_timeout=5000"); err != nil {
|
||||
db.Close()
|
||||
return nil, core.E("ratelimit.newSQLiteStore", "busy_timeout", err)
|
||||
return nil, fmt.Errorf("ratelimit.newSQLiteStore: busy_timeout: %w", err)
|
||||
}
|
||||
|
||||
if err := createSchema(db); err != nil {
|
||||
|
|
@ -73,36 +71,45 @@ func createSchema(db *sql.DB) error {
|
|||
|
||||
for _, stmt := range stmts {
|
||||
if _, err := db.Exec(stmt); err != nil {
|
||||
return core.E("ratelimit.createSchema", "exec", err)
|
||||
return fmt.Errorf("ratelimit.createSchema: %w", err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// saveQuotas writes a complete quota snapshot to the quotas table.
|
||||
// saveQuotas upserts all quotas into the quotas table.
|
||||
func (s *sqliteStore) saveQuotas(quotas map[string]ModelQuota) error {
|
||||
tx, err := s.db.Begin()
|
||||
if err != nil {
|
||||
return core.E("ratelimit.saveQuotas", "begin", err)
|
||||
return fmt.Errorf("ratelimit.saveQuotas: begin: %w", err)
|
||||
}
|
||||
defer tx.Rollback()
|
||||
|
||||
if _, err := tx.Exec("DELETE FROM quotas"); err != nil {
|
||||
return core.E("ratelimit.saveQuotas", "clear", err)
|
||||
stmt, err := tx.Prepare(`INSERT INTO quotas (model, max_rpm, max_tpm, max_rpd)
|
||||
VALUES (?, ?, ?, ?)
|
||||
ON CONFLICT(model) DO UPDATE SET
|
||||
max_rpm = excluded.max_rpm,
|
||||
max_tpm = excluded.max_tpm,
|
||||
max_rpd = excluded.max_rpd`)
|
||||
if err != nil {
|
||||
return fmt.Errorf("ratelimit.saveQuotas: prepare: %w", err)
|
||||
}
|
||||
defer stmt.Close()
|
||||
|
||||
for model, q := range quotas {
|
||||
if _, err := stmt.Exec(model, q.MaxRPM, q.MaxTPM, q.MaxRPD); err != nil {
|
||||
return fmt.Errorf("ratelimit.saveQuotas: exec %s: %w", model, err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := insertQuotas(tx, quotas); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return commitTx(tx, "ratelimit.saveQuotas")
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
// loadQuotas reads all rows from the quotas table.
|
||||
func (s *sqliteStore) loadQuotas() (map[string]ModelQuota, error) {
|
||||
rows, err := s.db.Query("SELECT model, max_rpm, max_tpm, max_rpd FROM quotas")
|
||||
if err != nil {
|
||||
return nil, core.E("ratelimit.loadQuotas", "query", err)
|
||||
return nil, fmt.Errorf("ratelimit.loadQuotas: query: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
|
|
@ -111,137 +118,71 @@ func (s *sqliteStore) loadQuotas() (map[string]ModelQuota, error) {
|
|||
var model string
|
||||
var q ModelQuota
|
||||
if err := rows.Scan(&model, &q.MaxRPM, &q.MaxTPM, &q.MaxRPD); err != nil {
|
||||
return nil, core.E("ratelimit.loadQuotas", "scan", err)
|
||||
return nil, fmt.Errorf("ratelimit.loadQuotas: scan: %w", err)
|
||||
}
|
||||
result[model] = q
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, core.E("ratelimit.loadQuotas", "rows", err)
|
||||
return nil, fmt.Errorf("ratelimit.loadQuotas: rows: %w", err)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// saveSnapshot writes quotas and state as a single atomic snapshot.
|
||||
func (s *sqliteStore) saveSnapshot(quotas map[string]ModelQuota, state map[string]*UsageStats) error {
|
||||
tx, err := s.db.Begin()
|
||||
if err != nil {
|
||||
return core.E("ratelimit.saveSnapshot", "begin", err)
|
||||
}
|
||||
defer tx.Rollback()
|
||||
|
||||
if err := clearSnapshotTables(tx, true); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := insertQuotas(tx, quotas); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := insertState(tx, state); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return commitTx(tx, "ratelimit.saveSnapshot")
|
||||
}
|
||||
|
||||
// saveState writes all usage state to SQLite in a single transaction.
|
||||
// It uses a truncate-and-insert approach for simplicity in this version,
|
||||
// but ensures atomicity via a single transaction.
|
||||
// It deletes existing rows and inserts fresh data for each model.
|
||||
func (s *sqliteStore) saveState(state map[string]*UsageStats) error {
|
||||
tx, err := s.db.Begin()
|
||||
if err != nil {
|
||||
return core.E("ratelimit.saveState", "begin", err)
|
||||
return fmt.Errorf("ratelimit.saveState: begin: %w", err)
|
||||
}
|
||||
defer tx.Rollback()
|
||||
|
||||
if err := clearSnapshotTables(tx, false); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := insertState(tx, state); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return commitTx(tx, "ratelimit.saveState")
|
||||
}
|
||||
|
||||
func clearSnapshotTables(tx *sql.Tx, includeQuotas bool) error {
|
||||
if includeQuotas {
|
||||
if _, err := tx.Exec("DELETE FROM quotas"); err != nil {
|
||||
return core.E("ratelimit.saveSnapshot", "clear quotas", err)
|
||||
}
|
||||
}
|
||||
// Clear existing state.
|
||||
if _, err := tx.Exec("DELETE FROM requests"); err != nil {
|
||||
return core.E("ratelimit.saveState", "clear requests", err)
|
||||
return fmt.Errorf("ratelimit.saveState: clear requests: %w", err)
|
||||
}
|
||||
if _, err := tx.Exec("DELETE FROM tokens"); err != nil {
|
||||
return core.E("ratelimit.saveState", "clear tokens", err)
|
||||
return fmt.Errorf("ratelimit.saveState: clear tokens: %w", err)
|
||||
}
|
||||
if _, err := tx.Exec("DELETE FROM daily"); err != nil {
|
||||
return core.E("ratelimit.saveState", "clear daily", err)
|
||||
return fmt.Errorf("ratelimit.saveState: clear daily: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func insertQuotas(tx *sql.Tx, quotas map[string]ModelQuota) error {
|
||||
stmt, err := tx.Prepare("INSERT INTO quotas (model, max_rpm, max_tpm, max_rpd) VALUES (?, ?, ?, ?)")
|
||||
if err != nil {
|
||||
return core.E("ratelimit.saveQuotas", "prepare", err)
|
||||
}
|
||||
defer stmt.Close()
|
||||
|
||||
for model, q := range quotas {
|
||||
if _, err := stmt.Exec(model, q.MaxRPM, q.MaxTPM, q.MaxRPD); err != nil {
|
||||
return core.E("ratelimit.saveQuotas", core.Concat("exec ", model), err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func insertState(tx *sql.Tx, state map[string]*UsageStats) error {
|
||||
reqStmt, err := tx.Prepare("INSERT INTO requests (model, ts) VALUES (?, ?)")
|
||||
if err != nil {
|
||||
return core.E("ratelimit.saveState", "prepare requests", err)
|
||||
return fmt.Errorf("ratelimit.saveState: prepare requests: %w", err)
|
||||
}
|
||||
defer reqStmt.Close()
|
||||
|
||||
tokStmt, err := tx.Prepare("INSERT INTO tokens (model, ts, count) VALUES (?, ?, ?)")
|
||||
if err != nil {
|
||||
return core.E("ratelimit.saveState", "prepare tokens", err)
|
||||
return fmt.Errorf("ratelimit.saveState: prepare tokens: %w", err)
|
||||
}
|
||||
defer tokStmt.Close()
|
||||
|
||||
dayStmt, err := tx.Prepare("INSERT INTO daily (model, day_start, day_count) VALUES (?, ?, ?)")
|
||||
if err != nil {
|
||||
return core.E("ratelimit.saveState", "prepare daily", err)
|
||||
return fmt.Errorf("ratelimit.saveState: prepare daily: %w", err)
|
||||
}
|
||||
defer dayStmt.Close()
|
||||
|
||||
for model, stats := range state {
|
||||
if stats == nil {
|
||||
continue
|
||||
}
|
||||
for _, t := range stats.Requests {
|
||||
if _, err := reqStmt.Exec(model, t.UnixNano()); err != nil {
|
||||
return core.E("ratelimit.saveState", core.Concat("insert request ", model), err)
|
||||
return fmt.Errorf("ratelimit.saveState: insert request %s: %w", model, err)
|
||||
}
|
||||
}
|
||||
for _, te := range stats.Tokens {
|
||||
if _, err := tokStmt.Exec(model, te.Time.UnixNano(), te.Count); err != nil {
|
||||
return core.E("ratelimit.saveState", core.Concat("insert token ", model), err)
|
||||
return fmt.Errorf("ratelimit.saveState: insert token %s: %w", model, err)
|
||||
}
|
||||
}
|
||||
if _, err := dayStmt.Exec(model, stats.DayStart.UnixNano(), stats.DayCount); err != nil {
|
||||
return core.E("ratelimit.saveState", core.Concat("insert daily ", model), err)
|
||||
return fmt.Errorf("ratelimit.saveState: insert daily %s: %w", model, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func commitTx(tx *sql.Tx, scope string) error {
|
||||
if err := tx.Commit(); err != nil {
|
||||
return core.E(scope, "commit", err)
|
||||
}
|
||||
return nil
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
// loadState reconstructs the UsageStats map from SQLite tables.
|
||||
|
|
@ -251,7 +192,7 @@ func (s *sqliteStore) loadState() (map[string]*UsageStats, error) {
|
|||
// Load daily counters first (these define which models have state).
|
||||
rows, err := s.db.Query("SELECT model, day_start, day_count FROM daily")
|
||||
if err != nil {
|
||||
return nil, core.E("ratelimit.loadState", "query daily", err)
|
||||
return nil, fmt.Errorf("ratelimit.loadState: query daily: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
|
|
@ -260,7 +201,7 @@ func (s *sqliteStore) loadState() (map[string]*UsageStats, error) {
|
|||
var dayStartNano int64
|
||||
var dayCount int
|
||||
if err := rows.Scan(&model, &dayStartNano, &dayCount); err != nil {
|
||||
return nil, core.E("ratelimit.loadState", "scan daily", err)
|
||||
return nil, fmt.Errorf("ratelimit.loadState: scan daily: %w", err)
|
||||
}
|
||||
result[model] = &UsageStats{
|
||||
DayStart: time.Unix(0, dayStartNano),
|
||||
|
|
@ -268,13 +209,13 @@ func (s *sqliteStore) loadState() (map[string]*UsageStats, error) {
|
|||
}
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, core.E("ratelimit.loadState", "daily rows", err)
|
||||
return nil, fmt.Errorf("ratelimit.loadState: daily rows: %w", err)
|
||||
}
|
||||
|
||||
// Load requests.
|
||||
reqRows, err := s.db.Query("SELECT model, ts FROM requests ORDER BY ts")
|
||||
if err != nil {
|
||||
return nil, core.E("ratelimit.loadState", "query requests", err)
|
||||
return nil, fmt.Errorf("ratelimit.loadState: query requests: %w", err)
|
||||
}
|
||||
defer reqRows.Close()
|
||||
|
||||
|
|
@ -282,7 +223,7 @@ func (s *sqliteStore) loadState() (map[string]*UsageStats, error) {
|
|||
var model string
|
||||
var tsNano int64
|
||||
if err := reqRows.Scan(&model, &tsNano); err != nil {
|
||||
return nil, core.E("ratelimit.loadState", "scan requests", err)
|
||||
return nil, fmt.Errorf("ratelimit.loadState: scan requests: %w", err)
|
||||
}
|
||||
if _, ok := result[model]; !ok {
|
||||
result[model] = &UsageStats{}
|
||||
|
|
@ -290,13 +231,13 @@ func (s *sqliteStore) loadState() (map[string]*UsageStats, error) {
|
|||
result[model].Requests = append(result[model].Requests, time.Unix(0, tsNano))
|
||||
}
|
||||
if err := reqRows.Err(); err != nil {
|
||||
return nil, core.E("ratelimit.loadState", "request rows", err)
|
||||
return nil, fmt.Errorf("ratelimit.loadState: request rows: %w", err)
|
||||
}
|
||||
|
||||
// Load tokens.
|
||||
tokRows, err := s.db.Query("SELECT model, ts, count FROM tokens ORDER BY ts")
|
||||
if err != nil {
|
||||
return nil, core.E("ratelimit.loadState", "query tokens", err)
|
||||
return nil, fmt.Errorf("ratelimit.loadState: query tokens: %w", err)
|
||||
}
|
||||
defer tokRows.Close()
|
||||
|
||||
|
|
@ -305,7 +246,7 @@ func (s *sqliteStore) loadState() (map[string]*UsageStats, error) {
|
|||
var tsNano int64
|
||||
var count int
|
||||
if err := tokRows.Scan(&model, &tsNano, &count); err != nil {
|
||||
return nil, core.E("ratelimit.loadState", "scan tokens", err)
|
||||
return nil, fmt.Errorf("ratelimit.loadState: scan tokens: %w", err)
|
||||
}
|
||||
if _, ok := result[model]; !ok {
|
||||
result[model] = &UsageStats{}
|
||||
|
|
@ -316,7 +257,7 @@ func (s *sqliteStore) loadState() (map[string]*UsageStats, error) {
|
|||
})
|
||||
}
|
||||
if err := tokRows.Err(); err != nil {
|
||||
return nil, core.E("ratelimit.loadState", "token rows", err)
|
||||
return nil, fmt.Errorf("ratelimit.loadState: token rows: %w", err)
|
||||
}
|
||||
|
||||
return result, nil
|
||||
|
|
|
|||
303
sqlite_test.go
303
sqlite_test.go
|
|
@ -1,8 +1,8 @@
|
|||
// SPDX-License-Identifier: EUPL-1.2
|
||||
|
||||
package ratelimit
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
|
@ -14,17 +14,18 @@ import (
|
|||
|
||||
// --- Phase 2: SQLite basic tests ---
|
||||
|
||||
func TestSQLite_NewSQLiteStore_Good(t *testing.T) {
|
||||
dbPath := testPath(t.TempDir(), "test.db")
|
||||
func TestNewSQLiteStore_Good(t *testing.T) {
|
||||
dbPath := filepath.Join(t.TempDir(), "test.db")
|
||||
store, err := newSQLiteStore(dbPath)
|
||||
require.NoError(t, err)
|
||||
defer store.close()
|
||||
|
||||
// Verify the database file was created.
|
||||
assert.True(t, pathExists(dbPath), "database file should exist")
|
||||
_, statErr := os.Stat(dbPath)
|
||||
assert.NoError(t, statErr, "database file should exist")
|
||||
}
|
||||
|
||||
func TestSQLite_NewSQLiteStore_Bad(t *testing.T) {
|
||||
func TestNewSQLiteStore_Bad(t *testing.T) {
|
||||
t.Run("invalid path returns error", func(t *testing.T) {
|
||||
// Path inside a non-existent directory with no parent.
|
||||
_, err := newSQLiteStore("/nonexistent/deep/nested/dir/test.db")
|
||||
|
|
@ -32,8 +33,8 @@ func TestSQLite_NewSQLiteStore_Bad(t *testing.T) {
|
|||
})
|
||||
}
|
||||
|
||||
func TestSQLite_QuotasRoundTrip_Good(t *testing.T) {
|
||||
dbPath := testPath(t.TempDir(), "quotas.db")
|
||||
func TestSQLiteQuotasRoundTrip_Good(t *testing.T) {
|
||||
dbPath := filepath.Join(t.TempDir(), "quotas.db")
|
||||
store, err := newSQLiteStore(dbPath)
|
||||
require.NoError(t, err)
|
||||
defer store.close()
|
||||
|
|
@ -59,8 +60,8 @@ func TestSQLite_QuotasRoundTrip_Good(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
func TestSQLite_QuotasOverwrite_Good(t *testing.T) {
|
||||
dbPath := testPath(t.TempDir(), "overwrite.db")
|
||||
func TestSQLiteQuotasUpsert_Good(t *testing.T) {
|
||||
dbPath := filepath.Join(t.TempDir(), "upsert.db")
|
||||
store, err := newSQLiteStore(dbPath)
|
||||
require.NoError(t, err)
|
||||
defer store.close()
|
||||
|
|
@ -70,7 +71,7 @@ func TestSQLite_QuotasOverwrite_Good(t *testing.T) {
|
|||
"model-a": {MaxRPM: 100, MaxTPM: 50000, MaxRPD: 1000},
|
||||
}))
|
||||
|
||||
// Save a second snapshot with updated values.
|
||||
// Upsert with updated values.
|
||||
require.NoError(t, store.saveQuotas(map[string]ModelQuota{
|
||||
"model-a": {MaxRPM: 999, MaxTPM: 888, MaxRPD: 777},
|
||||
}))
|
||||
|
|
@ -84,8 +85,8 @@ func TestSQLite_QuotasOverwrite_Good(t *testing.T) {
|
|||
assert.Equal(t, 777, q.MaxRPD, "should have updated RPD")
|
||||
}
|
||||
|
||||
func TestSQLite_StateRoundTrip_Good(t *testing.T) {
|
||||
dbPath := testPath(t.TempDir(), "state.db")
|
||||
func TestSQLiteStateRoundTrip_Good(t *testing.T) {
|
||||
dbPath := filepath.Join(t.TempDir(), "state.db")
|
||||
store, err := newSQLiteStore(dbPath)
|
||||
require.NoError(t, err)
|
||||
defer store.close()
|
||||
|
|
@ -143,8 +144,8 @@ func TestSQLite_StateRoundTrip_Good(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
func TestSQLite_StateOverwrite_Good(t *testing.T) {
|
||||
dbPath := testPath(t.TempDir(), "overwrite.db")
|
||||
func TestSQLiteStateOverwrite_Good(t *testing.T) {
|
||||
dbPath := filepath.Join(t.TempDir(), "overwrite.db")
|
||||
store, err := newSQLiteStore(dbPath)
|
||||
require.NoError(t, err)
|
||||
defer store.close()
|
||||
|
|
@ -181,8 +182,8 @@ func TestSQLite_StateOverwrite_Good(t *testing.T) {
|
|||
assert.Len(t, b.Requests, 1)
|
||||
}
|
||||
|
||||
func TestSQLite_EmptyState_Good(t *testing.T) {
|
||||
dbPath := testPath(t.TempDir(), "empty.db")
|
||||
func TestSQLiteEmptyState_Good(t *testing.T) {
|
||||
dbPath := filepath.Join(t.TempDir(), "empty.db")
|
||||
store, err := newSQLiteStore(dbPath)
|
||||
require.NoError(t, err)
|
||||
defer store.close()
|
||||
|
|
@ -197,8 +198,8 @@ func TestSQLite_EmptyState_Good(t *testing.T) {
|
|||
assert.Empty(t, state, "should return empty state from fresh DB")
|
||||
}
|
||||
|
||||
func TestSQLite_Close_Good(t *testing.T) {
|
||||
dbPath := testPath(t.TempDir(), "close.db")
|
||||
func TestSQLiteClose_Good(t *testing.T) {
|
||||
dbPath := filepath.Join(t.TempDir(), "close.db")
|
||||
store, err := newSQLiteStore(dbPath)
|
||||
require.NoError(t, err)
|
||||
|
||||
|
|
@ -207,8 +208,8 @@ func TestSQLite_Close_Good(t *testing.T) {
|
|||
|
||||
// --- Phase 2: SQLite integration tests ---
|
||||
|
||||
func TestSQLite_NewWithSQLite_Good(t *testing.T) {
|
||||
dbPath := testPath(t.TempDir(), "limiter.db")
|
||||
func TestNewWithSQLite_Good(t *testing.T) {
|
||||
dbPath := filepath.Join(t.TempDir(), "limiter.db")
|
||||
rl, err := NewWithSQLite(dbPath)
|
||||
require.NoError(t, err)
|
||||
defer rl.Close()
|
||||
|
|
@ -221,8 +222,8 @@ func TestSQLite_NewWithSQLite_Good(t *testing.T) {
|
|||
assert.NotNil(t, rl.sqlite, "SQLite store should be initialised")
|
||||
}
|
||||
|
||||
func TestSQLite_NewWithSQLiteConfig_Good(t *testing.T) {
|
||||
dbPath := testPath(t.TempDir(), "config.db")
|
||||
func TestNewWithSQLiteConfig_Good(t *testing.T) {
|
||||
dbPath := filepath.Join(t.TempDir(), "config.db")
|
||||
rl, err := NewWithSQLiteConfig(dbPath, Config{
|
||||
Providers: []Provider{ProviderAnthropic},
|
||||
Quotas: map[string]ModelQuota{
|
||||
|
|
@ -242,8 +243,8 @@ func TestSQLite_NewWithSQLiteConfig_Good(t *testing.T) {
|
|||
assert.False(t, hasGemini, "should not have Gemini models")
|
||||
}
|
||||
|
||||
func TestSQLite_PersistAndLoad_Good(t *testing.T) {
|
||||
dbPath := testPath(t.TempDir(), "persist.db")
|
||||
func TestSQLitePersistAndLoad_Good(t *testing.T) {
|
||||
dbPath := filepath.Join(t.TempDir(), "persist.db")
|
||||
rl, err := NewWithSQLite(dbPath)
|
||||
require.NoError(t, err)
|
||||
|
||||
|
|
@ -271,8 +272,8 @@ func TestSQLite_PersistAndLoad_Good(t *testing.T) {
|
|||
assert.Equal(t, 500, stats.MaxRPD)
|
||||
}
|
||||
|
||||
func TestSQLite_PersistMultipleModels_Good(t *testing.T) {
|
||||
dbPath := testPath(t.TempDir(), "multi.db")
|
||||
func TestSQLitePersistMultipleModels_Good(t *testing.T) {
|
||||
dbPath := filepath.Join(t.TempDir(), "multi.db")
|
||||
rl, err := NewWithSQLiteConfig(dbPath, Config{
|
||||
Providers: []Provider{ProviderGemini, ProviderAnthropic},
|
||||
})
|
||||
|
|
@ -301,8 +302,8 @@ func TestSQLite_PersistMultipleModels_Good(t *testing.T) {
|
|||
assert.Equal(t, 400, claude.TPM)
|
||||
}
|
||||
|
||||
func TestSQLite_RecordUsageThenPersistReload_Good(t *testing.T) {
|
||||
dbPath := testPath(t.TempDir(), "record.db")
|
||||
func TestSQLiteRecordUsageThenPersistReload_Good(t *testing.T) {
|
||||
dbPath := filepath.Join(t.TempDir(), "record.db")
|
||||
rl, err := NewWithSQLite(dbPath)
|
||||
require.NoError(t, err)
|
||||
|
||||
|
|
@ -339,7 +340,7 @@ func TestSQLite_RecordUsageThenPersistReload_Good(t *testing.T) {
|
|||
assert.Equal(t, 1000, stats2.TPM, "TPM should survive reload")
|
||||
}
|
||||
|
||||
func TestSQLite_CloseNoOp_Good(t *testing.T) {
|
||||
func TestSQLiteClose_Good_NoOp(t *testing.T) {
|
||||
// Close on YAML-backed limiter is a no-op.
|
||||
rl := newTestLimiter(t)
|
||||
assert.NoError(t, rl.Close(), "Close on YAML limiter should be no-op")
|
||||
|
|
@ -347,8 +348,8 @@ func TestSQLite_CloseNoOp_Good(t *testing.T) {
|
|||
|
||||
// --- Phase 2: Concurrent SQLite ---
|
||||
|
||||
func TestSQLite_Concurrent_Good(t *testing.T) {
|
||||
dbPath := testPath(t.TempDir(), "concurrent.db")
|
||||
func TestSQLiteConcurrent_Good(t *testing.T) {
|
||||
dbPath := filepath.Join(t.TempDir(), "concurrent.db")
|
||||
rl, err := NewWithSQLite(dbPath)
|
||||
require.NoError(t, err)
|
||||
defer rl.Close()
|
||||
|
|
@ -397,10 +398,10 @@ func TestSQLite_Concurrent_Good(t *testing.T) {
|
|||
|
||||
// --- Phase 2: YAML backward compatibility ---
|
||||
|
||||
func TestSQLite_YAMLBackwardCompat_Good(t *testing.T) {
|
||||
func TestYAMLBackwardCompat_Good(t *testing.T) {
|
||||
// Verify that the default YAML backend still works after SQLite additions.
|
||||
tmpDir := t.TempDir()
|
||||
path := testPath(tmpDir, "compat.yaml")
|
||||
path := filepath.Join(tmpDir, "compat.yaml")
|
||||
|
||||
rl1, err := New()
|
||||
require.NoError(t, err)
|
||||
|
|
@ -424,59 +425,22 @@ func TestSQLite_YAMLBackwardCompat_Good(t *testing.T) {
|
|||
assert.Equal(t, 200, stats.TPM)
|
||||
}
|
||||
|
||||
func TestSQLite_ConfigBackendDefault_Good(t *testing.T) {
|
||||
func TestConfigBackendDefault_Good(t *testing.T) {
|
||||
// Empty Backend string should default to YAML behaviour.
|
||||
rl, err := NewWithConfig(Config{
|
||||
FilePath: testPath(t.TempDir(), "default.yaml"),
|
||||
FilePath: filepath.Join(t.TempDir(), "default.yaml"),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Nil(t, rl.sqlite, "empty backend should use YAML (no sqlite)")
|
||||
}
|
||||
|
||||
func TestSQLite_ConfigBackendSQLite_Good(t *testing.T) {
|
||||
dbPath := testPath(t.TempDir(), "config-backend.db")
|
||||
rl, err := NewWithConfig(Config{
|
||||
Backend: backendSQLite,
|
||||
FilePath: dbPath,
|
||||
Quotas: map[string]ModelQuota{
|
||||
"backend-model": {MaxRPM: 10, MaxTPM: 1000, MaxRPD: 50},
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
defer rl.Close()
|
||||
|
||||
require.NotNil(t, rl.sqlite)
|
||||
rl.RecordUsage("backend-model", 10, 10)
|
||||
require.NoError(t, rl.Persist())
|
||||
|
||||
assert.True(t, pathExists(dbPath), "sqlite backend should persist to the configured DB path")
|
||||
}
|
||||
|
||||
func TestSQLite_ConfigBackendSQLiteDefaultPath_Good(t *testing.T) {
|
||||
home := t.TempDir()
|
||||
t.Setenv("HOME", home)
|
||||
t.Setenv("USERPROFILE", "")
|
||||
t.Setenv("home", "")
|
||||
|
||||
rl, err := NewWithConfig(Config{
|
||||
Backend: backendSQLite,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
defer rl.Close()
|
||||
|
||||
require.NotNil(t, rl.sqlite)
|
||||
require.NoError(t, rl.Persist())
|
||||
|
||||
assert.True(t, pathExists(testPath(home, defaultStateDirName, defaultSQLiteStateFile)), "sqlite backend should use the default home DB path")
|
||||
}
|
||||
|
||||
// --- Phase 2: MigrateYAMLToSQLite ---
|
||||
|
||||
func TestSQLite_MigrateYAMLToSQLite_Good(t *testing.T) {
|
||||
func TestMigrateYAMLToSQLite_Good(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
yamlPath := testPath(tmpDir, "state.yaml")
|
||||
sqlitePath := testPath(tmpDir, "migrated.db")
|
||||
yamlPath := filepath.Join(tmpDir, "state.yaml")
|
||||
sqlitePath := filepath.Join(tmpDir, "migrated.db")
|
||||
|
||||
// Create a YAML-backed limiter with state.
|
||||
rl, err := New()
|
||||
|
|
@ -512,89 +476,26 @@ func TestSQLite_MigrateYAMLToSQLite_Good(t *testing.T) {
|
|||
assert.Equal(t, 2, stats.RPD, "should have 2 daily requests")
|
||||
}
|
||||
|
||||
func TestSQLite_MigrateYAMLToSQLite_Bad(t *testing.T) {
|
||||
func TestMigrateYAMLToSQLite_Bad(t *testing.T) {
|
||||
t.Run("non-existent YAML file", func(t *testing.T) {
|
||||
err := MigrateYAMLToSQLite("/nonexistent/state.yaml", testPath(t.TempDir(), "out.db"))
|
||||
err := MigrateYAMLToSQLite("/nonexistent/state.yaml", filepath.Join(t.TempDir(), "out.db"))
|
||||
assert.Error(t, err, "should fail with non-existent YAML file")
|
||||
})
|
||||
|
||||
t.Run("corrupt YAML file", func(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
yamlPath := testPath(tmpDir, "corrupt.yaml")
|
||||
writeTestFile(t, yamlPath, "{{{{not yaml!")
|
||||
yamlPath := filepath.Join(tmpDir, "corrupt.yaml")
|
||||
require.NoError(t, os.WriteFile(yamlPath, []byte("{{{{not yaml!"), 0644))
|
||||
|
||||
err := MigrateYAMLToSQLite(yamlPath, testPath(tmpDir, "out.db"))
|
||||
err := MigrateYAMLToSQLite(yamlPath, filepath.Join(tmpDir, "out.db"))
|
||||
assert.Error(t, err, "should fail with corrupt YAML")
|
||||
})
|
||||
}
|
||||
|
||||
func TestSQLite_MigrateYAMLToSQLiteAtomic_Good(t *testing.T) {
|
||||
func TestMigrateYAMLToSQLitePreservesAllGeminiModels_Good(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
yamlPath := testPath(tmpDir, "atomic.yaml")
|
||||
sqlitePath := testPath(tmpDir, "atomic.db")
|
||||
now := time.Now().UTC()
|
||||
|
||||
store, err := newSQLiteStore(sqlitePath)
|
||||
require.NoError(t, err)
|
||||
|
||||
originalQuotas := map[string]ModelQuota{
|
||||
"old-model": {MaxRPM: 1, MaxTPM: 2, MaxRPD: 3},
|
||||
}
|
||||
originalState := map[string]*UsageStats{
|
||||
"old-model": {
|
||||
Requests: []time.Time{now},
|
||||
Tokens: []TokenEntry{{Time: now, Count: 9}},
|
||||
DayStart: now,
|
||||
DayCount: 1,
|
||||
},
|
||||
}
|
||||
require.NoError(t, store.saveSnapshot(originalQuotas, originalState))
|
||||
|
||||
_, err = store.db.Exec(`CREATE TRIGGER fail_daily_migrate BEFORE INSERT ON daily
|
||||
BEGIN SELECT RAISE(ABORT, 'forced daily failure'); END`)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, store.close())
|
||||
|
||||
migrated := &RateLimiter{
|
||||
Quotas: map[string]ModelQuota{
|
||||
"new-model": {MaxRPM: 10, MaxTPM: 20, MaxRPD: 30},
|
||||
},
|
||||
State: map[string]*UsageStats{
|
||||
"new-model": {
|
||||
Requests: []time.Time{now.Add(5 * time.Second)},
|
||||
Tokens: []TokenEntry{{Time: now.Add(5 * time.Second), Count: 99}},
|
||||
DayStart: now.Add(5 * time.Second),
|
||||
DayCount: 2,
|
||||
},
|
||||
},
|
||||
}
|
||||
data, err := yaml.Marshal(migrated)
|
||||
require.NoError(t, err)
|
||||
writeTestFile(t, yamlPath, string(data))
|
||||
|
||||
err = MigrateYAMLToSQLite(yamlPath, sqlitePath)
|
||||
require.Error(t, err)
|
||||
|
||||
store, err = newSQLiteStore(sqlitePath)
|
||||
require.NoError(t, err)
|
||||
defer store.close()
|
||||
|
||||
quotas, err := store.loadQuotas()
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, originalQuotas, quotas)
|
||||
|
||||
state, err := store.loadState()
|
||||
require.NoError(t, err)
|
||||
require.Contains(t, state, "old-model")
|
||||
assert.Equal(t, originalState["old-model"].DayCount, state["old-model"].DayCount)
|
||||
assert.Equal(t, originalState["old-model"].Tokens[0].Count, state["old-model"].Tokens[0].Count)
|
||||
assert.NotContains(t, state, "new-model")
|
||||
}
|
||||
|
||||
func TestSQLite_MigrateYAMLToSQLitePreservesAllGeminiModels_Good(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
yamlPath := testPath(tmpDir, "full.yaml")
|
||||
sqlitePath := testPath(tmpDir, "full.db")
|
||||
yamlPath := filepath.Join(tmpDir, "full.yaml")
|
||||
sqlitePath := filepath.Join(tmpDir, "full.db")
|
||||
|
||||
// Create a full YAML state with all Gemini models.
|
||||
rl, err := New()
|
||||
|
|
@ -623,12 +524,12 @@ func TestSQLite_MigrateYAMLToSQLitePreservesAllGeminiModels_Good(t *testing.T) {
|
|||
|
||||
// --- Phase 2: Corrupt DB recovery ---
|
||||
|
||||
func TestSQLite_CorruptDB_Ugly(t *testing.T) {
|
||||
func TestSQLiteCorruptDB_Ugly(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
dbPath := testPath(tmpDir, "corrupt.db")
|
||||
dbPath := filepath.Join(tmpDir, "corrupt.db")
|
||||
|
||||
// Write garbage to the DB file.
|
||||
writeTestFile(t, dbPath, "THIS IS NOT A SQLITE DATABASE")
|
||||
require.NoError(t, os.WriteFile(dbPath, []byte("THIS IS NOT A SQLITE DATABASE"), 0644))
|
||||
|
||||
// Opening a corrupt DB may succeed (sqlite is lazy about validation),
|
||||
// but operations on it should fail gracefully.
|
||||
|
|
@ -645,9 +546,9 @@ func TestSQLite_CorruptDB_Ugly(t *testing.T) {
|
|||
assert.Error(t, err, "loading from corrupt DB should return an error")
|
||||
}
|
||||
|
||||
func TestSQLite_TruncatedDB_Ugly(t *testing.T) {
|
||||
func TestSQLiteTruncatedDB_Ugly(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
dbPath := testPath(tmpDir, "truncated.db")
|
||||
dbPath := filepath.Join(tmpDir, "truncated.db")
|
||||
|
||||
// Create a valid DB first.
|
||||
store, err := newSQLiteStore(dbPath)
|
||||
|
|
@ -658,7 +559,11 @@ func TestSQLite_TruncatedDB_Ugly(t *testing.T) {
|
|||
require.NoError(t, store.close())
|
||||
|
||||
// Truncate the file to simulate corruption.
|
||||
overwriteTestFile(t, dbPath, "TRUNC")
|
||||
f, err := os.OpenFile(dbPath, os.O_WRONLY|os.O_TRUNC, 0644)
|
||||
require.NoError(t, err)
|
||||
_, err = f.Write([]byte("TRUNC"))
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, f.Close())
|
||||
|
||||
// Opening should either fail or operations should fail.
|
||||
store2, err := newSQLiteStore(dbPath)
|
||||
|
|
@ -672,9 +577,9 @@ func TestSQLite_TruncatedDB_Ugly(t *testing.T) {
|
|||
assert.Error(t, err, "loading from truncated DB should return an error")
|
||||
}
|
||||
|
||||
func TestSQLite_EmptyModelState_Good(t *testing.T) {
|
||||
func TestSQLiteEmptyModelState_Good(t *testing.T) {
|
||||
// State with no requests or tokens but with a daily counter.
|
||||
dbPath := testPath(t.TempDir(), "empty-state.db")
|
||||
dbPath := filepath.Join(t.TempDir(), "empty-state.db")
|
||||
store, err := newSQLiteStore(dbPath)
|
||||
require.NoError(t, err)
|
||||
defer store.close()
|
||||
|
|
@ -701,8 +606,8 @@ func TestSQLite_EmptyModelState_Good(t *testing.T) {
|
|||
|
||||
// --- Phase 2: End-to-end with persist cycle ---
|
||||
|
||||
func TestSQLite_EndToEnd_Good(t *testing.T) {
|
||||
dbPath := testPath(t.TempDir(), "e2e.db")
|
||||
func TestSQLiteEndToEnd_Good(t *testing.T) {
|
||||
dbPath := filepath.Join(t.TempDir(), "e2e.db")
|
||||
|
||||
// Session 1: Create limiter, record usage, persist.
|
||||
rl1, err := NewWithSQLiteConfig(dbPath, Config{
|
||||
|
|
@ -745,82 +650,10 @@ func TestSQLite_EndToEnd_Good(t *testing.T) {
|
|||
assert.Equal(t, 5, custom.MaxRPM)
|
||||
}
|
||||
|
||||
func TestSQLite_LoadReplacesPersistedSnapshot_Good(t *testing.T) {
|
||||
dbPath := testPath(t.TempDir(), "replace.db")
|
||||
rl, err := NewWithSQLiteConfig(dbPath, Config{
|
||||
Quotas: map[string]ModelQuota{
|
||||
"model-a": {MaxRPM: 1, MaxTPM: 100, MaxRPD: 10},
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
rl.RecordUsage("model-a", 10, 10)
|
||||
require.NoError(t, rl.Persist())
|
||||
|
||||
delete(rl.Quotas, "model-a")
|
||||
rl.Quotas["model-b"] = ModelQuota{MaxRPM: 2, MaxTPM: 200, MaxRPD: 20}
|
||||
rl.Reset("")
|
||||
rl.RecordUsage("model-b", 5, 5)
|
||||
require.NoError(t, rl.Persist())
|
||||
require.NoError(t, rl.Close())
|
||||
|
||||
rl2, err := NewWithSQLiteConfig(dbPath, Config{
|
||||
Providers: []Provider{ProviderGemini},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
defer rl2.Close()
|
||||
|
||||
rl2.State["stale-memory"] = &UsageStats{DayStart: time.Now(), DayCount: 99}
|
||||
require.NoError(t, rl2.Load())
|
||||
|
||||
assert.NotContains(t, rl2.Quotas, "gemini-3-pro-preview")
|
||||
assert.NotContains(t, rl2.Quotas, "model-a")
|
||||
assert.Contains(t, rl2.Quotas, "model-b")
|
||||
assert.NotContains(t, rl2.State, "stale-memory")
|
||||
assert.NotContains(t, rl2.State, "model-a")
|
||||
assert.Equal(t, 1, rl2.Stats("model-b").RPD)
|
||||
}
|
||||
|
||||
func TestSQLite_PersistAtomic_Good(t *testing.T) {
|
||||
dbPath := testPath(t.TempDir(), "persist-atomic.db")
|
||||
rl, err := NewWithSQLiteConfig(dbPath, Config{
|
||||
Quotas: map[string]ModelQuota{
|
||||
"old-model": {MaxRPM: 1, MaxTPM: 100, MaxRPD: 10},
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
rl.RecordUsage("old-model", 10, 10)
|
||||
require.NoError(t, rl.Persist())
|
||||
|
||||
_, err = rl.sqlite.db.Exec(`CREATE TRIGGER fail_daily_persist BEFORE INSERT ON daily
|
||||
BEGIN SELECT RAISE(ABORT, 'forced daily failure'); END`)
|
||||
require.NoError(t, err)
|
||||
|
||||
delete(rl.Quotas, "old-model")
|
||||
rl.Quotas["new-model"] = ModelQuota{MaxRPM: 2, MaxTPM: 200, MaxRPD: 20}
|
||||
rl.Reset("")
|
||||
rl.RecordUsage("new-model", 50, 50)
|
||||
|
||||
err = rl.Persist()
|
||||
require.Error(t, err)
|
||||
require.NoError(t, rl.Close())
|
||||
|
||||
rl2, err := NewWithSQLiteConfig(dbPath, Config{})
|
||||
require.NoError(t, err)
|
||||
defer rl2.Close()
|
||||
require.NoError(t, rl2.Load())
|
||||
|
||||
assert.Contains(t, rl2.Quotas, "old-model")
|
||||
assert.NotContains(t, rl2.Quotas, "new-model")
|
||||
assert.Equal(t, 1, rl2.Stats("old-model").RPD)
|
||||
assert.Equal(t, 0, rl2.Stats("new-model").RPD)
|
||||
}
|
||||
|
||||
// --- Phase 2: Benchmark ---
|
||||
|
||||
func BenchmarkSQLitePersist(b *testing.B) {
|
||||
dbPath := testPath(b.TempDir(), "bench.db")
|
||||
dbPath := filepath.Join(b.TempDir(), "bench.db")
|
||||
rl, err := NewWithSQLite(dbPath)
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
|
|
@ -845,7 +678,7 @@ func BenchmarkSQLitePersist(b *testing.B) {
|
|||
}
|
||||
|
||||
func BenchmarkSQLiteLoad(b *testing.B) {
|
||||
dbPath := testPath(b.TempDir(), "bench-load.db")
|
||||
dbPath := filepath.Join(b.TempDir(), "bench-load.db")
|
||||
rl, err := NewWithSQLite(dbPath)
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
|
|
@ -876,10 +709,10 @@ func BenchmarkSQLiteLoad(b *testing.B) {
|
|||
|
||||
// TestMigrateYAMLToSQLiteWithFullState tests migration of a realistic YAML
|
||||
// file that contains the full serialised RateLimiter struct.
|
||||
func TestSQLite_MigrateYAMLToSQLiteWithFullState_Good(t *testing.T) {
|
||||
func TestMigrateYAMLToSQLiteWithFullState_Good(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
yamlPath := testPath(tmpDir, "realistic.yaml")
|
||||
sqlitePath := testPath(tmpDir, "realistic.db")
|
||||
yamlPath := filepath.Join(tmpDir, "realistic.yaml")
|
||||
sqlitePath := filepath.Join(tmpDir, "realistic.db")
|
||||
|
||||
now := time.Now()
|
||||
|
||||
|
|
@ -912,7 +745,7 @@ func TestSQLite_MigrateYAMLToSQLiteWithFullState_Good(t *testing.T) {
|
|||
|
||||
data, err := yaml.Marshal(rl)
|
||||
require.NoError(t, err)
|
||||
writeTestFile(t, yamlPath, string(data))
|
||||
require.NoError(t, os.WriteFile(yamlPath, data, 0644))
|
||||
|
||||
// Migrate.
|
||||
require.NoError(t, MigrateYAMLToSQLite(yamlPath, sqlitePath))
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue