Compare commits
13 commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
781e0ee3d6 | ||
|
|
2ad4870bd0 | ||
|
|
ed5949ec3a | ||
| 61ccc226b2 | |||
|
|
b3a6279f35 | ||
| 0e8d02a528 | |||
|
|
1ec0ea4d28 | ||
| eea295f017 | |||
|
|
75f27a4906 | ||
| 27723ce8e9 | |||
|
|
ed1cdc11b2 | ||
| 52316d5377 | |||
|
|
36cc0a4750 |
18 changed files with 1094 additions and 491 deletions
11
CLAUDE.md
11
CLAUDE.md
|
|
@ -1,3 +1,5 @@
|
||||||
|
<!-- SPDX-License-Identifier: EUPL-1.2 -->
|
||||||
|
|
||||||
# CLAUDE.md
|
# CLAUDE.md
|
||||||
|
|
||||||
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
|
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
|
||||||
|
|
@ -6,7 +8,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
|
||||||
|
|
||||||
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.
|
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: `forge.lthn.ai/core/go-ratelimit` — Go 1.26, no CGO required.
|
Module: `dappco.re/go/core/go-ratelimit` — Go 1.26, no CGO required.
|
||||||
|
|
||||||
## Commands
|
## Commands
|
||||||
|
|
||||||
|
|
@ -28,7 +30,7 @@ Pre-commit gate: `go test -race ./...` and `go vet ./...` must both pass.
|
||||||
- **Conventional commits**: `type(scope): description` — scopes: `ratelimit`, `sqlite`, `persist`, `config`
|
- **Conventional commits**: `type(scope): description` — scopes: `ratelimit`, `sqlite`, `persist`, `config`
|
||||||
- **Co-Author line** on every commit: `Co-Authored-By: Virgil <virgil@lethean.io>`
|
- **Co-Author line** on every commit: `Co-Authored-By: Virgil <virgil@lethean.io>`
|
||||||
- **Coverage** must not drop below 95%
|
- **Coverage** must not drop below 95%
|
||||||
- **Error format**: `coreerr.E("ratelimit.FunctionName", "what", err)` via `go-log` — lowercase, no trailing punctuation
|
- **Error format**: `core.E("ratelimit.FunctionName", "what", err)` via `dappco.re/go/core` — lowercase, no trailing punctuation
|
||||||
- **No `init()` functions**, no global mutable state
|
- **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.
|
- **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.
|
||||||
|
|
||||||
|
|
@ -60,10 +62,9 @@ SQLite tests use `_Good`/`_Bad`/`_Ugly` suffixes (happy path / expected errors /
|
||||||
|
|
||||||
## Dependencies
|
## Dependencies
|
||||||
|
|
||||||
Five direct dependencies — do not add more without justification:
|
Four direct dependencies — do not add more without justification:
|
||||||
|
|
||||||
- `forge.lthn.ai/core/go-io` — file I/O abstraction
|
- `dappco.re/go/core` — file I/O helpers, structured errors, JSON helpers, path/environment utilities
|
||||||
- `forge.lthn.ai/core/go-log` — structured error handling (`coreerr.E`)
|
|
||||||
- `gopkg.in/yaml.v3` — YAML backend
|
- `gopkg.in/yaml.v3` — YAML backend
|
||||||
- `modernc.org/sqlite` — pure Go SQLite (no CGO)
|
- `modernc.org/sqlite` — pure Go SQLite (no CGO)
|
||||||
- `github.com/stretchr/testify` — test-only
|
- `github.com/stretchr/testify` — test-only
|
||||||
|
|
|
||||||
|
|
@ -1,15 +1,21 @@
|
||||||
|
<!-- SPDX-License-Identifier: EUPL-1.2 -->
|
||||||
|
|
||||||
# Contributing
|
# Contributing
|
||||||
|
|
||||||
Thank you for your interest in contributing!
|
Thank you for your interest in contributing!
|
||||||
|
|
||||||
## Requirements
|
## Requirements
|
||||||
- **Go Version**: 1.26 or higher is required.
|
- **Go Version**: 1.26 or higher is required.
|
||||||
- **Tools**: `golangci-lint` and `task` (Taskfile.dev) are recommended.
|
- **Tools**: `golangci-lint` is recommended.
|
||||||
|
|
||||||
## Development Workflow
|
## Development Workflow
|
||||||
1. **Testing**: Ensure all tests pass before submitting changes.
|
1. **Testing**: Ensure all tests pass before submitting changes.
|
||||||
```bash
|
```bash
|
||||||
|
go build ./...
|
||||||
go test ./...
|
go test ./...
|
||||||
|
go test -race ./...
|
||||||
|
go test -cover ./...
|
||||||
|
go mod tidy
|
||||||
```
|
```
|
||||||
2. **Code Style**: All code must follow standard Go formatting.
|
2. **Code Style**: All code must follow standard Go formatting.
|
||||||
```bash
|
```bash
|
||||||
|
|
@ -22,14 +28,22 @@ Thank you for your interest in contributing!
|
||||||
```
|
```
|
||||||
|
|
||||||
## Commit Message Format
|
## Commit Message Format
|
||||||
We follow the [Conventional Commits](https://www.conventionalcommits.org/) specification:
|
We follow the [Conventional Commits](https://www.conventionalcommits.org/) specification using the repository format `type(scope): description`:
|
||||||
- `feat`: A new feature
|
- `feat`: A new feature
|
||||||
- `fix`: A bug fix
|
- `fix`: A bug fix
|
||||||
- `docs`: Documentation changes
|
- `docs`: Documentation changes
|
||||||
- `refactor`: A code change that neither fixes a bug nor adds a feature
|
- `refactor`: A code change that neither fixes a bug nor adds a feature
|
||||||
- `chore`: Changes to the build process or auxiliary tools and libraries
|
- `chore`: Changes to the build process or auxiliary tools and libraries
|
||||||
|
|
||||||
Example: `feat: add new endpoint for health check`
|
Common scopes: `ratelimit`, `sqlite`, `persist`, `config`
|
||||||
|
|
||||||
## License
|
Example:
|
||||||
|
|
||||||
|
```text
|
||||||
|
fix(ratelimit): align module metadata with dappco.re
|
||||||
|
|
||||||
|
Co-Authored-By: Virgil <virgil@lethean.io>
|
||||||
|
```
|
||||||
|
|
||||||
|
## Licence
|
||||||
By contributing to this project, you agree that your contributions will be licensed under the **European Union Public Licence (EUPL-1.2)**.
|
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,30 +1,50 @@
|
||||||
[](https://pkg.go.dev/forge.lthn.ai/core/go-ratelimit)
|
<!-- SPDX-License-Identifier: EUPL-1.2 -->
|
||||||
[](LICENSE.md)
|
|
||||||
|
[](https://pkg.go.dev/dappco.re/go/core/go-ratelimit)
|
||||||
|

|
||||||
[](go.mod)
|
[](go.mod)
|
||||||
|
|
||||||
# go-ratelimit
|
# 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.
|
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**: `forge.lthn.ai/core/go-ratelimit`
|
**Module**: `dappco.re/go/core/go-ratelimit`
|
||||||
**Licence**: EUPL-1.2
|
**Licence**: EUPL-1.2
|
||||||
**Language**: Go 1.25
|
**Language**: Go 1.26
|
||||||
|
|
||||||
## Quick Start
|
## Quick Start
|
||||||
|
|
||||||
```go
|
```go
|
||||||
import "forge.lthn.ai/core/go-ratelimit"
|
import "dappco.re/go/core/go-ratelimit"
|
||||||
|
|
||||||
// YAML backend (default, single-process)
|
// YAML backend (default, single-process)
|
||||||
rl, err := ratelimit.New()
|
rl, err := ratelimit.New()
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
// SQLite backend (multi-process)
|
// SQLite backend (multi-process)
|
||||||
rl, err := ratelimit.NewWithSQLite("~/.core/ratelimits.db")
|
rl, err = ratelimit.NewWithSQLite("/tmp/ratelimits.db")
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
defer rl.Close()
|
defer rl.Close()
|
||||||
|
|
||||||
ok, reason := rl.CanSend("gemini-2.0-flash", 1500)
|
if rl.CanSend("gemini-2.0-flash", 1500) {
|
||||||
if ok {
|
rl.RecordUsage("gemini-2.0-flash", 1000, 500)
|
||||||
rl.RecordUsage("gemini-2.0-flash", 1500)
|
}
|
||||||
|
|
||||||
|
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)
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
@ -37,12 +57,14 @@ if ok {
|
||||||
## Build & Test
|
## Build & Test
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
|
go build ./...
|
||||||
go test ./...
|
go test ./...
|
||||||
go test -race ./...
|
go test -race ./...
|
||||||
go vet ./...
|
go vet ./...
|
||||||
go build ./...
|
go test -cover ./...
|
||||||
|
go mod tidy
|
||||||
```
|
```
|
||||||
|
|
||||||
## Licence
|
## Licence
|
||||||
|
|
||||||
European Union Public Licence 1.2 — see [LICENCE](LICENCE) for details.
|
European Union Public Licence 1.2.
|
||||||
|
|
|
||||||
|
|
@ -1,3 +1,5 @@
|
||||||
|
<!-- SPDX-License-Identifier: EUPL-1.2 -->
|
||||||
|
|
||||||
# API Contract
|
# 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`.
|
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`.
|
||||||
|
|
@ -12,6 +14,8 @@ Test coverage is marked `yes` when the symbol is exercised by the existing test
|
||||||
| 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 | `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 | `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 | `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 | `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 | `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 | `NewWithConfig` | `func NewWithConfig(cfg Config) (*RateLimiter, error)` | Creates a YAML-backed limiter from explicit configuration, defaulting to Gemini when config is empty. | yes |
|
||||||
|
|
@ -25,8 +29,9 @@ Test coverage is marked `yes` when the symbol is exercised by the existing test
|
||||||
| Method | `Persist` | `func (rl *RateLimiter) Persist() error` | Persists a snapshot of quotas and usage state to YAML or SQLite. | 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 | `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 | `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 | `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 `CanSend` succeeds or the context is cancelled. | 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 | `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 | `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 | `Iter` | `func (rl *RateLimiter) Iter() iter.Seq2[string, ModelStats]` | Returns a sorted iterator of model names paired with current stats snapshots. | yes |
|
||||||
|
|
|
||||||
|
|
@ -1,3 +1,5 @@
|
||||||
|
<!-- SPDX-License-Identifier: EUPL-1.2 -->
|
||||||
|
|
||||||
---
|
---
|
||||||
title: Architecture
|
title: Architecture
|
||||||
description: Internals of go-ratelimit -- sliding window algorithm, provider quota system, persistence backends, and concurrency model.
|
description: Internals of go-ratelimit -- sliding window algorithm, provider quota system, persistence backends, and concurrency model.
|
||||||
|
|
@ -10,7 +12,7 @@ three independent quota dimensions per model -- requests per minute (RPM), token
|
||||||
per minute (TPM), and requests per day (RPD) -- using an in-memory sliding window
|
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.
|
that can be persisted across process restarts via YAML or SQLite.
|
||||||
|
|
||||||
Module path: `forge.lthn.ai/core/go-ratelimit`
|
Module path: `dappco.re/go/core/go-ratelimit`
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|
@ -117,6 +119,12 @@ 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
|
is the cheapest comparison (a single integer). TPM is checked last because it
|
||||||
requires summing the token counts in the sliding window.
|
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
|
### Daily Reset
|
||||||
|
|
||||||
The daily counter resets automatically inside `prune()`. When
|
The daily counter resets automatically inside `prune()`. When
|
||||||
|
|
@ -252,7 +260,7 @@ state:
|
||||||
day_count: 42
|
day_count: 42
|
||||||
```
|
```
|
||||||
|
|
||||||
`Persist()` creates parent directories with `os.MkdirAll` before writing.
|
`Persist()` creates parent directories with the `core.Fs` helper before writing.
|
||||||
`Load()` treats a missing file as an empty state (no error). Corrupt or
|
`Load()` treats a missing file as an empty state (no error). Corrupt or
|
||||||
unreadable files return an error.
|
unreadable files return an error.
|
||||||
|
|
||||||
|
|
@ -317,8 +325,8 @@ precision and allows efficient range queries using the composite indices.
|
||||||
|
|
||||||
### Save Strategy
|
### Save Strategy
|
||||||
|
|
||||||
- **Quotas**: `INSERT ... ON CONFLICT(model) DO UPDATE` (upsert). Existing quota
|
- **Quotas**: full snapshot replace inside a single transaction. `saveQuotas()`
|
||||||
rows are updated in place without deleting unrelated models.
|
clears the table and reinserts the current quota map.
|
||||||
- **State**: Delete-then-insert inside a single transaction. All three state
|
- **State**: Delete-then-insert inside a single transaction. All three state
|
||||||
tables (`requests`, `tokens`, `daily`) are truncated and rewritten atomically.
|
tables (`requests`, `tokens`, `daily`) are truncated and rewritten atomically.
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,3 +1,5 @@
|
||||||
|
<!-- SPDX-License-Identifier: EUPL-1.2 -->
|
||||||
|
|
||||||
---
|
---
|
||||||
title: Development Guide
|
title: Development Guide
|
||||||
description: How to build, test, and contribute to go-ratelimit -- prerequisites, test patterns, coding standards, and commit conventions.
|
description: How to build, test, and contribute to go-ratelimit -- prerequisites, test patterns, coding standards, and commit conventions.
|
||||||
|
|
@ -18,6 +20,9 @@ No C toolchain, no system SQLite library, no external build tools. A plain
|
||||||
## Build and Test
|
## Build and Test
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
|
# Compile all packages
|
||||||
|
go build ./...
|
||||||
|
|
||||||
# Run all tests
|
# Run all tests
|
||||||
go test ./...
|
go test ./...
|
||||||
|
|
||||||
|
|
@ -42,12 +47,16 @@ go vet ./...
|
||||||
# Lint (requires golangci-lint)
|
# Lint (requires golangci-lint)
|
||||||
golangci-lint run ./...
|
golangci-lint run ./...
|
||||||
|
|
||||||
|
# Coverage check
|
||||||
|
go test -cover ./...
|
||||||
|
|
||||||
# Tidy dependencies
|
# Tidy dependencies
|
||||||
go mod tidy
|
go mod tidy
|
||||||
```
|
```
|
||||||
|
|
||||||
All three commands (`go test -race ./...`, `go vet ./...`, and `go mod tidy`)
|
Before a commit is pushed, `go build ./...`, `go test -race ./...`,
|
||||||
must produce no errors or warnings before a commit is pushed.
|
`go vet ./...`, `go test -cover ./...`, and `go mod tidy` must all pass
|
||||||
|
without errors, and coverage must remain at or above 95%.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|
@ -147,17 +156,8 @@ The following benchmarks are included:
|
||||||
|
|
||||||
### Coverage
|
### Coverage
|
||||||
|
|
||||||
Current coverage: 95.1%. The remaining paths cannot be covered in unit tests
|
Maintain at least 95% statement coverage. Verify it with `go test -cover ./...`
|
||||||
without modifying production code:
|
and document any justified exception in the commit or PR that introduces it.
|
||||||
|
|
||||||
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.
|
|
||||||
3. `os.UserHomeDir()` error path in `NewWithConfig()` -- triggered only when
|
|
||||||
`$HOME` is unset, which test infrastructure prevents.
|
|
||||||
|
|
||||||
Do not lower coverage below 95% without a documented reason.
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|
@ -172,8 +172,8 @@ Do not use American spellings in identifiers, comments, or documentation.
|
||||||
|
|
||||||
- All exported types, functions, and fields must have doc comments.
|
- All exported types, functions, and fields must have doc comments.
|
||||||
- Error strings must be lowercase and not end with punctuation (Go convention).
|
- Error strings must be lowercase and not end with punctuation (Go convention).
|
||||||
- Contextual errors use `fmt.Errorf("ratelimit.Function: what: %w", err)` so
|
- Contextual errors use `core.E("ratelimit.Function", "what", err)` so errors
|
||||||
errors identify their origin clearly.
|
identify their origin clearly.
|
||||||
- No `init()` functions.
|
- No `init()` functions.
|
||||||
- No global mutable state. `DefaultProfiles()` returns a fresh map on each call.
|
- No global mutable state. `DefaultProfiles()` returns a fresh map on each call.
|
||||||
|
|
||||||
|
|
@ -196,6 +196,7 @@ Direct dependencies are intentionally minimal:
|
||||||
|
|
||||||
| Dependency | Purpose |
|
| 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 |
|
| `gopkg.in/yaml.v3` | YAML serialisation for legacy backend |
|
||||||
| `modernc.org/sqlite` | Pure Go SQLite for persistent backend |
|
| `modernc.org/sqlite` | Pure Go SQLite for persistent backend |
|
||||||
| `github.com/stretchr/testify` | Test assertions (test-only) |
|
| `github.com/stretchr/testify` | Test assertions (test-only) |
|
||||||
|
|
|
||||||
|
|
@ -1,10 +1,13 @@
|
||||||
|
<!-- SPDX-License-Identifier: EUPL-1.2 -->
|
||||||
|
|
||||||
# Project History
|
# Project History
|
||||||
|
|
||||||
## Origin
|
## Origin
|
||||||
|
|
||||||
go-ratelimit was extracted from the `pkg/ratelimit` package inside
|
go-ratelimit was extracted from the `pkg/ratelimit` package inside
|
||||||
`forge.lthn.ai/core/go` on 19 February 2026. The extraction gave the package
|
`forge.lthn.ai/core/go` on 19 February 2026. The package now lives at
|
||||||
its own module path, repository, and independent development cadence.
|
`dappco.re/go/core/go-ratelimit`, with its own repository and independent
|
||||||
|
development cadence.
|
||||||
|
|
||||||
Initial commit: `fa1a6fc` — `feat: extract go-ratelimit from core/go pkg/ratelimit`
|
Initial commit: `fa1a6fc` — `feat: extract go-ratelimit from core/go pkg/ratelimit`
|
||||||
|
|
||||||
|
|
@ -25,7 +28,7 @@ Commit: `3c63b10` — `feat(ratelimit): generalise beyond Gemini with provider p
|
||||||
|
|
||||||
Supplementary commit: `db958f2` — `test: expand race coverage and benchmarks`
|
Supplementary commit: `db958f2` — `test: expand race coverage and benchmarks`
|
||||||
|
|
||||||
Coverage increased from 77.1% to 95.1%. The test suite was rewritten using
|
Coverage increased from 77.1% to above the 95% floor. The test suite was rewritten using
|
||||||
testify with table-driven subtests throughout.
|
testify with table-driven subtests throughout.
|
||||||
|
|
||||||
### Tests added
|
### Tests added
|
||||||
|
|
@ -58,18 +61,6 @@ testify with table-driven subtests throughout.
|
||||||
- `BenchmarkAllStats` — 5 models x 200 entries
|
- `BenchmarkAllStats` — 5 models x 200 entries
|
||||||
- `BenchmarkPersist` — YAML I/O
|
- `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.
|
`go test -race ./...` passed clean. `go vet ./...` produced no warnings.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
@ -139,7 +130,7 @@ established elsewhere in the ecosystem.
|
||||||
|
|
||||||
- `TestNewSQLiteStore_Good / _Bad` — creation and invalid path handling
|
- `TestNewSQLiteStore_Good / _Bad` — creation and invalid path handling
|
||||||
- `TestSQLiteQuotasRoundTrip_Good` — save/load round-trip
|
- `TestSQLiteQuotasRoundTrip_Good` — save/load round-trip
|
||||||
- `TestSQLiteQuotasUpsert_Good` — upsert replaces existing rows
|
- `TestSQLite_QuotasOverwrite_Good` — the latest quota snapshot replaces previous rows
|
||||||
- `TestSQLiteStateRoundTrip_Good` — multi-model state with nanosecond precision
|
- `TestSQLiteStateRoundTrip_Good` — multi-model state with nanosecond precision
|
||||||
- `TestSQLiteStateOverwrite_Good` — delete-then-insert atomicity
|
- `TestSQLiteStateOverwrite_Good` — delete-then-insert atomicity
|
||||||
- `TestSQLiteEmptyState_Good` — fresh database returns empty maps
|
- `TestSQLiteEmptyState_Good` — fresh database returns empty maps
|
||||||
|
|
@ -168,11 +159,10 @@ Not yet implemented. Intended downstream integrations:
|
||||||
|
|
||||||
## Known Limitations
|
## Known Limitations
|
||||||
|
|
||||||
**CountTokens URL is hardcoded.** The `CountTokens` helper calls
|
**CountTokens URL is hardcoded.** The exported `CountTokens` helper calls
|
||||||
`generativelanguage.googleapis.com` directly. There is no way to override the
|
`generativelanguage.googleapis.com` directly. Callers cannot redirect it to
|
||||||
base URL, which prevents testing the success path in unit tests and prevents
|
Gemini-compatible proxies or alternate endpoints without going through an
|
||||||
use with Gemini-compatible proxies. A future refactor would accept a base URL
|
internal helper or refactoring the API to accept a base URL or `http.Client`.
|
||||||
parameter or an `http.Client`.
|
|
||||||
|
|
||||||
**saveState is a full table replace.** On every `Persist()` call, the `requests`,
|
**saveState is a full table replace.** On every `Persist()` call, the `requests`,
|
||||||
`tokens`, and `daily` tables are truncated and rewritten. For a limiter tracking
|
`tokens`, and `daily` tables are truncated and rewritten. For a limiter tracking
|
||||||
|
|
@ -186,10 +176,10 @@ SQLite on `Persist()`. The database does not grow unboundedly between persist
|
||||||
cycles because `saveState` replaces all rows, but if `Persist()` is called
|
cycles because `saveState` replaces all rows, but if `Persist()` is called
|
||||||
frequently the WAL file can grow transiently.
|
frequently the WAL file can grow transiently.
|
||||||
|
|
||||||
**WaitForCapacity polling interval is fixed at 1 second.** This is appropriate
|
**WaitForCapacity now sleeps using `Decide`’s `RetryAfter` hint** (with a
|
||||||
for RPM-scale limits but is coarse for sub-second limits. If a caller needs
|
one-second fallback when no hint exists). This reduces busy looping on long
|
||||||
finer-grained waiting (e.g., smoothing requests within a minute), they must
|
windows but remains coarse for sub-second smoothing; callers that need
|
||||||
implement their own loop.
|
sub-second pacing should implement their own loop.
|
||||||
|
|
||||||
**No automatic persistence.** `Persist()` must be called explicitly. If a
|
**No automatic persistence.** `Persist()` must be called explicitly. If a
|
||||||
process exits without calling `Persist()`, any usage recorded since the last
|
process exits without calling `Persist()`, any usage recorded since the last
|
||||||
|
|
|
||||||
|
|
@ -1,3 +1,5 @@
|
||||||
|
<!-- SPDX-License-Identifier: EUPL-1.2 -->
|
||||||
|
|
||||||
---
|
---
|
||||||
title: go-ratelimit
|
title: go-ratelimit
|
||||||
description: Provider-agnostic sliding window rate limiter for LLM API calls, with YAML and SQLite persistence backends.
|
description: Provider-agnostic sliding window rate limiter for LLM API calls, with YAML and SQLite persistence backends.
|
||||||
|
|
@ -5,7 +7,7 @@ description: Provider-agnostic sliding window rate limiter for LLM API calls, wi
|
||||||
|
|
||||||
# go-ratelimit
|
# go-ratelimit
|
||||||
|
|
||||||
**Module**: `forge.lthn.ai/core/go-ratelimit`
|
**Module**: `dappco.re/go/core/go-ratelimit`
|
||||||
**Licence**: EUPL-1.2
|
**Licence**: EUPL-1.2
|
||||||
**Go version**: 1.26+
|
**Go version**: 1.26+
|
||||||
|
|
||||||
|
|
@ -19,7 +21,7 @@ migration helper is included.
|
||||||
## Quick Start
|
## Quick Start
|
||||||
|
|
||||||
```go
|
```go
|
||||||
import "forge.lthn.ai/core/go-ratelimit"
|
import "dappco.re/go/core/go-ratelimit"
|
||||||
|
|
||||||
// Create a limiter with Gemini defaults (YAML backend).
|
// Create a limiter with Gemini defaults (YAML backend).
|
||||||
rl, err := ratelimit.New()
|
rl, err := ratelimit.New()
|
||||||
|
|
@ -84,6 +86,8 @@ if err := rl.WaitForCapacity(ctx, "claude-opus-4", 2000); err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
// Capacity is available; proceed with the API call.
|
// Capacity is available; proceed with the API call.
|
||||||
|
|
||||||
|
// WaitForCapacity uses Decide's RetryAfter hint to avoid tight polling.
|
||||||
```
|
```
|
||||||
|
|
||||||
## Package Layout
|
## Package Layout
|
||||||
|
|
@ -103,6 +107,7 @@ The module is a single package with no sub-packages.
|
||||||
|
|
||||||
| Dependency | Purpose | Category |
|
| 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 |
|
| `gopkg.in/yaml.v3` | YAML serialisation for the legacy persistence backend | Direct |
|
||||||
| `modernc.org/sqlite` | Pure Go SQLite driver (no CGO required) | Direct |
|
| `modernc.org/sqlite` | Pure Go SQLite driver (no CGO required) | Direct |
|
||||||
| `github.com/stretchr/testify` | Test assertions (`assert`, `require`) | Test only |
|
| `github.com/stretchr/testify` | Test assertions (`assert`, `require`) | Test only |
|
||||||
|
|
|
||||||
|
|
@ -1,3 +1,5 @@
|
||||||
|
<!-- SPDX-License-Identifier: EUPL-1.2 -->
|
||||||
|
|
||||||
# Security Attack Vector Mapping
|
# 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.
|
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.
|
||||||
|
|
@ -14,7 +16,7 @@ Note: `CODEX.md` was not present anywhere under `/workspace` during this scan, s
|
||||||
| `(*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).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).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).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:414` | Caller-controlled `ctx`, `model`, `tokens` | Calls `CanSend(model, tokens)` once per second until capacity is available or `ctx.Done()` fires | No direct validation; relies on downstream `CanSend()` and caller-supplied context cancellation | Inherits the unknown-model and negative-token bypasses from `CanSend()`; repeated calls with long-lived contexts can accumulate goroutines and lock pressure |
|
| `(*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).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 |
|
| `(*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 |
|
| `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 |
|
||||||
|
|
|
||||||
158
error_test.go
158
error_test.go
|
|
@ -1,8 +1,9 @@
|
||||||
|
// SPDX-License-Identifier: EUPL-1.2
|
||||||
|
|
||||||
package ratelimit
|
package ratelimit
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"os"
|
"syscall"
|
||||||
"path/filepath"
|
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
|
@ -10,8 +11,8 @@ import (
|
||||||
"github.com/stretchr/testify/require"
|
"github.com/stretchr/testify/require"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestSQLiteErrorPaths(t *testing.T) {
|
func TestError_SQLiteErrorPaths_Bad(t *testing.T) {
|
||||||
dbPath := filepath.Join(t.TempDir(), "error.db")
|
dbPath := testPath(t.TempDir(), "error.db")
|
||||||
rl, err := NewWithSQLite(dbPath)
|
rl, err := NewWithSQLite(dbPath)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
|
@ -39,17 +40,17 @@ func TestSQLiteErrorPaths(t *testing.T) {
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSQLiteInitErrors(t *testing.T) {
|
func TestError_SQLiteInitErrors_Bad(t *testing.T) {
|
||||||
t.Run("WAL pragma failure", func(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
|
// 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.
|
// modernc.org/sqlite doesn't support all DSN options that might cause PRAGMA to fail but connection to succeed.
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestPersistYAML(t *testing.T) {
|
func TestError_PersistYAML_Good(t *testing.T) {
|
||||||
t.Run("successful YAML persist and load", func(t *testing.T) {
|
t.Run("successful YAML persist and load", func(t *testing.T) {
|
||||||
tmpDir := t.TempDir()
|
tmpDir := t.TempDir()
|
||||||
path := filepath.Join(tmpDir, "ratelimits.yaml")
|
path := testPath(tmpDir, "ratelimits.yaml")
|
||||||
rl, _ := New()
|
rl, _ := New()
|
||||||
rl.filePath = path
|
rl.filePath = path
|
||||||
rl.Quotas["test"] = ModelQuota{MaxRPM: 1}
|
rl.Quotas["test"] = ModelQuota{MaxRPM: 1}
|
||||||
|
|
@ -65,9 +66,9 @@ func TestPersistYAML(t *testing.T) {
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSQLiteLoadViaLimiter(t *testing.T) {
|
func TestError_SQLiteLoadViaLimiter_Bad(t *testing.T) {
|
||||||
t.Run("Load returns error when SQLite DB is closed", func(t *testing.T) {
|
t.Run("Load returns error when SQLite DB is closed", func(t *testing.T) {
|
||||||
dbPath := filepath.Join(t.TempDir(), "load-err.db")
|
dbPath := testPath(t.TempDir(), "load-err.db")
|
||||||
rl, err := NewWithSQLite(dbPath)
|
rl, err := NewWithSQLite(dbPath)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
|
@ -79,7 +80,7 @@ func TestSQLiteLoadViaLimiter(t *testing.T) {
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("Load returns error when loadState fails", func(t *testing.T) {
|
t.Run("Load returns error when loadState fails", func(t *testing.T) {
|
||||||
dbPath := filepath.Join(t.TempDir(), "load-state-err.db")
|
dbPath := testPath(t.TempDir(), "load-state-err.db")
|
||||||
rl, err := NewWithSQLite(dbPath)
|
rl, err := NewWithSQLite(dbPath)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
|
@ -96,9 +97,9 @@ func TestSQLiteLoadViaLimiter(t *testing.T) {
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSQLitePersistViaLimiter(t *testing.T) {
|
func TestError_SQLitePersistViaLimiter_Bad(t *testing.T) {
|
||||||
t.Run("Persist returns error when SQLite saveQuotas fails", func(t *testing.T) {
|
t.Run("Persist returns error when SQLite saveQuotas fails", func(t *testing.T) {
|
||||||
dbPath := filepath.Join(t.TempDir(), "persist-err.db")
|
dbPath := testPath(t.TempDir(), "persist-err.db")
|
||||||
rl, err := NewWithSQLite(dbPath)
|
rl, err := NewWithSQLite(dbPath)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
|
@ -113,7 +114,7 @@ func TestSQLitePersistViaLimiter(t *testing.T) {
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("Persist returns error when SQLite saveState fails", func(t *testing.T) {
|
t.Run("Persist returns error when SQLite saveState fails", func(t *testing.T) {
|
||||||
dbPath := filepath.Join(t.TempDir(), "persist-state-err.db")
|
dbPath := testPath(t.TempDir(), "persist-state-err.db")
|
||||||
rl, err := NewWithSQLite(dbPath)
|
rl, err := NewWithSQLite(dbPath)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
|
@ -130,7 +131,7 @@ func TestSQLitePersistViaLimiter(t *testing.T) {
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestNewWithSQLiteErrors(t *testing.T) {
|
func TestError_NewWithSQLite_Bad(t *testing.T) {
|
||||||
t.Run("NewWithSQLite with invalid path", func(t *testing.T) {
|
t.Run("NewWithSQLite with invalid path", func(t *testing.T) {
|
||||||
_, err := NewWithSQLite("/nonexistent/deep/nested/dir/test.db")
|
_, err := NewWithSQLite("/nonexistent/deep/nested/dir/test.db")
|
||||||
assert.Error(t, err, "should fail with invalid path")
|
assert.Error(t, err, "should fail with invalid path")
|
||||||
|
|
@ -144,9 +145,9 @@ func TestNewWithSQLiteErrors(t *testing.T) {
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSQLiteSaveStateErrors(t *testing.T) {
|
func TestError_SQLiteSaveState_Bad(t *testing.T) {
|
||||||
t.Run("saveState fails when tokens table is dropped", func(t *testing.T) {
|
t.Run("saveState fails when tokens table is dropped", func(t *testing.T) {
|
||||||
dbPath := filepath.Join(t.TempDir(), "tokens-err.db")
|
dbPath := testPath(t.TempDir(), "tokens-err.db")
|
||||||
store, err := newSQLiteStore(dbPath)
|
store, err := newSQLiteStore(dbPath)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
defer store.close()
|
defer store.close()
|
||||||
|
|
@ -166,7 +167,7 @@ func TestSQLiteSaveStateErrors(t *testing.T) {
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("saveState fails when daily table is dropped", func(t *testing.T) {
|
t.Run("saveState fails when daily table is dropped", func(t *testing.T) {
|
||||||
dbPath := filepath.Join(t.TempDir(), "daily-err.db")
|
dbPath := testPath(t.TempDir(), "daily-err.db")
|
||||||
store, err := newSQLiteStore(dbPath)
|
store, err := newSQLiteStore(dbPath)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
defer store.close()
|
defer store.close()
|
||||||
|
|
@ -185,7 +186,7 @@ func TestSQLiteSaveStateErrors(t *testing.T) {
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("saveState fails on request insert with renamed column", func(t *testing.T) {
|
t.Run("saveState fails on request insert with renamed column", func(t *testing.T) {
|
||||||
dbPath := filepath.Join(t.TempDir(), "req-insert-err.db")
|
dbPath := testPath(t.TempDir(), "req-insert-err.db")
|
||||||
store, err := newSQLiteStore(dbPath)
|
store, err := newSQLiteStore(dbPath)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
defer store.close()
|
defer store.close()
|
||||||
|
|
@ -206,7 +207,7 @@ func TestSQLiteSaveStateErrors(t *testing.T) {
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("saveState fails on token insert with renamed column", func(t *testing.T) {
|
t.Run("saveState fails on token insert with renamed column", func(t *testing.T) {
|
||||||
dbPath := filepath.Join(t.TempDir(), "tok-insert-err.db")
|
dbPath := testPath(t.TempDir(), "tok-insert-err.db")
|
||||||
store, err := newSQLiteStore(dbPath)
|
store, err := newSQLiteStore(dbPath)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
defer store.close()
|
defer store.close()
|
||||||
|
|
@ -227,7 +228,7 @@ func TestSQLiteSaveStateErrors(t *testing.T) {
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("saveState fails on daily insert with renamed column", func(t *testing.T) {
|
t.Run("saveState fails on daily insert with renamed column", func(t *testing.T) {
|
||||||
dbPath := filepath.Join(t.TempDir(), "day-insert-err.db")
|
dbPath := testPath(t.TempDir(), "day-insert-err.db")
|
||||||
store, err := newSQLiteStore(dbPath)
|
store, err := newSQLiteStore(dbPath)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
defer store.close()
|
defer store.close()
|
||||||
|
|
@ -247,9 +248,9 @@ func TestSQLiteSaveStateErrors(t *testing.T) {
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSQLiteLoadStateErrors(t *testing.T) {
|
func TestError_SQLiteLoadState_Bad(t *testing.T) {
|
||||||
t.Run("loadState fails when requests table is dropped", func(t *testing.T) {
|
t.Run("loadState fails when requests table is dropped", func(t *testing.T) {
|
||||||
dbPath := filepath.Join(t.TempDir(), "req-err.db")
|
dbPath := testPath(t.TempDir(), "req-err.db")
|
||||||
store, err := newSQLiteStore(dbPath)
|
store, err := newSQLiteStore(dbPath)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
defer store.close()
|
defer store.close()
|
||||||
|
|
@ -271,7 +272,7 @@ func TestSQLiteLoadStateErrors(t *testing.T) {
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("loadState fails when tokens table is dropped", func(t *testing.T) {
|
t.Run("loadState fails when tokens table is dropped", func(t *testing.T) {
|
||||||
dbPath := filepath.Join(t.TempDir(), "tok-err.db")
|
dbPath := testPath(t.TempDir(), "tok-err.db")
|
||||||
store, err := newSQLiteStore(dbPath)
|
store, err := newSQLiteStore(dbPath)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
defer store.close()
|
defer store.close()
|
||||||
|
|
@ -293,7 +294,7 @@ func TestSQLiteLoadStateErrors(t *testing.T) {
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("loadState fails when daily table is dropped", func(t *testing.T) {
|
t.Run("loadState fails when daily table is dropped", func(t *testing.T) {
|
||||||
dbPath := filepath.Join(t.TempDir(), "daily-load-err.db")
|
dbPath := testPath(t.TempDir(), "daily-load-err.db")
|
||||||
store, err := newSQLiteStore(dbPath)
|
store, err := newSQLiteStore(dbPath)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
defer store.close()
|
defer store.close()
|
||||||
|
|
@ -314,9 +315,9 @@ func TestSQLiteLoadStateErrors(t *testing.T) {
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSQLiteSaveQuotasExecError(t *testing.T) {
|
func TestError_SQLiteSaveQuotasExec_Bad(t *testing.T) {
|
||||||
t.Run("saveQuotas fails with renamed column at prepare", func(t *testing.T) {
|
t.Run("saveQuotas fails with renamed column at prepare", func(t *testing.T) {
|
||||||
dbPath := filepath.Join(t.TempDir(), "quota-exec-err.db")
|
dbPath := testPath(t.TempDir(), "quota-exec-err.db")
|
||||||
store, err := newSQLiteStore(dbPath)
|
store, err := newSQLiteStore(dbPath)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
defer store.close()
|
defer store.close()
|
||||||
|
|
@ -332,7 +333,7 @@ func TestSQLiteSaveQuotasExecError(t *testing.T) {
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("saveQuotas fails at exec via trigger", func(t *testing.T) {
|
t.Run("saveQuotas fails at exec via trigger", func(t *testing.T) {
|
||||||
dbPath := filepath.Join(t.TempDir(), "quota-trigger.db")
|
dbPath := testPath(t.TempDir(), "quota-trigger.db")
|
||||||
store, err := newSQLiteStore(dbPath)
|
store, err := newSQLiteStore(dbPath)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
defer store.close()
|
defer store.close()
|
||||||
|
|
@ -350,9 +351,9 @@ func TestSQLiteSaveQuotasExecError(t *testing.T) {
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSQLiteSaveStateExecErrors(t *testing.T) {
|
func TestError_SQLiteSaveStateExec_Bad(t *testing.T) {
|
||||||
t.Run("request insert exec fails via trigger", func(t *testing.T) {
|
t.Run("request insert exec fails via trigger", func(t *testing.T) {
|
||||||
dbPath := filepath.Join(t.TempDir(), "trigger-req.db")
|
dbPath := testPath(t.TempDir(), "trigger-req.db")
|
||||||
store, err := newSQLiteStore(dbPath)
|
store, err := newSQLiteStore(dbPath)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
defer store.close()
|
defer store.close()
|
||||||
|
|
@ -375,7 +376,7 @@ func TestSQLiteSaveStateExecErrors(t *testing.T) {
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("token insert exec fails via trigger", func(t *testing.T) {
|
t.Run("token insert exec fails via trigger", func(t *testing.T) {
|
||||||
dbPath := filepath.Join(t.TempDir(), "trigger-tok.db")
|
dbPath := testPath(t.TempDir(), "trigger-tok.db")
|
||||||
store, err := newSQLiteStore(dbPath)
|
store, err := newSQLiteStore(dbPath)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
defer store.close()
|
defer store.close()
|
||||||
|
|
@ -398,7 +399,7 @@ func TestSQLiteSaveStateExecErrors(t *testing.T) {
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("daily insert exec fails via trigger", func(t *testing.T) {
|
t.Run("daily insert exec fails via trigger", func(t *testing.T) {
|
||||||
dbPath := filepath.Join(t.TempDir(), "trigger-day.db")
|
dbPath := testPath(t.TempDir(), "trigger-day.db")
|
||||||
store, err := newSQLiteStore(dbPath)
|
store, err := newSQLiteStore(dbPath)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
defer store.close()
|
defer store.close()
|
||||||
|
|
@ -420,9 +421,9 @@ func TestSQLiteSaveStateExecErrors(t *testing.T) {
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSQLiteLoadQuotasScanError(t *testing.T) {
|
func TestError_SQLiteLoadQuotasScan_Bad(t *testing.T) {
|
||||||
t.Run("loadQuotas fails with renamed column", func(t *testing.T) {
|
t.Run("loadQuotas fails with renamed column", func(t *testing.T) {
|
||||||
dbPath := filepath.Join(t.TempDir(), "quota-scan-err.db")
|
dbPath := testPath(t.TempDir(), "quota-scan-err.db")
|
||||||
store, err := newSQLiteStore(dbPath)
|
store, err := newSQLiteStore(dbPath)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
defer store.close()
|
defer store.close()
|
||||||
|
|
@ -441,26 +442,29 @@ func TestSQLiteLoadQuotasScanError(t *testing.T) {
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestNewSQLiteStoreInReadOnlyDir(t *testing.T) {
|
func TestError_NewSQLiteStoreInReadOnlyDir_Bad(t *testing.T) {
|
||||||
if os.Getuid() == 0 {
|
if isRootUser() {
|
||||||
t.Skip("chmod restrictions do not apply to root")
|
t.Skip("chmod restrictions do not apply to root")
|
||||||
}
|
}
|
||||||
|
|
||||||
t.Run("fails when parent directory is read-only", func(t *testing.T) {
|
t.Run("fails when parent directory is read-only", func(t *testing.T) {
|
||||||
tmpDir := t.TempDir()
|
tmpDir := t.TempDir()
|
||||||
readonlyDir := filepath.Join(tmpDir, "readonly")
|
readonlyDir := testPath(tmpDir, "readonly")
|
||||||
require.NoError(t, os.MkdirAll(readonlyDir, 0555))
|
ensureTestDir(t, readonlyDir)
|
||||||
defer os.Chmod(readonlyDir, 0755)
|
setPathMode(t, readonlyDir, 0o555)
|
||||||
|
defer func() {
|
||||||
|
_ = syscall.Chmod(readonlyDir, 0o755)
|
||||||
|
}()
|
||||||
|
|
||||||
dbPath := filepath.Join(readonlyDir, "test.db")
|
dbPath := testPath(readonlyDir, "test.db")
|
||||||
_, err := newSQLiteStore(dbPath)
|
_, err := newSQLiteStore(dbPath)
|
||||||
assert.Error(t, err, "should fail when directory is read-only")
|
assert.Error(t, err, "should fail when directory is read-only")
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSQLiteCreateSchemaError(t *testing.T) {
|
func TestError_SQLiteCreateSchema_Bad(t *testing.T) {
|
||||||
t.Run("createSchema fails on closed DB", func(t *testing.T) {
|
t.Run("createSchema fails on closed DB", func(t *testing.T) {
|
||||||
dbPath := filepath.Join(t.TempDir(), "schema-err.db")
|
dbPath := testPath(t.TempDir(), "schema-err.db")
|
||||||
store, err := newSQLiteStore(dbPath)
|
store, err := newSQLiteStore(dbPath)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
|
@ -473,9 +477,9 @@ func TestSQLiteCreateSchemaError(t *testing.T) {
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSQLiteLoadStateScanErrors(t *testing.T) {
|
func TestError_SQLiteLoadStateScan_Bad(t *testing.T) {
|
||||||
t.Run("scan daily fails with NULL values", func(t *testing.T) {
|
t.Run("scan daily fails with NULL values", func(t *testing.T) {
|
||||||
dbPath := filepath.Join(t.TempDir(), "scan-daily.db")
|
dbPath := testPath(t.TempDir(), "scan-daily.db")
|
||||||
store, err := newSQLiteStore(dbPath)
|
store, err := newSQLiteStore(dbPath)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
defer store.close()
|
defer store.close()
|
||||||
|
|
@ -495,7 +499,7 @@ func TestSQLiteLoadStateScanErrors(t *testing.T) {
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("scan requests fails with NULL ts", func(t *testing.T) {
|
t.Run("scan requests fails with NULL ts", func(t *testing.T) {
|
||||||
dbPath := filepath.Join(t.TempDir(), "scan-req.db")
|
dbPath := testPath(t.TempDir(), "scan-req.db")
|
||||||
store, err := newSQLiteStore(dbPath)
|
store, err := newSQLiteStore(dbPath)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
defer store.close()
|
defer store.close()
|
||||||
|
|
@ -520,7 +524,7 @@ func TestSQLiteLoadStateScanErrors(t *testing.T) {
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("scan tokens fails with NULL values", func(t *testing.T) {
|
t.Run("scan tokens fails with NULL values", func(t *testing.T) {
|
||||||
dbPath := filepath.Join(t.TempDir(), "scan-tok.db")
|
dbPath := testPath(t.TempDir(), "scan-tok.db")
|
||||||
store, err := newSQLiteStore(dbPath)
|
store, err := newSQLiteStore(dbPath)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
defer store.close()
|
defer store.close()
|
||||||
|
|
@ -545,9 +549,9 @@ func TestSQLiteLoadStateScanErrors(t *testing.T) {
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSQLiteLoadQuotasScanWithBadSchema(t *testing.T) {
|
func TestError_SQLiteLoadQuotasScanWithBadSchema_Bad(t *testing.T) {
|
||||||
t.Run("scan fails with NULL quota values", func(t *testing.T) {
|
t.Run("scan fails with NULL quota values", func(t *testing.T) {
|
||||||
dbPath := filepath.Join(t.TempDir(), "scan-quota.db")
|
dbPath := testPath(t.TempDir(), "scan-quota.db")
|
||||||
store, err := newSQLiteStore(dbPath)
|
store, err := newSQLiteStore(dbPath)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
defer store.close()
|
defer store.close()
|
||||||
|
|
@ -566,11 +570,11 @@ func TestSQLiteLoadQuotasScanWithBadSchema(t *testing.T) {
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestMigrateYAMLToSQLiteWithSaveErrors(t *testing.T) {
|
func TestError_MigrateYAMLToSQLiteWithSaveErrors_Bad(t *testing.T) {
|
||||||
t.Run("saveQuotas failure during migration via trigger", func(t *testing.T) {
|
t.Run("saveQuotas failure during migration via trigger", func(t *testing.T) {
|
||||||
tmpDir := t.TempDir()
|
tmpDir := t.TempDir()
|
||||||
yamlPath := filepath.Join(tmpDir, "with-quotas.yaml")
|
yamlPath := testPath(tmpDir, "with-quotas.yaml")
|
||||||
sqlitePath := filepath.Join(tmpDir, "migrate-quota-err.db")
|
sqlitePath := testPath(tmpDir, "migrate-quota-err.db")
|
||||||
|
|
||||||
// Write a YAML file with quotas.
|
// Write a YAML file with quotas.
|
||||||
yamlData := `quotas:
|
yamlData := `quotas:
|
||||||
|
|
@ -579,7 +583,7 @@ func TestMigrateYAMLToSQLiteWithSaveErrors(t *testing.T) {
|
||||||
max_tpm: 100
|
max_tpm: 100
|
||||||
max_rpd: 50
|
max_rpd: 50
|
||||||
`
|
`
|
||||||
require.NoError(t, os.WriteFile(yamlPath, []byte(yamlData), 0644))
|
writeTestFile(t, yamlPath, yamlData)
|
||||||
|
|
||||||
// Pre-create DB with a trigger that aborts quota inserts.
|
// Pre-create DB with a trigger that aborts quota inserts.
|
||||||
store, err := newSQLiteStore(sqlitePath)
|
store, err := newSQLiteStore(sqlitePath)
|
||||||
|
|
@ -596,8 +600,8 @@ func TestMigrateYAMLToSQLiteWithSaveErrors(t *testing.T) {
|
||||||
|
|
||||||
t.Run("saveState failure during migration via trigger", func(t *testing.T) {
|
t.Run("saveState failure during migration via trigger", func(t *testing.T) {
|
||||||
tmpDir := t.TempDir()
|
tmpDir := t.TempDir()
|
||||||
yamlPath := filepath.Join(tmpDir, "with-state.yaml")
|
yamlPath := testPath(tmpDir, "with-state.yaml")
|
||||||
sqlitePath := filepath.Join(tmpDir, "migrate-state-err.db")
|
sqlitePath := testPath(tmpDir, "migrate-state-err.db")
|
||||||
|
|
||||||
// Write YAML with state.
|
// Write YAML with state.
|
||||||
yamlData := `state:
|
yamlData := `state:
|
||||||
|
|
@ -607,7 +611,7 @@ func TestMigrateYAMLToSQLiteWithSaveErrors(t *testing.T) {
|
||||||
day_start: 2026-01-01T00:00:00Z
|
day_start: 2026-01-01T00:00:00Z
|
||||||
day_count: 1
|
day_count: 1
|
||||||
`
|
`
|
||||||
require.NoError(t, os.WriteFile(yamlPath, []byte(yamlData), 0644))
|
writeTestFile(t, yamlPath, yamlData)
|
||||||
|
|
||||||
// Pre-create DB with a trigger that aborts daily inserts.
|
// Pre-create DB with a trigger that aborts daily inserts.
|
||||||
store, err := newSQLiteStore(sqlitePath)
|
store, err := newSQLiteStore(sqlitePath)
|
||||||
|
|
@ -622,13 +626,13 @@ func TestMigrateYAMLToSQLiteWithSaveErrors(t *testing.T) {
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestMigrateYAMLToSQLiteNilQuotasAndState(t *testing.T) {
|
func TestError_MigrateYAMLToSQLiteNilQuotasAndState_Good(t *testing.T) {
|
||||||
t.Run("YAML with empty quotas and state migrates cleanly", func(t *testing.T) {
|
t.Run("YAML with empty quotas and state migrates cleanly", func(t *testing.T) {
|
||||||
tmpDir := t.TempDir()
|
tmpDir := t.TempDir()
|
||||||
yamlPath := filepath.Join(tmpDir, "empty.yaml")
|
yamlPath := testPath(tmpDir, "empty.yaml")
|
||||||
require.NoError(t, os.WriteFile(yamlPath, []byte("{}"), 0644))
|
writeTestFile(t, yamlPath, "{}")
|
||||||
|
|
||||||
sqlitePath := filepath.Join(tmpDir, "empty.db")
|
sqlitePath := testPath(tmpDir, "empty.db")
|
||||||
require.NoError(t, MigrateYAMLToSQLite(yamlPath, sqlitePath))
|
require.NoError(t, MigrateYAMLToSQLite(yamlPath, sqlitePath))
|
||||||
|
|
||||||
store, err := newSQLiteStore(sqlitePath)
|
store, err := newSQLiteStore(sqlitePath)
|
||||||
|
|
@ -645,30 +649,18 @@ func TestMigrateYAMLToSQLiteNilQuotasAndState(t *testing.T) {
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestNewWithConfigUserHomeDirError(t *testing.T) {
|
func TestError_NewWithConfigHomeUnavailable_Bad(t *testing.T) {
|
||||||
// Unset HOME to trigger os.UserHomeDir() error.
|
// Clear all supported home env vars so defaultStatePath cannot resolve a home directory.
|
||||||
home := os.Getenv("HOME")
|
t.Setenv("CORE_HOME", "")
|
||||||
os.Unsetenv("HOME")
|
t.Setenv("HOME", "")
|
||||||
// Also unset fallback env vars that UserHomeDir checks.
|
t.Setenv("home", "")
|
||||||
plan9Home := os.Getenv("home")
|
t.Setenv("USERPROFILE", "")
|
||||||
os.Unsetenv("home")
|
|
||||||
userProfile := os.Getenv("USERPROFILE")
|
|
||||||
os.Unsetenv("USERPROFILE")
|
|
||||||
defer func() {
|
|
||||||
os.Setenv("HOME", home)
|
|
||||||
if plan9Home != "" {
|
|
||||||
os.Setenv("home", plan9Home)
|
|
||||||
}
|
|
||||||
if userProfile != "" {
|
|
||||||
os.Setenv("USERPROFILE", userProfile)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
_, err := NewWithConfig(Config{})
|
_, err := NewWithConfig(Config{})
|
||||||
assert.Error(t, err, "should fail when HOME is unset")
|
assert.Error(t, err, "should fail when HOME is unset")
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestPersistMarshalError(t *testing.T) {
|
func TestError_PersistMarshal_Good(t *testing.T) {
|
||||||
// yaml.Marshal on a struct with map[string]ModelQuota and map[string]*UsageStats
|
// 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
|
// should not fail in practice. We test the error path by using a type that
|
||||||
// yaml.Marshal cannot handle: a channel.
|
// yaml.Marshal cannot handle: a channel.
|
||||||
|
|
@ -680,20 +672,20 @@ func TestPersistMarshalError(t *testing.T) {
|
||||||
assert.NoError(t, rl.Persist(), "valid persist should succeed")
|
assert.NoError(t, rl.Persist(), "valid persist should succeed")
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestMigrateErrorsExtended(t *testing.T) {
|
func TestError_MigrateErrorsExtended_Bad(t *testing.T) {
|
||||||
t.Run("unmarshal failure", func(t *testing.T) {
|
t.Run("unmarshal failure", func(t *testing.T) {
|
||||||
tmpDir := t.TempDir()
|
tmpDir := t.TempDir()
|
||||||
path := filepath.Join(tmpDir, "bad.yaml")
|
path := testPath(tmpDir, "bad.yaml")
|
||||||
require.NoError(t, os.WriteFile(path, []byte("invalid: yaml: ["), 0644))
|
writeTestFile(t, path, "invalid: yaml: [")
|
||||||
err := MigrateYAMLToSQLite(path, filepath.Join(tmpDir, "out.db"))
|
err := MigrateYAMLToSQLite(path, testPath(tmpDir, "out.db"))
|
||||||
assert.Error(t, err)
|
assert.Error(t, err)
|
||||||
assert.Contains(t, err.Error(), "ratelimit.MigrateYAMLToSQLite: unmarshal")
|
assert.Contains(t, err.Error(), "ratelimit.MigrateYAMLToSQLite: unmarshal")
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("sqlite open failure", func(t *testing.T) {
|
t.Run("sqlite open failure", func(t *testing.T) {
|
||||||
tmpDir := t.TempDir()
|
tmpDir := t.TempDir()
|
||||||
yamlPath := filepath.Join(tmpDir, "ok.yaml")
|
yamlPath := testPath(tmpDir, "ok.yaml")
|
||||||
require.NoError(t, os.WriteFile(yamlPath, []byte("quotas: {}"), 0644))
|
writeTestFile(t, yamlPath, "quotas: {}")
|
||||||
// Use an invalid sqlite path (dir where file should be)
|
// Use an invalid sqlite path (dir where file should be)
|
||||||
err := MigrateYAMLToSQLite(yamlPath, "/dev/null/not-a-db")
|
err := MigrateYAMLToSQLite(yamlPath, "/dev/null/not-a-db")
|
||||||
assert.Error(t, err)
|
assert.Error(t, err)
|
||||||
|
|
|
||||||
12
go.mod
12
go.mod
|
|
@ -1,24 +1,24 @@
|
||||||
module forge.lthn.ai/core/go-ratelimit
|
// SPDX-License-Identifier: EUPL-1.2
|
||||||
|
|
||||||
|
module dappco.re/go/core/go-ratelimit
|
||||||
|
|
||||||
go 1.26.0
|
go 1.26.0
|
||||||
|
|
||||||
require (
|
require (
|
||||||
dappco.re/go/core/io v0.2.0
|
dappco.re/go/core v0.8.0-alpha.1
|
||||||
dappco.re/go/core/log v0.1.0
|
|
||||||
gopkg.in/yaml.v3 v3.0.1
|
gopkg.in/yaml.v3 v3.0.1
|
||||||
modernc.org/sqlite v1.47.0
|
modernc.org/sqlite v1.47.0
|
||||||
)
|
)
|
||||||
|
|
||||||
require (
|
require (
|
||||||
forge.lthn.ai/core/go-log v0.0.4 // indirect
|
|
||||||
github.com/dustin/go-humanize v1.0.1 // indirect
|
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||||
github.com/google/uuid v1.6.0 // indirect
|
github.com/google/uuid v1.6.0 // indirect
|
||||||
|
github.com/kr/text v0.2.0 // indirect
|
||||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||||
github.com/ncruces/go-strftime v1.0.0 // indirect
|
github.com/ncruces/go-strftime v1.0.0 // indirect
|
||||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||||
golang.org/x/mod v0.34.0 // indirect
|
|
||||||
golang.org/x/sync v0.20.0 // indirect
|
|
||||||
golang.org/x/sys v0.42.0 // indirect
|
golang.org/x/sys v0.42.0 // indirect
|
||||||
|
golang.org/x/tools v0.43.0 // indirect
|
||||||
modernc.org/libc v1.70.0 // indirect
|
modernc.org/libc v1.70.0 // indirect
|
||||||
modernc.org/mathutil v1.7.1 // indirect
|
modernc.org/mathutil v1.7.1 // indirect
|
||||||
modernc.org/memory v1.11.0 // indirect
|
modernc.org/memory v1.11.0 // indirect
|
||||||
|
|
|
||||||
9
go.sum
9
go.sum
|
|
@ -1,9 +1,6 @@
|
||||||
dappco.re/go/core/io v0.2.0 h1:zuudgIiTsQQ5ipVt97saWdGLROovbEB/zdVyy9/l+I4=
|
dappco.re/go/core v0.8.0-alpha.1 h1:gj7+Scv+L63Z7wMxbJYHhaRFkHJo2u4MMPuUSv/Dhtk=
|
||||||
dappco.re/go/core/io v0.2.0/go.mod h1:1QnQV6X9LNgFKfm8SkOtR9LLaj3bDcsOIeJOOyjbL5E=
|
dappco.re/go/core v0.8.0-alpha.1/go.mod h1:f2/tBZ3+3IqDrg2F5F598llv0nmb/4gJVCFzM5geE4A=
|
||||||
dappco.re/go/core/log v0.1.0 h1:pa71Vq2TD2aoEUQWFKwNcaJ3GBY8HbaNGqtE688Unyc=
|
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
|
||||||
dappco.re/go/core/log v0.1.0/go.mod h1:Nkqb8gsXhZAO8VLpx7B8i1iAmohhzqA20b9Zr8VUcJs=
|
|
||||||
forge.lthn.ai/core/go-log v0.0.4 h1:KTuCEPgFmuM8KJfnyQ8vPOU1Jg654W74h8IJvfQMfv0=
|
|
||||||
forge.lthn.ai/core/go-log v0.0.4/go.mod h1:r14MXKOD3LF/sI8XUJQhRk/SZHBE7jAFVuCfgkXoZPw=
|
|
||||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
|
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=
|
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
|
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
|
||||||
|
|
|
||||||
|
|
@ -1,3 +1,5 @@
|
||||||
|
// SPDX-License-Identifier: EUPL-1.2
|
||||||
|
|
||||||
package ratelimit
|
package ratelimit
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
|
@ -10,7 +12,7 @@ import (
|
||||||
"github.com/stretchr/testify/require"
|
"github.com/stretchr/testify/require"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestIterators(t *testing.T) {
|
func TestIter_Iterators_Good(t *testing.T) {
|
||||||
rl, err := NewWithConfig(Config{
|
rl, err := NewWithConfig(Config{
|
||||||
Quotas: map[string]ModelQuota{
|
Quotas: map[string]ModelQuota{
|
||||||
"model-c": {MaxRPM: 10},
|
"model-c": {MaxRPM: 10},
|
||||||
|
|
@ -77,7 +79,7 @@ func TestIterators(t *testing.T) {
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestIterEarlyBreak(t *testing.T) {
|
func TestIter_IterEarlyBreak_Good(t *testing.T) {
|
||||||
rl, err := NewWithConfig(Config{
|
rl, err := NewWithConfig(Config{
|
||||||
Quotas: map[string]ModelQuota{
|
Quotas: map[string]ModelQuota{
|
||||||
"model-a": {MaxRPM: 10},
|
"model-a": {MaxRPM: 10},
|
||||||
|
|
@ -110,7 +112,7 @@ func TestIterEarlyBreak(t *testing.T) {
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCountTokensFull(t *testing.T) {
|
func TestIter_CountTokensFull_Ugly(t *testing.T) {
|
||||||
t.Run("empty model is rejected", func(t *testing.T) {
|
t.Run("empty model is rejected", func(t *testing.T) {
|
||||||
_, err := CountTokens(context.Background(), "key", "", "text")
|
_, err := CountTokens(context.Background(), "key", "", "text")
|
||||||
assert.Error(t, err)
|
assert.Error(t, err)
|
||||||
|
|
|
||||||
495
ratelimit.go
495
ratelimit.go
|
|
@ -1,28 +1,26 @@
|
||||||
|
// SPDX-License-Identifier: EUPL-1.2
|
||||||
|
|
||||||
package ratelimit
|
package ratelimit
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
"io"
|
||||||
|
"io/fs"
|
||||||
"iter"
|
"iter"
|
||||||
"maps"
|
"maps"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/url"
|
"net/url"
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
"slices"
|
"slices"
|
||||||
"strings"
|
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
coreio "dappco.re/go/core/io"
|
core "dappco.re/go/core"
|
||||||
coreerr "dappco.re/go/core/log"
|
|
||||||
"gopkg.in/yaml.v3"
|
"gopkg.in/yaml.v3"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Provider identifies an LLM provider for quota profiles.
|
// Provider identifies an LLM provider for quota profiles.
|
||||||
|
//
|
||||||
|
// provider := ProviderOpenAI
|
||||||
type Provider string
|
type Provider string
|
||||||
|
|
||||||
const (
|
const (
|
||||||
|
|
@ -47,6 +45,8 @@ const (
|
||||||
)
|
)
|
||||||
|
|
||||||
// ModelQuota defines the rate limits for a specific model.
|
// ModelQuota defines the rate limits for a specific model.
|
||||||
|
//
|
||||||
|
// quota := ModelQuota{MaxRPM: 60, MaxTPM: 90000, MaxRPD: 1000}
|
||||||
type ModelQuota struct {
|
type ModelQuota struct {
|
||||||
MaxRPM int `yaml:"max_rpm"` // Requests per minute (0 = unlimited)
|
MaxRPM int `yaml:"max_rpm"` // Requests per minute (0 = unlimited)
|
||||||
MaxTPM int `yaml:"max_tpm"` // Tokens per minute (0 = unlimited)
|
MaxTPM int `yaml:"max_tpm"` // Tokens per minute (0 = unlimited)
|
||||||
|
|
@ -54,12 +54,18 @@ type ModelQuota struct {
|
||||||
}
|
}
|
||||||
|
|
||||||
// ProviderProfile bundles model quotas for a provider.
|
// ProviderProfile bundles model quotas for a provider.
|
||||||
|
//
|
||||||
|
// profile := ProviderProfile{Provider: ProviderGemini, Models: DefaultProfiles()[ProviderGemini].Models}
|
||||||
type ProviderProfile struct {
|
type ProviderProfile struct {
|
||||||
Provider Provider `yaml:"provider"`
|
// Provider identifies the provider that owns the profile.
|
||||||
Models map[string]ModelQuota `yaml:"models"`
|
Provider Provider `yaml:"provider"`
|
||||||
|
// Models maps model names to quotas.
|
||||||
|
Models map[string]ModelQuota `yaml:"models"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Config controls RateLimiter initialisation.
|
// Config controls RateLimiter initialisation.
|
||||||
|
//
|
||||||
|
// cfg := Config{Providers: []Provider{ProviderGemini}, FilePath: "/tmp/ratelimits.yaml"}
|
||||||
type Config struct {
|
type Config struct {
|
||||||
// FilePath overrides the default state file location.
|
// FilePath overrides the default state file location.
|
||||||
// If empty, defaults to ~/.core/ratelimits.yaml.
|
// If empty, defaults to ~/.core/ratelimits.yaml.
|
||||||
|
|
@ -79,23 +85,35 @@ type Config struct {
|
||||||
}
|
}
|
||||||
|
|
||||||
// TokenEntry records a token usage event.
|
// TokenEntry records a token usage event.
|
||||||
|
//
|
||||||
|
// entry := TokenEntry{Time: time.Now(), Count: 512}
|
||||||
type TokenEntry struct {
|
type TokenEntry struct {
|
||||||
Time time.Time `yaml:"time"`
|
Time time.Time `yaml:"time"`
|
||||||
Count int `yaml:"count"`
|
Count int `yaml:"count"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// UsageStats tracks usage history for a model.
|
// UsageStats tracks usage history for a model.
|
||||||
|
//
|
||||||
|
// stats := UsageStats{DayStart: time.Now(), DayCount: 1}
|
||||||
type UsageStats struct {
|
type UsageStats struct {
|
||||||
Requests []time.Time `yaml:"requests"` // Sliding window (1m)
|
Requests []time.Time `yaml:"requests"` // Sliding window (1m)
|
||||||
Tokens []TokenEntry `yaml:"tokens"` // Sliding window (1m)
|
Tokens []TokenEntry `yaml:"tokens"` // Sliding window (1m)
|
||||||
DayStart time.Time `yaml:"day_start"`
|
// DayStart is the start of the rolling 24-hour window.
|
||||||
DayCount int `yaml:"day_count"`
|
DayStart time.Time `yaml:"day_start"`
|
||||||
|
// DayCount is the number of requests recorded in the rolling 24-hour window.
|
||||||
|
DayCount int `yaml:"day_count"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// RateLimiter manages rate limits across multiple models.
|
// RateLimiter manages rate limits across multiple models.
|
||||||
|
//
|
||||||
|
// rl, err := New()
|
||||||
|
// if err != nil { /* handle error */ }
|
||||||
|
// defer rl.Close()
|
||||||
type RateLimiter struct {
|
type RateLimiter struct {
|
||||||
mu sync.RWMutex
|
mu sync.RWMutex
|
||||||
Quotas map[string]ModelQuota `yaml:"quotas"`
|
// Quotas holds the configured per-model limits.
|
||||||
|
Quotas map[string]ModelQuota `yaml:"quotas"`
|
||||||
|
// State holds per-model usage windows.
|
||||||
State map[string]*UsageStats `yaml:"state"`
|
State map[string]*UsageStats `yaml:"state"`
|
||||||
filePath string
|
filePath string
|
||||||
sqlite *sqliteStore // non-nil when backend is "sqlite"
|
sqlite *sqliteStore // non-nil when backend is "sqlite"
|
||||||
|
|
@ -103,6 +121,9 @@ type RateLimiter struct {
|
||||||
|
|
||||||
// DefaultProfiles returns pre-configured quota profiles for each provider.
|
// DefaultProfiles returns pre-configured quota profiles for each provider.
|
||||||
// Values are based on published rate limits as of Feb 2026.
|
// Values are based on published rate limits as of Feb 2026.
|
||||||
|
//
|
||||||
|
// profiles := DefaultProfiles()
|
||||||
|
// openAI := profiles[ProviderOpenAI]
|
||||||
func DefaultProfiles() map[Provider]ProviderProfile {
|
func DefaultProfiles() map[Provider]ProviderProfile {
|
||||||
return map[Provider]ProviderProfile{
|
return map[Provider]ProviderProfile{
|
||||||
ProviderGemini: {
|
ProviderGemini: {
|
||||||
|
|
@ -146,6 +167,8 @@ func DefaultProfiles() map[Provider]ProviderProfile {
|
||||||
|
|
||||||
// New creates a new RateLimiter with Gemini defaults.
|
// New creates a new RateLimiter with Gemini defaults.
|
||||||
// This preserves backward compatibility -- existing callers are unaffected.
|
// This preserves backward compatibility -- existing callers are unaffected.
|
||||||
|
//
|
||||||
|
// rl, err := New()
|
||||||
func New() (*RateLimiter, error) {
|
func New() (*RateLimiter, error) {
|
||||||
return NewWithConfig(Config{
|
return NewWithConfig(Config{
|
||||||
Providers: []Provider{ProviderGemini},
|
Providers: []Provider{ProviderGemini},
|
||||||
|
|
@ -154,6 +177,8 @@ func New() (*RateLimiter, error) {
|
||||||
|
|
||||||
// NewWithConfig creates a RateLimiter from explicit configuration.
|
// NewWithConfig creates a RateLimiter from explicit configuration.
|
||||||
// If no providers or quotas are specified, Gemini defaults are used.
|
// If no providers or quotas are specified, Gemini defaults are used.
|
||||||
|
//
|
||||||
|
// rl, err := NewWithConfig(Config{Providers: []Provider{ProviderAnthropic}})
|
||||||
func NewWithConfig(cfg Config) (*RateLimiter, error) {
|
func NewWithConfig(cfg Config) (*RateLimiter, error) {
|
||||||
backend, err := normaliseBackend(cfg.Backend)
|
backend, err := normaliseBackend(cfg.Backend)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|
@ -170,8 +195,8 @@ func NewWithConfig(cfg Config) (*RateLimiter, error) {
|
||||||
|
|
||||||
if backend == backendSQLite {
|
if backend == backendSQLite {
|
||||||
if cfg.FilePath == "" {
|
if cfg.FilePath == "" {
|
||||||
if err := os.MkdirAll(filepath.Dir(filePath), 0o755); err != nil {
|
if err := ensureDir(core.PathDir(filePath)); err != nil {
|
||||||
return nil, coreerr.E("ratelimit.NewWithConfig", "mkdir", err)
|
return nil, core.E("ratelimit.NewWithConfig", "mkdir", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return NewWithSQLiteConfig(filePath, cfg)
|
return NewWithSQLiteConfig(filePath, cfg)
|
||||||
|
|
@ -183,6 +208,8 @@ func NewWithConfig(cfg Config) (*RateLimiter, error) {
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetQuota sets or updates the quota for a specific model at runtime.
|
// SetQuota sets or updates the quota for a specific model at runtime.
|
||||||
|
//
|
||||||
|
// rl.SetQuota("gpt-4o-mini", ModelQuota{MaxRPM: 60, MaxTPM: 200000})
|
||||||
func (rl *RateLimiter) SetQuota(model string, quota ModelQuota) {
|
func (rl *RateLimiter) SetQuota(model string, quota ModelQuota) {
|
||||||
rl.mu.Lock()
|
rl.mu.Lock()
|
||||||
defer rl.mu.Unlock()
|
defer rl.mu.Unlock()
|
||||||
|
|
@ -191,6 +218,8 @@ func (rl *RateLimiter) SetQuota(model string, quota ModelQuota) {
|
||||||
|
|
||||||
// AddProvider loads all default quotas for a provider.
|
// AddProvider loads all default quotas for a provider.
|
||||||
// Existing quotas for models in the profile are overwritten.
|
// Existing quotas for models in the profile are overwritten.
|
||||||
|
//
|
||||||
|
// rl.AddProvider(ProviderOpenAI)
|
||||||
func (rl *RateLimiter) AddProvider(provider Provider) {
|
func (rl *RateLimiter) AddProvider(provider Provider) {
|
||||||
rl.mu.Lock()
|
rl.mu.Lock()
|
||||||
defer rl.mu.Unlock()
|
defer rl.mu.Unlock()
|
||||||
|
|
@ -202,6 +231,8 @@ func (rl *RateLimiter) AddProvider(provider Provider) {
|
||||||
}
|
}
|
||||||
|
|
||||||
// Load reads the state from disk (YAML) or database (SQLite).
|
// Load reads the state from disk (YAML) or database (SQLite).
|
||||||
|
//
|
||||||
|
// if err := rl.Load(); err != nil { /* handle error */ }
|
||||||
func (rl *RateLimiter) Load() error {
|
func (rl *RateLimiter) Load() error {
|
||||||
rl.mu.Lock()
|
rl.mu.Lock()
|
||||||
defer rl.mu.Unlock()
|
defer rl.mu.Unlock()
|
||||||
|
|
@ -210,15 +241,20 @@ func (rl *RateLimiter) Load() error {
|
||||||
return rl.loadSQLite()
|
return rl.loadSQLite()
|
||||||
}
|
}
|
||||||
|
|
||||||
content, err := coreio.Local.Read(rl.filePath)
|
content, err := readLocalFile(rl.filePath)
|
||||||
if os.IsNotExist(err) {
|
if core.Is(err, fs.ErrNotExist) {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
return yaml.Unmarshal([]byte(content), rl)
|
if err := yaml.Unmarshal([]byte(content), rl); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
ensureMaps(rl)
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// loadSQLite reads quotas and state from the SQLite backend.
|
// loadSQLite reads quotas and state from the SQLite backend.
|
||||||
|
|
@ -244,6 +280,8 @@ func (rl *RateLimiter) loadSQLite() error {
|
||||||
|
|
||||||
// Persist writes a snapshot of the state to disk (YAML) or database (SQLite).
|
// Persist writes a snapshot of the state to disk (YAML) or database (SQLite).
|
||||||
// It clones the state under a lock and performs I/O without blocking other callers.
|
// It clones the state under a lock and performs I/O without blocking other callers.
|
||||||
|
//
|
||||||
|
// if err := rl.Persist(); err != nil { /* handle error */ }
|
||||||
func (rl *RateLimiter) Persist() error {
|
func (rl *RateLimiter) Persist() error {
|
||||||
rl.mu.Lock()
|
rl.mu.Lock()
|
||||||
quotas := maps.Clone(rl.Quotas)
|
quotas := maps.Clone(rl.Quotas)
|
||||||
|
|
@ -265,7 +303,7 @@ func (rl *RateLimiter) Persist() error {
|
||||||
|
|
||||||
if sqlite != nil {
|
if sqlite != nil {
|
||||||
if err := sqlite.saveSnapshot(quotas, state); err != nil {
|
if err := sqlite.saveSnapshot(quotas, state); err != nil {
|
||||||
return coreerr.E("ratelimit.Persist", "sqlite snapshot", err)
|
return core.E("ratelimit.Persist", "sqlite snapshot", err)
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
@ -280,11 +318,11 @@ func (rl *RateLimiter) Persist() error {
|
||||||
State: state,
|
State: state,
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return coreerr.E("ratelimit.Persist", "marshal", err)
|
return core.E("ratelimit.Persist", "marshal", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := coreio.Local.Write(filePath, string(data)); err != nil {
|
if err := writeLocalFile(filePath, string(data)); err != nil {
|
||||||
return coreerr.E("ratelimit.Persist", "write", err)
|
return core.E("ratelimit.Persist", "write", err)
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
@ -334,6 +372,9 @@ func (rl *RateLimiter) prune(model string) {
|
||||||
|
|
||||||
// BackgroundPrune starts a goroutine that periodically prunes all model states.
|
// BackgroundPrune starts a goroutine that periodically prunes all model states.
|
||||||
// It returns a function to stop the pruner.
|
// It returns a function to stop the pruner.
|
||||||
|
//
|
||||||
|
// stop := rl.BackgroundPrune(30 * time.Second)
|
||||||
|
// defer stop()
|
||||||
func (rl *RateLimiter) BackgroundPrune(interval time.Duration) func() {
|
func (rl *RateLimiter) BackgroundPrune(interval time.Duration) func() {
|
||||||
if interval <= 0 {
|
if interval <= 0 {
|
||||||
return func() {}
|
return func() {}
|
||||||
|
|
@ -360,53 +401,15 @@ func (rl *RateLimiter) BackgroundPrune(interval time.Duration) func() {
|
||||||
}
|
}
|
||||||
|
|
||||||
// CanSend checks if a request can be sent without violating limits.
|
// CanSend checks if a request can be sent without violating limits.
|
||||||
|
//
|
||||||
|
// ok := rl.CanSend("gemini-3-pro-preview", 1200)
|
||||||
func (rl *RateLimiter) CanSend(model string, estimatedTokens int) bool {
|
func (rl *RateLimiter) CanSend(model string, estimatedTokens int) bool {
|
||||||
if estimatedTokens < 0 {
|
return rl.Decide(model, estimatedTokens).Allowed
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
rl.mu.Lock()
|
|
||||||
defer rl.mu.Unlock()
|
|
||||||
|
|
||||||
quota, ok := rl.Quotas[model]
|
|
||||||
if !ok {
|
|
||||||
return true // Unknown models are allowed
|
|
||||||
}
|
|
||||||
|
|
||||||
// Unlimited check
|
|
||||||
if quota.MaxRPM == 0 && quota.MaxTPM == 0 && quota.MaxRPD == 0 {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
rl.prune(model)
|
|
||||||
stats, ok := rl.State[model]
|
|
||||||
if !ok {
|
|
||||||
stats = &UsageStats{DayStart: time.Now()}
|
|
||||||
rl.State[model] = stats
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check RPD
|
|
||||||
if quota.MaxRPD > 0 && stats.DayCount >= quota.MaxRPD {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check RPM
|
|
||||||
if quota.MaxRPM > 0 && len(stats.Requests) >= quota.MaxRPM {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check TPM
|
|
||||||
if quota.MaxTPM > 0 {
|
|
||||||
currentTokens := totalTokenCount(stats.Tokens)
|
|
||||||
if estimatedTokens > quota.MaxTPM || currentTokens > quota.MaxTPM-estimatedTokens {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return true
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// RecordUsage records a successful API call.
|
// RecordUsage records a successful API call.
|
||||||
|
//
|
||||||
|
// rl.RecordUsage("gemini-3-pro-preview", 900, 300)
|
||||||
func (rl *RateLimiter) RecordUsage(model string, promptTokens, outputTokens int) {
|
func (rl *RateLimiter) RecordUsage(model string, promptTokens, outputTokens int) {
|
||||||
rl.mu.Lock()
|
rl.mu.Lock()
|
||||||
defer rl.mu.Unlock()
|
defer rl.mu.Unlock()
|
||||||
|
|
@ -426,29 +429,38 @@ func (rl *RateLimiter) RecordUsage(model string, promptTokens, outputTokens int)
|
||||||
}
|
}
|
||||||
|
|
||||||
// WaitForCapacity blocks until capacity is available or context is cancelled.
|
// WaitForCapacity blocks until capacity is available or context is cancelled.
|
||||||
|
//
|
||||||
|
// err := rl.WaitForCapacity(ctx, "gemini-3-pro-preview", 1200)
|
||||||
func (rl *RateLimiter) WaitForCapacity(ctx context.Context, model string, tokens int) error {
|
func (rl *RateLimiter) WaitForCapacity(ctx context.Context, model string, tokens int) error {
|
||||||
if tokens < 0 {
|
if tokens < 0 {
|
||||||
return coreerr.E("ratelimit.WaitForCapacity", "negative tokens", nil)
|
return core.E("ratelimit.WaitForCapacity", "negative tokens", nil)
|
||||||
}
|
}
|
||||||
|
|
||||||
ticker := time.NewTicker(1 * time.Second)
|
|
||||||
defer ticker.Stop()
|
|
||||||
|
|
||||||
for {
|
for {
|
||||||
if rl.CanSend(model, tokens) {
|
decision := rl.Decide(model, tokens)
|
||||||
|
if decision.Allowed {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
sleep := decision.RetryAfter
|
||||||
|
if sleep <= 0 {
|
||||||
|
sleep = time.Second
|
||||||
|
}
|
||||||
|
|
||||||
|
timer := time.NewTimer(sleep)
|
||||||
select {
|
select {
|
||||||
case <-ctx.Done():
|
case <-ctx.Done():
|
||||||
|
timer.Stop()
|
||||||
return ctx.Err()
|
return ctx.Err()
|
||||||
case <-ticker.C:
|
case <-timer.C:
|
||||||
// check again
|
timer.Stop()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Reset clears stats for a model (or all if model is empty).
|
// Reset clears stats for a model (or all if model is empty).
|
||||||
|
//
|
||||||
|
// rl.Reset("gemini-3-pro-preview")
|
||||||
func (rl *RateLimiter) Reset(model string) {
|
func (rl *RateLimiter) Reset(model string) {
|
||||||
rl.mu.Lock()
|
rl.mu.Lock()
|
||||||
defer rl.mu.Unlock()
|
defer rl.mu.Unlock()
|
||||||
|
|
@ -461,17 +473,58 @@ func (rl *RateLimiter) Reset(model string) {
|
||||||
}
|
}
|
||||||
|
|
||||||
// ModelStats represents a snapshot of usage.
|
// ModelStats represents a snapshot of usage.
|
||||||
|
//
|
||||||
|
// stats := rl.Stats("gemini-3-pro-preview")
|
||||||
type ModelStats struct {
|
type ModelStats struct {
|
||||||
RPM int
|
// RPM is the current requests-per-minute usage in the sliding window.
|
||||||
MaxRPM int
|
RPM int
|
||||||
TPM int
|
// MaxRPM is the configured requests-per-minute limit.
|
||||||
MaxTPM int
|
MaxRPM int
|
||||||
RPD int
|
// TPM is the current tokens-per-minute usage in the sliding window.
|
||||||
MaxRPD int
|
TPM int
|
||||||
|
// MaxTPM is the configured tokens-per-minute limit.
|
||||||
|
MaxTPM int
|
||||||
|
// RPD is the current requests-per-day usage in the rolling 24-hour window.
|
||||||
|
RPD int
|
||||||
|
// MaxRPD is the configured requests-per-day limit.
|
||||||
|
MaxRPD int
|
||||||
|
// DayStart is the start of the current rolling 24-hour window.
|
||||||
DayStart time.Time
|
DayStart time.Time
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// DecisionCode identifies the reason for an allow or deny outcome from Decide.
|
||||||
|
type DecisionCode string
|
||||||
|
|
||||||
|
const (
|
||||||
|
// DecisionAllowed means the request fits within all configured limits.
|
||||||
|
DecisionAllowed DecisionCode = "ok"
|
||||||
|
// DecisionUnknownModel means the model has no configured quotas and is therefore allowed.
|
||||||
|
DecisionUnknownModel DecisionCode = "unknown_model"
|
||||||
|
// DecisionUnlimited means the model is configured with no limits.
|
||||||
|
DecisionUnlimited DecisionCode = "unlimited"
|
||||||
|
// DecisionInvalidTokens means a negative token estimate was provided.
|
||||||
|
DecisionInvalidTokens DecisionCode = "invalid_tokens"
|
||||||
|
// DecisionRPDLimit means the rolling 24-hour request limit has been reached.
|
||||||
|
DecisionRPDLimit DecisionCode = "rpd_exceeded"
|
||||||
|
// DecisionRPMLimit means the per-minute request limit has been reached.
|
||||||
|
DecisionRPMLimit DecisionCode = "rpm_exceeded"
|
||||||
|
// DecisionTPMLimit means the per-minute token limit would be exceeded.
|
||||||
|
DecisionTPMLimit DecisionCode = "tpm_exceeded"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Decision captures an allow/deny decision with context for agents.
|
||||||
|
// RetryAfter is zero when the request is allowed or when no meaningful wait time exists.
|
||||||
|
type Decision struct {
|
||||||
|
Allowed bool
|
||||||
|
Code DecisionCode
|
||||||
|
Reason string
|
||||||
|
RetryAfter time.Duration
|
||||||
|
Stats ModelStats
|
||||||
|
}
|
||||||
|
|
||||||
// Models returns a sorted iterator over all model names tracked by the limiter.
|
// Models returns a sorted iterator over all model names tracked by the limiter.
|
||||||
|
//
|
||||||
|
// for model := range rl.Models() { println(model) }
|
||||||
func (rl *RateLimiter) Models() iter.Seq[string] {
|
func (rl *RateLimiter) Models() iter.Seq[string] {
|
||||||
rl.mu.RLock()
|
rl.mu.RLock()
|
||||||
defer rl.mu.RUnlock()
|
defer rl.mu.RUnlock()
|
||||||
|
|
@ -488,6 +541,8 @@ func (rl *RateLimiter) Models() iter.Seq[string] {
|
||||||
}
|
}
|
||||||
|
|
||||||
// Iter returns a sorted iterator over all model names and their current stats.
|
// Iter returns a sorted iterator over all model names and their current stats.
|
||||||
|
//
|
||||||
|
// for model, stats := range rl.Iter() { _ = stats; println(model) }
|
||||||
func (rl *RateLimiter) Iter() iter.Seq2[string, ModelStats] {
|
func (rl *RateLimiter) Iter() iter.Seq2[string, ModelStats] {
|
||||||
return func(yield func(string, ModelStats) bool) {
|
return func(yield func(string, ModelStats) bool) {
|
||||||
stats := rl.AllStats()
|
stats := rl.AllStats()
|
||||||
|
|
@ -500,33 +555,20 @@ func (rl *RateLimiter) Iter() iter.Seq2[string, ModelStats] {
|
||||||
}
|
}
|
||||||
|
|
||||||
// Stats returns current stats for a model.
|
// Stats returns current stats for a model.
|
||||||
|
//
|
||||||
|
// stats := rl.Stats("gemini-3-pro-preview")
|
||||||
func (rl *RateLimiter) Stats(model string) ModelStats {
|
func (rl *RateLimiter) Stats(model string) ModelStats {
|
||||||
rl.mu.Lock()
|
rl.mu.Lock()
|
||||||
defer rl.mu.Unlock()
|
defer rl.mu.Unlock()
|
||||||
|
|
||||||
rl.prune(model)
|
rl.prune(model)
|
||||||
|
|
||||||
stats := ModelStats{}
|
return rl.snapshotLocked(model)
|
||||||
quota, ok := rl.Quotas[model]
|
|
||||||
if ok {
|
|
||||||
stats.MaxRPM = quota.MaxRPM
|
|
||||||
stats.MaxTPM = quota.MaxTPM
|
|
||||||
stats.MaxRPD = quota.MaxRPD
|
|
||||||
}
|
|
||||||
|
|
||||||
if s, ok := rl.State[model]; ok {
|
|
||||||
stats.RPM = len(s.Requests)
|
|
||||||
stats.RPD = s.DayCount
|
|
||||||
stats.DayStart = s.DayStart
|
|
||||||
for _, t := range s.Tokens {
|
|
||||||
stats.TPM += t.Count
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return stats
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// AllStats returns stats for all tracked models.
|
// AllStats returns stats for all tracked models.
|
||||||
|
//
|
||||||
|
// all := rl.AllStats()
|
||||||
func (rl *RateLimiter) AllStats() map[string]ModelStats {
|
func (rl *RateLimiter) AllStats() map[string]ModelStats {
|
||||||
rl.mu.Lock()
|
rl.mu.Lock()
|
||||||
defer rl.mu.Unlock()
|
defer rl.mu.Unlock()
|
||||||
|
|
@ -544,27 +586,112 @@ func (rl *RateLimiter) AllStats() map[string]ModelStats {
|
||||||
for m := range result {
|
for m := range result {
|
||||||
rl.prune(m)
|
rl.prune(m)
|
||||||
|
|
||||||
ms := ModelStats{}
|
result[m] = rl.snapshotLocked(m)
|
||||||
if q, ok := rl.Quotas[m]; ok {
|
|
||||||
ms.MaxRPM = q.MaxRPM
|
|
||||||
ms.MaxTPM = q.MaxTPM
|
|
||||||
ms.MaxRPD = q.MaxRPD
|
|
||||||
}
|
|
||||||
if s, ok := rl.State[m]; ok && s != nil {
|
|
||||||
ms.RPM = len(s.Requests)
|
|
||||||
ms.RPD = s.DayCount
|
|
||||||
ms.DayStart = s.DayStart
|
|
||||||
ms.TPM = totalTokenCount(s.Tokens)
|
|
||||||
}
|
|
||||||
result[m] = ms
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Decide returns structured allow/deny information for an estimated request.
|
||||||
|
// It never records usage; call RecordUsage after a successful decision.
|
||||||
|
func (rl *RateLimiter) Decide(model string, estimatedTokens int) Decision {
|
||||||
|
rl.mu.Lock()
|
||||||
|
defer rl.mu.Unlock()
|
||||||
|
|
||||||
|
now := time.Now()
|
||||||
|
decision := Decision{}
|
||||||
|
|
||||||
|
if estimatedTokens < 0 {
|
||||||
|
decision.Allowed = false
|
||||||
|
decision.Code = DecisionInvalidTokens
|
||||||
|
decision.Reason = "estimated tokens must be non-negative"
|
||||||
|
decision.Stats = rl.snapshotLocked(model)
|
||||||
|
return decision
|
||||||
|
}
|
||||||
|
|
||||||
|
quota, ok := rl.Quotas[model]
|
||||||
|
if !ok {
|
||||||
|
decision.Allowed = true
|
||||||
|
decision.Code = DecisionUnknownModel
|
||||||
|
decision.Reason = "model has no configured quota"
|
||||||
|
decision.Stats = rl.snapshotLocked(model)
|
||||||
|
return decision
|
||||||
|
}
|
||||||
|
|
||||||
|
if quota.MaxRPM == 0 && quota.MaxTPM == 0 && quota.MaxRPD == 0 {
|
||||||
|
decision.Allowed = true
|
||||||
|
decision.Code = DecisionUnlimited
|
||||||
|
decision.Reason = "all limits are unlimited"
|
||||||
|
decision.Stats = rl.snapshotLocked(model)
|
||||||
|
return decision
|
||||||
|
}
|
||||||
|
|
||||||
|
rl.prune(model)
|
||||||
|
stats, ok := rl.State[model]
|
||||||
|
if !ok || stats == nil {
|
||||||
|
stats = &UsageStats{DayStart: now}
|
||||||
|
rl.State[model] = stats
|
||||||
|
}
|
||||||
|
|
||||||
|
decision.Stats = rl.snapshotLocked(model)
|
||||||
|
|
||||||
|
if quota.MaxRPD > 0 && stats.DayCount >= quota.MaxRPD {
|
||||||
|
decision.Code = DecisionRPDLimit
|
||||||
|
decision.Reason = "daily request limit reached"
|
||||||
|
decision.RetryAfter = nonNegativeDuration(stats.DayStart.Add(24 * time.Hour).Sub(now))
|
||||||
|
return decision
|
||||||
|
}
|
||||||
|
|
||||||
|
if quota.MaxRPM > 0 && len(stats.Requests) >= quota.MaxRPM {
|
||||||
|
decision.Code = DecisionRPMLimit
|
||||||
|
decision.Reason = "per-minute request limit reached"
|
||||||
|
if len(stats.Requests) > 0 {
|
||||||
|
decision.RetryAfter = nonNegativeDuration(stats.Requests[0].Add(time.Minute).Sub(now))
|
||||||
|
}
|
||||||
|
return decision
|
||||||
|
}
|
||||||
|
|
||||||
|
if quota.MaxTPM > 0 {
|
||||||
|
currentTokens := totalTokenCount(stats.Tokens)
|
||||||
|
if estimatedTokens > quota.MaxTPM || currentTokens > quota.MaxTPM-estimatedTokens {
|
||||||
|
decision.Code = DecisionTPMLimit
|
||||||
|
decision.Reason = "per-minute token limit reached"
|
||||||
|
decision.RetryAfter = retryAfterForTokens(now, stats.Tokens, quota.MaxTPM, estimatedTokens)
|
||||||
|
return decision
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
decision.Allowed = true
|
||||||
|
decision.Code = DecisionAllowed
|
||||||
|
decision.Reason = "within quota"
|
||||||
|
return decision
|
||||||
|
}
|
||||||
|
|
||||||
|
// snapshotLocked builds ModelStats for the provided model.
|
||||||
|
// Caller must hold rl.mu.
|
||||||
|
func (rl *RateLimiter) snapshotLocked(model string) ModelStats {
|
||||||
|
stats := ModelStats{}
|
||||||
|
|
||||||
|
if q, ok := rl.Quotas[model]; ok {
|
||||||
|
stats.MaxRPM = q.MaxRPM
|
||||||
|
stats.MaxTPM = q.MaxTPM
|
||||||
|
stats.MaxRPD = q.MaxRPD
|
||||||
|
}
|
||||||
|
|
||||||
|
if s, ok := rl.State[model]; ok && s != nil {
|
||||||
|
stats.RPM = len(s.Requests)
|
||||||
|
stats.RPD = s.DayCount
|
||||||
|
stats.DayStart = s.DayStart
|
||||||
|
stats.TPM = totalTokenCount(s.Tokens)
|
||||||
|
}
|
||||||
|
return stats
|
||||||
|
}
|
||||||
|
|
||||||
// NewWithSQLite creates a SQLite-backed RateLimiter with Gemini defaults.
|
// NewWithSQLite creates a SQLite-backed RateLimiter with Gemini defaults.
|
||||||
// The database is created at dbPath if it does not exist. Use Close() to
|
// The database is created at dbPath if it does not exist. Use Close() to
|
||||||
// release the database connection when finished.
|
// release the database connection when finished.
|
||||||
|
//
|
||||||
|
// rl, err := NewWithSQLite("/tmp/ratelimits.db")
|
||||||
func NewWithSQLite(dbPath string) (*RateLimiter, error) {
|
func NewWithSQLite(dbPath string) (*RateLimiter, error) {
|
||||||
return NewWithSQLiteConfig(dbPath, Config{
|
return NewWithSQLiteConfig(dbPath, Config{
|
||||||
Providers: []Provider{ProviderGemini},
|
Providers: []Provider{ProviderGemini},
|
||||||
|
|
@ -574,6 +701,8 @@ func NewWithSQLite(dbPath string) (*RateLimiter, error) {
|
||||||
// NewWithSQLiteConfig creates a SQLite-backed RateLimiter with custom config.
|
// NewWithSQLiteConfig creates a SQLite-backed RateLimiter with custom config.
|
||||||
// The Backend field in cfg is ignored (always "sqlite"). Use Close() to
|
// The Backend field in cfg is ignored (always "sqlite"). Use Close() to
|
||||||
// release the database connection when finished.
|
// release the database connection when finished.
|
||||||
|
//
|
||||||
|
// rl, err := NewWithSQLiteConfig("/tmp/ratelimits.db", Config{Providers: []Provider{ProviderOpenAI}})
|
||||||
func NewWithSQLiteConfig(dbPath string, cfg Config) (*RateLimiter, error) {
|
func NewWithSQLiteConfig(dbPath string, cfg Config) (*RateLimiter, error) {
|
||||||
store, err := newSQLiteStore(dbPath)
|
store, err := newSQLiteStore(dbPath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|
@ -588,6 +717,8 @@ func NewWithSQLiteConfig(dbPath string, cfg Config) (*RateLimiter, error) {
|
||||||
// Close releases resources held by the RateLimiter. For YAML-backed
|
// Close releases resources held by the RateLimiter. For YAML-backed
|
||||||
// limiters this is a no-op. For SQLite-backed limiters it closes the
|
// limiters this is a no-op. For SQLite-backed limiters it closes the
|
||||||
// database connection.
|
// database connection.
|
||||||
|
//
|
||||||
|
// defer rl.Close()
|
||||||
func (rl *RateLimiter) Close() error {
|
func (rl *RateLimiter) Close() error {
|
||||||
if rl.sqlite != nil {
|
if rl.sqlite != nil {
|
||||||
return rl.sqlite.close()
|
return rl.sqlite.close()
|
||||||
|
|
@ -598,16 +729,18 @@ func (rl *RateLimiter) Close() error {
|
||||||
// MigrateYAMLToSQLite reads state from a YAML file and writes it to a new
|
// MigrateYAMLToSQLite reads state from a YAML file and writes it to a new
|
||||||
// SQLite database. Both quotas and usage state are migrated. The SQLite
|
// SQLite database. Both quotas and usage state are migrated. The SQLite
|
||||||
// database is created if it does not exist.
|
// database is created if it does not exist.
|
||||||
|
//
|
||||||
|
// err := MigrateYAMLToSQLite("ratelimits.yaml", "ratelimits.db")
|
||||||
func MigrateYAMLToSQLite(yamlPath, sqlitePath string) error {
|
func MigrateYAMLToSQLite(yamlPath, sqlitePath string) error {
|
||||||
// Load from YAML.
|
// Load from YAML.
|
||||||
content, err := coreio.Local.Read(yamlPath)
|
content, err := readLocalFile(yamlPath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return coreerr.E("ratelimit.MigrateYAMLToSQLite", "read", err)
|
return core.E("ratelimit.MigrateYAMLToSQLite", "read", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
var rl RateLimiter
|
var rl RateLimiter
|
||||||
if err := yaml.Unmarshal([]byte(content), &rl); err != nil {
|
if err := yaml.Unmarshal([]byte(content), &rl); err != nil {
|
||||||
return coreerr.E("ratelimit.MigrateYAMLToSQLite", "unmarshal", err)
|
return core.E("ratelimit.MigrateYAMLToSQLite", "unmarshal", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Write to SQLite.
|
// Write to SQLite.
|
||||||
|
|
@ -624,6 +757,8 @@ func MigrateYAMLToSQLite(yamlPath, sqlitePath string) error {
|
||||||
}
|
}
|
||||||
|
|
||||||
// CountTokens calls the Google API to count tokens for a prompt.
|
// CountTokens calls the Google API to count tokens for a prompt.
|
||||||
|
//
|
||||||
|
// tokens, err := CountTokens(ctx, apiKey, "gemini-3-pro-preview", prompt)
|
||||||
func CountTokens(ctx context.Context, apiKey, model, text string) (int, error) {
|
func CountTokens(ctx context.Context, apiKey, model, text string) (int, error) {
|
||||||
return countTokensWithClient(ctx, http.DefaultClient, "https://generativelanguage.googleapis.com", apiKey, model, text)
|
return countTokensWithClient(ctx, http.DefaultClient, "https://generativelanguage.googleapis.com", apiKey, model, text)
|
||||||
}
|
}
|
||||||
|
|
@ -631,7 +766,7 @@ func CountTokens(ctx context.Context, apiKey, model, text string) (int, error) {
|
||||||
func countTokensWithClient(ctx context.Context, client *http.Client, baseURL, apiKey, model, text string) (int, error) {
|
func countTokensWithClient(ctx context.Context, client *http.Client, baseURL, apiKey, model, text string) (int, error) {
|
||||||
requestURL, err := countTokensURL(baseURL, model)
|
requestURL, err := countTokensURL(baseURL, model)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, coreerr.E("ratelimit.CountTokens", "build url", err)
|
return 0, core.E("ratelimit.CountTokens", "build url", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
reqBody := map[string]any{
|
reqBody := map[string]any{
|
||||||
|
|
@ -644,14 +779,14 @@ func countTokensWithClient(ctx context.Context, client *http.Client, baseURL, ap
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
jsonBody, err := json.Marshal(reqBody)
|
jsonBody := core.JSONMarshal(reqBody)
|
||||||
if err != nil {
|
if !jsonBody.OK {
|
||||||
return 0, coreerr.E("ratelimit.CountTokens", "marshal request", err)
|
return 0, core.E("ratelimit.CountTokens", "marshal request", resultError(jsonBody))
|
||||||
}
|
}
|
||||||
|
|
||||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, requestURL, bytes.NewReader(jsonBody))
|
req, err := http.NewRequestWithContext(ctx, http.MethodPost, requestURL, core.NewReader(string(jsonBody.Value.([]byte))))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, coreerr.E("ratelimit.CountTokens", "new request", err)
|
return 0, core.E("ratelimit.CountTokens", "new request", err)
|
||||||
}
|
}
|
||||||
req.Header.Set("Content-Type", "application/json")
|
req.Header.Set("Content-Type", "application/json")
|
||||||
req.Header.Set("x-goog-api-key", apiKey)
|
req.Header.Set("x-goog-api-key", apiKey)
|
||||||
|
|
@ -662,23 +797,29 @@ func countTokensWithClient(ctx context.Context, client *http.Client, baseURL, ap
|
||||||
|
|
||||||
resp, err := client.Do(req)
|
resp, err := client.Do(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, coreerr.E("ratelimit.CountTokens", "do request", err)
|
return 0, core.E("ratelimit.CountTokens", "do request", err)
|
||||||
}
|
}
|
||||||
defer resp.Body.Close()
|
defer resp.Body.Close()
|
||||||
|
|
||||||
if resp.StatusCode != http.StatusOK {
|
if resp.StatusCode != http.StatusOK {
|
||||||
body, err := readLimitedBody(resp.Body, countTokensErrorBodyLimit)
|
body, err := readLimitedBody(resp.Body, countTokensErrorBodyLimit)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, coreerr.E("ratelimit.CountTokens", "read error body", err)
|
return 0, core.E("ratelimit.CountTokens", "read error body", err)
|
||||||
}
|
}
|
||||||
return 0, coreerr.E("ratelimit.CountTokens", fmt.Sprintf("api error status %d: %s", resp.StatusCode, body), nil)
|
return 0, core.E("ratelimit.CountTokens", core.Sprintf("api error status %d: %s", resp.StatusCode, body), nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
body, err := readLimitedBody(resp.Body, countTokensSuccessBodyLimit)
|
||||||
|
if err != nil {
|
||||||
|
return 0, core.E("ratelimit.CountTokens", "decode response", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
var result struct {
|
var result struct {
|
||||||
TotalTokens int `json:"totalTokens"`
|
TotalTokens int `json:"totalTokens"`
|
||||||
}
|
}
|
||||||
if err := json.NewDecoder(io.LimitReader(resp.Body, countTokensSuccessBodyLimit)).Decode(&result); err != nil {
|
decode := core.JSONUnmarshalString(body, &result)
|
||||||
return 0, coreerr.E("ratelimit.CountTokens", "decode response", err)
|
if !decode.OK {
|
||||||
|
return 0, core.E("ratelimit.CountTokens", "decode response", resultError(decode))
|
||||||
}
|
}
|
||||||
|
|
||||||
return result.TotalTokens, nil
|
return result.TotalTokens, nil
|
||||||
|
|
@ -693,6 +834,15 @@ func newConfiguredRateLimiter(cfg Config) *RateLimiter {
|
||||||
return rl
|
return rl
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func ensureMaps(rl *RateLimiter) {
|
||||||
|
if rl.Quotas == nil {
|
||||||
|
rl.Quotas = make(map[string]ModelQuota)
|
||||||
|
}
|
||||||
|
if rl.State == nil {
|
||||||
|
rl.State = make(map[string]*UsageStats)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func applyConfig(rl *RateLimiter, cfg Config) {
|
func applyConfig(rl *RateLimiter, cfg Config) {
|
||||||
profiles := DefaultProfiles()
|
profiles := DefaultProfiles()
|
||||||
providers := cfg.Providers
|
providers := cfg.Providers
|
||||||
|
|
@ -711,20 +861,20 @@ func applyConfig(rl *RateLimiter, cfg Config) {
|
||||||
}
|
}
|
||||||
|
|
||||||
func normaliseBackend(backend string) (string, error) {
|
func normaliseBackend(backend string) (string, error) {
|
||||||
switch strings.ToLower(strings.TrimSpace(backend)) {
|
switch core.Lower(core.Trim(backend)) {
|
||||||
case "", backendYAML:
|
case "", backendYAML:
|
||||||
return backendYAML, nil
|
return backendYAML, nil
|
||||||
case backendSQLite:
|
case backendSQLite:
|
||||||
return backendSQLite, nil
|
return backendSQLite, nil
|
||||||
default:
|
default:
|
||||||
return "", coreerr.E("ratelimit.NewWithConfig", fmt.Sprintf("unknown backend %q", backend), nil)
|
return "", core.E("ratelimit.NewWithConfig", core.Sprintf("unknown backend %q", backend), nil)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func defaultStatePath(backend string) (string, error) {
|
func defaultStatePath(backend string) (string, error) {
|
||||||
home, err := os.UserHomeDir()
|
home := currentHomeDir()
|
||||||
if err != nil {
|
if home == "" {
|
||||||
return "", err
|
return "", core.E("ratelimit.defaultStatePath", "home dir unavailable", nil)
|
||||||
}
|
}
|
||||||
|
|
||||||
fileName := defaultYAMLStateFile
|
fileName := defaultYAMLStateFile
|
||||||
|
|
@ -732,7 +882,16 @@ func defaultStatePath(backend string) (string, error) {
|
||||||
fileName = defaultSQLiteStateFile
|
fileName = defaultSQLiteStateFile
|
||||||
}
|
}
|
||||||
|
|
||||||
return filepath.Join(home, defaultStateDirName, fileName), nil
|
return core.Path(home, defaultStateDirName, fileName), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func currentHomeDir() string {
|
||||||
|
for _, key := range []string{"CORE_HOME", "HOME", "home", "USERPROFILE"} {
|
||||||
|
if value := core.Trim(core.Env(key)); value != "" {
|
||||||
|
return value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
func safeTokenSum(a, b int) int {
|
func safeTokenSum(a, b int) int {
|
||||||
|
|
@ -760,9 +919,40 @@ func safeTokenTotal(tokens []TokenEntry) int {
|
||||||
return total
|
return total
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func retryAfterForTokens(now time.Time, tokens []TokenEntry, maxTPM, estimatedTokens int) time.Duration {
|
||||||
|
if maxTPM <= 0 {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
deficit := totalTokenCount(tokens) + estimatedTokens - maxTPM
|
||||||
|
if deficit <= 0 {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
remaining := deficit
|
||||||
|
for _, entry := range tokens {
|
||||||
|
if entry.Count < 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
remaining -= entry.Count
|
||||||
|
if remaining <= 0 {
|
||||||
|
return nonNegativeDuration(entry.Time.Add(time.Minute).Sub(now))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func nonNegativeDuration(value time.Duration) time.Duration {
|
||||||
|
if value < 0 {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
return value
|
||||||
|
}
|
||||||
|
|
||||||
func countTokensURL(baseURL, model string) (string, error) {
|
func countTokensURL(baseURL, model string) (string, error) {
|
||||||
if strings.TrimSpace(model) == "" {
|
if core.Trim(model) == "" {
|
||||||
return "", fmt.Errorf("empty model")
|
return "", core.E("ratelimit.countTokensURL", "empty model", nil)
|
||||||
}
|
}
|
||||||
|
|
||||||
parsed, err := url.Parse(baseURL)
|
parsed, err := url.Parse(baseURL)
|
||||||
|
|
@ -770,10 +960,10 @@ func countTokensURL(baseURL, model string) (string, error) {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
if parsed.Scheme == "" || parsed.Host == "" {
|
if parsed.Scheme == "" || parsed.Host == "" {
|
||||||
return "", fmt.Errorf("invalid base url")
|
return "", core.E("ratelimit.countTokensURL", "invalid base url", nil)
|
||||||
}
|
}
|
||||||
|
|
||||||
return strings.TrimRight(parsed.String(), "/") + "/v1beta/models/" + url.PathEscape(model) + ":countTokens", nil
|
return core.Concat(core.TrimSuffix(parsed.String(), "/"), "/v1beta/models/", url.PathEscape(model), ":countTokens"), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func readLimitedBody(r io.Reader, limit int64) (string, error) {
|
func readLimitedBody(r io.Reader, limit int64) (string, error) {
|
||||||
|
|
@ -793,3 +983,40 @@ func readLimitedBody(r io.Reader, limit int64) (string, error) {
|
||||||
}
|
}
|
||||||
return result, nil
|
return result, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func readLocalFile(path string) (string, error) {
|
||||||
|
var fs core.Fs
|
||||||
|
result := fs.Read(path)
|
||||||
|
if !result.OK {
|
||||||
|
return "", resultError(result)
|
||||||
|
}
|
||||||
|
|
||||||
|
content, ok := result.Value.(string)
|
||||||
|
if !ok {
|
||||||
|
return "", core.E("ratelimit.readLocalFile", "read returned non-string", nil)
|
||||||
|
}
|
||||||
|
return content, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeLocalFile(path, content string) error {
|
||||||
|
var fs core.Fs
|
||||||
|
return resultError(fs.Write(path, content))
|
||||||
|
}
|
||||||
|
|
||||||
|
func ensureDir(path string) error {
|
||||||
|
var fs core.Fs
|
||||||
|
return resultError(fs.EnsureDir(path))
|
||||||
|
}
|
||||||
|
|
||||||
|
func resultError(result core.Result) error {
|
||||||
|
if result.OK {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if err, ok := result.Value.(error); ok {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if result.Value == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return core.E("ratelimit.resultError", core.Sprint(result.Value), nil)
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,29 +1,95 @@
|
||||||
|
// SPDX-License-Identifier: EUPL-1.2
|
||||||
|
|
||||||
package ratelimit
|
package ratelimit
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/http/httptest"
|
"net/http/httptest"
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
"strings"
|
|
||||||
"sync"
|
"sync"
|
||||||
|
"syscall"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
core "dappco.re/go/core"
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
"github.com/stretchr/testify/require"
|
"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.
|
// newTestLimiter returns a RateLimiter with file path set to a temp directory.
|
||||||
func newTestLimiter(t *testing.T) *RateLimiter {
|
func newTestLimiter(t *testing.T) *RateLimiter {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
rl, err := New()
|
rl, err := New()
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
rl.filePath = filepath.Join(t.TempDir(), "ratelimits.yaml")
|
rl.filePath = testPath(t.TempDir(), "ratelimits.yaml")
|
||||||
return rl
|
return rl
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -41,7 +107,7 @@ func (errReader) Read([]byte) (int, error) {
|
||||||
|
|
||||||
// --- Phase 0: CanSend boundary conditions ---
|
// --- Phase 0: CanSend boundary conditions ---
|
||||||
|
|
||||||
func TestCanSend(t *testing.T) {
|
func TestRatelimit_CanSend_Good(t *testing.T) {
|
||||||
t.Run("fresh state allows send", func(t *testing.T) {
|
t.Run("fresh state allows send", func(t *testing.T) {
|
||||||
rl := newTestLimiter(t)
|
rl := newTestLimiter(t)
|
||||||
model := "test-model"
|
model := "test-model"
|
||||||
|
|
@ -187,9 +253,133 @@ func TestCanSend(t *testing.T) {
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --- 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 ---
|
// --- Phase 0: Sliding window / prune tests ---
|
||||||
|
|
||||||
func TestPrune(t *testing.T) {
|
func TestRatelimit_Prune_Good(t *testing.T) {
|
||||||
t.Run("removes old entries", func(t *testing.T) {
|
t.Run("removes old entries", func(t *testing.T) {
|
||||||
rl := newTestLimiter(t)
|
rl := newTestLimiter(t)
|
||||||
model := "test-prune"
|
model := "test-prune"
|
||||||
|
|
@ -304,7 +494,7 @@ func TestPrune(t *testing.T) {
|
||||||
|
|
||||||
// --- Phase 0: RecordUsage ---
|
// --- Phase 0: RecordUsage ---
|
||||||
|
|
||||||
func TestRecordUsage(t *testing.T) {
|
func TestRatelimit_RecordUsage_Good(t *testing.T) {
|
||||||
t.Run("records into fresh state", func(t *testing.T) {
|
t.Run("records into fresh state", func(t *testing.T) {
|
||||||
rl := newTestLimiter(t)
|
rl := newTestLimiter(t)
|
||||||
model := "record-fresh"
|
model := "record-fresh"
|
||||||
|
|
@ -375,7 +565,7 @@ func TestRecordUsage(t *testing.T) {
|
||||||
|
|
||||||
// --- Phase 0: Reset ---
|
// --- Phase 0: Reset ---
|
||||||
|
|
||||||
func TestReset(t *testing.T) {
|
func TestRatelimit_Reset_Good(t *testing.T) {
|
||||||
t.Run("reset single model", func(t *testing.T) {
|
t.Run("reset single model", func(t *testing.T) {
|
||||||
rl := newTestLimiter(t)
|
rl := newTestLimiter(t)
|
||||||
rl.RecordUsage("model-a", 10, 10)
|
rl.RecordUsage("model-a", 10, 10)
|
||||||
|
|
@ -409,7 +599,7 @@ func TestReset(t *testing.T) {
|
||||||
|
|
||||||
// --- Phase 0: WaitForCapacity ---
|
// --- Phase 0: WaitForCapacity ---
|
||||||
|
|
||||||
func TestWaitForCapacity(t *testing.T) {
|
func TestRatelimit_WaitForCapacity_Good(t *testing.T) {
|
||||||
t.Run("context cancelled returns error", func(t *testing.T) {
|
t.Run("context cancelled returns error", func(t *testing.T) {
|
||||||
rl := newTestLimiter(t)
|
rl := newTestLimiter(t)
|
||||||
model := "wait-cancel"
|
model := "wait-cancel"
|
||||||
|
|
@ -467,7 +657,7 @@ func TestWaitForCapacity(t *testing.T) {
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestNilUsageStats(t *testing.T) {
|
func TestRatelimit_NilUsageStats_Ugly(t *testing.T) {
|
||||||
t.Run("CanSend replaces nil state without panicking", func(t *testing.T) {
|
t.Run("CanSend replaces nil state without panicking", func(t *testing.T) {
|
||||||
rl := newTestLimiter(t)
|
rl := newTestLimiter(t)
|
||||||
model := "nil-cansend"
|
model := "nil-cansend"
|
||||||
|
|
@ -514,7 +704,7 @@ func TestNilUsageStats(t *testing.T) {
|
||||||
|
|
||||||
// --- Phase 0: Stats ---
|
// --- Phase 0: Stats ---
|
||||||
|
|
||||||
func TestStats(t *testing.T) {
|
func TestRatelimit_Stats_Good(t *testing.T) {
|
||||||
t.Run("returns stats for known model with usage", func(t *testing.T) {
|
t.Run("returns stats for known model with usage", func(t *testing.T) {
|
||||||
rl := newTestLimiter(t)
|
rl := newTestLimiter(t)
|
||||||
model := "stats-test"
|
model := "stats-test"
|
||||||
|
|
@ -554,7 +744,7 @@ func TestStats(t *testing.T) {
|
||||||
|
|
||||||
// --- Phase 0: AllStats ---
|
// --- Phase 0: AllStats ---
|
||||||
|
|
||||||
func TestAllStats(t *testing.T) {
|
func TestRatelimit_AllStats_Good(t *testing.T) {
|
||||||
t.Run("includes all default quotas plus state-only models", func(t *testing.T) {
|
t.Run("includes all default quotas plus state-only models", func(t *testing.T) {
|
||||||
rl := newTestLimiter(t)
|
rl := newTestLimiter(t)
|
||||||
rl.RecordUsage("gemini-3-pro-preview", 1000, 500)
|
rl.RecordUsage("gemini-3-pro-preview", 1000, 500)
|
||||||
|
|
@ -612,10 +802,10 @@ func TestAllStats(t *testing.T) {
|
||||||
|
|
||||||
// --- Phase 0: Persist and Load ---
|
// --- Phase 0: Persist and Load ---
|
||||||
|
|
||||||
func TestPersistAndLoad(t *testing.T) {
|
func TestRatelimit_PersistAndLoad_Ugly(t *testing.T) {
|
||||||
t.Run("round-trip preserves state", func(t *testing.T) {
|
t.Run("round-trip preserves state", func(t *testing.T) {
|
||||||
tmpDir := t.TempDir()
|
tmpDir := t.TempDir()
|
||||||
path := filepath.Join(tmpDir, "ratelimits.yaml")
|
path := testPath(tmpDir, "ratelimits.yaml")
|
||||||
|
|
||||||
rl1, err := New()
|
rl1, err := New()
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
@ -638,7 +828,7 @@ func TestPersistAndLoad(t *testing.T) {
|
||||||
|
|
||||||
t.Run("load from non-existent file is not an error", func(t *testing.T) {
|
t.Run("load from non-existent file is not an error", func(t *testing.T) {
|
||||||
rl := newTestLimiter(t)
|
rl := newTestLimiter(t)
|
||||||
rl.filePath = filepath.Join(t.TempDir(), "does-not-exist.yaml")
|
rl.filePath = testPath(t.TempDir(), "does-not-exist.yaml")
|
||||||
|
|
||||||
err := rl.Load()
|
err := rl.Load()
|
||||||
assert.NoError(t, err, "loading non-existent file should not error")
|
assert.NoError(t, err, "loading non-existent file should not error")
|
||||||
|
|
@ -646,8 +836,8 @@ func TestPersistAndLoad(t *testing.T) {
|
||||||
|
|
||||||
t.Run("load from corrupt YAML returns error", func(t *testing.T) {
|
t.Run("load from corrupt YAML returns error", func(t *testing.T) {
|
||||||
tmpDir := t.TempDir()
|
tmpDir := t.TempDir()
|
||||||
path := filepath.Join(tmpDir, "corrupt.yaml")
|
path := testPath(tmpDir, "corrupt.yaml")
|
||||||
require.NoError(t, os.WriteFile(path, []byte("{{{{invalid yaml!!!!"), 0644))
|
writeTestFile(t, path, "{{{{invalid yaml!!!!")
|
||||||
|
|
||||||
rl := newTestLimiter(t)
|
rl := newTestLimiter(t)
|
||||||
rl.filePath = path
|
rl.filePath = path
|
||||||
|
|
@ -657,13 +847,13 @@ func TestPersistAndLoad(t *testing.T) {
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("load from unreadable file returns error", func(t *testing.T) {
|
t.Run("load from unreadable file returns error", func(t *testing.T) {
|
||||||
if os.Getuid() == 0 {
|
if isRootUser() {
|
||||||
t.Skip("chmod 000 does not restrict root")
|
t.Skip("chmod 000 does not restrict root")
|
||||||
}
|
}
|
||||||
tmpDir := t.TempDir()
|
tmpDir := t.TempDir()
|
||||||
path := filepath.Join(tmpDir, "unreadable.yaml")
|
path := testPath(tmpDir, "unreadable.yaml")
|
||||||
require.NoError(t, os.WriteFile(path, []byte("quotas: {}"), 0644))
|
writeTestFile(t, path, "quotas: {}")
|
||||||
require.NoError(t, os.Chmod(path, 0000))
|
setPathMode(t, path, 0o000)
|
||||||
|
|
||||||
rl := newTestLimiter(t)
|
rl := newTestLimiter(t)
|
||||||
rl.filePath = path
|
rl.filePath = path
|
||||||
|
|
@ -672,12 +862,12 @@ func TestPersistAndLoad(t *testing.T) {
|
||||||
assert.Error(t, err, "unreadable file should produce an error")
|
assert.Error(t, err, "unreadable file should produce an error")
|
||||||
|
|
||||||
// Clean up permissions for temp dir cleanup
|
// Clean up permissions for temp dir cleanup
|
||||||
_ = os.Chmod(path, 0644)
|
_ = syscall.Chmod(path, 0o644)
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("persist to nested non-existent directory creates it", func(t *testing.T) {
|
t.Run("persist to nested non-existent directory creates it", func(t *testing.T) {
|
||||||
tmpDir := t.TempDir()
|
tmpDir := t.TempDir()
|
||||||
path := filepath.Join(tmpDir, "nested", "deep", "ratelimits.yaml")
|
path := testPath(tmpDir, "nested", "deep", "ratelimits.yaml")
|
||||||
|
|
||||||
rl := newTestLimiter(t)
|
rl := newTestLimiter(t)
|
||||||
rl.filePath = path
|
rl.filePath = path
|
||||||
|
|
@ -686,32 +876,32 @@ func TestPersistAndLoad(t *testing.T) {
|
||||||
err := rl.Persist()
|
err := rl.Persist()
|
||||||
assert.NoError(t, err, "should create nested directories")
|
assert.NoError(t, err, "should create nested directories")
|
||||||
|
|
||||||
_, statErr := os.Stat(path)
|
assert.True(t, pathExists(path), "file should exist")
|
||||||
assert.NoError(t, statErr, "file should exist")
|
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("persist to unwritable directory returns error", func(t *testing.T) {
|
t.Run("persist to unwritable directory returns error", func(t *testing.T) {
|
||||||
if os.Getuid() == 0 {
|
if isRootUser() {
|
||||||
t.Skip("chmod 0555 does not restrict root")
|
t.Skip("chmod 0555 does not restrict root")
|
||||||
}
|
}
|
||||||
tmpDir := t.TempDir()
|
tmpDir := t.TempDir()
|
||||||
unwritable := filepath.Join(tmpDir, "readonly")
|
unwritable := testPath(tmpDir, "readonly")
|
||||||
require.NoError(t, os.MkdirAll(unwritable, 0555))
|
ensureTestDir(t, unwritable)
|
||||||
|
setPathMode(t, unwritable, 0o555)
|
||||||
|
|
||||||
rl := newTestLimiter(t)
|
rl := newTestLimiter(t)
|
||||||
rl.filePath = filepath.Join(unwritable, "sub", "ratelimits.yaml")
|
rl.filePath = testPath(unwritable, "sub", "ratelimits.yaml")
|
||||||
|
|
||||||
err := rl.Persist()
|
err := rl.Persist()
|
||||||
assert.Error(t, err, "should fail when directory is unwritable")
|
assert.Error(t, err, "should fail when directory is unwritable")
|
||||||
|
|
||||||
// Clean up
|
// Clean up
|
||||||
_ = os.Chmod(unwritable, 0755)
|
_ = syscall.Chmod(unwritable, 0o755)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- Phase 0: Default quotas ---
|
// --- Phase 0: Default quotas ---
|
||||||
|
|
||||||
func TestDefaultQuotas(t *testing.T) {
|
func TestRatelimit_DefaultQuotas_Good(t *testing.T) {
|
||||||
rl := newTestLimiter(t)
|
rl := newTestLimiter(t)
|
||||||
|
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
|
|
@ -740,7 +930,7 @@ func TestDefaultQuotas(t *testing.T) {
|
||||||
|
|
||||||
// --- Phase 0: Concurrent access (race test) ---
|
// --- Phase 0: Concurrent access (race test) ---
|
||||||
|
|
||||||
func TestConcurrentAccess(t *testing.T) {
|
func TestRatelimit_ConcurrentAccess_Good(t *testing.T) {
|
||||||
rl := newTestLimiter(t)
|
rl := newTestLimiter(t)
|
||||||
model := "concurrent-test"
|
model := "concurrent-test"
|
||||||
rl.Quotas[model] = ModelQuota{MaxRPM: 1000, MaxTPM: 10000000, MaxRPD: 10000}
|
rl.Quotas[model] = ModelQuota{MaxRPM: 1000, MaxTPM: 10000000, MaxRPD: 10000}
|
||||||
|
|
@ -766,7 +956,7 @@ func TestConcurrentAccess(t *testing.T) {
|
||||||
assert.Equal(t, expected, stats.RPD, "all recordings should be counted")
|
assert.Equal(t, expected, stats.RPD, "all recordings should be counted")
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestConcurrentResetAndRecord(t *testing.T) {
|
func TestRatelimit_ConcurrentResetAndRecord_Ugly(t *testing.T) {
|
||||||
rl := newTestLimiter(t)
|
rl := newTestLimiter(t)
|
||||||
model := "concurrent-reset"
|
model := "concurrent-reset"
|
||||||
rl.Quotas[model] = ModelQuota{MaxRPM: 10000, MaxTPM: 100000000, MaxRPD: 100000}
|
rl.Quotas[model] = ModelQuota{MaxRPM: 10000, MaxTPM: 100000000, MaxRPD: 100000}
|
||||||
|
|
@ -804,7 +994,7 @@ func TestConcurrentResetAndRecord(t *testing.T) {
|
||||||
// No assertion needed -- if we get here without -race flagging, mutex is sound
|
// No assertion needed -- if we get here without -race flagging, mutex is sound
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestBackgroundPrune(t *testing.T) {
|
func TestRatelimit_BackgroundPrune_Good(t *testing.T) {
|
||||||
rl := newTestLimiter(t)
|
rl := newTestLimiter(t)
|
||||||
model := "prune-me"
|
model := "prune-me"
|
||||||
rl.Quotas[model] = ModelQuota{MaxRPM: 100}
|
rl.Quotas[model] = ModelQuota{MaxRPM: 100}
|
||||||
|
|
@ -843,7 +1033,7 @@ func TestBackgroundPrune(t *testing.T) {
|
||||||
|
|
||||||
// --- Phase 0: CountTokens (with mock HTTP server) ---
|
// --- Phase 0: CountTokens (with mock HTTP server) ---
|
||||||
|
|
||||||
func TestCountTokens(t *testing.T) {
|
func TestRatelimit_CountTokens_Ugly(t *testing.T) {
|
||||||
t.Run("successful token count", func(t *testing.T) {
|
t.Run("successful token count", func(t *testing.T) {
|
||||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
assert.Equal(t, http.MethodPost, r.Method)
|
assert.Equal(t, http.MethodPost, r.Method)
|
||||||
|
|
@ -858,13 +1048,13 @@ func TestCountTokens(t *testing.T) {
|
||||||
} `json:"parts"`
|
} `json:"parts"`
|
||||||
} `json:"contents"`
|
} `json:"contents"`
|
||||||
}
|
}
|
||||||
require.NoError(t, json.NewDecoder(r.Body).Decode(&body))
|
decodeJSONBody(t, r.Body, &body)
|
||||||
require.Len(t, body.Contents, 1)
|
require.Len(t, body.Contents, 1)
|
||||||
require.Len(t, body.Contents[0].Parts, 1)
|
require.Len(t, body.Contents[0].Parts, 1)
|
||||||
assert.Equal(t, "hello", body.Contents[0].Parts[0].Text)
|
assert.Equal(t, "hello", body.Contents[0].Parts[0].Text)
|
||||||
|
|
||||||
w.Header().Set("Content-Type", "application/json")
|
w.Header().Set("Content-Type", "application/json")
|
||||||
require.NoError(t, json.NewEncoder(w).Encode(map[string]int{"totalTokens": 42}))
|
writeJSONBody(t, w, map[string]int{"totalTokens": 42})
|
||||||
}))
|
}))
|
||||||
defer server.Close()
|
defer server.Close()
|
||||||
|
|
||||||
|
|
@ -878,7 +1068,7 @@ func TestCountTokens(t *testing.T) {
|
||||||
assert.Equal(t, "/v1beta/models/folder%2Fmodel%3Fdebug=1:countTokens", r.URL.EscapedPath())
|
assert.Equal(t, "/v1beta/models/folder%2Fmodel%3Fdebug=1:countTokens", r.URL.EscapedPath())
|
||||||
assert.Empty(t, r.URL.RawQuery)
|
assert.Empty(t, r.URL.RawQuery)
|
||||||
w.Header().Set("Content-Type", "application/json")
|
w.Header().Set("Content-Type", "application/json")
|
||||||
require.NoError(t, json.NewEncoder(w).Encode(map[string]int{"totalTokens": 7}))
|
writeJSONBody(t, w, map[string]int{"totalTokens": 7})
|
||||||
}))
|
}))
|
||||||
defer server.Close()
|
defer server.Close()
|
||||||
|
|
||||||
|
|
@ -888,10 +1078,10 @@ func TestCountTokens(t *testing.T) {
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("API error body is truncated", func(t *testing.T) {
|
t.Run("API error body is truncated", func(t *testing.T) {
|
||||||
largeBody := strings.Repeat("x", countTokensErrorBodyLimit+256)
|
largeBody := repeatString("x", countTokensErrorBodyLimit+256)
|
||||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
w.WriteHeader(http.StatusUnauthorized)
|
w.WriteHeader(http.StatusUnauthorized)
|
||||||
_, err := fmt.Fprint(w, largeBody)
|
_, err := io.WriteString(w, largeBody)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
}))
|
}))
|
||||||
defer server.Close()
|
defer server.Close()
|
||||||
|
|
@ -899,7 +1089,7 @@ func TestCountTokens(t *testing.T) {
|
||||||
_, err := countTokensWithClient(context.Background(), server.Client(), server.URL, "fake-key", "test-model", "hello")
|
_, err := countTokensWithClient(context.Background(), server.Client(), server.URL, "fake-key", "test-model", "hello")
|
||||||
require.Error(t, err)
|
require.Error(t, err)
|
||||||
assert.Contains(t, err.Error(), "api error status 401")
|
assert.Contains(t, err.Error(), "api error status 401")
|
||||||
assert.True(t, strings.Count(err.Error(), "x") < len(largeBody), "error body should be bounded")
|
assert.True(t, substringCount(err.Error(), "x") < len(largeBody), "error body should be bounded")
|
||||||
assert.Contains(t, err.Error(), "...")
|
assert.Contains(t, err.Error(), "...")
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
@ -953,7 +1143,7 @@ func TestCountTokens(t *testing.T) {
|
||||||
t.Run("nil client falls back to http.DefaultClient", func(t *testing.T) {
|
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) {
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
w.Header().Set("Content-Type", "application/json")
|
w.Header().Set("Content-Type", "application/json")
|
||||||
require.NoError(t, json.NewEncoder(w).Encode(map[string]int{"totalTokens": 11}))
|
writeJSONBody(t, w, map[string]int{"totalTokens": 11})
|
||||||
}))
|
}))
|
||||||
defer server.Close()
|
defer server.Close()
|
||||||
|
|
||||||
|
|
@ -969,8 +1159,8 @@ func TestCountTokens(t *testing.T) {
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestPersistSkipsNilState(t *testing.T) {
|
func TestRatelimit_PersistSkipsNilState_Good(t *testing.T) {
|
||||||
path := filepath.Join(t.TempDir(), "nil-state.yaml")
|
path := testPath(t.TempDir(), "nil-state.yaml")
|
||||||
|
|
||||||
rl, err := New()
|
rl, err := New()
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
@ -986,7 +1176,7 @@ func TestPersistSkipsNilState(t *testing.T) {
|
||||||
assert.NotContains(t, rl2.State, "nil-model")
|
assert.NotContains(t, rl2.State, "nil-model")
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestTokenTotals(t *testing.T) {
|
func TestRatelimit_TokenTotals_Good(t *testing.T) {
|
||||||
maxInt := int(^uint(0) >> 1)
|
maxInt := int(^uint(0) >> 1)
|
||||||
|
|
||||||
assert.Equal(t, 25, safeTokenSum(-100, 25))
|
assert.Equal(t, 25, safeTokenSum(-100, 25))
|
||||||
|
|
@ -1056,7 +1246,7 @@ func BenchmarkCanSendConcurrent(b *testing.B) {
|
||||||
|
|
||||||
// --- Phase 1: Provider profiles and NewWithConfig ---
|
// --- Phase 1: Provider profiles and NewWithConfig ---
|
||||||
|
|
||||||
func TestDefaultProfiles(t *testing.T) {
|
func TestRatelimit_DefaultProfiles_Good(t *testing.T) {
|
||||||
profiles := DefaultProfiles()
|
profiles := DefaultProfiles()
|
||||||
|
|
||||||
t.Run("contains all four providers", func(t *testing.T) {
|
t.Run("contains all four providers", func(t *testing.T) {
|
||||||
|
|
@ -1097,10 +1287,10 @@ func TestDefaultProfiles(t *testing.T) {
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestNewWithConfig(t *testing.T) {
|
func TestRatelimit_NewWithConfig_Ugly(t *testing.T) {
|
||||||
t.Run("empty config defaults to Gemini", func(t *testing.T) {
|
t.Run("empty config defaults to Gemini", func(t *testing.T) {
|
||||||
rl, err := NewWithConfig(Config{
|
rl, err := NewWithConfig(Config{
|
||||||
FilePath: filepath.Join(t.TempDir(), "test.yaml"),
|
FilePath: testPath(t.TempDir(), "test.yaml"),
|
||||||
})
|
})
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
|
@ -1110,7 +1300,7 @@ func TestNewWithConfig(t *testing.T) {
|
||||||
|
|
||||||
t.Run("single provider loads only its models", func(t *testing.T) {
|
t.Run("single provider loads only its models", func(t *testing.T) {
|
||||||
rl, err := NewWithConfig(Config{
|
rl, err := NewWithConfig(Config{
|
||||||
FilePath: filepath.Join(t.TempDir(), "test.yaml"),
|
FilePath: testPath(t.TempDir(), "test.yaml"),
|
||||||
Providers: []Provider{ProviderOpenAI},
|
Providers: []Provider{ProviderOpenAI},
|
||||||
})
|
})
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
@ -1124,7 +1314,7 @@ func TestNewWithConfig(t *testing.T) {
|
||||||
|
|
||||||
t.Run("multiple providers merge models", func(t *testing.T) {
|
t.Run("multiple providers merge models", func(t *testing.T) {
|
||||||
rl, err := NewWithConfig(Config{
|
rl, err := NewWithConfig(Config{
|
||||||
FilePath: filepath.Join(t.TempDir(), "test.yaml"),
|
FilePath: testPath(t.TempDir(), "test.yaml"),
|
||||||
Providers: []Provider{ProviderGemini, ProviderAnthropic},
|
Providers: []Provider{ProviderGemini, ProviderAnthropic},
|
||||||
})
|
})
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
@ -1140,7 +1330,7 @@ func TestNewWithConfig(t *testing.T) {
|
||||||
|
|
||||||
t.Run("explicit quotas override provider defaults", func(t *testing.T) {
|
t.Run("explicit quotas override provider defaults", func(t *testing.T) {
|
||||||
rl, err := NewWithConfig(Config{
|
rl, err := NewWithConfig(Config{
|
||||||
FilePath: filepath.Join(t.TempDir(), "test.yaml"),
|
FilePath: testPath(t.TempDir(), "test.yaml"),
|
||||||
Providers: []Provider{ProviderGemini},
|
Providers: []Provider{ProviderGemini},
|
||||||
Quotas: map[string]ModelQuota{
|
Quotas: map[string]ModelQuota{
|
||||||
"gemini-3-pro-preview": {MaxRPM: 999, MaxTPM: 888, MaxRPD: 777},
|
"gemini-3-pro-preview": {MaxRPM: 999, MaxTPM: 888, MaxRPD: 777},
|
||||||
|
|
@ -1156,7 +1346,7 @@ func TestNewWithConfig(t *testing.T) {
|
||||||
|
|
||||||
t.Run("explicit quotas without providers", func(t *testing.T) {
|
t.Run("explicit quotas without providers", func(t *testing.T) {
|
||||||
rl, err := NewWithConfig(Config{
|
rl, err := NewWithConfig(Config{
|
||||||
FilePath: filepath.Join(t.TempDir(), "test.yaml"),
|
FilePath: testPath(t.TempDir(), "test.yaml"),
|
||||||
Quotas: map[string]ModelQuota{
|
Quotas: map[string]ModelQuota{
|
||||||
"my-custom-model": {MaxRPM: 10, MaxTPM: 1000, MaxRPD: 50},
|
"my-custom-model": {MaxRPM: 10, MaxTPM: 1000, MaxRPD: 50},
|
||||||
},
|
},
|
||||||
|
|
@ -1169,7 +1359,7 @@ func TestNewWithConfig(t *testing.T) {
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("custom file path is respected", func(t *testing.T) {
|
t.Run("custom file path is respected", func(t *testing.T) {
|
||||||
customPath := filepath.Join(t.TempDir(), "custom", "limits.yaml")
|
customPath := testPath(t.TempDir(), "custom", "limits.yaml")
|
||||||
rl, err := NewWithConfig(Config{
|
rl, err := NewWithConfig(Config{
|
||||||
FilePath: customPath,
|
FilePath: customPath,
|
||||||
Providers: []Provider{ProviderLocal},
|
Providers: []Provider{ProviderLocal},
|
||||||
|
|
@ -1179,13 +1369,12 @@ func TestNewWithConfig(t *testing.T) {
|
||||||
rl.RecordUsage("test", 1, 1)
|
rl.RecordUsage("test", 1, 1)
|
||||||
require.NoError(t, rl.Persist())
|
require.NoError(t, rl.Persist())
|
||||||
|
|
||||||
_, statErr := os.Stat(customPath)
|
assert.True(t, pathExists(customPath), "file should be created at custom path")
|
||||||
assert.NoError(t, statErr, "file should be created at custom path")
|
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("unknown provider is silently skipped", func(t *testing.T) {
|
t.Run("unknown provider is silently skipped", func(t *testing.T) {
|
||||||
rl, err := NewWithConfig(Config{
|
rl, err := NewWithConfig(Config{
|
||||||
FilePath: filepath.Join(t.TempDir(), "test.yaml"),
|
FilePath: testPath(t.TempDir(), "test.yaml"),
|
||||||
Providers: []Provider{"nonexistent-provider"},
|
Providers: []Provider{"nonexistent-provider"},
|
||||||
})
|
})
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
@ -1194,7 +1383,7 @@ func TestNewWithConfig(t *testing.T) {
|
||||||
|
|
||||||
t.Run("local provider with custom quotas", func(t *testing.T) {
|
t.Run("local provider with custom quotas", func(t *testing.T) {
|
||||||
rl, err := NewWithConfig(Config{
|
rl, err := NewWithConfig(Config{
|
||||||
FilePath: filepath.Join(t.TempDir(), "test.yaml"),
|
FilePath: testPath(t.TempDir(), "test.yaml"),
|
||||||
Providers: []Provider{ProviderLocal},
|
Providers: []Provider{ProviderLocal},
|
||||||
Quotas: map[string]ModelQuota{
|
Quotas: map[string]ModelQuota{
|
||||||
"llama-3.3-70b": {MaxRPM: 5, MaxTPM: 50000, MaxRPD: 0},
|
"llama-3.3-70b": {MaxRPM: 5, MaxTPM: 50000, MaxRPD: 0},
|
||||||
|
|
@ -1224,11 +1413,11 @@ func TestNewWithConfig(t *testing.T) {
|
||||||
|
|
||||||
rl, err := NewWithConfig(Config{})
|
rl, err := NewWithConfig(Config{})
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
assert.Equal(t, filepath.Join(home, defaultStateDirName, defaultYAMLStateFile), rl.filePath)
|
assert.Equal(t, testPath(home, defaultStateDirName, defaultYAMLStateFile), rl.filePath)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestNewBackwardCompatibility(t *testing.T) {
|
func TestRatelimit_NewBackwardCompatibility_Good(t *testing.T) {
|
||||||
// New() should produce the exact same result as before Phase 1
|
// New() should produce the exact same result as before Phase 1
|
||||||
rl, err := New()
|
rl, err := New()
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
@ -1251,7 +1440,7 @@ func TestNewBackwardCompatibility(t *testing.T) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSetQuota(t *testing.T) {
|
func TestRatelimit_SetQuota_Good(t *testing.T) {
|
||||||
t.Run("adds new model quota", func(t *testing.T) {
|
t.Run("adds new model quota", func(t *testing.T) {
|
||||||
rl := newTestLimiter(t)
|
rl := newTestLimiter(t)
|
||||||
rl.SetQuota("custom-model", ModelQuota{MaxRPM: 42, MaxTPM: 9999, MaxRPD: 100})
|
rl.SetQuota("custom-model", ModelQuota{MaxRPM: 42, MaxTPM: 9999, MaxRPD: 100})
|
||||||
|
|
@ -1279,7 +1468,7 @@ func TestSetQuota(t *testing.T) {
|
||||||
wg.Add(1)
|
wg.Add(1)
|
||||||
go func(n int) {
|
go func(n int) {
|
||||||
defer wg.Done()
|
defer wg.Done()
|
||||||
model := fmt.Sprintf("model-%d", n)
|
model := core.Sprintf("model-%d", n)
|
||||||
rl.SetQuota(model, ModelQuota{MaxRPM: n, MaxTPM: n * 100, MaxRPD: n * 10})
|
rl.SetQuota(model, ModelQuota{MaxRPM: n, MaxTPM: n * 100, MaxRPD: n * 10})
|
||||||
}(i)
|
}(i)
|
||||||
}
|
}
|
||||||
|
|
@ -1289,7 +1478,7 @@ func TestSetQuota(t *testing.T) {
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestAddProvider(t *testing.T) {
|
func TestRatelimit_AddProvider_Good(t *testing.T) {
|
||||||
t.Run("adds OpenAI models to existing limiter", func(t *testing.T) {
|
t.Run("adds OpenAI models to existing limiter", func(t *testing.T) {
|
||||||
rl := newTestLimiter(t) // starts with Gemini defaults
|
rl := newTestLimiter(t) // starts with Gemini defaults
|
||||||
geminiCount := len(rl.Quotas)
|
geminiCount := len(rl.Quotas)
|
||||||
|
|
@ -1351,7 +1540,7 @@ func TestAddProvider(t *testing.T) {
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestProviderConstants(t *testing.T) {
|
func TestRatelimit_ProviderConstants_Good(t *testing.T) {
|
||||||
// Verify the string values are stable (they may be used in YAML configs)
|
// Verify the string values are stable (they may be used in YAML configs)
|
||||||
assert.Equal(t, Provider("gemini"), ProviderGemini)
|
assert.Equal(t, Provider("gemini"), ProviderGemini)
|
||||||
assert.Equal(t, Provider("openai"), ProviderOpenAI)
|
assert.Equal(t, Provider("openai"), ProviderOpenAI)
|
||||||
|
|
@ -1361,7 +1550,7 @@ func TestProviderConstants(t *testing.T) {
|
||||||
|
|
||||||
// --- Phase 0 addendum: Additional concurrent and multi-model race tests ---
|
// --- Phase 0 addendum: Additional concurrent and multi-model race tests ---
|
||||||
|
|
||||||
func TestConcurrentMultipleModels(t *testing.T) {
|
func TestRatelimit_ConcurrentMultipleModels_Good(t *testing.T) {
|
||||||
rl := newTestLimiter(t)
|
rl := newTestLimiter(t)
|
||||||
models := []string{"model-a", "model-b", "model-c", "model-d", "model-e"}
|
models := []string{"model-a", "model-b", "model-c", "model-d", "model-e"}
|
||||||
for _, m := range models {
|
for _, m := range models {
|
||||||
|
|
@ -1391,9 +1580,9 @@ func TestConcurrentMultipleModels(t *testing.T) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestConcurrentPersistAndLoad(t *testing.T) {
|
func TestRatelimit_ConcurrentPersistAndLoad_Ugly(t *testing.T) {
|
||||||
tmpDir := t.TempDir()
|
tmpDir := t.TempDir()
|
||||||
path := filepath.Join(tmpDir, "concurrent.yaml")
|
path := testPath(tmpDir, "concurrent.yaml")
|
||||||
|
|
||||||
rl := newTestLimiter(t)
|
rl := newTestLimiter(t)
|
||||||
rl.filePath = path
|
rl.filePath = path
|
||||||
|
|
@ -1425,7 +1614,7 @@ func TestConcurrentPersistAndLoad(t *testing.T) {
|
||||||
// No panics or data races = pass
|
// No panics or data races = pass
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestConcurrentAllStatsAndRecordUsage(t *testing.T) {
|
func TestRatelimit_ConcurrentAllStatsAndRecordUsage_Good(t *testing.T) {
|
||||||
rl := newTestLimiter(t)
|
rl := newTestLimiter(t)
|
||||||
models := []string{"stats-a", "stats-b", "stats-c"}
|
models := []string{"stats-a", "stats-b", "stats-c"}
|
||||||
for _, m := range models {
|
for _, m := range models {
|
||||||
|
|
@ -1456,7 +1645,7 @@ func TestConcurrentAllStatsAndRecordUsage(t *testing.T) {
|
||||||
wg.Wait()
|
wg.Wait()
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestConcurrentWaitForCapacityAndRecordUsage(t *testing.T) {
|
func TestRatelimit_ConcurrentWaitForCapacityAndRecordUsage_Good(t *testing.T) {
|
||||||
rl := newTestLimiter(t)
|
rl := newTestLimiter(t)
|
||||||
model := "race-wait"
|
model := "race-wait"
|
||||||
rl.Quotas[model] = ModelQuota{MaxRPM: 100, MaxTPM: 10000000, MaxRPD: 10000}
|
rl.Quotas[model] = ModelQuota{MaxRPM: 100, MaxTPM: 10000000, MaxRPD: 10000}
|
||||||
|
|
@ -1553,7 +1742,7 @@ func BenchmarkAllStats(b *testing.B) {
|
||||||
|
|
||||||
func BenchmarkPersist(b *testing.B) {
|
func BenchmarkPersist(b *testing.B) {
|
||||||
tmpDir := b.TempDir()
|
tmpDir := b.TempDir()
|
||||||
path := filepath.Join(tmpDir, "bench.yaml")
|
path := testPath(tmpDir, "bench.yaml")
|
||||||
|
|
||||||
rl, _ := New()
|
rl, _ := New()
|
||||||
rl.filePath = path
|
rl.filePath = path
|
||||||
|
|
@ -1574,10 +1763,10 @@ func BenchmarkPersist(b *testing.B) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestEndToEndMultiProvider(t *testing.T) {
|
func TestRatelimit_EndToEndMultiProvider_Good(t *testing.T) {
|
||||||
// Simulate a real-world scenario: limiter for both Gemini and Anthropic
|
// Simulate a real-world scenario: limiter for both Gemini and Anthropic
|
||||||
rl, err := NewWithConfig(Config{
|
rl, err := NewWithConfig(Config{
|
||||||
FilePath: filepath.Join(t.TempDir(), "multi.yaml"),
|
FilePath: testPath(t.TempDir(), "multi.yaml"),
|
||||||
Providers: []Provider{ProviderGemini, ProviderAnthropic},
|
Providers: []Provider{ProviderGemini, ProviderAnthropic},
|
||||||
})
|
})
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
|
||||||
154
specs/RFC.md
Normal file
154
specs/RFC.md
Normal file
|
|
@ -0,0 +1,154 @@
|
||||||
|
# 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.
|
||||||
71
sqlite.go
71
sqlite.go
|
|
@ -1,11 +1,12 @@
|
||||||
|
// SPDX-License-Identifier: EUPL-1.2
|
||||||
|
|
||||||
package ratelimit
|
package ratelimit
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"database/sql"
|
"database/sql"
|
||||||
"fmt"
|
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
coreerr "dappco.re/go/core/log"
|
core "dappco.re/go/core"
|
||||||
_ "modernc.org/sqlite"
|
_ "modernc.org/sqlite"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
@ -20,7 +21,7 @@ type sqliteStore struct {
|
||||||
func newSQLiteStore(dbPath string) (*sqliteStore, error) {
|
func newSQLiteStore(dbPath string) (*sqliteStore, error) {
|
||||||
db, err := sql.Open("sqlite", dbPath)
|
db, err := sql.Open("sqlite", dbPath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, coreerr.E("ratelimit.newSQLiteStore", "open", err)
|
return nil, core.E("ratelimit.newSQLiteStore", "open", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Single connection for PRAGMA consistency.
|
// Single connection for PRAGMA consistency.
|
||||||
|
|
@ -28,11 +29,11 @@ func newSQLiteStore(dbPath string) (*sqliteStore, error) {
|
||||||
|
|
||||||
if _, err := db.Exec("PRAGMA journal_mode=WAL"); err != nil {
|
if _, err := db.Exec("PRAGMA journal_mode=WAL"); err != nil {
|
||||||
db.Close()
|
db.Close()
|
||||||
return nil, coreerr.E("ratelimit.newSQLiteStore", "WAL", err)
|
return nil, core.E("ratelimit.newSQLiteStore", "WAL", err)
|
||||||
}
|
}
|
||||||
if _, err := db.Exec("PRAGMA busy_timeout=5000"); err != nil {
|
if _, err := db.Exec("PRAGMA busy_timeout=5000"); err != nil {
|
||||||
db.Close()
|
db.Close()
|
||||||
return nil, coreerr.E("ratelimit.newSQLiteStore", "busy_timeout", err)
|
return nil, core.E("ratelimit.newSQLiteStore", "busy_timeout", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := createSchema(db); err != nil {
|
if err := createSchema(db); err != nil {
|
||||||
|
|
@ -72,7 +73,7 @@ func createSchema(db *sql.DB) error {
|
||||||
|
|
||||||
for _, stmt := range stmts {
|
for _, stmt := range stmts {
|
||||||
if _, err := db.Exec(stmt); err != nil {
|
if _, err := db.Exec(stmt); err != nil {
|
||||||
return coreerr.E("ratelimit.createSchema", "exec", err)
|
return core.E("ratelimit.createSchema", "exec", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
|
|
@ -82,12 +83,12 @@ func createSchema(db *sql.DB) error {
|
||||||
func (s *sqliteStore) saveQuotas(quotas map[string]ModelQuota) error {
|
func (s *sqliteStore) saveQuotas(quotas map[string]ModelQuota) error {
|
||||||
tx, err := s.db.Begin()
|
tx, err := s.db.Begin()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return coreerr.E("ratelimit.saveQuotas", "begin", err)
|
return core.E("ratelimit.saveQuotas", "begin", err)
|
||||||
}
|
}
|
||||||
defer tx.Rollback()
|
defer tx.Rollback()
|
||||||
|
|
||||||
if _, err := tx.Exec("DELETE FROM quotas"); err != nil {
|
if _, err := tx.Exec("DELETE FROM quotas"); err != nil {
|
||||||
return coreerr.E("ratelimit.saveQuotas", "clear", err)
|
return core.E("ratelimit.saveQuotas", "clear", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := insertQuotas(tx, quotas); err != nil {
|
if err := insertQuotas(tx, quotas); err != nil {
|
||||||
|
|
@ -101,7 +102,7 @@ func (s *sqliteStore) saveQuotas(quotas map[string]ModelQuota) error {
|
||||||
func (s *sqliteStore) loadQuotas() (map[string]ModelQuota, error) {
|
func (s *sqliteStore) loadQuotas() (map[string]ModelQuota, error) {
|
||||||
rows, err := s.db.Query("SELECT model, max_rpm, max_tpm, max_rpd FROM quotas")
|
rows, err := s.db.Query("SELECT model, max_rpm, max_tpm, max_rpd FROM quotas")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, coreerr.E("ratelimit.loadQuotas", "query", err)
|
return nil, core.E("ratelimit.loadQuotas", "query", err)
|
||||||
}
|
}
|
||||||
defer rows.Close()
|
defer rows.Close()
|
||||||
|
|
||||||
|
|
@ -110,12 +111,12 @@ func (s *sqliteStore) loadQuotas() (map[string]ModelQuota, error) {
|
||||||
var model string
|
var model string
|
||||||
var q ModelQuota
|
var q ModelQuota
|
||||||
if err := rows.Scan(&model, &q.MaxRPM, &q.MaxTPM, &q.MaxRPD); err != nil {
|
if err := rows.Scan(&model, &q.MaxRPM, &q.MaxTPM, &q.MaxRPD); err != nil {
|
||||||
return nil, coreerr.E("ratelimit.loadQuotas", "scan", err)
|
return nil, core.E("ratelimit.loadQuotas", "scan", err)
|
||||||
}
|
}
|
||||||
result[model] = q
|
result[model] = q
|
||||||
}
|
}
|
||||||
if err := rows.Err(); err != nil {
|
if err := rows.Err(); err != nil {
|
||||||
return nil, coreerr.E("ratelimit.loadQuotas", "rows", err)
|
return nil, core.E("ratelimit.loadQuotas", "rows", err)
|
||||||
}
|
}
|
||||||
return result, nil
|
return result, nil
|
||||||
}
|
}
|
||||||
|
|
@ -124,7 +125,7 @@ func (s *sqliteStore) loadQuotas() (map[string]ModelQuota, error) {
|
||||||
func (s *sqliteStore) saveSnapshot(quotas map[string]ModelQuota, state map[string]*UsageStats) error {
|
func (s *sqliteStore) saveSnapshot(quotas map[string]ModelQuota, state map[string]*UsageStats) error {
|
||||||
tx, err := s.db.Begin()
|
tx, err := s.db.Begin()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return coreerr.E("ratelimit.saveSnapshot", "begin", err)
|
return core.E("ratelimit.saveSnapshot", "begin", err)
|
||||||
}
|
}
|
||||||
defer tx.Rollback()
|
defer tx.Rollback()
|
||||||
|
|
||||||
|
|
@ -148,7 +149,7 @@ func (s *sqliteStore) saveSnapshot(quotas map[string]ModelQuota, state map[strin
|
||||||
func (s *sqliteStore) saveState(state map[string]*UsageStats) error {
|
func (s *sqliteStore) saveState(state map[string]*UsageStats) error {
|
||||||
tx, err := s.db.Begin()
|
tx, err := s.db.Begin()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return coreerr.E("ratelimit.saveState", "begin", err)
|
return core.E("ratelimit.saveState", "begin", err)
|
||||||
}
|
}
|
||||||
defer tx.Rollback()
|
defer tx.Rollback()
|
||||||
|
|
||||||
|
|
@ -166,17 +167,17 @@ func (s *sqliteStore) saveState(state map[string]*UsageStats) error {
|
||||||
func clearSnapshotTables(tx *sql.Tx, includeQuotas bool) error {
|
func clearSnapshotTables(tx *sql.Tx, includeQuotas bool) error {
|
||||||
if includeQuotas {
|
if includeQuotas {
|
||||||
if _, err := tx.Exec("DELETE FROM quotas"); err != nil {
|
if _, err := tx.Exec("DELETE FROM quotas"); err != nil {
|
||||||
return coreerr.E("ratelimit.saveSnapshot", "clear quotas", err)
|
return core.E("ratelimit.saveSnapshot", "clear quotas", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if _, err := tx.Exec("DELETE FROM requests"); err != nil {
|
if _, err := tx.Exec("DELETE FROM requests"); err != nil {
|
||||||
return coreerr.E("ratelimit.saveState", "clear requests", err)
|
return core.E("ratelimit.saveState", "clear requests", err)
|
||||||
}
|
}
|
||||||
if _, err := tx.Exec("DELETE FROM tokens"); err != nil {
|
if _, err := tx.Exec("DELETE FROM tokens"); err != nil {
|
||||||
return coreerr.E("ratelimit.saveState", "clear tokens", err)
|
return core.E("ratelimit.saveState", "clear tokens", err)
|
||||||
}
|
}
|
||||||
if _, err := tx.Exec("DELETE FROM daily"); err != nil {
|
if _, err := tx.Exec("DELETE FROM daily"); err != nil {
|
||||||
return coreerr.E("ratelimit.saveState", "clear daily", err)
|
return core.E("ratelimit.saveState", "clear daily", err)
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
@ -184,13 +185,13 @@ func clearSnapshotTables(tx *sql.Tx, includeQuotas bool) error {
|
||||||
func insertQuotas(tx *sql.Tx, quotas map[string]ModelQuota) error {
|
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 (?, ?, ?, ?)")
|
stmt, err := tx.Prepare("INSERT INTO quotas (model, max_rpm, max_tpm, max_rpd) VALUES (?, ?, ?, ?)")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return coreerr.E("ratelimit.saveQuotas", "prepare", err)
|
return core.E("ratelimit.saveQuotas", "prepare", err)
|
||||||
}
|
}
|
||||||
defer stmt.Close()
|
defer stmt.Close()
|
||||||
|
|
||||||
for model, q := range quotas {
|
for model, q := range quotas {
|
||||||
if _, err := stmt.Exec(model, q.MaxRPM, q.MaxTPM, q.MaxRPD); err != nil {
|
if _, err := stmt.Exec(model, q.MaxRPM, q.MaxTPM, q.MaxRPD); err != nil {
|
||||||
return coreerr.E("ratelimit.saveQuotas", fmt.Sprintf("exec %s", model), err)
|
return core.E("ratelimit.saveQuotas", core.Concat("exec ", model), err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
|
|
@ -199,19 +200,19 @@ func insertQuotas(tx *sql.Tx, quotas map[string]ModelQuota) error {
|
||||||
func insertState(tx *sql.Tx, state map[string]*UsageStats) error {
|
func insertState(tx *sql.Tx, state map[string]*UsageStats) error {
|
||||||
reqStmt, err := tx.Prepare("INSERT INTO requests (model, ts) VALUES (?, ?)")
|
reqStmt, err := tx.Prepare("INSERT INTO requests (model, ts) VALUES (?, ?)")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return coreerr.E("ratelimit.saveState", "prepare requests", err)
|
return core.E("ratelimit.saveState", "prepare requests", err)
|
||||||
}
|
}
|
||||||
defer reqStmt.Close()
|
defer reqStmt.Close()
|
||||||
|
|
||||||
tokStmt, err := tx.Prepare("INSERT INTO tokens (model, ts, count) VALUES (?, ?, ?)")
|
tokStmt, err := tx.Prepare("INSERT INTO tokens (model, ts, count) VALUES (?, ?, ?)")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return coreerr.E("ratelimit.saveState", "prepare tokens", err)
|
return core.E("ratelimit.saveState", "prepare tokens", err)
|
||||||
}
|
}
|
||||||
defer tokStmt.Close()
|
defer tokStmt.Close()
|
||||||
|
|
||||||
dayStmt, err := tx.Prepare("INSERT INTO daily (model, day_start, day_count) VALUES (?, ?, ?)")
|
dayStmt, err := tx.Prepare("INSERT INTO daily (model, day_start, day_count) VALUES (?, ?, ?)")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return coreerr.E("ratelimit.saveState", "prepare daily", err)
|
return core.E("ratelimit.saveState", "prepare daily", err)
|
||||||
}
|
}
|
||||||
defer dayStmt.Close()
|
defer dayStmt.Close()
|
||||||
|
|
||||||
|
|
@ -221,16 +222,16 @@ func insertState(tx *sql.Tx, state map[string]*UsageStats) error {
|
||||||
}
|
}
|
||||||
for _, t := range stats.Requests {
|
for _, t := range stats.Requests {
|
||||||
if _, err := reqStmt.Exec(model, t.UnixNano()); err != nil {
|
if _, err := reqStmt.Exec(model, t.UnixNano()); err != nil {
|
||||||
return coreerr.E("ratelimit.saveState", fmt.Sprintf("insert request %s", model), err)
|
return core.E("ratelimit.saveState", core.Concat("insert request ", model), err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for _, te := range stats.Tokens {
|
for _, te := range stats.Tokens {
|
||||||
if _, err := tokStmt.Exec(model, te.Time.UnixNano(), te.Count); err != nil {
|
if _, err := tokStmt.Exec(model, te.Time.UnixNano(), te.Count); err != nil {
|
||||||
return coreerr.E("ratelimit.saveState", fmt.Sprintf("insert token %s", model), err)
|
return core.E("ratelimit.saveState", core.Concat("insert token ", model), err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if _, err := dayStmt.Exec(model, stats.DayStart.UnixNano(), stats.DayCount); err != nil {
|
if _, err := dayStmt.Exec(model, stats.DayStart.UnixNano(), stats.DayCount); err != nil {
|
||||||
return coreerr.E("ratelimit.saveState", fmt.Sprintf("insert daily %s", model), err)
|
return core.E("ratelimit.saveState", core.Concat("insert daily ", model), err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
|
|
@ -238,7 +239,7 @@ func insertState(tx *sql.Tx, state map[string]*UsageStats) error {
|
||||||
|
|
||||||
func commitTx(tx *sql.Tx, scope string) error {
|
func commitTx(tx *sql.Tx, scope string) error {
|
||||||
if err := tx.Commit(); err != nil {
|
if err := tx.Commit(); err != nil {
|
||||||
return coreerr.E(scope, "commit", err)
|
return core.E(scope, "commit", err)
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
@ -250,7 +251,7 @@ func (s *sqliteStore) loadState() (map[string]*UsageStats, error) {
|
||||||
// Load daily counters first (these define which models have state).
|
// Load daily counters first (these define which models have state).
|
||||||
rows, err := s.db.Query("SELECT model, day_start, day_count FROM daily")
|
rows, err := s.db.Query("SELECT model, day_start, day_count FROM daily")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, coreerr.E("ratelimit.loadState", "query daily", err)
|
return nil, core.E("ratelimit.loadState", "query daily", err)
|
||||||
}
|
}
|
||||||
defer rows.Close()
|
defer rows.Close()
|
||||||
|
|
||||||
|
|
@ -259,7 +260,7 @@ func (s *sqliteStore) loadState() (map[string]*UsageStats, error) {
|
||||||
var dayStartNano int64
|
var dayStartNano int64
|
||||||
var dayCount int
|
var dayCount int
|
||||||
if err := rows.Scan(&model, &dayStartNano, &dayCount); err != nil {
|
if err := rows.Scan(&model, &dayStartNano, &dayCount); err != nil {
|
||||||
return nil, coreerr.E("ratelimit.loadState", "scan daily", err)
|
return nil, core.E("ratelimit.loadState", "scan daily", err)
|
||||||
}
|
}
|
||||||
result[model] = &UsageStats{
|
result[model] = &UsageStats{
|
||||||
DayStart: time.Unix(0, dayStartNano),
|
DayStart: time.Unix(0, dayStartNano),
|
||||||
|
|
@ -267,13 +268,13 @@ func (s *sqliteStore) loadState() (map[string]*UsageStats, error) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if err := rows.Err(); err != nil {
|
if err := rows.Err(); err != nil {
|
||||||
return nil, coreerr.E("ratelimit.loadState", "daily rows", err)
|
return nil, core.E("ratelimit.loadState", "daily rows", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Load requests.
|
// Load requests.
|
||||||
reqRows, err := s.db.Query("SELECT model, ts FROM requests ORDER BY ts")
|
reqRows, err := s.db.Query("SELECT model, ts FROM requests ORDER BY ts")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, coreerr.E("ratelimit.loadState", "query requests", err)
|
return nil, core.E("ratelimit.loadState", "query requests", err)
|
||||||
}
|
}
|
||||||
defer reqRows.Close()
|
defer reqRows.Close()
|
||||||
|
|
||||||
|
|
@ -281,7 +282,7 @@ func (s *sqliteStore) loadState() (map[string]*UsageStats, error) {
|
||||||
var model string
|
var model string
|
||||||
var tsNano int64
|
var tsNano int64
|
||||||
if err := reqRows.Scan(&model, &tsNano); err != nil {
|
if err := reqRows.Scan(&model, &tsNano); err != nil {
|
||||||
return nil, coreerr.E("ratelimit.loadState", "scan requests", err)
|
return nil, core.E("ratelimit.loadState", "scan requests", err)
|
||||||
}
|
}
|
||||||
if _, ok := result[model]; !ok {
|
if _, ok := result[model]; !ok {
|
||||||
result[model] = &UsageStats{}
|
result[model] = &UsageStats{}
|
||||||
|
|
@ -289,13 +290,13 @@ func (s *sqliteStore) loadState() (map[string]*UsageStats, error) {
|
||||||
result[model].Requests = append(result[model].Requests, time.Unix(0, tsNano))
|
result[model].Requests = append(result[model].Requests, time.Unix(0, tsNano))
|
||||||
}
|
}
|
||||||
if err := reqRows.Err(); err != nil {
|
if err := reqRows.Err(); err != nil {
|
||||||
return nil, coreerr.E("ratelimit.loadState", "request rows", err)
|
return nil, core.E("ratelimit.loadState", "request rows", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Load tokens.
|
// Load tokens.
|
||||||
tokRows, err := s.db.Query("SELECT model, ts, count FROM tokens ORDER BY ts")
|
tokRows, err := s.db.Query("SELECT model, ts, count FROM tokens ORDER BY ts")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, coreerr.E("ratelimit.loadState", "query tokens", err)
|
return nil, core.E("ratelimit.loadState", "query tokens", err)
|
||||||
}
|
}
|
||||||
defer tokRows.Close()
|
defer tokRows.Close()
|
||||||
|
|
||||||
|
|
@ -304,7 +305,7 @@ func (s *sqliteStore) loadState() (map[string]*UsageStats, error) {
|
||||||
var tsNano int64
|
var tsNano int64
|
||||||
var count int
|
var count int
|
||||||
if err := tokRows.Scan(&model, &tsNano, &count); err != nil {
|
if err := tokRows.Scan(&model, &tsNano, &count); err != nil {
|
||||||
return nil, coreerr.E("ratelimit.loadState", "scan tokens", err)
|
return nil, core.E("ratelimit.loadState", "scan tokens", err)
|
||||||
}
|
}
|
||||||
if _, ok := result[model]; !ok {
|
if _, ok := result[model]; !ok {
|
||||||
result[model] = &UsageStats{}
|
result[model] = &UsageStats{}
|
||||||
|
|
@ -315,7 +316,7 @@ func (s *sqliteStore) loadState() (map[string]*UsageStats, error) {
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
if err := tokRows.Err(); err != nil {
|
if err := tokRows.Err(); err != nil {
|
||||||
return nil, coreerr.E("ratelimit.loadState", "token rows", err)
|
return nil, core.E("ratelimit.loadState", "token rows", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
return result, nil
|
return result, nil
|
||||||
|
|
|
||||||
159
sqlite_test.go
159
sqlite_test.go
|
|
@ -1,8 +1,8 @@
|
||||||
|
// SPDX-License-Identifier: EUPL-1.2
|
||||||
|
|
||||||
package ratelimit
|
package ratelimit
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
"sync"
|
"sync"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
@ -14,18 +14,17 @@ import (
|
||||||
|
|
||||||
// --- Phase 2: SQLite basic tests ---
|
// --- Phase 2: SQLite basic tests ---
|
||||||
|
|
||||||
func TestNewSQLiteStore_Good(t *testing.T) {
|
func TestSQLite_NewSQLiteStore_Good(t *testing.T) {
|
||||||
dbPath := filepath.Join(t.TempDir(), "test.db")
|
dbPath := testPath(t.TempDir(), "test.db")
|
||||||
store, err := newSQLiteStore(dbPath)
|
store, err := newSQLiteStore(dbPath)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
defer store.close()
|
defer store.close()
|
||||||
|
|
||||||
// Verify the database file was created.
|
// Verify the database file was created.
|
||||||
_, statErr := os.Stat(dbPath)
|
assert.True(t, pathExists(dbPath), "database file should exist")
|
||||||
assert.NoError(t, statErr, "database file should exist")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestNewSQLiteStore_Bad(t *testing.T) {
|
func TestSQLite_NewSQLiteStore_Bad(t *testing.T) {
|
||||||
t.Run("invalid path returns error", func(t *testing.T) {
|
t.Run("invalid path returns error", func(t *testing.T) {
|
||||||
// Path inside a non-existent directory with no parent.
|
// Path inside a non-existent directory with no parent.
|
||||||
_, err := newSQLiteStore("/nonexistent/deep/nested/dir/test.db")
|
_, err := newSQLiteStore("/nonexistent/deep/nested/dir/test.db")
|
||||||
|
|
@ -33,8 +32,8 @@ func TestNewSQLiteStore_Bad(t *testing.T) {
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSQLiteQuotasRoundTrip_Good(t *testing.T) {
|
func TestSQLite_QuotasRoundTrip_Good(t *testing.T) {
|
||||||
dbPath := filepath.Join(t.TempDir(), "quotas.db")
|
dbPath := testPath(t.TempDir(), "quotas.db")
|
||||||
store, err := newSQLiteStore(dbPath)
|
store, err := newSQLiteStore(dbPath)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
defer store.close()
|
defer store.close()
|
||||||
|
|
@ -60,8 +59,8 @@ func TestSQLiteQuotasRoundTrip_Good(t *testing.T) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSQLiteQuotasUpsert_Good(t *testing.T) {
|
func TestSQLite_QuotasOverwrite_Good(t *testing.T) {
|
||||||
dbPath := filepath.Join(t.TempDir(), "upsert.db")
|
dbPath := testPath(t.TempDir(), "overwrite.db")
|
||||||
store, err := newSQLiteStore(dbPath)
|
store, err := newSQLiteStore(dbPath)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
defer store.close()
|
defer store.close()
|
||||||
|
|
@ -71,7 +70,7 @@ func TestSQLiteQuotasUpsert_Good(t *testing.T) {
|
||||||
"model-a": {MaxRPM: 100, MaxTPM: 50000, MaxRPD: 1000},
|
"model-a": {MaxRPM: 100, MaxTPM: 50000, MaxRPD: 1000},
|
||||||
}))
|
}))
|
||||||
|
|
||||||
// Upsert with updated values.
|
// Save a second snapshot with updated values.
|
||||||
require.NoError(t, store.saveQuotas(map[string]ModelQuota{
|
require.NoError(t, store.saveQuotas(map[string]ModelQuota{
|
||||||
"model-a": {MaxRPM: 999, MaxTPM: 888, MaxRPD: 777},
|
"model-a": {MaxRPM: 999, MaxTPM: 888, MaxRPD: 777},
|
||||||
}))
|
}))
|
||||||
|
|
@ -85,8 +84,8 @@ func TestSQLiteQuotasUpsert_Good(t *testing.T) {
|
||||||
assert.Equal(t, 777, q.MaxRPD, "should have updated RPD")
|
assert.Equal(t, 777, q.MaxRPD, "should have updated RPD")
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSQLiteStateRoundTrip_Good(t *testing.T) {
|
func TestSQLite_StateRoundTrip_Good(t *testing.T) {
|
||||||
dbPath := filepath.Join(t.TempDir(), "state.db")
|
dbPath := testPath(t.TempDir(), "state.db")
|
||||||
store, err := newSQLiteStore(dbPath)
|
store, err := newSQLiteStore(dbPath)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
defer store.close()
|
defer store.close()
|
||||||
|
|
@ -144,8 +143,8 @@ func TestSQLiteStateRoundTrip_Good(t *testing.T) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSQLiteStateOverwrite_Good(t *testing.T) {
|
func TestSQLite_StateOverwrite_Good(t *testing.T) {
|
||||||
dbPath := filepath.Join(t.TempDir(), "overwrite.db")
|
dbPath := testPath(t.TempDir(), "overwrite.db")
|
||||||
store, err := newSQLiteStore(dbPath)
|
store, err := newSQLiteStore(dbPath)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
defer store.close()
|
defer store.close()
|
||||||
|
|
@ -182,8 +181,8 @@ func TestSQLiteStateOverwrite_Good(t *testing.T) {
|
||||||
assert.Len(t, b.Requests, 1)
|
assert.Len(t, b.Requests, 1)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSQLiteEmptyState_Good(t *testing.T) {
|
func TestSQLite_EmptyState_Good(t *testing.T) {
|
||||||
dbPath := filepath.Join(t.TempDir(), "empty.db")
|
dbPath := testPath(t.TempDir(), "empty.db")
|
||||||
store, err := newSQLiteStore(dbPath)
|
store, err := newSQLiteStore(dbPath)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
defer store.close()
|
defer store.close()
|
||||||
|
|
@ -198,8 +197,8 @@ func TestSQLiteEmptyState_Good(t *testing.T) {
|
||||||
assert.Empty(t, state, "should return empty state from fresh DB")
|
assert.Empty(t, state, "should return empty state from fresh DB")
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSQLiteClose_Good(t *testing.T) {
|
func TestSQLite_Close_Good(t *testing.T) {
|
||||||
dbPath := filepath.Join(t.TempDir(), "close.db")
|
dbPath := testPath(t.TempDir(), "close.db")
|
||||||
store, err := newSQLiteStore(dbPath)
|
store, err := newSQLiteStore(dbPath)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
|
@ -208,8 +207,8 @@ func TestSQLiteClose_Good(t *testing.T) {
|
||||||
|
|
||||||
// --- Phase 2: SQLite integration tests ---
|
// --- Phase 2: SQLite integration tests ---
|
||||||
|
|
||||||
func TestNewWithSQLite_Good(t *testing.T) {
|
func TestSQLite_NewWithSQLite_Good(t *testing.T) {
|
||||||
dbPath := filepath.Join(t.TempDir(), "limiter.db")
|
dbPath := testPath(t.TempDir(), "limiter.db")
|
||||||
rl, err := NewWithSQLite(dbPath)
|
rl, err := NewWithSQLite(dbPath)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
defer rl.Close()
|
defer rl.Close()
|
||||||
|
|
@ -222,8 +221,8 @@ func TestNewWithSQLite_Good(t *testing.T) {
|
||||||
assert.NotNil(t, rl.sqlite, "SQLite store should be initialised")
|
assert.NotNil(t, rl.sqlite, "SQLite store should be initialised")
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestNewWithSQLiteConfig_Good(t *testing.T) {
|
func TestSQLite_NewWithSQLiteConfig_Good(t *testing.T) {
|
||||||
dbPath := filepath.Join(t.TempDir(), "config.db")
|
dbPath := testPath(t.TempDir(), "config.db")
|
||||||
rl, err := NewWithSQLiteConfig(dbPath, Config{
|
rl, err := NewWithSQLiteConfig(dbPath, Config{
|
||||||
Providers: []Provider{ProviderAnthropic},
|
Providers: []Provider{ProviderAnthropic},
|
||||||
Quotas: map[string]ModelQuota{
|
Quotas: map[string]ModelQuota{
|
||||||
|
|
@ -243,8 +242,8 @@ func TestNewWithSQLiteConfig_Good(t *testing.T) {
|
||||||
assert.False(t, hasGemini, "should not have Gemini models")
|
assert.False(t, hasGemini, "should not have Gemini models")
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSQLitePersistAndLoad_Good(t *testing.T) {
|
func TestSQLite_PersistAndLoad_Good(t *testing.T) {
|
||||||
dbPath := filepath.Join(t.TempDir(), "persist.db")
|
dbPath := testPath(t.TempDir(), "persist.db")
|
||||||
rl, err := NewWithSQLite(dbPath)
|
rl, err := NewWithSQLite(dbPath)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
|
@ -272,8 +271,8 @@ func TestSQLitePersistAndLoad_Good(t *testing.T) {
|
||||||
assert.Equal(t, 500, stats.MaxRPD)
|
assert.Equal(t, 500, stats.MaxRPD)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSQLitePersistMultipleModels_Good(t *testing.T) {
|
func TestSQLite_PersistMultipleModels_Good(t *testing.T) {
|
||||||
dbPath := filepath.Join(t.TempDir(), "multi.db")
|
dbPath := testPath(t.TempDir(), "multi.db")
|
||||||
rl, err := NewWithSQLiteConfig(dbPath, Config{
|
rl, err := NewWithSQLiteConfig(dbPath, Config{
|
||||||
Providers: []Provider{ProviderGemini, ProviderAnthropic},
|
Providers: []Provider{ProviderGemini, ProviderAnthropic},
|
||||||
})
|
})
|
||||||
|
|
@ -302,8 +301,8 @@ func TestSQLitePersistMultipleModels_Good(t *testing.T) {
|
||||||
assert.Equal(t, 400, claude.TPM)
|
assert.Equal(t, 400, claude.TPM)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSQLiteRecordUsageThenPersistReload_Good(t *testing.T) {
|
func TestSQLite_RecordUsageThenPersistReload_Good(t *testing.T) {
|
||||||
dbPath := filepath.Join(t.TempDir(), "record.db")
|
dbPath := testPath(t.TempDir(), "record.db")
|
||||||
rl, err := NewWithSQLite(dbPath)
|
rl, err := NewWithSQLite(dbPath)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
|
@ -340,7 +339,7 @@ func TestSQLiteRecordUsageThenPersistReload_Good(t *testing.T) {
|
||||||
assert.Equal(t, 1000, stats2.TPM, "TPM should survive reload")
|
assert.Equal(t, 1000, stats2.TPM, "TPM should survive reload")
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSQLiteClose_Good_NoOp(t *testing.T) {
|
func TestSQLite_CloseNoOp_Good(t *testing.T) {
|
||||||
// Close on YAML-backed limiter is a no-op.
|
// Close on YAML-backed limiter is a no-op.
|
||||||
rl := newTestLimiter(t)
|
rl := newTestLimiter(t)
|
||||||
assert.NoError(t, rl.Close(), "Close on YAML limiter should be no-op")
|
assert.NoError(t, rl.Close(), "Close on YAML limiter should be no-op")
|
||||||
|
|
@ -348,8 +347,8 @@ func TestSQLiteClose_Good_NoOp(t *testing.T) {
|
||||||
|
|
||||||
// --- Phase 2: Concurrent SQLite ---
|
// --- Phase 2: Concurrent SQLite ---
|
||||||
|
|
||||||
func TestSQLiteConcurrent_Good(t *testing.T) {
|
func TestSQLite_Concurrent_Good(t *testing.T) {
|
||||||
dbPath := filepath.Join(t.TempDir(), "concurrent.db")
|
dbPath := testPath(t.TempDir(), "concurrent.db")
|
||||||
rl, err := NewWithSQLite(dbPath)
|
rl, err := NewWithSQLite(dbPath)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
defer rl.Close()
|
defer rl.Close()
|
||||||
|
|
@ -398,10 +397,10 @@ func TestSQLiteConcurrent_Good(t *testing.T) {
|
||||||
|
|
||||||
// --- Phase 2: YAML backward compatibility ---
|
// --- Phase 2: YAML backward compatibility ---
|
||||||
|
|
||||||
func TestYAMLBackwardCompat_Good(t *testing.T) {
|
func TestSQLite_YAMLBackwardCompat_Good(t *testing.T) {
|
||||||
// Verify that the default YAML backend still works after SQLite additions.
|
// Verify that the default YAML backend still works after SQLite additions.
|
||||||
tmpDir := t.TempDir()
|
tmpDir := t.TempDir()
|
||||||
path := filepath.Join(tmpDir, "compat.yaml")
|
path := testPath(tmpDir, "compat.yaml")
|
||||||
|
|
||||||
rl1, err := New()
|
rl1, err := New()
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
@ -425,18 +424,18 @@ func TestYAMLBackwardCompat_Good(t *testing.T) {
|
||||||
assert.Equal(t, 200, stats.TPM)
|
assert.Equal(t, 200, stats.TPM)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestConfigBackendDefault_Good(t *testing.T) {
|
func TestSQLite_ConfigBackendDefault_Good(t *testing.T) {
|
||||||
// Empty Backend string should default to YAML behaviour.
|
// Empty Backend string should default to YAML behaviour.
|
||||||
rl, err := NewWithConfig(Config{
|
rl, err := NewWithConfig(Config{
|
||||||
FilePath: filepath.Join(t.TempDir(), "default.yaml"),
|
FilePath: testPath(t.TempDir(), "default.yaml"),
|
||||||
})
|
})
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
assert.Nil(t, rl.sqlite, "empty backend should use YAML (no sqlite)")
|
assert.Nil(t, rl.sqlite, "empty backend should use YAML (no sqlite)")
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestConfigBackendSQLite_Good(t *testing.T) {
|
func TestSQLite_ConfigBackendSQLite_Good(t *testing.T) {
|
||||||
dbPath := filepath.Join(t.TempDir(), "config-backend.db")
|
dbPath := testPath(t.TempDir(), "config-backend.db")
|
||||||
rl, err := NewWithConfig(Config{
|
rl, err := NewWithConfig(Config{
|
||||||
Backend: backendSQLite,
|
Backend: backendSQLite,
|
||||||
FilePath: dbPath,
|
FilePath: dbPath,
|
||||||
|
|
@ -451,11 +450,10 @@ func TestConfigBackendSQLite_Good(t *testing.T) {
|
||||||
rl.RecordUsage("backend-model", 10, 10)
|
rl.RecordUsage("backend-model", 10, 10)
|
||||||
require.NoError(t, rl.Persist())
|
require.NoError(t, rl.Persist())
|
||||||
|
|
||||||
_, statErr := os.Stat(dbPath)
|
assert.True(t, pathExists(dbPath), "sqlite backend should persist to the configured DB path")
|
||||||
assert.NoError(t, statErr, "sqlite backend should persist to the configured DB path")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestConfigBackendSQLiteDefaultPath_Good(t *testing.T) {
|
func TestSQLite_ConfigBackendSQLiteDefaultPath_Good(t *testing.T) {
|
||||||
home := t.TempDir()
|
home := t.TempDir()
|
||||||
t.Setenv("HOME", home)
|
t.Setenv("HOME", home)
|
||||||
t.Setenv("USERPROFILE", "")
|
t.Setenv("USERPROFILE", "")
|
||||||
|
|
@ -470,16 +468,15 @@ func TestConfigBackendSQLiteDefaultPath_Good(t *testing.T) {
|
||||||
require.NotNil(t, rl.sqlite)
|
require.NotNil(t, rl.sqlite)
|
||||||
require.NoError(t, rl.Persist())
|
require.NoError(t, rl.Persist())
|
||||||
|
|
||||||
_, statErr := os.Stat(filepath.Join(home, defaultStateDirName, defaultSQLiteStateFile))
|
assert.True(t, pathExists(testPath(home, defaultStateDirName, defaultSQLiteStateFile)), "sqlite backend should use the default home DB path")
|
||||||
assert.NoError(t, statErr, "sqlite backend should use the default home DB path")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- Phase 2: MigrateYAMLToSQLite ---
|
// --- Phase 2: MigrateYAMLToSQLite ---
|
||||||
|
|
||||||
func TestMigrateYAMLToSQLite_Good(t *testing.T) {
|
func TestSQLite_MigrateYAMLToSQLite_Good(t *testing.T) {
|
||||||
tmpDir := t.TempDir()
|
tmpDir := t.TempDir()
|
||||||
yamlPath := filepath.Join(tmpDir, "state.yaml")
|
yamlPath := testPath(tmpDir, "state.yaml")
|
||||||
sqlitePath := filepath.Join(tmpDir, "migrated.db")
|
sqlitePath := testPath(tmpDir, "migrated.db")
|
||||||
|
|
||||||
// Create a YAML-backed limiter with state.
|
// Create a YAML-backed limiter with state.
|
||||||
rl, err := New()
|
rl, err := New()
|
||||||
|
|
@ -515,26 +512,26 @@ func TestMigrateYAMLToSQLite_Good(t *testing.T) {
|
||||||
assert.Equal(t, 2, stats.RPD, "should have 2 daily requests")
|
assert.Equal(t, 2, stats.RPD, "should have 2 daily requests")
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestMigrateYAMLToSQLite_Bad(t *testing.T) {
|
func TestSQLite_MigrateYAMLToSQLite_Bad(t *testing.T) {
|
||||||
t.Run("non-existent YAML file", func(t *testing.T) {
|
t.Run("non-existent YAML file", func(t *testing.T) {
|
||||||
err := MigrateYAMLToSQLite("/nonexistent/state.yaml", filepath.Join(t.TempDir(), "out.db"))
|
err := MigrateYAMLToSQLite("/nonexistent/state.yaml", testPath(t.TempDir(), "out.db"))
|
||||||
assert.Error(t, err, "should fail with non-existent YAML file")
|
assert.Error(t, err, "should fail with non-existent YAML file")
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("corrupt YAML file", func(t *testing.T) {
|
t.Run("corrupt YAML file", func(t *testing.T) {
|
||||||
tmpDir := t.TempDir()
|
tmpDir := t.TempDir()
|
||||||
yamlPath := filepath.Join(tmpDir, "corrupt.yaml")
|
yamlPath := testPath(tmpDir, "corrupt.yaml")
|
||||||
require.NoError(t, os.WriteFile(yamlPath, []byte("{{{{not yaml!"), 0644))
|
writeTestFile(t, yamlPath, "{{{{not yaml!")
|
||||||
|
|
||||||
err := MigrateYAMLToSQLite(yamlPath, filepath.Join(tmpDir, "out.db"))
|
err := MigrateYAMLToSQLite(yamlPath, testPath(tmpDir, "out.db"))
|
||||||
assert.Error(t, err, "should fail with corrupt YAML")
|
assert.Error(t, err, "should fail with corrupt YAML")
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestMigrateYAMLToSQLiteAtomic_Good(t *testing.T) {
|
func TestSQLite_MigrateYAMLToSQLiteAtomic_Good(t *testing.T) {
|
||||||
tmpDir := t.TempDir()
|
tmpDir := t.TempDir()
|
||||||
yamlPath := filepath.Join(tmpDir, "atomic.yaml")
|
yamlPath := testPath(tmpDir, "atomic.yaml")
|
||||||
sqlitePath := filepath.Join(tmpDir, "atomic.db")
|
sqlitePath := testPath(tmpDir, "atomic.db")
|
||||||
now := time.Now().UTC()
|
now := time.Now().UTC()
|
||||||
|
|
||||||
store, err := newSQLiteStore(sqlitePath)
|
store, err := newSQLiteStore(sqlitePath)
|
||||||
|
|
@ -573,7 +570,7 @@ func TestMigrateYAMLToSQLiteAtomic_Good(t *testing.T) {
|
||||||
}
|
}
|
||||||
data, err := yaml.Marshal(migrated)
|
data, err := yaml.Marshal(migrated)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
require.NoError(t, os.WriteFile(yamlPath, data, 0o644))
|
writeTestFile(t, yamlPath, string(data))
|
||||||
|
|
||||||
err = MigrateYAMLToSQLite(yamlPath, sqlitePath)
|
err = MigrateYAMLToSQLite(yamlPath, sqlitePath)
|
||||||
require.Error(t, err)
|
require.Error(t, err)
|
||||||
|
|
@ -594,10 +591,10 @@ func TestMigrateYAMLToSQLiteAtomic_Good(t *testing.T) {
|
||||||
assert.NotContains(t, state, "new-model")
|
assert.NotContains(t, state, "new-model")
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestMigrateYAMLToSQLitePreservesAllGeminiModels_Good(t *testing.T) {
|
func TestSQLite_MigrateYAMLToSQLitePreservesAllGeminiModels_Good(t *testing.T) {
|
||||||
tmpDir := t.TempDir()
|
tmpDir := t.TempDir()
|
||||||
yamlPath := filepath.Join(tmpDir, "full.yaml")
|
yamlPath := testPath(tmpDir, "full.yaml")
|
||||||
sqlitePath := filepath.Join(tmpDir, "full.db")
|
sqlitePath := testPath(tmpDir, "full.db")
|
||||||
|
|
||||||
// Create a full YAML state with all Gemini models.
|
// Create a full YAML state with all Gemini models.
|
||||||
rl, err := New()
|
rl, err := New()
|
||||||
|
|
@ -626,12 +623,12 @@ func TestMigrateYAMLToSQLitePreservesAllGeminiModels_Good(t *testing.T) {
|
||||||
|
|
||||||
// --- Phase 2: Corrupt DB recovery ---
|
// --- Phase 2: Corrupt DB recovery ---
|
||||||
|
|
||||||
func TestSQLiteCorruptDB_Ugly(t *testing.T) {
|
func TestSQLite_CorruptDB_Ugly(t *testing.T) {
|
||||||
tmpDir := t.TempDir()
|
tmpDir := t.TempDir()
|
||||||
dbPath := filepath.Join(tmpDir, "corrupt.db")
|
dbPath := testPath(tmpDir, "corrupt.db")
|
||||||
|
|
||||||
// Write garbage to the DB file.
|
// Write garbage to the DB file.
|
||||||
require.NoError(t, os.WriteFile(dbPath, []byte("THIS IS NOT A SQLITE DATABASE"), 0644))
|
writeTestFile(t, dbPath, "THIS IS NOT A SQLITE DATABASE")
|
||||||
|
|
||||||
// Opening a corrupt DB may succeed (sqlite is lazy about validation),
|
// Opening a corrupt DB may succeed (sqlite is lazy about validation),
|
||||||
// but operations on it should fail gracefully.
|
// but operations on it should fail gracefully.
|
||||||
|
|
@ -648,9 +645,9 @@ func TestSQLiteCorruptDB_Ugly(t *testing.T) {
|
||||||
assert.Error(t, err, "loading from corrupt DB should return an error")
|
assert.Error(t, err, "loading from corrupt DB should return an error")
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSQLiteTruncatedDB_Ugly(t *testing.T) {
|
func TestSQLite_TruncatedDB_Ugly(t *testing.T) {
|
||||||
tmpDir := t.TempDir()
|
tmpDir := t.TempDir()
|
||||||
dbPath := filepath.Join(tmpDir, "truncated.db")
|
dbPath := testPath(tmpDir, "truncated.db")
|
||||||
|
|
||||||
// Create a valid DB first.
|
// Create a valid DB first.
|
||||||
store, err := newSQLiteStore(dbPath)
|
store, err := newSQLiteStore(dbPath)
|
||||||
|
|
@ -661,11 +658,7 @@ func TestSQLiteTruncatedDB_Ugly(t *testing.T) {
|
||||||
require.NoError(t, store.close())
|
require.NoError(t, store.close())
|
||||||
|
|
||||||
// Truncate the file to simulate corruption.
|
// Truncate the file to simulate corruption.
|
||||||
f, err := os.OpenFile(dbPath, os.O_WRONLY|os.O_TRUNC, 0644)
|
overwriteTestFile(t, dbPath, "TRUNC")
|
||||||
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.
|
// Opening should either fail or operations should fail.
|
||||||
store2, err := newSQLiteStore(dbPath)
|
store2, err := newSQLiteStore(dbPath)
|
||||||
|
|
@ -679,9 +672,9 @@ func TestSQLiteTruncatedDB_Ugly(t *testing.T) {
|
||||||
assert.Error(t, err, "loading from truncated DB should return an error")
|
assert.Error(t, err, "loading from truncated DB should return an error")
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSQLiteEmptyModelState_Good(t *testing.T) {
|
func TestSQLite_EmptyModelState_Good(t *testing.T) {
|
||||||
// State with no requests or tokens but with a daily counter.
|
// State with no requests or tokens but with a daily counter.
|
||||||
dbPath := filepath.Join(t.TempDir(), "empty-state.db")
|
dbPath := testPath(t.TempDir(), "empty-state.db")
|
||||||
store, err := newSQLiteStore(dbPath)
|
store, err := newSQLiteStore(dbPath)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
defer store.close()
|
defer store.close()
|
||||||
|
|
@ -708,8 +701,8 @@ func TestSQLiteEmptyModelState_Good(t *testing.T) {
|
||||||
|
|
||||||
// --- Phase 2: End-to-end with persist cycle ---
|
// --- Phase 2: End-to-end with persist cycle ---
|
||||||
|
|
||||||
func TestSQLiteEndToEnd_Good(t *testing.T) {
|
func TestSQLite_EndToEnd_Good(t *testing.T) {
|
||||||
dbPath := filepath.Join(t.TempDir(), "e2e.db")
|
dbPath := testPath(t.TempDir(), "e2e.db")
|
||||||
|
|
||||||
// Session 1: Create limiter, record usage, persist.
|
// Session 1: Create limiter, record usage, persist.
|
||||||
rl1, err := NewWithSQLiteConfig(dbPath, Config{
|
rl1, err := NewWithSQLiteConfig(dbPath, Config{
|
||||||
|
|
@ -752,8 +745,8 @@ func TestSQLiteEndToEnd_Good(t *testing.T) {
|
||||||
assert.Equal(t, 5, custom.MaxRPM)
|
assert.Equal(t, 5, custom.MaxRPM)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSQLiteLoadReplacesPersistedSnapshot_Good(t *testing.T) {
|
func TestSQLite_LoadReplacesPersistedSnapshot_Good(t *testing.T) {
|
||||||
dbPath := filepath.Join(t.TempDir(), "replace.db")
|
dbPath := testPath(t.TempDir(), "replace.db")
|
||||||
rl, err := NewWithSQLiteConfig(dbPath, Config{
|
rl, err := NewWithSQLiteConfig(dbPath, Config{
|
||||||
Quotas: map[string]ModelQuota{
|
Quotas: map[string]ModelQuota{
|
||||||
"model-a": {MaxRPM: 1, MaxTPM: 100, MaxRPD: 10},
|
"model-a": {MaxRPM: 1, MaxTPM: 100, MaxRPD: 10},
|
||||||
|
|
@ -788,8 +781,8 @@ func TestSQLiteLoadReplacesPersistedSnapshot_Good(t *testing.T) {
|
||||||
assert.Equal(t, 1, rl2.Stats("model-b").RPD)
|
assert.Equal(t, 1, rl2.Stats("model-b").RPD)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSQLitePersistAtomic_Good(t *testing.T) {
|
func TestSQLite_PersistAtomic_Good(t *testing.T) {
|
||||||
dbPath := filepath.Join(t.TempDir(), "persist-atomic.db")
|
dbPath := testPath(t.TempDir(), "persist-atomic.db")
|
||||||
rl, err := NewWithSQLiteConfig(dbPath, Config{
|
rl, err := NewWithSQLiteConfig(dbPath, Config{
|
||||||
Quotas: map[string]ModelQuota{
|
Quotas: map[string]ModelQuota{
|
||||||
"old-model": {MaxRPM: 1, MaxTPM: 100, MaxRPD: 10},
|
"old-model": {MaxRPM: 1, MaxTPM: 100, MaxRPD: 10},
|
||||||
|
|
@ -827,7 +820,7 @@ func TestSQLitePersistAtomic_Good(t *testing.T) {
|
||||||
// --- Phase 2: Benchmark ---
|
// --- Phase 2: Benchmark ---
|
||||||
|
|
||||||
func BenchmarkSQLitePersist(b *testing.B) {
|
func BenchmarkSQLitePersist(b *testing.B) {
|
||||||
dbPath := filepath.Join(b.TempDir(), "bench.db")
|
dbPath := testPath(b.TempDir(), "bench.db")
|
||||||
rl, err := NewWithSQLite(dbPath)
|
rl, err := NewWithSQLite(dbPath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
b.Fatal(err)
|
b.Fatal(err)
|
||||||
|
|
@ -852,7 +845,7 @@ func BenchmarkSQLitePersist(b *testing.B) {
|
||||||
}
|
}
|
||||||
|
|
||||||
func BenchmarkSQLiteLoad(b *testing.B) {
|
func BenchmarkSQLiteLoad(b *testing.B) {
|
||||||
dbPath := filepath.Join(b.TempDir(), "bench-load.db")
|
dbPath := testPath(b.TempDir(), "bench-load.db")
|
||||||
rl, err := NewWithSQLite(dbPath)
|
rl, err := NewWithSQLite(dbPath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
b.Fatal(err)
|
b.Fatal(err)
|
||||||
|
|
@ -883,10 +876,10 @@ func BenchmarkSQLiteLoad(b *testing.B) {
|
||||||
|
|
||||||
// TestMigrateYAMLToSQLiteWithFullState tests migration of a realistic YAML
|
// TestMigrateYAMLToSQLiteWithFullState tests migration of a realistic YAML
|
||||||
// file that contains the full serialised RateLimiter struct.
|
// file that contains the full serialised RateLimiter struct.
|
||||||
func TestMigrateYAMLToSQLiteWithFullState_Good(t *testing.T) {
|
func TestSQLite_MigrateYAMLToSQLiteWithFullState_Good(t *testing.T) {
|
||||||
tmpDir := t.TempDir()
|
tmpDir := t.TempDir()
|
||||||
yamlPath := filepath.Join(tmpDir, "realistic.yaml")
|
yamlPath := testPath(tmpDir, "realistic.yaml")
|
||||||
sqlitePath := filepath.Join(tmpDir, "realistic.db")
|
sqlitePath := testPath(tmpDir, "realistic.db")
|
||||||
|
|
||||||
now := time.Now()
|
now := time.Now()
|
||||||
|
|
||||||
|
|
@ -919,7 +912,7 @@ func TestMigrateYAMLToSQLiteWithFullState_Good(t *testing.T) {
|
||||||
|
|
||||||
data, err := yaml.Marshal(rl)
|
data, err := yaml.Marshal(rl)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
require.NoError(t, os.WriteFile(yamlPath, data, 0644))
|
writeTestFile(t, yamlPath, string(data))
|
||||||
|
|
||||||
// Migrate.
|
// Migrate.
|
||||||
require.NoError(t, MigrateYAMLToSQLite(yamlPath, sqlitePath))
|
require.NoError(t, MigrateYAMLToSQLite(yamlPath, sqlitePath))
|
||||||
|
|
|
||||||
Loading…
Add table
Reference in a new issue