Skip to content

Commit

Permalink
Merge branch 'MDL-70309-master' of git://github.com/ferranrecio/moodle
Browse files Browse the repository at this point in the history
  • Loading branch information
sarjona committed Feb 2, 2021
2 parents 35a0bec + e161edc commit a00be13
Show file tree
Hide file tree
Showing 51 changed files with 1,290 additions and 277 deletions.
40 changes: 30 additions & 10 deletions cache/stores/mongodb/MongoDB/ChangeStream.php
Expand Up @@ -42,13 +42,33 @@ class ChangeStream implements Iterator
*/
const CURSOR_NOT_FOUND = 43;

/** @var array */
private static $nonResumableErrorCodes = [
136, // CappedPositionLost
237, // CursorKilled
11601, // Interrupted
/** @var int */
private static $cursorNotFound = 43;

/** @var int[] */
private static $resumableErrorCodes = [
6, // HostUnreachable
7, // HostNotFound
89, // NetworkTimeout
91, // ShutdownInProgress
189, // PrimarySteppedDown
262, // ExceededTimeLimit
9001, // SocketException
10107, // NotMaster
11600, // InterruptedAtShutdown
11602, // InterruptedDueToReplStateChange
13435, // NotMasterNoSlaveOk
13436, // NotMasterOrSecondary
63, // StaleShardVersion
150, // StaleEpoch
13388, // StaleConfig
234, // RetryChangeStream
133, // FailedToSatisfyReadPreference
];

/** @var int */
private static $wireVersionForResumableChangeStreamError = 9;

/** @var callable */
private $resumeCallable;

Expand Down Expand Up @@ -180,15 +200,15 @@ private function isResumableError(RuntimeException $exception)
return false;
}

if ($exception->hasErrorLabel('NonResumableChangeStreamError')) {
return false;
if ($exception->getCode() === self::$cursorNotFound) {
return true;
}

if (in_array($exception->getCode(), self::$nonResumableErrorCodes)) {
return false;
if (server_supports_feature($this->iterator->getServer(), self::$wireVersionForResumableChangeStreamError)) {
return $exception->hasErrorLabel('ResumableChangeStreamError');
}

return true;
return in_array($exception->getCode(), self::$resumableErrorCodes);
}

/**
Expand Down
105 changes: 103 additions & 2 deletions cache/stores/mongodb/MongoDB/Client.php
Expand Up @@ -17,6 +17,9 @@

namespace MongoDB;

use Iterator;
use Jean85\PrettyVersions;
use MongoDB\Driver\ClientEncryption;
use MongoDB\Driver\Exception\InvalidArgumentException as DriverInvalidArgumentException;
use MongoDB\Driver\Exception\RuntimeException as DriverRuntimeException;
use MongoDB\Driver\Manager;
Expand All @@ -31,9 +34,12 @@
use MongoDB\Model\BSONDocument;
use MongoDB\Model\DatabaseInfoIterator;
use MongoDB\Operation\DropDatabase;
use MongoDB\Operation\ListDatabaseNames;
use MongoDB\Operation\ListDatabases;
use MongoDB\Operation\Watch;
use Throwable;
use function is_array;
use function is_string;

class Client
{
Expand All @@ -50,6 +56,12 @@ class Client
/** @var integer */
private static $wireVersionForWritableCommandWriteConcern = 5;

/** @var string */
private static $handshakeSeparator = ' / ';

/** @var string|null */
private static $version;

/** @var Manager */
private $manager;

Expand Down Expand Up @@ -95,12 +107,22 @@ public function __construct($uri = 'mongodb://127.0.0.1/', array $uriOptions = [
{
$driverOptions += ['typeMap' => self::$defaultTypeMap];

if (isset($driverOptions['typeMap']) && ! is_array($driverOptions['typeMap'])) {
if (! is_array($driverOptions['typeMap'])) {
throw InvalidArgumentException::invalidType('"typeMap" driver option', $driverOptions['typeMap'], 'array');
}

if (isset($driverOptions['autoEncryption']['keyVaultClient'])) {
if ($driverOptions['autoEncryption']['keyVaultClient'] instanceof self) {
$driverOptions['autoEncryption']['keyVaultClient'] = $driverOptions['autoEncryption']['keyVaultClient']->manager;
} elseif (! $driverOptions['autoEncryption']['keyVaultClient'] instanceof Manager) {
throw InvalidArgumentException::invalidType('"keyVaultClient" autoEncryption option', $driverOptions['autoEncryption']['keyVaultClient'], [self::class, Manager::class]);
}
}

$driverOptions['driver'] = $this->mergeDriverInfo($driverOptions['driver'] ?? []);

$this->uri = (string) $uri;
$this->typeMap = isset($driverOptions['typeMap']) ? $driverOptions['typeMap'] : null;
$this->typeMap = $driverOptions['typeMap'] ?? null;

unset($driverOptions['typeMap']);

Expand Down Expand Up @@ -153,6 +175,26 @@ public function __toString()
return $this->uri;
}

/**
* Returns a ClientEncryption instance for explicit encryption and decryption
*
* @param array $options Encryption options
*
* @return ClientEncryption
*/
public function createClientEncryption(array $options)
{
if (isset($options['keyVaultClient'])) {
if ($options['keyVaultClient'] instanceof self) {
$options['keyVaultClient'] = $options['keyVaultClient']->manager;
} elseif (! $options['keyVaultClient'] instanceof Manager) {
throw InvalidArgumentException::invalidType('"keyVaultClient" option', $options['keyVaultClient'], [self::class, Manager::class]);
}
}

return $this->manager->createClientEncryption($options);
}

/**
* Drop a database.
*
Expand Down Expand Up @@ -233,6 +275,22 @@ public function getWriteConcern()
return $this->writeConcern;
}

/**
* List database names.
*
* @see ListDatabaseNames::__construct() for supported options
* @throws UnexpectedValueException if the command response was malformed
* @throws InvalidArgumentException for parameter/option parsing errors
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function listDatabaseNames(array $options = []) : Iterator
{
$operation = new ListDatabaseNames($options);
$server = select_server($this->manager, $options);

return $operation->execute($server);
}

/**
* List databases.
*
Expand Down Expand Up @@ -325,4 +383,47 @@ public function watch(array $pipeline = [], array $options = [])

return $operation->execute($server);
}

private static function getVersion() : string
{
if (self::$version === null) {
try {
self::$version = PrettyVersions::getVersion('mongodb/mongodb')->getPrettyVersion();
} catch (Throwable $t) {
return 'unknown';
}
}

return self::$version;
}

private function mergeDriverInfo(array $driver) : array
{
$mergedDriver = [
'name' => 'PHPLIB',
'version' => self::getVersion(),
];

if (isset($driver['name'])) {
if (! is_string($driver['name'])) {
throw InvalidArgumentException::invalidType('"name" handshake option', $driver['name'], 'string');
}

$mergedDriver['name'] .= self::$handshakeSeparator . $driver['name'];
}

if (isset($driver['version'])) {
if (! is_string($driver['version'])) {
throw InvalidArgumentException::invalidType('"version" handshake option', $driver['version'], 'string');
}

$mergedDriver['version'] .= self::$handshakeSeparator . $driver['version'];
}

if (isset($driver['platform'])) {
$mergedDriver['platform'] = $driver['platform'];
}

return $mergedDriver;
}
}
10 changes: 5 additions & 5 deletions cache/stores/mongodb/MongoDB/Collection.php
Expand Up @@ -162,10 +162,10 @@ public function __construct(Manager $manager, $databaseName, $collectionName, ar
$this->manager = $manager;
$this->databaseName = (string) $databaseName;
$this->collectionName = (string) $collectionName;
$this->readConcern = isset($options['readConcern']) ? $options['readConcern'] : $this->manager->getReadConcern();
$this->readPreference = isset($options['readPreference']) ? $options['readPreference'] : $this->manager->getReadPreference();
$this->typeMap = isset($options['typeMap']) ? $options['typeMap'] : self::$defaultTypeMap;
$this->writeConcern = isset($options['writeConcern']) ? $options['writeConcern'] : $this->manager->getWriteConcern();
$this->readConcern = $options['readConcern'] ?? $this->manager->getReadConcern();
$this->readPreference = $options['readPreference'] ?? $this->manager->getReadPreference();
$this->typeMap = $options['typeMap'] ?? self::$defaultTypeMap;
$this->writeConcern = $options['writeConcern'] ?? $this->manager->getWriteConcern();
}

/**
Expand Down Expand Up @@ -356,7 +356,7 @@ public function countDocuments($filter = [], array $options = [])
*/
public function createIndex($key, array $options = [])
{
$commandOptionKeys = ['maxTimeMS' => 1, 'session' => 1, 'writeConcern' => 1];
$commandOptionKeys = ['commitQuorum' => 1, 'maxTimeMS' => 1, 'session' => 1, 'writeConcern' => 1];
$indexOptions = array_diff_key($options, $commandOptionKeys);
$commandOptions = array_intersect_key($options, $commandOptionKeys);

Expand Down
139 changes: 139 additions & 0 deletions cache/stores/mongodb/MongoDB/Command/ListCollections.php
@@ -0,0 +1,139 @@
<?php
/*
* Copyright 2020-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

namespace MongoDB\Command;

use MongoDB\Driver\Command;
use MongoDB\Driver\Exception\RuntimeException as DriverRuntimeException;
use MongoDB\Driver\Server;
use MongoDB\Driver\Session;
use MongoDB\Exception\InvalidArgumentException;
use MongoDB\Model\CachingIterator;
use MongoDB\Operation\Executable;
use function is_array;
use function is_bool;
use function is_integer;
use function is_object;

/**
* Wrapper for the listCollections command.
*
* @internal
* @see http://docs.mongodb.org/manual/reference/command/listCollections/
*/
class ListCollections implements Executable
{
/** @var string */
private $databaseName;

/** @var array */
private $options;

/**
* Constructs a listCollections command.
*
* Supported options:
*
* * filter (document): Query by which to filter collections.
*
* * maxTimeMS (integer): The maximum amount of time to allow the query to
* run.
*
* * nameOnly (boolean): A flag to indicate whether the command should
* return just the collection/view names and type or return both the name
* and other information.
*
* * session (MongoDB\Driver\Session): Client session.
*
* Sessions are not supported for server versions < 3.6.
*
* @param string $databaseName Database name
* @param array $options Command options
* @throws InvalidArgumentException for parameter/option parsing errors
*/
public function __construct($databaseName, array $options = [])
{
if (isset($options['filter']) && ! is_array($options['filter']) && ! is_object($options['filter'])) {
throw InvalidArgumentException::invalidType('"filter" option', $options['filter'], 'array or object');
}

if (isset($options['maxTimeMS']) && ! is_integer($options['maxTimeMS'])) {
throw InvalidArgumentException::invalidType('"maxTimeMS" option', $options['maxTimeMS'], 'integer');
}

if (isset($options['nameOnly']) && ! is_bool($options['nameOnly'])) {
throw InvalidArgumentException::invalidType('"nameOnly" option', $options['nameOnly'], 'boolean');
}

if (isset($options['session']) && ! $options['session'] instanceof Session) {
throw InvalidArgumentException::invalidType('"session" option', $options['session'], Session::class);
}

$this->databaseName = (string) $databaseName;
$this->options = $options;
}

/**
* Execute the operation.
*
* @see Executable::execute()
* @param Server $server
* @return CachingIterator
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function execute(Server $server)
{
$cmd = ['listCollections' => 1];

if (! empty($this->options['filter'])) {
$cmd['filter'] = (object) $this->options['filter'];
}

if (isset($this->options['maxTimeMS'])) {
$cmd['maxTimeMS'] = $this->options['maxTimeMS'];
}

if (isset($this->options['nameOnly'])) {
$cmd['nameOnly'] = $this->options['nameOnly'];
}

$cursor = $server->executeReadCommand($this->databaseName, new Command($cmd), $this->createOptions());
$cursor->setTypeMap(['root' => 'array', 'document' => 'array']);

return new CachingIterator($cursor);
}

/**
* Create options for executing the command.
*
* Note: read preference is intentionally omitted, as the spec requires that
* the command be executed on the primary.
*
* @see http://php.net/manual/en/mongodb-driver-server.executecommand.php
* @return array
*/
private function createOptions()
{
$options = [];

if (isset($this->options['session'])) {
$options['session'] = $this->options['session'];
}

return $options;
}
}

0 comments on commit a00be13

Please sign in to comment.