Skip to content

Commit

Permalink
chroe: improve database caching
Browse files Browse the repository at this point in the history
  • Loading branch information
juneszh committed Feb 18, 2024
1 parent 153ad6e commit 5deb435
Show file tree
Hide file tree
Showing 4 changed files with 84 additions and 70 deletions.
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
},
"require": {
"php": ">=7.4",
"juneszh/alight": "^2.0",
"juneszh/alight": "*",
"gregwar/captcha": "^1.2",
"symfony/var-exporter": ">=5.4"
}
Expand Down
15 changes: 10 additions & 5 deletions src/Admin/Auth.php
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ public static function getUserId(): int
$userId = Model::getUserIdByKey($auth);
if ($userId) {
$cache = Cache::init();
$cacheKey = 'admin_user_auth_' . $userId;
$cacheKey = 'alight.admin_user.auth.' . $userId;
$authInfo = $cache->get($cacheKey);
if ($authInfo && $authInfo['session'] == $session) {
$userInfo = Model::getUserInfo($userId);
Expand Down Expand Up @@ -116,10 +116,15 @@ public static function store(int $userId, bool $renew = false)
'auth' => $auth,
'session' => $session,
];
$cache = Cache::init();
$cacheKey = 'admin_user_auth_' . $userId;
$cacheTime = Config::get('remember');
$cache->set($cacheKey, $authInfo, $cacheTime);

$cache6 = Cache::psr6();
$cacheKey = 'alight.admin_user.auth.' . $userId;
$cacheItem = $cache6->getItem($cacheKey);
$cacheItem->set($authInfo);
$cacheItem->expiresAfter((int) $cacheTime);
$cacheItem->tag('alight.admin_user');
$cache6->save($cacheItem);

setcookie('admin_auth', $auth, time() + $cacheTime, '/' . Config::get('path'), '.' . Request::host());
setcookie('admin_session', $session, time() + $cacheTime, '/' . Config::get('path'), '.' . Request::host());
Expand All @@ -138,7 +143,7 @@ public static function clear(int $userId)
{
if ($userId) {
$cache = Cache::init();
$cacheKey = 'admin_user_auth_' . $userId;
$cacheKey = 'alight.admin_user.auth.' . $userId;
$cache->delete($cacheKey);
}

Expand Down
10 changes: 5 additions & 5 deletions src/Admin/Controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ public static function captcha()
$captchaHash = Utility::randomHex();

$cache = Cache::init();
$cache->set('admin_captcha_' . $captchaHash, $code, 300);
$cache->set('alight.admin_captcha.' . $captchaHash, $code, 300);

setcookie('admin_captcha', $captchaHash, time() + 300, '/' . Config::get('path'), '.' . Request::host());

Expand Down Expand Up @@ -112,7 +112,7 @@ public static function login()

$captchaHash = $_COOKIE['admin_captcha'] ?? '';
$cache = Cache::init();
$cacheKey = 'admin_captcha_' . $captchaHash;
$cacheKey = 'alight.admin_captcha.' . $captchaHash;
$captchaCodeCache = $cache->get($cacheKey);
$cache->delete($cacheKey);
setcookie('admin_captcha', '', 0, '/' . Config::get('path'), '.' . Request::host());
Expand All @@ -129,15 +129,15 @@ public static function login()
}

$waitMinute = 15;
$failTimes = (int)$cache->get('admin_user_login_fail_' . $userId);
$failTimes = (int) $cache->get('alight.admin_login_fail.' . $userId);
if ($failTimes >= 5) {
Response::api(1004, ':try_again_later');
exit;
}

$userInfo = Model::getUserInfo($userId);
if (!password_verify($password, $userInfo['password'])) {
$cache->set('admin_user_login_fail_' . $userId, $failTimes + 1, $waitMinute * 60);
$cache->set('alight.admin_login_fail.' . $userId, $failTimes + 1, $waitMinute * 60);
Response::api(1003, ':invalid_account');
exit;
}
Expand Down Expand Up @@ -205,7 +205,7 @@ public static function console()
'time' => $hour . ':00',
'show' => isset($log[$hour]) ? 1 : 0,
'color' => isset($log[$hour]) ? $log[$hour]['view'] + $log[$hour]['edit'] : 0,
'title' => "\u{1F50E}" . ' ' . ($log[$hour]['view'] ?? 0) . ' ' . "\u{270F}" . ' ' . ($log[$hour]['edit'] ?? 0),
'title' => "\u{1F50D}" . ' ' . ($log[$hour]['view'] ?? 0) . ' ' . "\u{1F4BE}" . ' ' . ($log[$hour]['edit'] ?? 0),
];
}
}
Expand Down
127 changes: 68 additions & 59 deletions src/Admin/Model.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
use PDOException;
use Psr\SimpleCache\CacheException;
use Symfony\Component\Cache\Exception\InvalidArgumentException as ExceptionInvalidArgumentException;
use Symfony\Contracts\Cache\ItemInterface;

class Model
{
Expand All @@ -39,22 +40,23 @@ class Model
*/
public static function getCacheData(string $table, ?int $id = null, ?int $ttl = 86400): array
{
$cache = Cache::init();
$cacheKey = $table . '_data' . ($id === null ? '' : '_' . $id);
$cache6 = Cache::psr6();
$cacheKey = 'alight.' . $table . ($id === null ? '' : '.' . $id);

if ($cache->has($cacheKey)) {
$result = $cache->get($cacheKey);
} else {
$result = $cache6->get($cacheKey, function (ItemInterface $item) use ($table, $id, $ttl) {
$db = Database::init();
if ($id === null) {
$result = $db->select($table, '*', ['ORDER' => ['id' => 'ASC']]);
$item->tag('alight.' . $table . '.list');
} elseif ($id > 0) {
$result = $db->get($table, '*', ['id' => $id]);
} else {
return [];
$result = [];
}
$cache->set($cacheKey, $result, $ttl);
}
$item->expiresAfter($ttl);
$item->tag('alight.' . $table);
return $result;
});

return $result ?: [];
}
Expand Down Expand Up @@ -85,19 +87,17 @@ public static function getRoleList(): array
*/
public static function getUserIdByAccount(string $account): int
{
$cache = Cache::init();
$cacheKey = 'admin_user_id_by_account_' . md5($account);
$cache6 = Cache::psr6();
$cacheKey = 'alight.admin_user.id_by_account.' . md5($account);

if ($cache->has($cacheKey)) {
return $cache->get($cacheKey);
}
$result = $cache6->get($cacheKey, function (ItemInterface $item) use ($account) {
$db = Database::init();
$result = $db->get('admin_user', 'id', ['account' => $account]);

$db = Database::init();
$result = $db->get('admin_user', 'id', ['account' => $account]);

if ($result) {
$cache->set($cacheKey, (int) $result, 3600);
}
$item->expiresAfter(3600);
$item->tag('alight.admin_user');
return $result;
});

return (int) $result;
}
Expand All @@ -114,19 +114,17 @@ public static function getUserIdByAccount(string $account): int
*/
public static function getUserIdByKey(string $key): int
{
$cache = Cache::init();
$cacheKey = 'admin_user_id_by_key_' . $key;

if ($cache->has($cacheKey)) {
return $cache->get($cacheKey);
}
$cache6 = Cache::psr6();
$cacheKey = 'alight.admin_user.id_by_key.' . $key;

$db = Database::init();
$result = $db->get('admin_user', 'id', ['auth_key' => $key]);
$result = $cache6->get($cacheKey, function (ItemInterface $item) use ($key) {
$db = Database::init();
$result = $db->get('admin_user', 'id', ['auth_key' => $key]);

if ($result) {
$cache->set($cacheKey, (int) $result, 3600);
}
$item->expiresAfter(3600);
$item->tag('alight.admin_user');
return $result;
});

return (int) $result;
}
Expand Down Expand Up @@ -192,25 +190,26 @@ public static function userLog(int $userId, bool $edit = false)
*/
public static function getUserDateLog(int $userId, string $date): array
{
$cache = Cache::init();
$cacheKey = 'admin_user_date_log_' . $userId . '_' . str_replace('-', '', $date);
if ($cache->has($cacheKey)) {
return $cache->get($cacheKey);
}
$cache6 = Cache::psr6();
$cacheKey = 'alight.admin_log.user_date.' . $userId . '_' . str_replace('-', '', $date);

$now = time();
$today = date('Y-m-d', $now);
$result = $cache6->get($cacheKey, function (ItemInterface $item) use ($userId, $date) {
$now = time();
$today = date('Y-m-d', $now);

$db = Database::init();
if ($date === $today) {
$result = $db->select('admin_log', ['hour' => ['view', 'edit']], ['user_id' => $userId, 'date' => $date, 'hour[<]' => date('G', $now)]);
$cacheTime = 3600 - ($now - strtotime(date('Y-m-d H:00:00', $now)));
} else {
$result = $db->select('admin_log', ['hour' => ['view', 'edit']], ['user_id' => $userId, 'date' => $date]);
$cacheTime = 86400;
}
$db = Database::init();
if ($date === $today) {
$result = $db->select('admin_log', ['hour' => ['view', 'edit']], ['user_id' => $userId, 'date' => $date, 'hour[<]' => date('G', $now)]);
$cacheTime = 3600 - ($now - strtotime(date('Y-m-d H:00:00', $now)));
} else {
$result = $db->select('admin_log', ['hour' => ['view', 'edit']], ['user_id' => $userId, 'date' => $date]);
$cacheTime = 86400;
}

$cache->set($cacheKey, $result ?: [], $cacheTime);
$item->expiresAfter($cacheTime);
$item->tag(['alight.admin_log', 'alight.admin_log.list']);
return $result;
});

return $result ?: [];
}
Expand Down Expand Up @@ -301,10 +300,14 @@ public static function formInsert(string $table, array $data): int
$db->insert($table, $data);

if ($db->id()) {
$cache = Cache::init();
$cache->deleteMultiple([
$table . '_data',
$table . '_data_' . $db->id()
$cache6 = Cache::psr6();
$cacheKeys = [
'alight.' . $table,
'alight.' . $table . '.' . $db->id()
];
$cache6->deleteItems($cacheKeys);
$cache6->invalidateTags([
'alight.' . $table . '.list'
]);
}

Expand Down Expand Up @@ -348,10 +351,14 @@ public static function formUpdate(string $table, array $data, int $id): int
$result = $db->update($table, $data, ['id' => $id]);

if ($result->rowCount()) {
$cache = Cache::init();
$cache->deleteMultiple([
$table . '_data',
$table . '_data_' . $id
$cache6 = Cache::psr6();
$cacheKeys = [
'alight.' . $table,
'alight.' . $table . '.' . $db->id()
];
$cache6->deleteItems($cacheKeys);
$cache6->invalidateTags([
'alight.' . $table . '.list'
]);
}

Expand All @@ -378,15 +385,17 @@ public static function formUpdateMultiple(string $table, array $data, array $id)
$result = $db->update($table, $data, ['id' => $id]);

if ($result->rowCount()) {
$cache = Cache::init();
$cacheKeys = [$table . '_data'];
$cache6 = Cache::psr6();
$cacheKeys = ['alight.' .$table];
foreach ($id as $_id) {
$cacheKeys[] = $table . '_data_' . $_id;
$cacheKeys[] = 'alight.' . $table . '.' . $_id;
}
$cache->deleteMultiple($cacheKeys);
$cache6->deleteItems($cacheKeys);
$cache6->invalidateTags([
'alight.' . $table . '.list'
]);
}

return $result->rowCount() ? $id : (!$db->error ? $id : []);
}

}

0 comments on commit 5deb435

Please sign in to comment.