1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
|
import { DurableObject } from "cloudflare:workers";
interface ThrottleState {
limitTimes: number;
limitEndTimeMs: number;
executedTimesCurrentCycle: number;
currentCycle: number;
}
export interface TryApplyOptions {
limitCycleExecutionTimes: number;
limitCycleTimeMs: number;
}
export interface ThrottlerResponse {
granted: boolean;
state: ThrottleState;
}
export class ThrottlerDO extends DurableObject {
limitCycleExecutionTimes = 10; // 默认:每个周期10个请求
limitCycleTimeMs = 10 * 60 * 1000; // 默认:10分钟
constructor(ctx: DurableObjectState, env: Env) {
super(ctx, env);
}
async getState(): Promise<ThrottlerResponse> {
let state = await this.ctx.storage.get('throttle_state') as ThrottleState | null;
if (!state) {
state = {
limitTimes: 0,
limitEndTimeMs: 0,
executedTimesCurrentCycle: 0,
currentCycle: 0,
};
}
const currentMs = Date.now();
// 如果周期已过期,重置状态
if (state.limitEndTimeMs > 0 && currentMs > state.limitEndTimeMs) {
state = {
...state,
limitEndTimeMs: 0,
executedTimesCurrentCycle: 0,
};
}
const granted = state.executedTimesCurrentCycle < this.limitCycleExecutionTimes;
return { granted, state };
}
async tryApply(options?: TryApplyOptions): Promise<ThrottlerResponse> {
if (options) {
this.limitCycleExecutionTimes = options.limitCycleExecutionTimes;
this.limitCycleTimeMs = options.limitCycleTimeMs;
}
let granted = false;
let state = await this.ctx.storage.get('throttle_state') as ThrottleState | null;
if (!state) {
state = {
limitTimes: 0,
limitEndTimeMs: 0,
executedTimesCurrentCycle: 0,
currentCycle: 0,
};
}
const currentMs = Date.now();
// 如果周期过期,重置周期
if (state.limitEndTimeMs > 0 && currentMs > state.limitEndTimeMs) {
state.limitEndTimeMs = 0;
state.executedTimesCurrentCycle = 0;
}
// 检查请求是否可以被批准
if (state.executedTimesCurrentCycle < this.limitCycleExecutionTimes) {
state.executedTimesCurrentCycle++;
granted = true;
} else {
state.limitTimes++;
granted = false;
}
// 如果需要,初始化新周期
if (state.limitEndTimeMs === 0) {
state.limitEndTimeMs = currentMs + this.limitCycleTimeMs;
state.currentCycle++;
if (state.currentCycle >= 65535) {
state.currentCycle = 1;
}
}
await this.ctx.storage.put('throttle_state', state);
return { granted, state };
}
}
|