trypost/app/Models/Traits/HasUsage.php
Paulo Castellano e35b8df86a fix: cast cached post count to int and align local cache default to redis
Production crashed on every Inertia request after the PostHog branch
landed:

  TypeError: App\Models\Account::cachedPostCount(): Return value must
  be of type int, string returned at app/Models/Traits/HasUsage.php:80

Root cause: Laravel's RedisStore optimises is_numeric values by storing
them raw (not serialised) so they remain INCR/DECR-able atomically.
The side effect is that an int written via Cache::put comes back as a
string on read. The strict ': int' return type on cachedPostCount then
threw a TypeError.

Local dev and CI used the file/array/database drivers respectively,
which serialise everything blindly and preserve the int type, so the
bug never surfaced before deploy.

Fixes:
- Cast the Cache::remember result to (int) — defensive, survives any
  driver-specific behaviour. Documented inline so the cast is not
  later removed as redundant.
- Change config/cache.php default from 'database' to 'redis' so local
  dev matches prod by default and similar driver-specific bugs surface
  before merge instead of after deploy.
- Regression test that seeds the cache with a literal string (mimics
  the production Redis read) and asserts cachedPostCount still returns
  an int.
2026-05-07 14:31:07 -03:00

92 lines
3.3 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Models\Traits;
use App\Features\MemberLimit;
use App\Features\MonthlyCreditsLimit;
use App\Features\SocialAccountLimit;
use App\Features\WorkspaceLimit;
use App\Models\AiUsageLog;
use App\Models\Invite;
use App\Models\Post;
use Illuminate\Support\Facades\Cache;
use Laravel\Pennant\Feature;
/**
* Provides account-level usage counts and plan-resolved feature limits.
*
* The `featureLimits()` call resolves Pennant features for the account,
* which writes to the features cache table on first access. Pennant cache
* is invalidated automatically when `plan_id` changes (see Account::booted).
*/
trait HasUsage
{
/**
* Cache TTL for the per-account post count. Posts are unbounded by plan
* limits and not used for any quota gating, so a few minutes of staleness
* is acceptable in exchange for skipping a potentially heavy aggregate
* query on every authenticated request.
*/
private const POST_COUNT_CACHE_TTL = 300;
/**
* @return array{workspaceCount: int, socialAccountCount: int, memberCount: int, pendingInviteCount: int, postCount: int, creditsUsed: int}
*/
public function usage(): array
{
$workspaces = $this->workspaces()
->withCount('socialAccounts')
->get();
return [
'workspaceCount' => $workspaces->count(),
'socialAccountCount' => (int) $workspaces->sum('social_accounts_count'),
'memberCount' => $this->users()->count(),
'pendingInviteCount' => Invite::where('account_id', $this->id)
->whereNull('accepted_at')
->count(),
'postCount' => $this->cachedPostCount($workspaces->pluck('id')->all()),
'creditsUsed' => AiUsageLog::monthlyCredits($this->id),
];
}
/**
* @return array{workspaceLimit: int, socialAccountLimit: int, memberLimit: int, monthlyCreditsLimit: int}
*/
public function featureLimits(): array
{
return [
'workspaceLimit' => Feature::for($this)->value(WorkspaceLimit::class),
'socialAccountLimit' => Feature::for($this)->value(SocialAccountLimit::class),
'memberLimit' => Feature::for($this)->value(MemberLimit::class),
'monthlyCreditsLimit' => Feature::for($this)->value(MonthlyCreditsLimit::class),
];
}
/**
* The `(int)` cast on the cached value is load-bearing: Laravel's
* RedisStore skips serialize()/unserialize() for is_numeric values so
* they can be incremented atomically — the side effect is that an int
* stored via `Cache::put` comes back as a string on read. Without the
* cast, the strict `: int` return type throws a TypeError under the
* Redis cache driver (production). File/array/database drivers don't
* have this optimisation and preserve the type, which is why the bug
* never surfaced in tests or local dev.
*
* @param array<int, string> $workspaceIds
*/
private function cachedPostCount(array $workspaceIds): int
{
if (empty($workspaceIds)) {
return 0;
}
return (int) Cache::remember(
"account:{$this->id}:posts_count",
self::POST_COUNT_CACHE_TTL,
fn () => Post::whereIn('workspace_id', $workspaceIds)->count(),
);
}
}