diff --git a/src/Client.php b/src/Client.php index 171871923d..2ad5494bd5 100644 --- a/src/Client.php +++ b/src/Client.php @@ -2178,13 +2178,16 @@ class Client } } + // Both throws are raised ahead of the send, so the command never + // reached the server and a caller may safely replay it. They carry + // HostUnreachable to say so in a code rather than in text. if (!$this->isConnected) { - throw new Exception('Client is not connected to MongoDB'); + throw new Exception('Client is not connected to MongoDB', Exception::HOST_UNREACHABLE); } if (!$this->client->isConnected()) { $this->isConnected = false; - throw new Exception('Connection to MongoDB has been lost'); + throw new Exception('Connection to MongoDB has been lost', Exception::HOST_UNREACHABLE); } } diff --git a/src/Exception.php b/src/Exception.php index 7c47d6acd6..184d1bac22 100644 --- a/src/Exception.php +++ b/src/Exception.php @@ -9,6 +9,19 @@ namespace Utopia\Mongo; */ class Exception extends \Exception { + /** + * The connection was gone before the command left the client. + * + * MongoDB's own HostUnreachable. Carried by every throw raised out of + * connection validation, which runs ahead of the send: the command was + * never on the wire, so nothing was applied and a caller may safely + * replay it. Distinguishing this from a post-send failure used to be + * possible only by matching the message text, which callers cannot do + * safely - a message quotes caller-chosen values, a code cannot be + * spelled by a caller. + */ + public const int HOST_UNREACHABLE = 6; + protected array $errorLabels = []; protected ?array $writeErrors = null; protected ?array $writeConcernErrors = null; @@ -105,6 +118,15 @@ class Exception extends \Exception * * @return bool */ + /** + * Whether the command was still unsent when this failure was raised, so + * nothing was applied and the caller may replay it. + */ + public function isUnsentError(): bool + { + return $this->code === self::HOST_UNREACHABLE; + } + public function isTimeoutError(): bool { $timeoutCodes = [ diff --git a/tests/UnsentErrorTest.php b/tests/UnsentErrorTest.php new file mode 100644 index 0000000000..743f5ad7fb --- /dev/null +++ b/tests/UnsentErrorTest.php @@ -0,0 +1,40 @@ +assertTrue($unsent->isUnsentError()); + $this->assertFalse($unsent->isTimeoutError(), 'An unsent failure must not be confused with a post-send timeout'); + } + + public function testAPostSendTimeoutIsNotReportedAsUnsent(): void + { + $timeout = new Exception('Receive timeout: no data received within reasonable time', 11601); + + $this->assertTrue($timeout->isTimeoutError()); + $this->assertFalse( + $timeout->isUnsentError(), + 'The command was already on the wire, so its outcome is unknown and it must never be replayed blindly', + ); + } + + public function testAnUncodedFailureIsNotAssumedUnsent(): void + { + $this->assertFalse(new Exception('something went wrong')->isUnsentError()); + } +}