Skip to content

Commit b9a8f10

Browse files
committed
fix: refctor cache
1 parent 09b5f69 commit b9a8f10

File tree

4 files changed

+69
-14
lines changed

4 files changed

+69
-14
lines changed

config/packages/cache.yaml

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@ framework:
77
# Redis
88
app: cache.adapter.redis
99
default_redis_provider: '%env(REDIS_URL)%'
10+
# app: cache.adapter.filesystem
11+
# system: cache.adapter.system
1012

1113
# Namespaced pools use the above "app" backend by default
1214
pools:
@@ -16,7 +18,8 @@ framework:
1618
# fallbacks: 'cache.adapter.file_system'
1719
tokens_cache:
1820
adapter: cache.app
19-
default_lifetime: 86400 # 24 hours in seconds
21+
# default_lifetime: 86400 # 24 hours in seconds
22+
default_lifetime: "7 days"
2023
# TODO : Mettre le cache sur les sessions
2124
# session:
2225
# handler_id: Symfony\Component\HttpFoundation\Session\Storage\Handler\RedisSessionHandler

config/services.yaml

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@ services:
99
_defaults:
1010
autowire: true
1111
autoconfigure: true
12+
bind:
13+
'Symfony\\Contracts\\Cache\\CacheInterface $tokensCache': '@cache.pool.tokens_cache'
1214

1315
App\:
1416
resource: '../src/'
@@ -45,3 +47,7 @@ services:
4547
class: Symfony\Component\RateLimiter\Storage\RedisStorage
4648
arguments:
4749
- '@Redis'
50+
51+
# Inject named cache pools for direct use via autowiring
52+
Symfony\Contracts\Cache\CacheInterface $tokensCache:
53+
alias: 'cache.pool.tokens_cache'

src/Controller/TokenController.php

Lines changed: 23 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,9 @@
1313
use Psr\Cache\InvalidArgumentException;
1414
//use Symfony\Component\Cache\Adapter\AdapterInterface;
1515
use Symfony\Component\Cache\Adapter\FilesystemAdapter;
16+
use Symfony\Contracts\Cache\CacheInterface as ContractsCacheInterface;
17+
use Symfony\Component\Cache\Adapter\RedisAdapter;
18+
use Symfony\Component\Cache\Adapter\RedisTagAwareAdapter;
1619
use Symfony\Component\HttpFoundation\JsonResponse;
1720
use Symfony\Component\HttpFoundation\Request;
1821
use Symfony\Component\HttpFoundation\Response;
@@ -27,10 +30,12 @@ class TokenController
2730
use DataControllerTrait;
2831

2932
private TokenService $tokenService;
33+
private ContractsCacheInterface $tokensCache;
3034

31-
public function __construct(TokenService $tokenService)
35+
public function __construct(TokenService $tokenService, ContractsCacheInterface $tokensCache)
3236
{
3337
$this->tokenService = $tokenService;
38+
$this->tokensCache = $tokensCache;
3439
}
3540

3641
/**
@@ -138,22 +143,30 @@ public function showTokens(RequestContextService $ctx): JsonResponse
138143
// Get current user to scope the cache key by roles
139144
$user = $ctx->getCurrentUser();
140145
$rolesKey = md5(serialize($user ? $user->getRoles() : []));
141-
print_r($rolesKey);
142146

143147
// FilesystemAdapter expects an integer TTL (in seconds). 7 days = 604800 seconds
144148
$ttlSeconds = 7 * 24 * 3600;
145-
$cache = new FilesystemAdapter("tokens_{$rolesKey}", $ttlSeconds);
146-
print_r($cache);
149+
// $cache = new FilesystemAdapter("tokens_{$rolesKey}", $ttlSeconds);
150+
// $client = RedisAdapter::createConnection('redis://localhost');
151+
// $cache = new RedisTagAwareAdapter($client, "tokens_{$rolesKey}", $ttlSeconds);
152+
// print_r($cache);
153+
// Use injected named cache pool ($this->tokensCache) which is configured to use Redis
154+
$cache = $this->tokensCache;
147155

148156
// Use callback form as recommended by Symfony cache contracts.
149157
// The callback must return the data to cache (we store the decoded array, not a JsonResponse object).
150158
$tokensData = $cache->get('tokens_cache_'.$rolesKey, function (ItemInterface $item) use ($userAuth, $ttlSeconds) {
151-
$item->expiresAfter($ttlSeconds);
152-
$response = $this->tokenService->getTokens($userAuth);
153-
$content = $response->getContent();
154-
$decoded = json_decode($content, true);
155-
print_r($decoded);
156-
return $decoded ?: [];
159+
// $content = $response->getContent();
160+
// $decoded = json_decode($content, true);
161+
// print_r($decoded);
162+
// return $decoded ?: [];
163+
$response = $this->tokenService->getTokens($userAuth);
164+
$content = $response->getContent();
165+
$decoded = json_decode($content, true);
166+
return $decoded ?: [];
167+
168+
// $decoded = json_decode($content, true);
169+
// return $decoded ?: [];
157170

158171
// Fallback: if service returns array already
159172
// return is_array($response) ? $response : [];

src/Service/TokenService.php

Lines changed: 36 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
use Symfony\Component\HttpFoundation\Response;
1313
use Symfony\Component\HttpKernel\Exception\HttpException;
1414
use Symfony\Contracts\Cache\CacheInterface;
15+
use Symfony\Contracts\Cache\CacheInterface as ContractsCacheInterface;
1516

1617
/**
1718
* Class TokenService
@@ -22,10 +23,12 @@ class TokenService extends Service
2223
use NetworkControllerTrait;
2324

2425
private CacheInterface $cache;
26+
private ContractsCacheInterface $tokensCache;
2527

26-
public function __construct(EntityManagerInterface $entityManager, CacheInterface $cache)
28+
public function __construct(EntityManagerInterface $entityManager, CacheInterface $cache, ContractsCacheInterface $tokensCache)
2729
{
2830
$this->cache = $cache;
31+
$this->tokensCache = $tokensCache;
2932

3033
parent::__construct($entityManager);
3134
}
@@ -85,7 +88,12 @@ public function getToken(RequestContextService $ctx, string $uuid): JsonResponse
8588
throw new HttpException(Response::HTTP_NOT_FOUND, 'Token not found');
8689
}
8790

88-
return new JsonResponse($token->__toArray($ctx), Response::HTTP_OK);
91+
$userAuth = [
92+
'isAuthenticated' => $ctx->isAuthenticated(),
93+
'isAdmin' => $ctx->isAdmin()
94+
];
95+
96+
return new JsonResponse($token->__toArray($userAuth), Response::HTTP_OK);
8997
}
9098

9199
/**
@@ -115,6 +123,12 @@ public function createToken(array $dataJson = [], bool $deprecated = false): Jso
115123

116124
$this->createOrUpdateToken($token, $parsedJson, $count);
117125
$this->em->flush();
126+
// Invalidate tokens cache pool after creation
127+
try {
128+
$this->tokensCache->clear();
129+
} catch (\Throwable $e) {
130+
// don't break the API if cache clear fails
131+
}
118132
} else { // Multiple
119133
$tokens = $tokenRepository->findBy(['uuid' => array_column($parsedJson, 'uuid')]);
120134

@@ -190,6 +204,13 @@ public function updateToken(string $contractAddress, array $dataJson = []): Json
190204
$this->em->persist($token);
191205
$this->em->flush();
192206

207+
// Invalidate tokens cache pool after update
208+
try {
209+
$this->tokensCache->clear();
210+
} catch (\Throwable $e) {
211+
// ignore cache errors
212+
}
213+
193214
return new JsonResponse(
194215
["status" => "success", "message" => "Token updated successfully"],
195216
Response::HTTP_ACCEPTED
@@ -210,6 +231,13 @@ public function deleteToken(string $contractAddress): JsonResponse
210231
$this->em->remove($token);
211232
$this->em->flush();
212233

234+
// Invalidate tokens cache pool after delete
235+
try {
236+
$this->tokensCache->clear();
237+
} catch (\Throwable $e) {
238+
// ignore
239+
}
240+
213241
return new JsonResponse(
214242
["status" => "success", "message" => "Token deleted successfully"],
215243
Response::HTTP_OK
@@ -230,7 +258,12 @@ public function showLatestUpdated(RequestContextService $ctx): JsonResponse
230258
/** @var Token $lastTokenUpdated */
231259
$lastTokenUpdated = $tokenRepository->getLastTokenUpdated()[0];
232260

233-
return new JsonResponse($lastTokenUpdated->__toArray($ctx), Response::HTTP_OK);
261+
$userAuth = [
262+
'isAuthenticated' => $ctx->isAuthenticated(),
263+
'isAdmin' => $ctx->isAdmin()
264+
];
265+
266+
return new JsonResponse($lastTokenUpdated->__toArray($userAuth), Response::HTTP_OK);
234267
}
235268

236269
/**

0 commit comments

Comments
 (0)