新增 Exact Cache 模块,为已有的 ExactCache 核心类提供完整的管理界面和统计功能: - 模块骨架:module.json + ExactCacheModule(实现 ModuleInterface 全部 7 个方法) - AJAX 控制器:4 个 handler(保存设置/清空缓存/重置统计/获取统计),含安全三要素 - 成本估算器:基于 UsageTracker 历史数据估算缓存节省金额 - 日统计:7 天滚动统计,shutdown 批量写入,retry-once transient lock - 管理界面:统计卡片 + Chart.js 7 天趋势图 + 设置表单 + 缓存管理 - settings-page.php:添加精确缓存 tab(与 GEO/API Gateway 相同模式) - ExactCache.php:仅添加 get_entries() 只读方法,零核心影响 - uninstall.php:添加 option + transient 批量清理 经过 3 轮 Codex 架构审查(v1.0→v2.0→v2.1→v2.2),所有 P0/P1 问题已解决。 Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
55 lines
1.5 KiB
PHP
55 lines
1.5 KiB
PHP
<?php
|
||
/**
|
||
* Cost Estimator - 缓存成本节省估算
|
||
*
|
||
* 基于缓存命中次数和平均请求成本估算节省金额。
|
||
*
|
||
* @package WPMind\Modules\ExactCache
|
||
* @since 1.0.0
|
||
*/
|
||
|
||
declare(strict_types=1);
|
||
|
||
namespace WPMind\Modules\ExactCache;
|
||
|
||
final class CostEstimator {
|
||
|
||
/**
|
||
* 获取估算的成本节省
|
||
*
|
||
* 计算公式:节省金额 = 缓存命中次数 × 平均每次请求成本
|
||
*
|
||
* @return array{total_usd: float, total_cny: float, avg_cost_per_request: float}
|
||
*/
|
||
public static function get_estimated_savings(): array {
|
||
$cache_stats = \WPMind\Cache\ExactCache::instance()->get_stats();
|
||
$hits = (int) ($cache_stats['hits'] ?? 0);
|
||
|
||
if ($hits === 0) {
|
||
return ['total_usd' => 0.0, 'total_cny' => 0.0, 'avg_cost_per_request' => 0.0];
|
||
}
|
||
|
||
// 从 UsageTracker 获取平均请求成本
|
||
$usage_stats = [];
|
||
if (class_exists('\WPMind\Modules\CostControl\UsageTracker')) {
|
||
$usage_stats = \WPMind\Modules\CostControl\UsageTracker::get_stats();
|
||
}
|
||
|
||
$total_cost = (float) ($usage_stats['total']['cost_usd'] ?? 0.0);
|
||
$total_requests = (int) ($usage_stats['total']['requests'] ?? 0);
|
||
|
||
if ($total_requests === 0) {
|
||
return ['total_usd' => 0.0, 'total_cny' => 0.0, 'avg_cost_per_request' => 0.0];
|
||
}
|
||
|
||
$avg_cost = $total_cost / $total_requests;
|
||
$saved_usd = $hits * $avg_cost;
|
||
$saved_cny = $saved_usd * 7.2; // 近似汇率
|
||
|
||
return [
|
||
'total_usd' => round($saved_usd, 4),
|
||
'total_cny' => round($saved_cny, 2),
|
||
'avg_cost_per_request' => round($avg_cost, 6),
|
||
];
|
||
}
|
||
}
|