This commit is contained in:
2026-07-10 02:39:19 +03:30
parent d5639f05fc
commit 2b3c03b62a
2 changed files with 53 additions and 19 deletions

View File

@@ -1,14 +1,31 @@
<?php <?php
function redisClient(): Redis function redisClient(): ?Redis
{ {
static $redis = null; static $redis = null;
static $initialized = false;
if ($initialized) {
return $redis;
}
$initialized = true;
if (!class_exists('Redis')) {
return null;
}
if ($redis === null) { if ($redis === null) {
$config = require __DIR__ . '/../config/config.php'; $config = require __DIR__ . '/../config/config.php';
$redis = new Redis(); $redis = new Redis();
try {
if (!@$redis->connect($config['redis']['host'], $config['redis']['port'])) { if (!@$redis->connect($config['redis']['host'], $config['redis']['port'])) {
throw new RuntimeException('Redis connection failed.'); $redis = null;
}
} catch (Throwable $e) {
$redis = null;
} }
} }
return $redis; return $redis;
} }

View File

@@ -21,12 +21,24 @@ class Paste
if ($expire_time !== null) { if ($expire_time !== null) {
$ttl = max(1, $expire_time - time()); $ttl = max(1, $expire_time - time());
$redis = redisClient(); $redis = redisClient();
if ($redis !== null) {
try {
$redis->setex("paste:{$id}", $ttl, json_encode([ $redis->setex("paste:{$id}", $ttl, json_encode([
'encrypted_text' => $encrypted_text, 'encrypted_text' => $encrypted_text,
'iv' => $iv, 'iv' => $iv,
'password_hash' => $password_hash, 'password_hash' => $password_hash,
])); ]));
return true; return true;
} catch (Throwable $e) {
// Fall back to MySQL so expiring pastes still work without Redis.
}
}
$stmt = $this->pdo->prepare(
'INSERT INTO pastes (id, encrypted_text, iv, expire_time, password_hash)
VALUES (?, ?, ?, ?, ?)'
);
return $stmt->execute([$id, $encrypted_text, $iv, $expire_time, $password_hash]);
} }
$stmt = $this->pdo->prepare( $stmt = $this->pdo->prepare(
@@ -39,8 +51,9 @@ class Paste
public function get(string $id): array|false public function get(string $id): array|false
{ {
$redis = redisClient(); $redis = redisClient();
if ($redis !== null) {
try {
$raw = $redis->get("paste:{$id}"); $raw = $redis->get("paste:{$id}");
if ($raw !== false) { if ($raw !== false) {
$json = json_decode($raw, true); $json = json_decode($raw, true);
return [ return [
@@ -50,6 +63,10 @@ class Paste
'expire_time' => time() + $redis->ttl("paste:{$id}"), 'expire_time' => time() + $redis->ttl("paste:{$id}"),
]; ];
} }
} catch (Throwable $e) {
// Ignore Redis failures and fall back to MySQL.
}
}
$stmt = $this->pdo->prepare('SELECT * FROM pastes WHERE id = ? LIMIT 1'); $stmt = $this->pdo->prepare('SELECT * FROM pastes WHERE id = ? LIMIT 1');
$stmt->execute([$id]); $stmt->execute([$id]);