Merge pull request #28 from utopia-php/feat-client-updates

Feat client updates
This commit is contained in:
Jake Barnby authored and GitHub committed 2025-09-30 22:36:04 +13:00
commit b9c9c2e3f6
11 files changed
+2184 -378

No files matched your search

+1 -1
View File
@@ -17,4 +17,4 @@ jobs:
- name: Run CodeQL
run: |
docker run --rm -v $PWD:/app composer sh -c \
"composer install --profile --ignore-platform-reqs && composer analyse"
"composer install --profile --ignore-platform-reqs && composer check"
-4
View File
@@ -5,9 +5,6 @@ jobs:
lint:
name: Tests
runs-on: ubuntu-latest
strategy:
matrix:
php-versions: ['8.3'] # add PHP versions as required
steps:
- name: Checkout repository
@@ -24,7 +21,6 @@ jobs:
- name: Build
run: |
export PHP_VERSION=${{ matrix.php-versions }}
docker compose build
docker compose up -d
sleep 10
+9 -9
View File
@@ -23,21 +23,21 @@
},
"scripts":{
"test": "phpunit",
"analyse": "vendor/bin/phpstan analyse",
"check": "vendor/bin/phpstan analyse --memory-limit=1G --level=max src",
"format": "vendor/bin/pint",
"lint": "vendor/bin/pint --test"
},
"require": {
"php": ">=8.0",
"ext-mongodb": "2.1.1",
"mongodb/mongodb": "2.1.0",
"ramsey/uuid": "^4.9.0"
"ext-mongodb": "2.1.*",
"mongodb/mongodb": "2.1.*",
"ramsey/uuid": "4.9.*"
},
"require-dev": {
"fakerphp/faker": "^1.14",
"phpunit/phpunit": "^9.4",
"swoole/ide-helper": "4.8.0",
"laravel/pint": "1.2.*",
"phpstan/phpstan": "2.1.*"
"fakerphp/faker": "1.*",
"phpunit/phpunit": "9.*",
"swoole/ide-helper": "5.1.*",
"laravel/pint": "*",
"phpstan/phpstan": "*"
}
}
Generated
+87 -81
View File
@@ -4,29 +4,29 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "0edc06298a5d7d385ed1f0e19925baec",
"content-hash": "1d493c50f129de83162ce431a615288c",
"packages": [
{
"name": "brick/math",
"version": "0.13.1",
"version": "0.14.0",
"source": {
"type": "git",
"url": "https://github.com/brick/math.git",
"reference": "fc7ed316430118cc7836bf45faff18d5dfc8de04"
"reference": "113a8ee2656b882d4c3164fa31aa6e12cbb7aaa2"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/brick/math/zipball/fc7ed316430118cc7836bf45faff18d5dfc8de04",
"reference": "fc7ed316430118cc7836bf45faff18d5dfc8de04",
"url": "https://api.github.com/repos/brick/math/zipball/113a8ee2656b882d4c3164fa31aa6e12cbb7aaa2",
"reference": "113a8ee2656b882d4c3164fa31aa6e12cbb7aaa2",
"shasum": ""
},
"require": {
"php": "^8.1"
"php": "^8.2"
},
"require-dev": {
"php-coveralls/php-coveralls": "^2.2",
"phpunit/phpunit": "^10.1",
"vimeo/psalm": "6.8.8"
"phpstan/phpstan": "2.1.22",
"phpunit/phpunit": "^11.5"
},
"type": "library",
"autoload": {
@@ -56,7 +56,7 @@
],
"support": {
"issues": "https://github.com/brick/math/issues",
"source": "https://github.com/brick/math/tree/0.13.1"
"source": "https://github.com/brick/math/tree/0.14.0"
},
"funding": [
{
@@ -64,20 +64,20 @@
"type": "github"
}
],
"time": "2025-03-29T13:50:30+00:00"
"time": "2025-08-29T12:40:03+00:00"
},
{
"name": "mongodb/mongodb",
"version": "2.1.0",
"version": "2.1.1",
"source": {
"type": "git",
"url": "https://github.com/mongodb/mongo-php-library.git",
"reference": "3bbe7ba9578724c7e1f47fcd17c881c0995baaad"
"reference": "f399d24905dd42f97dfe0af9706129743ef247ac"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/mongodb/mongo-php-library/zipball/3bbe7ba9578724c7e1f47fcd17c881c0995baaad",
"reference": "3bbe7ba9578724c7e1f47fcd17c881c0995baaad",
"url": "https://api.github.com/repos/mongodb/mongo-php-library/zipball/f399d24905dd42f97dfe0af9706129743ef247ac",
"reference": "f399d24905dd42f97dfe0af9706129743ef247ac",
"shasum": ""
},
"require": {
@@ -139,9 +139,9 @@
],
"support": {
"issues": "https://github.com/mongodb/mongo-php-library/issues",
"source": "https://github.com/mongodb/mongo-php-library/tree/2.1.0"
"source": "https://github.com/mongodb/mongo-php-library/tree/2.1.1"
},
"time": "2025-05-23T10:48:05+00:00"
"time": "2025-08-13T20:50:05+00:00"
},
{
"name": "psr/log",
@@ -271,20 +271,20 @@
},
{
"name": "ramsey/uuid",
"version": "4.9.0",
"version": "4.9.1",
"source": {
"type": "git",
"url": "https://github.com/ramsey/uuid.git",
"reference": "4e0e23cc785f0724a0e838279a9eb03f28b092a0"
"reference": "81f941f6f729b1e3ceea61d9d014f8b6c6800440"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/ramsey/uuid/zipball/4e0e23cc785f0724a0e838279a9eb03f28b092a0",
"reference": "4e0e23cc785f0724a0e838279a9eb03f28b092a0",
"url": "https://api.github.com/repos/ramsey/uuid/zipball/81f941f6f729b1e3ceea61d9d014f8b6c6800440",
"reference": "81f941f6f729b1e3ceea61d9d014f8b6c6800440",
"shasum": ""
},
"require": {
"brick/math": "^0.8.8 || ^0.9 || ^0.10 || ^0.11 || ^0.12 || ^0.13",
"brick/math": "^0.8.8 || ^0.9 || ^0.10 || ^0.11 || ^0.12 || ^0.13 || ^0.14",
"php": "^8.0",
"ramsey/collection": "^1.2 || ^2.0"
},
@@ -343,22 +343,22 @@
],
"support": {
"issues": "https://github.com/ramsey/uuid/issues",
"source": "https://github.com/ramsey/uuid/tree/4.9.0"
"source": "https://github.com/ramsey/uuid/tree/4.9.1"
},
"time": "2025-06-25T14:20:11+00:00"
"time": "2025-09-04T20:59:21+00:00"
},
{
"name": "symfony/polyfill-php85",
"version": "v1.32.0",
"version": "v1.33.0",
"source": {
"type": "git",
"url": "https://github.com/symfony/polyfill-php85.git",
"reference": "6fedf31ce4e3648f4ff5ca58bfd53127d38f05fd"
"reference": "d4e5fcd4ab3d998ab16c0db48e6cbb9a01993f91"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/polyfill-php85/zipball/6fedf31ce4e3648f4ff5ca58bfd53127d38f05fd",
"reference": "6fedf31ce4e3648f4ff5ca58bfd53127d38f05fd",
"url": "https://api.github.com/repos/symfony/polyfill-php85/zipball/d4e5fcd4ab3d998ab16c0db48e6cbb9a01993f91",
"reference": "d4e5fcd4ab3d998ab16c0db48e6cbb9a01993f91",
"shasum": ""
},
"require": {
@@ -405,7 +405,7 @@
"shim"
],
"support": {
"source": "https://github.com/symfony/polyfill-php85/tree/v1.32.0"
"source": "https://github.com/symfony/polyfill-php85/tree/v1.33.0"
},
"funding": [
{
@@ -416,12 +416,16 @@
"url": "https://github.com/fabpot",
"type": "github"
},
{
"url": "https://github.com/nicolas-grekas",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
"type": "tidelift"
}
],
"time": "2025-05-02T08:40:52+00:00"
"time": "2025-06-23T16:12:55+00:00"
}
],
"packages-dev": [
@@ -560,16 +564,16 @@
},
{
"name": "laravel/pint",
"version": "v1.2.1",
"version": "v1.25.1",
"source": {
"type": "git",
"url": "https://github.com/laravel/pint.git",
"reference": "e60e2112ee779ce60f253695b273d1646a17d6f1"
"reference": "5016e263f95d97670d71b9a987bd8996ade6d8d9"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/laravel/pint/zipball/e60e2112ee779ce60f253695b273d1646a17d6f1",
"reference": "e60e2112ee779ce60f253695b273d1646a17d6f1",
"url": "https://api.github.com/repos/laravel/pint/zipball/5016e263f95d97670d71b9a987bd8996ade6d8d9",
"reference": "5016e263f95d97670d71b9a987bd8996ade6d8d9",
"shasum": ""
},
"require": {
@@ -577,16 +581,16 @@
"ext-mbstring": "*",
"ext-tokenizer": "*",
"ext-xml": "*",
"php": "^8.0"
"php": "^8.2.0"
},
"require-dev": {
"friendsofphp/php-cs-fixer": "^3.11.0",
"illuminate/view": "^9.32.0",
"laravel-zero/framework": "^9.2.0",
"mockery/mockery": "^1.5.1",
"nunomaduro/larastan": "^2.2.0",
"nunomaduro/termwind": "^1.14.0",
"pestphp/pest": "^1.22.1"
"friendsofphp/php-cs-fixer": "^3.87.2",
"illuminate/view": "^11.46.0",
"larastan/larastan": "^3.7.1",
"laravel-zero/framework": "^11.45.0",
"mockery/mockery": "^1.6.12",
"nunomaduro/termwind": "^2.3.1",
"pestphp/pest": "^2.36.0"
},
"bin": [
"builds/pint"
@@ -622,7 +626,7 @@
"issues": "https://github.com/laravel/pint/issues",
"source": "https://github.com/laravel/pint"
},
"time": "2022-11-29T16:25:20+00:00"
"time": "2025-09-19T02:57:12+00:00"
},
{
"name": "myclabs/deep-copy",
@@ -862,16 +866,16 @@
},
{
"name": "phpstan/phpstan",
"version": "2.1.22",
"version": "2.1.29",
"source": {
"type": "git",
"url": "https://github.com/phpstan/phpstan.git",
"reference": "41600c8379eb5aee63e9413fe9e97273e25d57e4"
"url": "https://github.com/phpstan/phpstan-phar-composer-source.git",
"reference": "git"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/phpstan/phpstan/zipball/41600c8379eb5aee63e9413fe9e97273e25d57e4",
"reference": "41600c8379eb5aee63e9413fe9e97273e25d57e4",
"url": "https://api.github.com/repos/phpstan/phpstan/zipball/d618573eed4a1b6b75e37b2e0b65ac65c885d88e",
"reference": "d618573eed4a1b6b75e37b2e0b65ac65c885d88e",
"shasum": ""
},
"require": {
@@ -916,7 +920,7 @@
"type": "github"
}
],
"time": "2025-08-04T19:17:37+00:00"
"time": "2025-09-25T06:58:18+00:00"
},
{
"name": "phpunit/php-code-coverage",
@@ -1239,16 +1243,16 @@
},
{
"name": "phpunit/phpunit",
"version": "9.6.24",
"version": "9.6.29",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/phpunit.git",
"reference": "ea49afa29aeea25ea7bf9de9fdd7cab163cc0701"
"reference": "9ecfec57835a5581bc888ea7e13b51eb55ab9dd3"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/ea49afa29aeea25ea7bf9de9fdd7cab163cc0701",
"reference": "ea49afa29aeea25ea7bf9de9fdd7cab163cc0701",
"url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/9ecfec57835a5581bc888ea7e13b51eb55ab9dd3",
"reference": "9ecfec57835a5581bc888ea7e13b51eb55ab9dd3",
"shasum": ""
},
"require": {
@@ -1273,7 +1277,7 @@
"sebastian/comparator": "^4.0.9",
"sebastian/diff": "^4.0.6",
"sebastian/environment": "^5.1.5",
"sebastian/exporter": "^4.0.6",
"sebastian/exporter": "^4.0.8",
"sebastian/global-state": "^5.0.8",
"sebastian/object-enumerator": "^4.0.4",
"sebastian/resource-operations": "^3.0.4",
@@ -1322,7 +1326,7 @@
"support": {
"issues": "https://github.com/sebastianbergmann/phpunit/issues",
"security": "https://github.com/sebastianbergmann/phpunit/security/policy",
"source": "https://github.com/sebastianbergmann/phpunit/tree/9.6.24"
"source": "https://github.com/sebastianbergmann/phpunit/tree/9.6.29"
},
"funding": [
{
@@ -1346,7 +1350,7 @@
"type": "tidelift"
}
],
"time": "2025-08-10T08:32:42+00:00"
"time": "2025-09-24T06:29:11+00:00"
},
{
"name": "psr/container",
@@ -1842,16 +1846,16 @@
},
{
"name": "sebastian/exporter",
"version": "4.0.6",
"version": "4.0.8",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/exporter.git",
"reference": "78c00df8f170e02473b682df15bfcdacc3d32d72"
"reference": "14c6ba52f95a36c3d27c835d65efc7123c446e8c"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/sebastianbergmann/exporter/zipball/78c00df8f170e02473b682df15bfcdacc3d32d72",
"reference": "78c00df8f170e02473b682df15bfcdacc3d32d72",
"url": "https://api.github.com/repos/sebastianbergmann/exporter/zipball/14c6ba52f95a36c3d27c835d65efc7123c446e8c",
"reference": "14c6ba52f95a36c3d27c835d65efc7123c446e8c",
"shasum": ""
},
"require": {
@@ -1907,15 +1911,27 @@
],
"support": {
"issues": "https://github.com/sebastianbergmann/exporter/issues",
"source": "https://github.com/sebastianbergmann/exporter/tree/4.0.6"
"source": "https://github.com/sebastianbergmann/exporter/tree/4.0.8"
},
"funding": [
{
"url": "https://github.com/sebastianbergmann",
"type": "github"
},
{
"url": "https://liberapay.com/sebastianbergmann",
"type": "liberapay"
},
{
"url": "https://thanks.dev/u/gh/sebastianbergmann",
"type": "thanks_dev"
},
{
"url": "https://tidelift.com/funding/github/packagist/sebastian/exporter",
"type": "tidelift"
}
],
"time": "2024-03-02T06:33:00+00:00"
"time": "2025-09-24T06:03:27+00:00"
},
{
"name": "sebastian/global-state",
@@ -2402,16 +2418,16 @@
},
{
"name": "swoole/ide-helper",
"version": "4.8.0",
"version": "5.1.8",
"source": {
"type": "git",
"url": "https://github.com/swoole/ide-helper.git",
"reference": "837a2b20242e3cebf0ba1168e876f0f1ca9a14e3"
"reference": "2806169ec7385e3b5eb484efef1f4764af46d995"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/swoole/ide-helper/zipball/837a2b20242e3cebf0ba1168e876f0f1ca9a14e3",
"reference": "837a2b20242e3cebf0ba1168e876f0f1ca9a14e3",
"url": "https://api.github.com/repos/swoole/ide-helper/zipball/2806169ec7385e3b5eb484efef1f4764af46d995",
"reference": "2806169ec7385e3b5eb484efef1f4764af46d995",
"shasum": ""
},
"type": "library",
@@ -2428,19 +2444,9 @@
"description": "IDE help files for Swoole.",
"support": {
"issues": "https://github.com/swoole/ide-helper/issues",
"source": "https://github.com/swoole/ide-helper/tree/4.8.0"
"source": "https://github.com/swoole/ide-helper/tree/5.1.8"
},
"funding": [
{
"url": "https://gitee.com/swoole/swoole?donate=true",
"type": "custom"
},
{
"url": "https://github.com/swoole",
"type": "github"
}
],
"time": "2021-10-14T19:39:28+00:00"
"time": "2025-08-04T05:40:28+00:00"
},
{
"name": "symfony/deprecation-contracts",
@@ -2562,13 +2568,13 @@
],
"aliases": [],
"minimum-stability": "stable",
"stability-flags": [],
"stability-flags": {},
"prefer-stable": false,
"prefer-lowest": false,
"platform": {
"php": ">=8.0",
"ext-mongodb": "2.1.1"
"ext-mongodb": "2.1.*"
},
"platform-dev": [],
"plugin-api-version": "2.2.0"
"platform-dev": {},
"plugin-api-version": "2.6.0"
}
+2 -4
View File
@@ -1,12 +1,10 @@
version: '3.1'
services:
tests:
container_name: utopia-mongo-test-1
build:
context: .
dockerfile: Dockerfile-php-${PHP_VERSION:-8.3}
dockerfile: php${PHP_VERSION:-83}.Dockerfile
networks:
- database
volumes:
@@ -15,7 +13,7 @@ services:
- "8882:8882"
mongo:
image: mongo:5
image: mongo:8
container_name: utopia-mongo-1
networks:
- database
+2 -2
View File
@@ -1,4 +1,4 @@
FROM composer:2.0 as composer
FROM composer:2.0 AS composer
ARG TESTING=false
ENV TESTING=$TESTING
@@ -33,7 +33,7 @@ RUN \
&& ./configure \
&& make && make install
FROM compile as final
FROM compile AS final
LABEL maintainer="team@appwrite.io"
+35 -28
View File
@@ -34,7 +34,7 @@ class Auth
return [
[
"saslStart" => 1,
"mechanism" => "SCRAM-SHA-1",
"mechanism" => "SCRAM-SHA-256",
"payload" => $payload,
"autoAuthorize" => 1,
"options" => ["skipEmptyExchange" => true],
@@ -84,9 +84,9 @@ class Auth
if (empty($challenge)) {
return $this->generateInitialResponse($authcid, $authzid);
} else {
return $this->generateResponse($challenge, $this->secret);
}
return $this->generateResponse($challenge, $this->secret);
}
/**
@@ -110,10 +110,10 @@ class Auth
*/
private function generateInitialResponse(string $authcid, string $authzid): string
{
$gs2CbindFlag = 'n,';
$gs2CbindFlag = 'n,';
$this->gs2Header = $gs2CbindFlag . (!empty($authzid) ? 'a=' . $authzid : '') . ',';
// I must generate a client nonce and "save" it for later comparison on second response.
// Generate a client nonce and "save" it for later comparison on second response.
$this->cnonce = $this->generateCnonce();
$this->firstMessageBare = 'n=' . $authcid . ',r=' . $this->cnonce;
@@ -124,8 +124,8 @@ class Auth
/**
* Parses and verifies a non-empty SCRAM challenge.
*
* @param string $challenge The SCRAM challenge
* @param string $password The password challenge
* @param string $challenge The SCRAM challenge
* @param string $password The password challenge
* @return string|false The response to send; false in case of wrong challenge or if an initial response has not
* been generated first.
*/
@@ -141,7 +141,7 @@ class Auth
return false;
}
$nonce = $matches[1];
$salt = base64_decode($matches[2]);
$salt = base64_decode($matches[2]);
if (!$salt) {
return false;
@@ -153,17 +153,17 @@ class Auth
return false;
}
$channelBinding = 'c=' . base64_encode($this->gs2Header);
$finalMessage = $channelBinding . ',r=' . $nonce;
$saltedPassword = $this->hi($password, $salt, $i);
$channelBinding = 'c=' . base64_encode($this->gs2Header);
$finalMessage = $channelBinding . ',r=' . $nonce;
$saltedPassword = $this->hi($password, $salt, $i);
$this->saltedPassword = $saltedPassword;
$clientKey = $this->hmac($saltedPassword, "Client Key");
$storedKey = $this->hash($clientKey);
$authMessage = $this->firstMessageBare . ',' . $challenge . ',' . $finalMessage;
$this->authMessage = $authMessage;
$clientSignature = $this->hmac($storedKey, $authMessage);
$clientProof = $clientKey ^ $clientSignature;
$proof = ',p=' . base64_encode($clientProof);
$clientKey = $this->hmac($saltedPassword, "Client Key");
$storedKey = $this->hash($clientKey);
$authMessage = $this->firstMessageBare . ',' . $challenge . ',' . $finalMessage;
$this->authMessage = $authMessage;
$clientSignature = $this->hmac($storedKey, $authMessage);
$clientProof = $clientKey ^ $clientSignature;
$proof = ',p=' . base64_encode($clientProof);
return $finalMessage . $proof;
}
@@ -171,18 +171,18 @@ class Auth
/**
* Hi() call, which is essentially PBKDF2 (RFC-2898) with HMAC-H() as the pseudorandom function.
*
* @param string $str The string to hash.
* @param string $str The string to hash.
* @param string $salt The salt value.
* @param int $i The iteration count.
* @return string The hashed string.
*/
private function hi(string $str, string $salt, int $i): string
{
$int1 = "\0\0\0\1";
$ui = $this->hmac($str, $salt . $int1);
$int1 = "\0\0\0\1";
$ui = $this->hmac($str, $salt . $int1);
$result = $ui;
for ($k = 1; $k < $i; $k++) {
$ui = $this->hmac($str, $ui);
$ui = $this->hmac($str, $ui);
$result = $result ^ $ui;
}
return $result;
@@ -207,10 +207,10 @@ class Auth
return false;
}
$verifier = $matches[1];
$verifier = $matches[1];
$proposedServerSignature = base64_decode($verifier);
$serverKey = $this->hmac($this->saltedPassword, "Server Key");
$serverSignature = $this->hmac($serverKey, $this->authMessage);
$serverKey = $this->hmac($this->saltedPassword, "Server Key");
$serverSignature = $this->hmac($serverKey, $this->authMessage);
return $proposedServerSignature === $serverSignature;
}
@@ -245,7 +245,7 @@ class Auth
*/
private function hash($data): string
{
return hash('sha1', $data, true);
return hash('sha256', $data, true);
}
/**
@@ -255,7 +255,7 @@ class Auth
*/
private function hmac($key, $str): string
{
return hash_hmac('sha1', $str, $key, true);
return hash_hmac('sha256', $str, $key, true);
}
/**
@@ -279,10 +279,17 @@ class Auth
}
/**
* Encode credentials for MongoDB SCRAM-SHA-256
* For SCRAM-SHA-256, we store the raw password and let the SCRAM mechanism handle it
*
* @param string $username
* @param string $password
* @return string
*/
public static function encodeCredentials($username, $password): string
{
return \md5($username . ':mongo:' . $password);
// For SCRAM-SHA-256, return the raw password
// The SCRAM mechanism will handle the proper hashing
return $password;
}
}
+1360 -246
View File
File diff suppressed because it is too large. Load diff
+252
View File
@@ -2,6 +2,258 @@
namespace Utopia\Mongo;
/**
* Base MongoDB exception class with enhanced error categorization.
*
* Provides better error handling and categorization for MongoDB 8+ operations.
*/
class Exception extends \Exception
{
protected array $errorLabels = [];
protected ?array $writeErrors = null;
protected ?array $writeConcernErrors = null;
protected ?string $operationType = null;
/**
* @param string $message Error message
* @param int $code Error code
* @param \Throwable|null $previous Previous exception
* @param array $errorLabels MongoDB error labels
* @param array|null $writeErrors Write errors if applicable
* @param array|null $writeConcernErrors Write concern errors if applicable
* @param string|null $operationType Operation type that caused the error
*/
public function __construct(
string $message = '',
int $code = 0,
?\Throwable $previous = null,
array $errorLabels = [],
?array $writeErrors = null,
?array $writeConcernErrors = null,
?string $operationType = null
) {
parent::__construct($message, $code, $previous);
$this->errorLabels = $errorLabels;
$this->writeErrors = $writeErrors;
$this->writeConcernErrors = $writeConcernErrors;
$this->operationType = $operationType;
}
/**
* Check if this is a transient error that can be retried.
*
* @return bool
*/
public function isTransientError(): bool
{
return in_array('TransientTransactionError', $this->errorLabels) ||
in_array('UnknownTransactionCommitResult', $this->errorLabels) ||
$this->isNetworkError() ||
$this->isRetryableWrite();
}
/**
* Check if this is a network-related error.
*
* @return bool
*/
public function isNetworkError(): bool
{
$networkErrorCodes = [
11600, 11601, 11602, // Socket errors
89, // NetworkTimeout
9001, // SocketException
6, // HostUnreachable
7, // HostNotFound
];
return in_array($this->code, $networkErrorCodes);
}
/**
* Check if this is a retryable write error.
*
* @return bool
*/
public function isRetryableWrite(): bool
{
return in_array('RetryableWriteError', $this->errorLabels);
}
/**
* Check if this is a duplicate key error.
*
* @return bool
*/
public function isDuplicateKeyError(): bool
{
return $this->code === 11000 || $this->code === 11001;
}
/**
* Check if this is a write concern error.
*
* @return bool
*/
public function isWriteConcernError(): bool
{
return !empty($this->writeConcernErrors);
}
/**
* Check if this is a timeout error.
*
* @return bool
*/
public function isTimeoutError(): bool
{
$timeoutCodes = [
50, // MaxTimeMSExpired
89, // NetworkTimeout
11601, // SocketTimeout
];
return in_array($this->code, $timeoutCodes);
}
/**
* Get error labels.
*
* @return array
*/
public function getErrorLabels(): array
{
return $this->errorLabels;
}
/**
* Get write errors.
*
* @return array|null
*/
public function getWriteErrors(): ?array
{
return $this->writeErrors;
}
/**
* Get write concern errors.
*
* @return array|null
*/
public function getWriteConcernErrors(): ?array
{
return $this->writeConcernErrors;
}
/**
* Get the operation type that caused this error.
*
* @return string|null
*/
public function getOperationType(): ?string
{
return $this->operationType;
}
/**
* Get a human-readable error category.
*
* @return string
*/
public function getErrorCategory(): string
{
if ($this->isNetworkError()) {
return 'Network Error';
}
if ($this->isTimeoutError()) {
return 'Timeout Error';
}
if ($this->isDuplicateKeyError()) {
return 'Duplicate Key Error';
}
if ($this->isWriteConcernError()) {
return 'Write Concern Error';
}
if ($this->isTransientError()) {
return 'Transient Error';
}
return 'MongoDB Error';
}
/**
* Create exception from MongoDB error response.
*
* @param \stdClass $errorResponse MongoDB error response
* @param string|null $operationType Operation type
* @return static
*/
public static function fromResponse(\stdClass $errorResponse, ?string $operationType = null): static
{
$message = $errorResponse->errmsg ?? 'Unknown MongoDB error';
$code = $errorResponse->code ?? 0;
$errorLabels = $errorResponse->errorLabels ?? [];
$writeErrors = $errorResponse->writeErrors ?? null;
$writeConcernErrors = $errorResponse->writeConcernErrors ?? null;
return new static(
$message,
$code,
null,
$errorLabels,
$writeErrors,
$writeConcernErrors,
$operationType
);
}
}
/**
* Connection-related exception.
*/
class ConnectionException extends Exception
{
}
/**
* Authentication-related exception.
*/
class AuthenticationException extends Exception
{
}
/**
* Transaction-related exception.
*/
class TransactionException extends Exception
{
}
/**
* Bulk write operation exception.
*/
class BulkWriteException extends Exception
{
private array $result;
public function __construct(string $message, array $result, int $code = 0, ?\Throwable $previous = null)
{
parent::__construct($message, $code, $previous);
$this->result = $result;
}
/**
* Get the bulk write result.
*
* @return array
*/
public function getResult(): array
{
return $this->result;
}
}
+12 -3
View File
@@ -13,6 +13,7 @@ class MongoTest extends TestCase
/**
* @throws Exception
* @throws \Exception
*/
public static function getDatabase(): Client
{
@@ -20,7 +21,15 @@ class MongoTest extends TestCase
return self::$db;
}
$client = new Client('testing', 'mongo', 27017, 'root', 'example', false);
$client = new Client(
database: 'testing',
host: 'mongo',
port: 27017,
user: 'root',
password: 'example',
useCoroutine: false
);
$client->connect();
self::$db = $client;
@@ -29,7 +38,7 @@ class MongoTest extends TestCase
public function testDeleteDatabase()
{
self::assertTrue($this->getDatabase()->dropDatabase([]));
self::assertTrue($this->getDatabase()->dropDatabase());
}
@@ -221,7 +230,7 @@ class MongoTest extends TestCase
$this->getDatabase()->find(
'movies',
['$where' => 'sleep(1000) || true'],
['maxTimeMS'=> 1]
['maxTimeMS' => 1]
)->cursor->firstBatch ?? [];
}
+424
View File
@@ -0,0 +1,424 @@
<?php
namespace Utopia\Tests;
use PHPUnit\Framework\TestCase;
use Utopia\Mongo\Client;
use Utopia\Mongo\Exception;
class TransactionTest extends TestCase
{
private static ?Client $client = null;
public static function setUpBeforeClass(): void
{
try {
self::$client = new Client(
database: 'testing',
host: 'mongo',
port: 27017,
user: 'root',
password: 'example',
useCoroutine: false
);
self::$client->connect();
} catch (Exception $e) {
self::markTestSkipped('MongoDB connection failed: ' . $e->getMessage());
}
}
public static function tearDownAfterClass(): void
{
self::$client?->close();
}
private function getClient(): Client
{
if (!self::$client) {
self::markTestSkipped('MongoDB client not available');
}
return self::$client;
}
/**
* Check if MongoDB instance supports transactions (requires replica set)
*/
private function isReplicatSet(): bool
{
try {
$client = $this->getClient();
// Try to get server status to check if it's a replica set
$result = $client->query(['isMaster' => 1], 'admin');
// Check various fields that indicate replica set or sharding
$isReplicaSet = isset($result->setName) ||
isset($result->hosts) ||
isset($result->ismaster) && isset($result->secondary) ||
isset($result->isWritablePrimary) ||
isset($result->msg) && $result->msg === 'isdbgrid';
if (!$isReplicaSet) {
return false;
}
} catch (\Exception $e) {
try {
$client = $this->getClient();
$testSession = $client->startSession();
$client->startTransaction($testSession);
// Try a simple insert with transaction params
$client->insert(
'_test_tx_check',
['test' => true],
['session' => $testSession]
);
// If we get here, transactions work - abort and clean up
$client->abortTransaction($testSession);
$client->endSessions([$testSession]);
$client->delete('_test_tx_check', ['test' => true]);
} catch (Exception $txError) {
if (strpos($txError->getMessage(), 'Transaction numbers are only allowed') !== false ||
strpos($txError->getMessage(), 'IllegalOperation') !== false) {
return false;
}
}
}
return true;
}
/**
* Test basic session creation and cleanup
*/
public function testSessionManagement()
{
$client = $this->getClient();
// Create session with options
$session = $client->startSession([
'causalConsistency' => true,
'defaultTransactionOptions' => [
'readConcern' => ['level' => 'majority'],
'writeConcern' => ['w' => 1, 'j' => true]
]
]);
$this->assertArrayHasKey('id', $session);
$this->assertArrayHasKey('sessionId', $session);
// Get session state
$state = $client->getSessionState($session);
$this->assertEquals('none', $state['state']);
$this->assertEquals(0, $state['txnNumber']);
// End session
$client->endSessions([$session]);
// Verify session is cleaned up
$stateAfterEnd = $client->getSessionState($session);
$this->assertArrayHasKey('error', $stateAfterEnd);
}
/**
* Test transaction with proper state management
*/
public function testTransactionStateManagement()
{
if (!$this->isReplicatSet()) {
$this->expectNotToPerformAssertions();
return;
}
$client = $this->getClient();
$session = $client->startSession();
try {
// Start transaction
$result = $client->startTransaction($session, [
'readConcern' => ['level' => 'majority'],
'writeConcern' => ['w' => 1]
]);
$this->assertTrue($result);
// Verify transaction state
$state = $client->getSessionState($session);
$this->assertEquals('in_progress', $state['state']);
$this->assertEquals(1, $state['txnNumber']);
// Perform operations within transaction
$client->insert(
'test_collection',
['name' => 'test_doc', 'value' => 42],
['session' => $session]
);
// Commit transaction
$commitResult = $client->commitTransaction($session);
$this->assertNotNull($commitResult);
// Verify final state
$finalState = $client->getSessionState($session);
$this->assertEquals('committed', $finalState['state']);
} finally {
$client->endSessions([$session]);
}
}
/**
* Test transaction abort functionality
*/
public function testTransactionAbort()
{
if (!$this->isReplicatSet()) {
$this->expectNotToPerformAssertions();
return;
}
$client = $this->getClient();
$session = $client->startSession();
try {
$client->startTransaction($session);
// Insert a document
$client->insert(
'test_collection',
['name' => 'abort_test', 'value' => 999],
['session' => $session]
);
// Abort transaction
$abortResult = $client->abortTransaction($session);
$this->assertNotNull($abortResult);
// Verify transaction was aborted
$state = $client->getSessionState($session);
$this->assertEquals('aborted', $state['state']);
// Verify document was not inserted (transaction rolled back)
$found = $client->find('test_collection', ['name' => 'abort_test']);
$this->assertEmpty($found->cursor->firstBatch);
} finally {
$client->endSessions([$session]);
}
}
/**
* Test withTransaction helper with retry logic
*/
public function testWithTransactionHelper()
{
if (!$this->isReplicatSet()) {
$this->expectNotToPerformAssertions();
return;
}
$client = $this->getClient();
$session = $client->startSession();
try {
$result = $client->withTransaction($session, function ($session) use ($client) {
// Insert multiple documents in transaction
$client->insert(
'test_collection',
['name' => 'with_transaction_1', 'counter' => 1],
['session' => $session]
);
$client->insert(
'test_collection',
['name' => 'with_transaction_2', 'counter' => 2],
['session' => $session]
);
return 'transaction_completed';
}, [
'readConcern' => ['level' => 'majority'],
'writeConcern' => ['w' => 1],
'maxRetries' => 3
]);
$this->assertEquals('transaction_completed', $result);
// Verify both documents were inserted
$found1 = $client->find('test_collection', ['name' => 'with_transaction_1']);
$found2 = $client->find('test_collection', ['name' => 'with_transaction_2']);
$this->assertNotEmpty($found1->cursor->firstBatch);
$this->assertNotEmpty($found2->cursor->firstBatch);
} finally {
$client->endSessions([$session]);
}
}
/**
* Test read and write concerns validation
*/
public function testReadWriteConcerns()
{
$client = $this->getClient();
// Test valid write concern
$writeConcern = $client->createWriteConcern(['w' => 'majority', 'j' => true, 'wtimeout' => 5000]);
$this->assertEquals('majority', $writeConcern['w']);
$this->assertTrue($writeConcern['j']);
$this->assertEquals(5000, $writeConcern['wtimeout']);
// Test valid read concern
$readConcern = $client->createReadConcern(['level' => 'majority']);
$this->assertEquals('majority', $readConcern['level']);
// Test invalid read concern should throw exception
$this->expectException(Exception::class);
$client->createReadConcern(['level' => 'invalid']);
}
/**
* Test CRUD operations with session and concerns
*/
public function testCRUDWithSessionAndConcerns()
{
if (!$this->isReplicatSet()) {
$this->expectNotToPerformAssertions();
return;
}
$client = $this->getClient();
$session = $client->startSession();
try {
$client->startTransaction($session);
// Insert with session and write concern
$insertedDoc = $client->insert(
'test_collection',
['name' => 'crud_test', 'status' => 'active'],
[
'session' => $session,
'writeConcern' => ['w' => 1, 'j' => true]
]
);
$this->assertArrayHasKey('_id', $insertedDoc);
// Find with session and read concern
$found = $client->find(
'test_collection',
['name' => 'crud_test'],
[
'session' => $session,
'readConcern' => ['level' => 'local']
]
);
$this->assertNotEmpty($found->cursor->firstBatch);
// Update with session
$client->update(
'test_collection',
['name' => 'crud_test'],
['$set' => ['status' => 'updated']],
[
'session' => $session,
'writeConcern' => ['w' => 1]
]
);
// Count with session
$count = $client->count(
'test_collection',
['name' => 'crud_test'],
[
'session' => $session,
'readConcern' => ['level' => 'local']
]
);
$this->assertEquals(1, $count);
$client->commitTransaction($session);
} finally {
$client->endSessions([$session]);
}
}
/**
* Test connection validation and health checks
*/
public function testConnectionValidation()
{
$client = $this->getClient();
// Get connection info
$info = $client->getConnectionInfo();
$this->assertTrue($info['connected']);
$this->assertEquals('mongo', $info['host']);
$this->assertEquals(27017, $info['port']);
$this->assertEquals('testing', $info['database']);
$this->assertIsInt($info['activeSessions']);
}
/**
* Test causal consistency tracking
*/
public function testCausalConsistency()
{
$client = $this->getClient();
// Perform an operation to get operation time
$client->find('test_collection', []);
// Check if operation time is tracked
$operationTime = $client->getOperationTime();
$clusterTime = $client->getClusterTime();
// These may be null if not in a replica set, which is fine for testing
$this->assertTrue($operationTime === null || is_object($operationTime));
$this->assertTrue($clusterTime === null || is_object($clusterTime));
}
/**
* Test session cleanup
*/
public function testSessionCleanup()
{
$client = $this->getClient();
// Create multiple sessions
$sessions = [];
for ($i = 0; $i < 3; $i++) {
$sessions[] = $client->startSession();
}
// Verify sessions are active
$info = $client->getConnectionInfo();
$this->assertGreaterThanOrEqual(3, $info['activeSessions']);
// End all sessions
$client->endSessions($sessions);
// Verify sessions are cleaned up
$infoAfter = $client->getConnectionInfo();
$this->assertLessThan($info['activeSessions'], $infoAfter['activeSessions']);
}
protected function tearDown(): void
{
// Clean up test data
if (self::$client) {
try {
self::$client->dropCollection('test_collection');
} catch (Exception $e) {
// Ignore cleanup errors
}
}
}
}