57 lines
1.8 KiB
PHP
57 lines
1.8 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
|
|
namespace app\mcp\service;
|
|
|
|
use think\facade\Cache;
|
|
use think\facade\Log;
|
|
|
|
/**
|
|
* 基于系统缓存的固定窗口限流(缓存驱动为 redis 时计数更准确;文件缓存下为近似值)。
|
|
* 计数只是保护措施:缓存读写出错(如文件缓存在并发调用时读到写了一半的文件)时放行并记日志,
|
|
* 不能让记账失败把正常查询变成“内部错误”。
|
|
*/
|
|
class RateLimiter
|
|
{
|
|
/** 记一次并判断是否仍在限额内 */
|
|
public static function hit(string $key, int $limit, int $windowSeconds): bool
|
|
{
|
|
try {
|
|
$bucket = 'ai_mcp_rl_' . $key . '_' . intdiv(time(), $windowSeconds);
|
|
$count = (int) Cache::get($bucket, 0) + 1;
|
|
Cache::set($bucket, $count, $windowSeconds * 2);
|
|
return $count <= $limit;
|
|
} catch (\Throwable $e) {
|
|
Log::warning('[ai_mcp] 限流计数失败,本次放行: ' . $e->getMessage());
|
|
return true;
|
|
}
|
|
}
|
|
|
|
public static function rowsToday(int $adminId): int
|
|
{
|
|
try {
|
|
return (int) Cache::get(self::rowsKey($adminId), 0);
|
|
} catch (\Throwable $e) {
|
|
Log::warning('[ai_mcp] 读取今日行数失败: ' . $e->getMessage());
|
|
return 0;
|
|
}
|
|
}
|
|
|
|
public static function addRows(int $adminId, int $rows): void
|
|
{
|
|
if ($rows <= 0) {
|
|
return;
|
|
}
|
|
try {
|
|
Cache::set(self::rowsKey($adminId), self::rowsToday($adminId) + $rows, 90000);
|
|
} catch (\Throwable $e) {
|
|
Log::warning('[ai_mcp] 记录今日行数失败: ' . $e->getMessage());
|
|
}
|
|
}
|
|
|
|
private static function rowsKey(int $adminId): string
|
|
{
|
|
return 'ai_mcp_rows_' . $adminId . '_' . date('Ymd');
|
|
}
|
|
}
|