Skip to content

[Cache] Add CouchbaseCollectionAdapter compatibility with sdk 3.0.0 #40120

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 9, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/psalm.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ jobs:
uses: shivammathur/setup-php@v2
with:
php-version: '8.0'
extensions: "json,memcached,mongodb,redis,xsl,ldap,dom"
extensions: "json,couchbase,memcached,mongodb,redis,xsl,ldap,dom"
ini-values: "memory_limit=-1"
coverage: none

Expand Down
6 changes: 5 additions & 1 deletion src/Symfony/Component/Cache/Adapter/AbstractAdapter.php
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,11 @@ public static function createConnection(string $dsn, array $options = [])
return MemcachedAdapter::createConnection($dsn, $options);
}
if (0 === strpos($dsn, 'couchbase:')) {
return CouchbaseBucketAdapter::createConnection($dsn, $options);
if (CouchbaseBucketAdapter::isSupported()) {
return CouchbaseBucketAdapter::createConnection($dsn, $options);
}

return CouchbaseCollectionAdapter::createConnection($dsn, $options);
}

throw new InvalidArgumentException(sprintf('Unsupported DSN: "%s".', $dsn));
Expand Down
233 changes: 233 additions & 0 deletions src/Symfony/Component/Cache/Adapter/CouchbaseCollectionAdapter.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,233 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Cache\Adapter;

use Couchbase\Bucket;
use Couchbase\Cluster;
use Couchbase\ClusterOptions;
use Couchbase\Collection;
use Couchbase\DocumentNotFoundException;
use Couchbase\UpsertOptions;
use Symfony\Component\Cache\Exception\CacheException;
use Symfony\Component\Cache\Exception\InvalidArgumentException;
use Symfony\Component\Cache\Marshaller\DefaultMarshaller;
use Symfony\Component\Cache\Marshaller\MarshallerInterface;

/**
* @author Antonio Jose Cerezo Aranda <aj.cerezo@gmail.com>
*/
class CouchbaseCollectionAdapter extends AbstractAdapter
{
private const THIRTY_DAYS_IN_SECONDS = 2592000;
private const MAX_KEY_LENGTH = 250;

/** @var Collection */
private $connection;
private $marshaller;

public function __construct(Collection $connection, string $namespace = '', int $defaultLifetime = 0, MarshallerInterface $marshaller = null)
{
if (!static::isSupported()) {
throw new CacheException('Couchbase >= 3.0.0 < 4.0.0 is required.');
}

$this->maxIdLength = static::MAX_KEY_LENGTH;

$this->connection = $connection;

parent::__construct($namespace, $defaultLifetime);
$this->enableVersioning();
$this->marshaller = $marshaller ?? new DefaultMarshaller();
}

/**
* @param array|string $dsn
*
* @return Bucket|Collection
*/
public static function createConnection($dsn, array $options = [])
{
if (\is_string($dsn)) {
$dsn = [$dsn];
} elseif (!\is_array($dsn)) {
throw new \TypeError(sprintf('Argument 1 passed to "%s()" must be array or string, "%s" given.', __METHOD__, get_debug_type($dsn)));
}

if (!static::isSupported()) {
throw new CacheException('Couchbase >= 3.0.0 < 4.0.0 is required.');
}

set_error_handler(function ($type, $msg, $file, $line): bool { throw new \ErrorException($msg, 0, $type, $file, $line); });

$dsnPattern = '/^(?<protocol>couchbase(?:s)?)\:\/\/(?:(?<username>[^\:]+)\:(?<password>[^\@]{6,})@)?'
.'(?<host>[^\:]+(?:\:\d+)?)(?:\/(?<bucketName>[^\/\?]+))(?:(?:\/(?<scopeName>[^\/]+))'
.'(?:\/(?<collectionName>[^\/\?]+)))?(?:\/)?(?:\?(?<options>.*))?$/i';

$newServers = [];
$protocol = 'couchbase';
try {
$username = $options['username'] ?? '';
$password = $options['password'] ?? '';

foreach ($dsn as $server) {
if (0 !== strpos($server, 'couchbase:')) {
throw new InvalidArgumentException(sprintf('Invalid Couchbase DSN: "%s" does not start with "couchbase:".', $server));
}

preg_match($dsnPattern, $server, $matches);

$username = $matches['username'] ?: $username;
$password = $matches['password'] ?: $password;
$protocol = $matches['protocol'] ?: $protocol;

if (isset($matches['options'])) {
$optionsInDsn = self::getOptions($matches['options']);

foreach ($optionsInDsn as $parameter => $value) {
$options[$parameter] = $value;
}
}

$newServers[] = $matches['host'];
}

$option = isset($matches['options']) ? '?'.$matches['options'] : '';
$connectionString = $protocol.'://'.implode(',', $newServers).$option;

$clusterOptions = new ClusterOptions();
$clusterOptions->credentials($username, $password);

$client = new Cluster($connectionString, $clusterOptions);

$bucket = $client->bucket($matches['bucketName']);
$collection = $bucket->defaultCollection();
if (!empty($matches['scopeName'])) {
$scope = $bucket->scope($matches['scopeName']);
$collection = $scope->collection($matches['collectionName']);
}

return $collection;
} finally {
restore_error_handler();
}
}

public static function isSupported(): bool
{
return \extension_loaded('couchbase') && version_compare(phpversion('couchbase'), '3.0', '>=') && version_compare(phpversion('couchbase'), '4.0', '<');
}

private static function getOptions(string $options): array
{
$results = [];
$optionsInArray = explode('&', $options);

foreach ($optionsInArray as $option) {
[$key, $value] = explode('=', $option);

$results[$key] = $value;
}

return $results;
}

/**
* {@inheritdoc}
*/
protected function doFetch(array $ids): array
{
$results = [];
foreach ($ids as $id) {
try {
$resultCouchbase = $this->connection->get($id);
} catch (DocumentNotFoundException $exception) {
continue;
}

$content = $resultCouchbase->value ?? $resultCouchbase->content();

$results[$id] = $this->marshaller->unmarshall($content);
}

return $results;
}

/**
* {@inheritdoc}
*/
protected function doHave($id): bool
{
return $this->connection->exists($id)->exists();
}

/**
* {@inheritdoc}
*/
protected function doClear($namespace): bool
{
return false;
}

/**
* {@inheritdoc}
*/
protected function doDelete(array $ids): bool
{
$idsErrors = [];
foreach ($ids as $id) {
try {
$result = $this->connection->remove($id);

if (null === $result->mutationToken()) {
$idsErrors[] = $id;
}
} catch (DocumentNotFoundException $exception) {
}
}

return 0 === \count($idsErrors);
}

/**
* {@inheritdoc}
*/
protected function doSave(array $values, $lifetime)
{
if (!$values = $this->marshaller->marshall($values, $failed)) {
return $failed;
}

$lifetime = $this->normalizeExpiry($lifetime);
$upsertOptions = new UpsertOptions();
$upsertOptions->expiry($lifetime);

$ko = [];
foreach ($values as $key => $value) {
try {
$this->connection->upsert($key, $value, $upsertOptions);
} catch (\Exception $exception) {
$ko[$key] = '';
}
}

return [] === $ko ? true : $ko;
}

private function normalizeExpiry(int $expiry): int
{
if ($expiry && $expiry > static::THIRTY_DAYS_IN_SECONDS) {
$expiry += time();
}

return $expiry;
}
}
1 change: 1 addition & 0 deletions src/Symfony/Component/Cache/LockRegistry.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ final class LockRegistry
__DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'ArrayAdapter.php',
__DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'ChainAdapter.php',
__DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'CouchbaseBucketAdapter.php',
__DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'CouchbaseCollectionAdapter.php',
__DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'DoctrineAdapter.php',
__DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'FilesystemAdapter.php',
__DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'FilesystemTagAwareAdapter.php',
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Cache\Tests\Adapter;

use Couchbase\Collection;
use Psr\Cache\CacheItemPoolInterface;
use Symfony\Component\Cache\Adapter\AbstractAdapter;
use Symfony\Component\Cache\Adapter\CouchbaseCollectionAdapter;

/**
* @requires extension couchbase <4.0.0
* @requires extension couchbase >=3.0.0
* @group integration
*
* @author Antonio Jose Cerezo Aranda <aj.cerezo@gmail.com>
*/
class CouchbaseCollectionAdapterTest extends AdapterTestCase
{
protected $skippedTests = [
'testClearPrefix' => 'Couchbase cannot clear by prefix',
];

/** @var Collection */
protected static $client;

public static function setupBeforeClass(): void
{
if (!CouchbaseCollectionAdapter::isSupported()) {
self::markTestSkipped('Couchbase >= 3.0.0 < 4.0.0 is required.');
}

self::$client = AbstractAdapter::createConnection('couchbase://'.getenv('COUCHBASE_HOST').'/cache',
['username' => getenv('COUCHBASE_USER'), 'password' => getenv('COUCHBASE_PASS')]
);
}

/**
* {@inheritdoc}
*/
public function createCachePool($defaultLifetime = 0): CacheItemPoolInterface
{
if (!CouchbaseCollectionAdapter::isSupported()) {
self::markTestSkipped('Couchbase >= 3.0.0 < 4.0.0 is required.');
}

$client = $defaultLifetime
? AbstractAdapter::createConnection('couchbase://'
.getenv('COUCHBASE_USER')
.':'.getenv('COUCHBASE_PASS')
.'@'.getenv('COUCHBASE_HOST')
.'/cache')
: self::$client;

return new CouchbaseCollectionAdapter($client, str_replace('\\', '.', __CLASS__), $defaultLifetime);
}
}