From 37e771f0bec9d5cd0be80969e2fe84e31e75d2a3 Mon Sep 17 00:00:00 2001 From: Zankaria Date: Thu, 29 May 2025 23:55:04 +0200 Subject: [PATCH] MemcacheCacheDriver.php: fix configuration --- inc/Data/Driver/MemcacheCacheDriver.php | 34 ++++++++++++++++++++++--- 1 file changed, 31 insertions(+), 3 deletions(-) diff --git a/inc/Data/Driver/MemcacheCacheDriver.php b/inc/Data/Driver/MemcacheCacheDriver.php index 04f62895..f05c51e7 100644 --- a/inc/Data/Driver/MemcacheCacheDriver.php +++ b/inc/Data/Driver/MemcacheCacheDriver.php @@ -5,9 +5,12 @@ defined('TINYBOARD') or exit; class MemcachedCacheDriver implements CacheDriver { + use CacheDriverTrait; + private \Memcached $inner; - public function __construct(string $prefix, string $memcached_server) { + + public function __construct(string $prefix, string $server_uri, int $server_port, int $server_weight) { $this->inner = new \Memcached(); if (!$this->inner->setOption(\Memcached::OPT_BINARY_PROTOCOL, true)) { throw new \RuntimeException('Unable to set the memcached protocol!'); @@ -15,8 +18,33 @@ class MemcachedCacheDriver implements CacheDriver { if (!$this->inner->setOption(\Memcached::OPT_PREFIX_KEY, $prefix)) { throw new \RuntimeException('Unable to set the memcached prefix!'); } - if (!$this->inner->addServers($memcached_server)) { - throw new \RuntimeException('Unable to add the memcached server!'); + + $maybe_unix_path = self::asUnixSocketPath($server_uri); + $is_unix = $maybe_unix_path !== null; + if ($is_unix) { + $server_uri = $maybe_unix_path; + } + + // Memcached keeps the server connections open across requests. + $current_servers = $this->inner->getServerList(); + $found_in_curr = false; + foreach ($current_servers as $curr) { + // Ignore the port if the server is connected with a unix socket. + if ($curr['host'] === $server_uri && ($is_unix || $curr['port'] === $server_port)) { + $found_in_curr = true; + } + } + + if (!$found_in_curr) { + if (!empty($current_servers)) { + if ($this->inner->resetServerList()) { + throw new \RuntimeException('Unable to reset the memcached server list!'); + } + + if ($this->inner->addServer($server_uri, $server_port, $server_weight)) { + throw new \RuntimeException('Unable to add memcached servers!'); + } + } } }