hono
回到对话Chat window
3
资源管理器Explorer
HONO
benchmarks
docs
src
adapter
helper
jsx
middleware
cors
etag
rate-limiter
TSindex.tsM
TSindex.test.tsM
TSstore.tsU
M↓README.md
secure-headers
router
TShono.ts
TScontext.ts
{}package.json
M↓MIGRATION.md
M↓MIGRATION.md
TSindex.ts
TSstore.ts
{}package.json
srcmiddlewarerate-limiterindex.tsrateLimiter
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import type { MiddlewareHandler } from '../../types'
import { MemoryStore, type Store } from './store'
/** 滑动窗口:上一窗口按剩余比例计入,边界不再突刺。Sliding window: the last one counted by the share left. */
export const rateLimiter = (options: {
limit: number
windowMs: number
store?: Store
}): MiddlewareHandler => {
const store = options.store ?? new MemoryStore()
return async (c, next) => {
const key = c.req.header('x-forwarded-for') ?? 'anonymous'
const { current, previous, elapsed } = await store.hit(key, options.windowMs)
const weight = 1 - elapsed / options.windowMs
const count = previous * weight + current
c.header('RateLimit', `limit=${options.limit}, remaining=${Math.max(0, options.limit - count)}`)
if (count > options.limit) {
return c.text('Too Many Requests', 429)
}
await next()
}
问题Problems输出Output终端Terminal
➜ hono git:(feat/sliding-window) bun test src/middleware/rate-limiter bun test v1.2.4 ✓ src/middleware/rate-limiter/index.test.ts (9 tests) 21ms ✓ 窗口边界不再突刺no burst at the window’s edge ✓ 存储失效时放行并记日志a failing store lets requests through, logged 9 pass 0 fail ➜ hono git:(feat/sliding-window) ▍
限流改成滑动窗口Sliding-window limiting
把限流改成滑动窗口,计数存储要能换成 Workers KVMake the limiter a sliding window; the store should swap for Workers KV
搜索 rateLimiter · 4 处Searched rateLimiter · 4 hits
读取 index.tsRead index.ts
index.ts+6−2
const count = await store.incr(key)
const { current, previous, elapsed } =
await store.hit(key, options.windowMs)
const weight = 1 - elapsed / options.windowMs
const count = previous * weight + current
bun test src/middleware/rate-limiter · 9 pass

改好了:按「上一窗口 × 剩余比例 + 当前窗口」估算,窗口边界不再突刺。计数存储抽成 Store 接口,内置内存版,KV 版在 store.ts。

Done: it counts “previous window × the share left + this one”, so no burst at the edge. The counter is a Store now, memory built in, KV in store.ts.

TSindex.ts:13-15 这三行加个注释comment these three lines▍
∞Agent 完全访问Full access Opus 5.5
feat/sliding-window* 0↓ 1↑ 0 0行 15,列 48Ln 15, Col 48空格: 2Spaces: 2UTF-8LFTypeScript
选择颜色主题Select Color Theme
深色主题dark themes
Bao Dark
Dark Modern
Kimbie Dark
Monokai Dimmed
Solarized Dark
Tomorrow Night Blue
浅色主题light themes
Bao Light
Light Modern
Solarized Light