cost-limiter 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +11 -0
- package/LICENSE +15 -0
- package/README.md +495 -0
- package/dist/index.cjs +384 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +151 -0
- package/dist/index.d.ts +151 -0
- package/dist/index.js +349 -0
- package/dist/index.js.map +1 -0
- package/package.json +73 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## [0.1.0] — 2026-05-15
|
|
4
|
+
|
|
5
|
+
### Added
|
|
6
|
+
|
|
7
|
+
- `CostLimiter` with per-user, per-team, per-api-key, and global dollar budgets.
|
|
8
|
+
- Minute, hour, day, and month windows with hard limits and soft `BudgetWarning` events at 80%.
|
|
9
|
+
- Pluggable storage: `MemoryCostStorage`, `RedisCostStorage`.
|
|
10
|
+
- Pricing snapshot for major OpenAI, Anthropic, Google, Mistral, and Groq models with override hook.
|
|
11
|
+
- Client wrappers: `wrap(openai)`, `wrapAnthropic(anthropic)`.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 cost-limiter contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND.
|
package/README.md
ADDED
|
@@ -0,0 +1,495 @@
|
|
|
1
|
+
# cost-limiter
|
|
2
|
+
|
|
3
|
+
[](https://www.npmjs.com/package/cost-limiter)
|
|
4
|
+
[](https://bundlephobia.com/package/cost-limiter)
|
|
5
|
+
[](./LICENSE)
|
|
6
|
+
[](https://www.typescriptlang.org/)
|
|
7
|
+
|
|
8
|
+
**Your LLM API bill is not a rate-limit problem — it's a cost problem.** `cost-limiter` wraps OpenAI, Anthropic, and other LLM clients with **dollar budgets** per user, per team, per API key, and globally. Built-in pricing tables for every current model, multiple time windows, soft warnings at 80%, hard limits with proper `429 Retry-After` data, and a pluggable storage backend so Redis-backed limits work across N app servers.
|
|
9
|
+
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
## Installation
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
npm install cost-limiter
|
|
16
|
+
pnpm add cost-limiter
|
|
17
|
+
yarn add cost-limiter
|
|
18
|
+
# Optional:
|
|
19
|
+
npm install ioredis # for distributed enforcement
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
---
|
|
23
|
+
|
|
24
|
+
## Quick Start
|
|
25
|
+
|
|
26
|
+
```ts
|
|
27
|
+
import OpenAI from "openai";
|
|
28
|
+
import { CostLimiter } from "cost-limiter";
|
|
29
|
+
|
|
30
|
+
const limiter = new CostLimiter({
|
|
31
|
+
budgets: { perUser: { day: 0.50, month: 5.00 } },
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
const openai = limiter.wrap(new OpenAI());
|
|
35
|
+
await openai.chat.completions.create({
|
|
36
|
+
userId: "usr_123",
|
|
37
|
+
model: "gpt-4o-mini",
|
|
38
|
+
messages: [{ role: "user", content: "Hi" }],
|
|
39
|
+
} as any);
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
---
|
|
43
|
+
|
|
44
|
+
## Core Usage Examples
|
|
45
|
+
|
|
46
|
+
### 1. Per-user daily and monthly budgets (OpenAI)
|
|
47
|
+
|
|
48
|
+
```ts
|
|
49
|
+
import OpenAI from "openai";
|
|
50
|
+
import { CostLimiter } from "cost-limiter";
|
|
51
|
+
|
|
52
|
+
const limiter = new CostLimiter({
|
|
53
|
+
budgets: { perUser: { day: 1.00, month: 25.00 } },
|
|
54
|
+
});
|
|
55
|
+
const openai = limiter.wrap(new OpenAI());
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
### 2. Per-team budget (Anthropic)
|
|
59
|
+
|
|
60
|
+
```ts
|
|
61
|
+
import Anthropic from "@anthropic-ai/sdk";
|
|
62
|
+
import { CostLimiter } from "cost-limiter";
|
|
63
|
+
|
|
64
|
+
const limiter = new CostLimiter({
|
|
65
|
+
budgets: { perTeam: { day: 50, month: 500 } },
|
|
66
|
+
});
|
|
67
|
+
const anthropic = limiter.wrapAnthropic(new Anthropic());
|
|
68
|
+
|
|
69
|
+
await anthropic.messages.create({
|
|
70
|
+
teamId: "team_abc",
|
|
71
|
+
model: "claude-sonnet-4",
|
|
72
|
+
max_tokens: 200,
|
|
73
|
+
messages: [{ role: "user", content: "Hi" }],
|
|
74
|
+
} as any);
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
### 3. Listen to BudgetWarning at 80%
|
|
78
|
+
|
|
79
|
+
```ts
|
|
80
|
+
limiter.on("BudgetWarning", (e) => {
|
|
81
|
+
console.warn(`User ${e.key} is at ${(e.percent * 100).toFixed(1)}% of ${e.window} budget`);
|
|
82
|
+
});
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
### 4. Return 429 on CostLimitError
|
|
86
|
+
|
|
87
|
+
```ts
|
|
88
|
+
import { CostLimitError } from "cost-limiter";
|
|
89
|
+
|
|
90
|
+
app.post("/chat", async (req, res) => {
|
|
91
|
+
try {
|
|
92
|
+
const completion = await openai.chat.completions.create({ userId: req.user.id, ...req.body });
|
|
93
|
+
res.json(completion);
|
|
94
|
+
} catch (err) {
|
|
95
|
+
if (err instanceof CostLimitError) {
|
|
96
|
+
const seconds = Math.ceil((err.resetAt.getTime() - Date.now()) / 1000);
|
|
97
|
+
res.setHeader("Retry-After", seconds);
|
|
98
|
+
return res.status(429).json({ error: err.message, resetAt: err.resetAt });
|
|
99
|
+
}
|
|
100
|
+
throw err;
|
|
101
|
+
}
|
|
102
|
+
});
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
### 5. Usage report for a dashboard
|
|
106
|
+
|
|
107
|
+
```ts
|
|
108
|
+
const report = await limiter.getUsage("usr_123");
|
|
109
|
+
// { dimension: "user", key: "usr_123", spend: { day: 0.42, month: 1.83, ... }, limit: { day: 1, ... } }
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
### 6. Memory in dev, Redis in prod
|
|
113
|
+
|
|
114
|
+
```ts
|
|
115
|
+
import Redis from "ioredis";
|
|
116
|
+
import { CostLimiter, MemoryCostStorage, RedisCostStorage } from "cost-limiter";
|
|
117
|
+
|
|
118
|
+
const storage = process.env.NODE_ENV === "production"
|
|
119
|
+
? new RedisCostStorage(new Redis(process.env.REDIS_URL!))
|
|
120
|
+
: new MemoryCostStorage();
|
|
121
|
+
|
|
122
|
+
const limiter = new CostLimiter({ storage, budgets: { perUser: { day: 1 } } });
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
---
|
|
126
|
+
|
|
127
|
+
## Framework Integration Examples
|
|
128
|
+
|
|
129
|
+
### Express middleware
|
|
130
|
+
|
|
131
|
+
```ts
|
|
132
|
+
import express from "express";
|
|
133
|
+
import { CostLimiter, CostLimitError } from "cost-limiter";
|
|
134
|
+
|
|
135
|
+
const limiter = new CostLimiter({ budgets: { perUser: { day: 1 } } });
|
|
136
|
+
const app = express();
|
|
137
|
+
app.use(
|
|
138
|
+
limiter.middleware((req: any) => ({
|
|
139
|
+
userId: req.user?.id,
|
|
140
|
+
estimatedCostUsd: 0.0001,
|
|
141
|
+
})),
|
|
142
|
+
);
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
### Hono middleware
|
|
146
|
+
|
|
147
|
+
```ts
|
|
148
|
+
import { Hono } from "hono";
|
|
149
|
+
import { CostLimiter, CostLimitError } from "cost-limiter";
|
|
150
|
+
|
|
151
|
+
const limiter = new CostLimiter({ budgets: { perUser: { day: 1 } } });
|
|
152
|
+
const app = new Hono();
|
|
153
|
+
app.use("*", async (c, next) => {
|
|
154
|
+
try {
|
|
155
|
+
await limiter.check({ userId: c.req.header("x-user-id") ?? "anon", provider: "openai", model: "gpt-4o-mini", inputTokens: 0 });
|
|
156
|
+
await next();
|
|
157
|
+
} catch (err) {
|
|
158
|
+
if (err instanceof CostLimitError) {
|
|
159
|
+
return c.json({ error: err.message }, 429, { "Retry-After": String(Math.ceil((err.resetAt.getTime() - Date.now()) / 1000)) });
|
|
160
|
+
}
|
|
161
|
+
throw err;
|
|
162
|
+
}
|
|
163
|
+
});
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
### Next.js App Router
|
|
167
|
+
|
|
168
|
+
```ts
|
|
169
|
+
// app/api/chat/route.ts
|
|
170
|
+
import OpenAI from "openai";
|
|
171
|
+
import { CostLimiter, CostLimitError } from "cost-limiter";
|
|
172
|
+
import { NextResponse } from "next/server";
|
|
173
|
+
|
|
174
|
+
const limiter = new CostLimiter({ budgets: { perUser: { day: 1 } } });
|
|
175
|
+
const openai = limiter.wrap(new OpenAI());
|
|
176
|
+
|
|
177
|
+
export async function POST(req: Request) {
|
|
178
|
+
const { userId, ...body } = await req.json();
|
|
179
|
+
try {
|
|
180
|
+
const completion = await openai.chat.completions.create({ userId, ...body } as any);
|
|
181
|
+
return NextResponse.json(completion);
|
|
182
|
+
} catch (err) {
|
|
183
|
+
if (err instanceof CostLimitError) {
|
|
184
|
+
return NextResponse.json({ error: err.message }, { status: 429, headers: { "Retry-After": String(Math.ceil((err.resetAt.getTime() - Date.now()) / 1000)) } });
|
|
185
|
+
}
|
|
186
|
+
throw err;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
### tRPC procedure middleware
|
|
192
|
+
|
|
193
|
+
```ts
|
|
194
|
+
import { initTRPC, TRPCError } from "@trpc/server";
|
|
195
|
+
import { CostLimiter, CostLimitError } from "cost-limiter";
|
|
196
|
+
|
|
197
|
+
const limiter = new CostLimiter({ budgets: { perUser: { day: 1 } } });
|
|
198
|
+
const t = initTRPC.create();
|
|
199
|
+
|
|
200
|
+
const withBudget = t.middleware(async ({ ctx, next }) => {
|
|
201
|
+
try {
|
|
202
|
+
await limiter.check({ userId: (ctx as { userId: string }).userId, provider: "openai", model: "gpt-4o-mini", inputTokens: 0, estimatedCostUsd: 0.001 });
|
|
203
|
+
} catch (err) {
|
|
204
|
+
if (err instanceof CostLimitError) throw new TRPCError({ code: "TOO_MANY_REQUESTS", message: err.message });
|
|
205
|
+
throw err;
|
|
206
|
+
}
|
|
207
|
+
return next();
|
|
208
|
+
});
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
---
|
|
212
|
+
|
|
213
|
+
## Configuration Reference
|
|
214
|
+
|
|
215
|
+
### `new CostLimiter(options)`
|
|
216
|
+
|
|
217
|
+
| Option | Type | Default | Description |
|
|
218
|
+
| -------------- | --------------------- | ---------------------- | ------------------------------------------ |
|
|
219
|
+
| `budgets` | `BudgetConfig` | `{}` | Per-dimension/window budgets in USD |
|
|
220
|
+
| `storage` | `StorageAdapter` | `new MemoryCostStorage()` | Where to persist counters |
|
|
221
|
+
| `pricing` | `"auto" \| Record<...>`| `"auto"` | Pricing table (override or extend) |
|
|
222
|
+
| `warnThreshold`| `number` | `0.8` | Emit `BudgetWarning` at this fraction |
|
|
223
|
+
|
|
224
|
+
### `BudgetConfig`
|
|
225
|
+
|
|
226
|
+
```ts
|
|
227
|
+
interface BudgetConfig {
|
|
228
|
+
perUser?: { minute?: number; hour?: number; day?: number; month?: number };
|
|
229
|
+
perTeam?: { minute?: number; hour?: number; day?: number; month?: number };
|
|
230
|
+
perApiKey?: { minute?: number; hour?: number; day?: number; month?: number };
|
|
231
|
+
global?: { minute?: number; hour?: number; day?: number; month?: number };
|
|
232
|
+
}
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
### `RedisCostStorage(redisClient, prefix?)`
|
|
236
|
+
|
|
237
|
+
| Option | Type | Default | Description |
|
|
238
|
+
| --------------- | ----------- | ---------------- | ---------------------------- |
|
|
239
|
+
| `redis` | `RedisLike` | — | `ioredis` client (or compat) |
|
|
240
|
+
| `prefix` | `string` | `"cost-limiter"` | Key namespace |
|
|
241
|
+
|
|
242
|
+
### `wrap(client, ctx?)` options
|
|
243
|
+
|
|
244
|
+
| Option | Type | Default | Description |
|
|
245
|
+
| ------------- | --------- | ------- | --------------------------------- |
|
|
246
|
+
| `ctx.provider`| `"openai"`| `"openai"` | Wire shape used for usage extraction |
|
|
247
|
+
|
|
248
|
+
---
|
|
249
|
+
|
|
250
|
+
## Pricing Reference
|
|
251
|
+
|
|
252
|
+
| Model | Input $/1M | Output $/1M |
|
|
253
|
+
| ------------------- | ---------: | ----------: |
|
|
254
|
+
| `gpt-4o` | 2.50 | 10.00 |
|
|
255
|
+
| `gpt-4o-mini` | 0.15 | 0.60 |
|
|
256
|
+
| `gpt-4-turbo` | 10.00 | 30.00 |
|
|
257
|
+
| `gpt-3.5-turbo` | 0.50 | 1.50 |
|
|
258
|
+
| `o1` | 15.00 | 60.00 |
|
|
259
|
+
| `o1-mini` | 3.00 | 12.00 |
|
|
260
|
+
| `o3-mini` | 1.10 | 4.40 |
|
|
261
|
+
| `claude-opus-4` | 15.00 | 75.00 |
|
|
262
|
+
| `claude-sonnet-4` | 3.00 | 15.00 |
|
|
263
|
+
| `claude-haiku-4` | 1.00 | 5.00 |
|
|
264
|
+
| `gemini-2.0-flash` | 0.10 | 0.40 |
|
|
265
|
+
| `gemini-1.5-pro` | 1.25 | 5.00 |
|
|
266
|
+
| `gemini-1.5-flash` | 0.075 | 0.30 |
|
|
267
|
+
| `llama-3.3-70b` | 0.59 | 0.79 |
|
|
268
|
+
| `mixtral-8x7b` | 0.24 | 0.24 |
|
|
269
|
+
|
|
270
|
+
Override:
|
|
271
|
+
|
|
272
|
+
```ts
|
|
273
|
+
import { CostLimiter, DEFAULT_PRICING } from "cost-limiter";
|
|
274
|
+
|
|
275
|
+
const limiter = new CostLimiter({
|
|
276
|
+
pricing: { ...DEFAULT_PRICING, "my-fine-tune": { inputPerMTokens: 0.5, outputPerMTokens: 2.0 } },
|
|
277
|
+
});
|
|
278
|
+
```
|
|
279
|
+
|
|
280
|
+
---
|
|
281
|
+
|
|
282
|
+
## Error Handling
|
|
283
|
+
|
|
284
|
+
```ts
|
|
285
|
+
class CostLimitError extends Error {
|
|
286
|
+
readonly limit: number;
|
|
287
|
+
readonly used: number;
|
|
288
|
+
readonly remaining: number;
|
|
289
|
+
readonly resetAt: Date;
|
|
290
|
+
readonly window: "minute" | "hour" | "day" | "month";
|
|
291
|
+
readonly dimension: "user" | "team" | "apiKey" | "global";
|
|
292
|
+
readonly dimensionKey: string;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
interface BudgetWarningEvent {
|
|
296
|
+
dimension: string;
|
|
297
|
+
key: string;
|
|
298
|
+
window: "minute" | "hour" | "day" | "month";
|
|
299
|
+
used: number;
|
|
300
|
+
limit: number;
|
|
301
|
+
percent: number;
|
|
302
|
+
}
|
|
303
|
+
```
|
|
304
|
+
|
|
305
|
+
Proper 429 response:
|
|
306
|
+
|
|
307
|
+
```ts
|
|
308
|
+
catch (err) {
|
|
309
|
+
if (err instanceof CostLimitError) {
|
|
310
|
+
const secs = Math.ceil((err.resetAt.getTime() - Date.now()) / 1000);
|
|
311
|
+
res.setHeader("Retry-After", secs);
|
|
312
|
+
return res.status(429).json({ limit: err.limit, used: err.used, resetAt: err.resetAt });
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
```
|
|
316
|
+
|
|
317
|
+
---
|
|
318
|
+
|
|
319
|
+
## TypeScript Types
|
|
320
|
+
|
|
321
|
+
```ts
|
|
322
|
+
import type {
|
|
323
|
+
BudgetConfig,
|
|
324
|
+
UsageReport,
|
|
325
|
+
CostLimitError,
|
|
326
|
+
BudgetWarningEvent,
|
|
327
|
+
StorageAdapter,
|
|
328
|
+
PricingConfig,
|
|
329
|
+
} from "cost-limiter";
|
|
330
|
+
```
|
|
331
|
+
|
|
332
|
+
Implement a custom adapter:
|
|
333
|
+
|
|
334
|
+
```ts
|
|
335
|
+
import type { StorageAdapter, Window } from "cost-limiter";
|
|
336
|
+
|
|
337
|
+
class PostgresStorage implements StorageAdapter {
|
|
338
|
+
async increment(key: string, amount: number, _w: Window, resetAt: Date) {
|
|
339
|
+
/* INSERT ... ON CONFLICT DO UPDATE */
|
|
340
|
+
return 0;
|
|
341
|
+
}
|
|
342
|
+
async get(key: string, _w: Window) { return 0; }
|
|
343
|
+
async reset(key: string) { /* DELETE */ }
|
|
344
|
+
}
|
|
345
|
+
```
|
|
346
|
+
|
|
347
|
+
---
|
|
348
|
+
|
|
349
|
+
## Real-World Recipe — Multi-Tenant SaaS LLM API
|
|
350
|
+
|
|
351
|
+
```ts
|
|
352
|
+
import express from "express";
|
|
353
|
+
import jwt from "jsonwebtoken";
|
|
354
|
+
import OpenAI from "openai";
|
|
355
|
+
import Redis from "ioredis";
|
|
356
|
+
import {
|
|
357
|
+
CostLimiter,
|
|
358
|
+
CostLimitError,
|
|
359
|
+
RedisCostStorage,
|
|
360
|
+
} from "cost-limiter";
|
|
361
|
+
|
|
362
|
+
const tierBudgets: Record<string, { day: number; month: number }> = {
|
|
363
|
+
free: { day: 0.10, month: 2.00 },
|
|
364
|
+
pro: { day: 1.00, month: 20.00 },
|
|
365
|
+
team: { day: 10.00, month: 200.00 },
|
|
366
|
+
};
|
|
367
|
+
|
|
368
|
+
const storage = new RedisCostStorage(new Redis(process.env.REDIS_URL!));
|
|
369
|
+
|
|
370
|
+
function limiterFor(tier: keyof typeof tierBudgets) {
|
|
371
|
+
return new CostLimiter({
|
|
372
|
+
storage,
|
|
373
|
+
budgets: tier === "team"
|
|
374
|
+
? { perTeam: tierBudgets.team }
|
|
375
|
+
: { perUser: tierBudgets[tier] },
|
|
376
|
+
});
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
const app = express();
|
|
380
|
+
app.use(express.json());
|
|
381
|
+
|
|
382
|
+
app.use((req: any, res, next) => {
|
|
383
|
+
const token = req.headers.authorization?.replace("Bearer ", "");
|
|
384
|
+
req.user = jwt.verify(token, process.env.JWT_SECRET!) as { userId: string; tier: string; teamId?: string };
|
|
385
|
+
next();
|
|
386
|
+
});
|
|
387
|
+
|
|
388
|
+
app.post("/chat", async (req: any, res) => {
|
|
389
|
+
const limiter = limiterFor(req.user.tier as keyof typeof tierBudgets);
|
|
390
|
+
limiter.on("BudgetWarning", (e) => {
|
|
391
|
+
fetch(process.env.WEBHOOK_URL!, {
|
|
392
|
+
method: "POST",
|
|
393
|
+
body: JSON.stringify({ at80: e }),
|
|
394
|
+
});
|
|
395
|
+
});
|
|
396
|
+
const openai = limiter.wrap(new OpenAI());
|
|
397
|
+
try {
|
|
398
|
+
const completion = await openai.chat.completions.create({
|
|
399
|
+
userId: req.user.userId,
|
|
400
|
+
teamId: req.user.teamId,
|
|
401
|
+
model: req.body.model ?? "gpt-4o-mini",
|
|
402
|
+
messages: req.body.messages,
|
|
403
|
+
} as any);
|
|
404
|
+
res.json(completion);
|
|
405
|
+
} catch (err) {
|
|
406
|
+
if (err instanceof CostLimitError) {
|
|
407
|
+
return res.status(429).json({ error: err.message, resetAt: err.resetAt });
|
|
408
|
+
}
|
|
409
|
+
throw err;
|
|
410
|
+
}
|
|
411
|
+
});
|
|
412
|
+
|
|
413
|
+
app.get("/usage", async (req: any, res) => {
|
|
414
|
+
const limiter = limiterFor(req.user.tier as keyof typeof tierBudgets);
|
|
415
|
+
res.json(await limiter.getUsage(req.user.userId));
|
|
416
|
+
});
|
|
417
|
+
|
|
418
|
+
app.listen(3000);
|
|
419
|
+
```
|
|
420
|
+
|
|
421
|
+
---
|
|
422
|
+
|
|
423
|
+
## Storage Adapter Guide — Postgres
|
|
424
|
+
|
|
425
|
+
```ts
|
|
426
|
+
import { Pool } from "pg";
|
|
427
|
+
import type { StorageAdapter, Window } from "cost-limiter";
|
|
428
|
+
|
|
429
|
+
export class PostgresCostStorage implements StorageAdapter {
|
|
430
|
+
constructor(private pool: Pool, private table = "cost_counters") {}
|
|
431
|
+
|
|
432
|
+
async init() {
|
|
433
|
+
await this.pool.query(`
|
|
434
|
+
CREATE TABLE IF NOT EXISTS ${this.table} (
|
|
435
|
+
key TEXT NOT NULL,
|
|
436
|
+
window TEXT NOT NULL,
|
|
437
|
+
value DOUBLE PRECISION NOT NULL DEFAULT 0,
|
|
438
|
+
reset_at TIMESTAMPTZ NOT NULL,
|
|
439
|
+
PRIMARY KEY (key, window)
|
|
440
|
+
);
|
|
441
|
+
`);
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
async increment(key: string, amount: number, window: Window, resetAt: Date): Promise<number> {
|
|
445
|
+
const res = await this.pool.query<{ value: number }>(
|
|
446
|
+
`INSERT INTO ${this.table} (key, window, value, reset_at)
|
|
447
|
+
VALUES ($1, $2, $3, $4)
|
|
448
|
+
ON CONFLICT (key, window) DO UPDATE SET
|
|
449
|
+
value = CASE
|
|
450
|
+
WHEN ${this.table}.reset_at <= NOW() THEN EXCLUDED.value
|
|
451
|
+
ELSE ${this.table}.value + EXCLUDED.value
|
|
452
|
+
END,
|
|
453
|
+
reset_at = CASE
|
|
454
|
+
WHEN ${this.table}.reset_at <= NOW() THEN EXCLUDED.reset_at
|
|
455
|
+
ELSE ${this.table}.reset_at
|
|
456
|
+
END
|
|
457
|
+
RETURNING value`,
|
|
458
|
+
[key, window, amount, resetAt],
|
|
459
|
+
);
|
|
460
|
+
return Number(res.rows[0]!.value);
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
async get(key: string, window: Window): Promise<number> {
|
|
464
|
+
const res = await this.pool.query<{ value: number }>(
|
|
465
|
+
`SELECT value FROM ${this.table} WHERE key = $1 AND window = $2 AND reset_at > NOW()`,
|
|
466
|
+
[key, window],
|
|
467
|
+
);
|
|
468
|
+
return res.rows[0] ? Number(res.rows[0].value) : 0;
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
async reset(key: string): Promise<void> {
|
|
472
|
+
await this.pool.query(`DELETE FROM ${this.table} WHERE key = $1`, [key]);
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
```
|
|
476
|
+
|
|
477
|
+
---
|
|
478
|
+
|
|
479
|
+
## Comparison Table
|
|
480
|
+
|
|
481
|
+
| Feature | express-rate-limit | bottleneck | **cost-limiter** |
|
|
482
|
+
| ---------------------- | :----------------: | :--------: | :--------------: |
|
|
483
|
+
| Token-based limiting | ⚠️ | ⚠️ | ✅ |
|
|
484
|
+
| Dollar budgets | ❌ | ❌ | ✅ |
|
|
485
|
+
| Per-user tracking | ✅ | ✅ | ✅ |
|
|
486
|
+
| Multi-window | ⚠️ | ❌ | ✅ |
|
|
487
|
+
| OpenAI/Anthropic wrap | ❌ | ❌ | ✅ |
|
|
488
|
+
| Redis backend | ✅ | ✅ | ✅ |
|
|
489
|
+
| TypeScript types | ⚠️ | ⚠️ | ✅ |
|
|
490
|
+
|
|
491
|
+
---
|
|
492
|
+
|
|
493
|
+
## License
|
|
494
|
+
|
|
495
|
+
MIT
|