64 lines
1.6 KiB
PHP
64 lines
1.6 KiB
PHP
|
|
<?php
|
||
|
|
|
||
|
|
declare(strict_types=1);
|
||
|
|
|
||
|
|
namespace Mod\Proxy\Services;
|
||
|
|
|
||
|
|
use Illuminate\Support\Facades\Cache;
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Tracks API usage per key — bytes for proxy, requests for SEO.
|
||
|
|
*
|
||
|
|
* $meter = app(UsageMeter::class);
|
||
|
|
* $meter->recordBytes('api-key-123', 1048576); // 1MB
|
||
|
|
* $meter->recordRequest('api-key-456');
|
||
|
|
* $usage = $meter->getUsage('api-key-123');
|
||
|
|
*/
|
||
|
|
class UsageMeter
|
||
|
|
{
|
||
|
|
/**
|
||
|
|
* $meter->recordBytes('key', 1048576);
|
||
|
|
*/
|
||
|
|
public function recordBytes(string $apiKey, int $bytes): void
|
||
|
|
{
|
||
|
|
$key = "usage:bytes:{$apiKey}";
|
||
|
|
$current = (int) Cache::get($key, 0);
|
||
|
|
Cache::put($key, $current + $bytes, 86400 * 30); // 30 day window
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* $meter->recordRequest('key');
|
||
|
|
*/
|
||
|
|
public function recordRequest(string $apiKey): void
|
||
|
|
{
|
||
|
|
$key = "usage:requests:{$apiKey}";
|
||
|
|
$current = (int) Cache::get($key, 0);
|
||
|
|
Cache::put($key, $current + 1, 86400 * 30);
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* $usage = $meter->getUsage('key');
|
||
|
|
* // ['bytes' => 104857600, 'requests' => 523, 'gb' => 0.1]
|
||
|
|
*/
|
||
|
|
public function getUsage(string $apiKey): array
|
||
|
|
{
|
||
|
|
$bytes = (int) Cache::get("usage:bytes:{$apiKey}", 0);
|
||
|
|
$requests = (int) Cache::get("usage:requests:{$apiKey}", 0);
|
||
|
|
|
||
|
|
return [
|
||
|
|
'bytes' => $bytes,
|
||
|
|
'gb' => round($bytes / (1024 * 1024 * 1024), 4),
|
||
|
|
'requests' => $requests,
|
||
|
|
];
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* $meter->resetUsage('key');
|
||
|
|
*/
|
||
|
|
public function resetUsage(string $apiKey): void
|
||
|
|
{
|
||
|
|
Cache::forget("usage:bytes:{$apiKey}");
|
||
|
|
Cache::forget("usage:requests:{$apiKey}");
|
||
|
|
}
|
||
|
|
}
|