mirror of
https://github.com/labring/FastGPT.git
synced 2025-07-23 13:03:50 +00:00
feat: QPS Limit middleware (#2956)
* feat: QPS Limit middleware * chore: use request-ip to get client ip * feat: frequencyLimit schema
This commit is contained in:
27
packages/service/common/system/frequencyLimit/schema.ts
Normal file
27
packages/service/common/system/frequencyLimit/schema.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
import { getMongoModel, Schema } from '../../mongo';
|
||||
import type { FrequencyLimitSchemaType } from './type';
|
||||
|
||||
const FrequencyLimitSchema = new Schema({
|
||||
eventId: {
|
||||
type: String,
|
||||
required: true
|
||||
},
|
||||
amount: {
|
||||
type: Number,
|
||||
default: 0
|
||||
},
|
||||
expiredTime: {
|
||||
type: Date,
|
||||
required: true
|
||||
}
|
||||
});
|
||||
|
||||
try {
|
||||
FrequencyLimitSchema.index({ eventId: 1 }, { unique: true });
|
||||
FrequencyLimitSchema.index({ expiredTime: 1 }, { expireAfterSeconds: 0 });
|
||||
} catch (error) {}
|
||||
|
||||
export const MongoFrequencyLimit = getMongoModel<FrequencyLimitSchemaType>(
|
||||
'frequency_limit',
|
||||
FrequencyLimitSchema
|
||||
);
|
6
packages/service/common/system/frequencyLimit/type.d.ts
vendored
Normal file
6
packages/service/common/system/frequencyLimit/type.d.ts
vendored
Normal file
@@ -0,0 +1,6 @@
|
||||
export type FrequencyLimitSchemaType = {
|
||||
_id: string;
|
||||
eventId: string; // 事件ID
|
||||
amount: number; // 当前数量
|
||||
expiredTime: Date; // 什么时候过期,过期则重置
|
||||
};
|
32
packages/service/common/system/frequencyLimit/utils.ts
Normal file
32
packages/service/common/system/frequencyLimit/utils.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
import { AuthFrequencyLimitProps } from '@fastgpt/global/common/frequenctLimit/type';
|
||||
import { MongoFrequencyLimit } from './schema';
|
||||
import { readFromSecondary } from '../../mongo/utils';
|
||||
|
||||
export const authFrequencyLimit = async ({
|
||||
eventId,
|
||||
maxAmount,
|
||||
expiredTime
|
||||
}: AuthFrequencyLimitProps) => {
|
||||
try {
|
||||
// 对应 eventId 的 account+1, 不存在的话,则创建一个
|
||||
const result = await MongoFrequencyLimit.findOneAndUpdate(
|
||||
{
|
||||
eventId
|
||||
},
|
||||
{
|
||||
$inc: { amount: 1 },
|
||||
$setOnInsert: { expiredTime }
|
||||
},
|
||||
{
|
||||
upsert: true,
|
||||
new: true,
|
||||
...readFromSecondary
|
||||
}
|
||||
);
|
||||
|
||||
// 因为始终会返回+1的结果,所以这里不能直接等,需要多一个。
|
||||
if (result.amount > maxAmount) {
|
||||
return Promise.reject(result);
|
||||
}
|
||||
} catch (error) {}
|
||||
};
|
Reference in New Issue
Block a user