44
55use Exception ;
66use Utopia \Database \Exception as DatabaseException ;
7+ use Utopia \Database \Exception \Authorization as AuthorizationException ;
8+ use Utopia \Database \Exception \Conflict as ConflictException ;
79use Utopia \Database \Exception \Duplicate as DuplicateException ;
10+ use Utopia \Database \Exception \Limit as LimitException ;
11+ use Utopia \Database \Exception \Relationship as RelationshipException ;
12+ use Utopia \Database \Exception \Restricted as RestrictedException ;
813use Utopia \Database \Exception \Timeout as TimeoutException ;
914use Utopia \Database \Exception \Transaction as TransactionException ;
1015
@@ -371,7 +376,10 @@ public function inTransaction(): bool
371376 */
372377 public function withTransaction (callable $ callback ): mixed
373378 {
374- for ($ attempts = 0 ; $ attempts < 3 ; $ attempts ++) {
379+ $ sleep = 50_000 ; // 50 milliseconds
380+ $ retries = 2 ;
381+
382+ for ($ attempts = 0 ; $ attempts <= $ retries ; $ attempts ++) {
375383 try {
376384 $ this ->startTransaction ();
377385 $ result = $ callback ();
@@ -380,18 +388,31 @@ public function withTransaction(callable $callback): mixed
380388 } catch (\Throwable $ action ) {
381389 try {
382390 $ this ->rollbackTransaction ();
391+
392+ if (
393+ $ action instanceof DuplicateException ||
394+ $ action instanceof RestrictedException ||
395+ $ action instanceof AuthorizationException ||
396+ $ action instanceof RelationshipException ||
397+ $ action instanceof ConflictException ||
398+ $ action instanceof LimitException
399+ ) {
400+ $ this ->inTransaction = 0 ;
401+ throw $ action ;
402+ }
403+
383404 } catch (\Throwable $ rollback ) {
384- if ($ attempts < 2 ) {
385- \usleep (5000 ); // 5ms
405+ if ($ attempts < $ retries ) {
406+ \usleep ($ sleep * ( $ attempts + 1 ));
386407 continue ;
387408 }
388409
389410 $ this ->inTransaction = 0 ;
390411 throw $ rollback ;
391412 }
392413
393- if ($ attempts < 2 ) {
394- \usleep (5000 ); // 5ms
414+ if ($ attempts < $ retries ) {
415+ \usleep ($ sleep * ( $ attempts + 1 ));
395416 continue ;
396417 }
397418
0 commit comments