$window, 'total' => 0, 'clients' => [], ]; } $key = hash('sha256', $ip); if ($state['total'] >= (int) config('mini_api.login_global_per_minute', 600) || ($state['clients'][$key] ?? 0) >= (int) config('mini_api.login_ip_per_minute', 60) || (!isset($state['clients'][$key]) && count($state['clients']) >= 4096)) { throw new ApiException(42901, '登录请求过于频繁,请稍后再试', 429); } $state['total']++; $state['clients'][$key] = ($state['clients'][$key] ?? 0) + 1; $json = json_encode($state, JSON_THROW_ON_ERROR); rewind($file); if (!ftruncate($file, 0) || fwrite($file, $json) !== strlen($json) || !fflush($file)) { throw new ApiException(50302, '登录服务暂时不可用', 503); } } finally { flock($file, LOCK_UN); fclose($file); } } }