From a1dd00fcba4f77e2837a367c03d76daa7feda77f Mon Sep 17 00:00:00 2001 From: Ruben van der Linde Date: Fri, 6 Nov 2026 08:09:19 +0100 Subject: [PATCH 1/2] fix(objects): the routes catch what they were written to catch ObjectsController imported OCP\DB\Exception, so five catch (Exception) blocks took database failures only and every other failure left the route. - create(): a failing webhook interception now never breaks the write (Throwable). - logs(): a failed lookup answers 404 (Exception), logged unless a plain miss. - vectorizeBatch(), getObjectVectorizationStats(): any failure answers the generic 500 (Throwable), now logged, since the text never reaches the client. - validate(): another Exception answers the 500 with its message. An Error stays with the server, so its text does not reach the client. Failures of an external source still leave the routes, for ObjectSourceErrorMiddleware to answer with their own status. Database failures get the same responses as before. The import is gone, so the trap cannot return. The pins from #5856 change with it: testOtherFailuresLeaveTheRoutes is replaced and the golden gains the new log lines. Assisted-by: ClaudeCode:claude-opus-5-5 --- lib/Controller/ObjectsController.php | 91 ++++++++++++++++--- .../ObjectsControllerBulkRoutesGoldenTest.php | 91 +++++++++++++++++-- .../ObjectsControllerCoverageTest.php | 20 +++- .../Unit/Controller/ObjectsControllerTest.php | 43 ++++++--- .../fixtures/objects-bulk-routes-golden.json | 22 +++++ 5 files changed, 228 insertions(+), 39 deletions(-) diff --git a/lib/Controller/ObjectsController.php b/lib/Controller/ObjectsController.php index a08c39daec02..5b3227c525be 100644 --- a/lib/Controller/ObjectsController.php +++ b/lib/Controller/ObjectsController.php @@ -74,6 +74,8 @@ use OCA\OpenRegister\Service\Interaction\ReadStateService; use OCA\OpenRegister\Service\Object\SchemaTypeConverter; use OCA\OpenRegister\Service\Object\UpsertOnKeyException; +use OCA\OpenRegister\Service\ObjectSource\DbalObjectSourceException; +use OCA\OpenRegister\Service\ObjectSource\DbalWriteException; use OCA\OpenRegister\Service\Object\UpsertOnKeyHandler; use OCA\OpenRegister\Service\ObjectService; use OCA\OpenRegister\Search\Service\Geo\GeoResponseCrs; @@ -96,7 +98,6 @@ use OCP\AppFramework\Http\Attribute\UserRateLimit; use OCP\AppFramework\Http\DataDownloadResponse; use OCP\AppFramework\Http\JSONResponse; -use OCP\DB\Exception; use OCP\IGroupManager; use OCP\IRequest; use OCP\IUserSession; @@ -3483,7 +3484,7 @@ public function create( request: $this->request, eventType: 'object.creating' ); - } catch (Exception $e) { + } catch (\Throwable $e) { // Log error but continue with original request if webhook fails. // This ensures webhook failures don't break the API. $this->logger->error( @@ -4470,7 +4471,7 @@ public function postPatch( * * @return JSONResponse JSON response with success or error. * - * @throws Exception + * @throws \Exception * * @NoAdminRequired * @NoCSRFRequired @@ -4930,8 +4931,8 @@ public function logs(string $id, string $register, string $schema, ObjectOperati } } catch (MultipleObjectsReturnedException $e) { return $this->ambiguousIdentifierResponse(id: $id); - } catch (Exception $e) { - return new JSONResponse(data: ['message' => 'Object not found'], statusCode: 404); + } catch (\Exception $e) { + return $this->historyLookupFailureResponse(failure: $e); } // Normalize and compare register. @@ -6416,7 +6417,7 @@ public function downloadFiles( unlink($zipInfo['path']); } - throw new Exception('Failed to read ZIP file content'); + throw new \RuntimeException('Failed to read ZIP file content'); } // Clean up temporary file after reading. @@ -6491,8 +6492,8 @@ public function vectorizeBatch(): JSONResponse { $result = $this->objectService->vectorizeBatchObjects(_views: $views, _batchSize: $batchSize); return new JSONResponse(data: ['success' => true, 'data' => $result]); - } catch (Exception $e) { - return new JSONResponse(data: ['success' => false, 'error' => 'Internal server error'], statusCode: 500); + } catch (\Throwable $e) { + return $this->vectorizationFailureResponse(failure: $e); } }//end vectorizeBatch() @@ -6523,8 +6524,8 @@ public function getObjectVectorizationStats(): JSONResponse { $stats = $this->objectService->getVectorizationStatistics(_views: $views); return new JSONResponse(data: ['success' => true, 'stats' => $stats]); - } catch (Exception $e) { - return new JSONResponse(data: ['success' => false, 'error' => 'Internal server error'], statusCode: 500); + } catch (\Throwable $e) { + return $this->vectorizationFailureResponse(failure: $e); } }//end getObjectVectorizationStats() @@ -6554,7 +6555,7 @@ public function validate(): JSONResponse { } return $this->validationResponse(window: $window, result: $this->validatedChunk(window: $window)); - } catch (Exception $e) { + } catch (\Exception $e) { return $this->validationFailureResponse(failure: $e); } }//end validate() @@ -6629,13 +6630,16 @@ private function validationResponse(ValidationWindow $window, array $result): JS /** * Log a failed bulk validation and answer it. * - * @param Exception $failure The failure. + * @param \Exception $failure The failure. * * @return JSONResponse The 500 answer. * + * @throws DbalObjectSourceException|DbalWriteException For ObjectSourceErrorMiddleware to answer. + * * @spec openspec/archive/retrofit-annotate-openregister-2026-04-23/tasks.md */ - private function validationFailureResponse(Exception $failure): JSONResponse { + private function validationFailureResponse(\Exception $failure): JSONResponse { + $this->rethrowExternalSourceFailure(failure: $failure); $this->logger->error( message: '[ObjectsController] Bulk validation failed', context: [ @@ -6652,6 +6656,67 @@ private function validationFailureResponse(Exception $failure): JSONResponse { ); }//end validationFailureResponse() + /** + * Log a failed vectorization route and answer it without the failure's text. + * + * @param \Throwable $failure The failure. + * + * @return JSONResponse The 500 answer. + * + * @throws DbalObjectSourceException|DbalWriteException For ObjectSourceErrorMiddleware to answer. + * + * @spec openspec/archive/retrofit-annotate-openregister-2026-04-23/tasks.md + */ + private function vectorizationFailureResponse(\Throwable $failure): JSONResponse { + $this->rethrowExternalSourceFailure(failure: $failure); + $this->logger->error( + message: '[ObjectsController] Vectorization route failed', + context: ['file' => __FILE__, 'line' => __LINE__, 'error' => $failure->getMessage()] + ); + + return new JSONResponse(data: ['success' => false, 'error' => 'Internal server error'], statusCode: 500); + }//end vectorizationFailureResponse() + + /** + * Answer an object history lookup that failed with a 404, logging anything but a plain miss. + * + * @param \Exception $failure The failure. + * + * @return JSONResponse The 404 answer. + * + * @throws DbalObjectSourceException|DbalWriteException For ObjectSourceErrorMiddleware to answer. + * + * @spec openspec/archive/retrofit-annotate-openregister-2026-04-23/tasks.md + */ + private function historyLookupFailureResponse(\Exception $failure): JSONResponse { + $this->rethrowExternalSourceFailure(failure: $failure); + if ($failure instanceof DoesNotExistException === false) { + $this->logger->error( + message: '[ObjectsController] Object history lookup failed', + context: ['file' => __FILE__, 'line' => __LINE__, 'error' => $failure->getMessage()] + ); + } + + return new JSONResponse(data: ['message' => 'Object not found'], statusCode: 404); + }//end historyLookupFailureResponse() + + /** + * Let an external source's failure leave the route: ObjectSourceErrorMiddleware answers it with its own status. + * + * @param \Throwable $failure The failure a route caught. + * + * @return void + * + * @throws DbalObjectSourceException|DbalWriteException When the failure is one of these. + * + * @spec openspec/specs/dbal-virtual-registers/spec.md + */ + private function rethrowExternalSourceFailure(\Throwable $failure): void { + if ($failure instanceof DbalObjectSourceException || $failure instanceof DbalWriteException) { + throw $failure; + } + }//end rethrowExternalSourceFailure() + /** * Collect UUID-to-name mappings for all related objects in a response. * diff --git a/tests/Unit/Controller/ObjectsControllerBulkRoutesGoldenTest.php b/tests/Unit/Controller/ObjectsControllerBulkRoutesGoldenTest.php index 82302a5af877..ba6f23f16055 100644 --- a/tests/Unit/Controller/ObjectsControllerBulkRoutesGoldenTest.php +++ b/tests/Unit/Controller/ObjectsControllerBulkRoutesGoldenTest.php @@ -9,6 +9,8 @@ use OCA\OpenRegister\Controller\ObjectsController; use OCA\OpenRegister\Kernel\Contracts\ObjectOperationsInterface; +use OCA\OpenRegister\Service\ObjectSource\DbalObjectSourceException; +use OCA\OpenRegister\Service\ObjectSource\DbalWriteException; use OCP\AppFramework\Http\JSONResponse; use OCP\DB\Exception as DatabaseException; use OCP\IRequest; @@ -23,7 +25,7 @@ * * Every case records each service call and log line, without file and line, * and the answer, and compares them with fixtures/objects-bulk-routes-golden.json. - * The routes answer a database failure themselves; any other failure leaves them. + * The routes answer their own failures; an external source's failure leaves them for ObjectSourceErrorMiddleware. * Set UPDATE_GOLDEN=1 to rewrite the fixture. * * @covers \OCA\OpenRegister\Controller\ObjectsController @@ -136,26 +138,97 @@ public function testVectorizationStatsMatchTheRecording(mixed $views, bool $fail $this->compareResponse(key: 'stats ' . $this->dataName(), response: $this->controller(request: $request, service: $service)->getObjectVectorizationStats()); } - public function testOtherFailuresLeaveTheRoutes(): void { + /** + * @return array + */ + public static function nonDatabaseFailures(): array { + return [ + 'exception' => [new RuntimeException('secret detail')], + 'error' => [new \TypeError('secret detail')], + ]; + } + + #[DataProvider('nonDatabaseFailures')] + public function testVectorizeBatchAnswersAnyFailure(\Throwable $failure): void { $service = $this->service(); - $service->method('validateAndSaveObjectsBySchema')->willThrowException(new RuntimeException('validate')); - $service->method('vectorizeBatchObjects')->willThrowException(new RuntimeException('vectorize')); - $service->method('getVectorizationStatistics')->willThrowException(new RuntimeException('stats')); + $service->method('vectorizeBatchObjects')->willThrowException($failure); $request = $this->createMock(IRequest::class); $request->method('getParams')->willReturn([]); - $request->method('getParam')->willReturnCallback(static fn (string $key) => $key === 'views' ? null : 1); + + $this->assertGenericFailure($this->controller(request: $request, service: $service)->vectorizeBatch()); + } + + #[DataProvider('nonDatabaseFailures')] + public function testVectorizationStatsAnswerAnyFailure(\Throwable $failure): void { + $service = $this->service(); + $service->method('getVectorizationStatistics')->willThrowException($failure); + + $this->assertGenericFailure( + $this->controller(request: $this->createMock(IRequest::class), service: $service)->getObjectVectorizationStats() + ); + } + + public function testValidateAnswersAnotherException(): void { + $service = $this->service(); + $service->method('validateAndSaveObjectsBySchema')->willThrowException(new RuntimeException('validate')); + + $response = $this->controller(request: $this->validationRequest(), service: $service)->validate(); + + $this->assertSame(500, $response->getStatus()); + $this->assertSame(['success' => false, 'error' => 'validate', 'message' => 'Validation failed'], $response->getData()); + } + + public function testValidateLeavesAnErrorToTheServer(): void { + $service = $this->service(); + $service->method('validateAndSaveObjectsBySchema')->willThrowException(new \TypeError('internal')); + + $this->expectException(\TypeError::class); + $this->controller(request: $this->validationRequest(), service: $service)->validate(); + } + + /** + * @return array + */ + public static function externalSourceFailures(): array { + return [ + 'read' => [new DbalObjectSourceException('source down', 503)], + 'write' => [new DbalWriteException('source refused', 409)], + ]; + } + + #[DataProvider('externalSourceFailures')] + public function testExternalSourceFailuresLeaveTheRoutes(\Exception $failure): void { + $service = $this->service(); + $service->method('validateAndSaveObjectsBySchema')->willThrowException($failure); + $service->method('vectorizeBatchObjects')->willThrowException($failure); + $service->method('getVectorizationStatistics')->willThrowException($failure); + $request = $this->validationRequest(); + $request->method('getParams')->willReturn([]); $controller = $this->controller(request: $request, service: $service); - foreach (['validate' => 'validate', 'vectorizeBatch' => 'vectorize', 'getObjectVectorizationStats' => 'stats'] as $route => $message) { + foreach (['validate', 'vectorizeBatch', 'getObjectVectorizationStats'] as $route) { try { $controller->$route(); $this->fail($route . ' answered'); - } catch (RuntimeException $failure) { - $this->assertSame($message, $failure->getMessage()); + } catch (\Exception $caught) { + $this->assertSame($failure, $caught, $route); } } } + private function validationRequest(): IRequest&\PHPUnit\Framework\MockObject\MockObject { + $request = $this->createMock(IRequest::class); + $request->method('getParam')->willReturnCallback(static fn (string $key) => $key === 'views' ? null : 1); + return $request; + } + + private function assertGenericFailure(JSONResponse $response): void { + $this->assertSame(500, $response->getStatus()); + $this->assertSame(['success' => false, 'error' => 'Internal server error'], $response->getData()); + $logged = array_column($this->calls, 'error'); + $this->assertSame('[ObjectsController] Vectorization route failed', $logged[0][0] ?? null); + } + private function service(): ObjectOperationsInterface&\PHPUnit\Framework\MockObject\MockObject { return $this->createMock(ObjectOperationsInterface::class); } diff --git a/tests/Unit/Controller/ObjectsControllerCoverageTest.php b/tests/Unit/Controller/ObjectsControllerCoverageTest.php index f3366a3f5141..fa053586b8ff 100644 --- a/tests/Unit/Controller/ObjectsControllerCoverageTest.php +++ b/tests/Unit/Controller/ObjectsControllerCoverageTest.php @@ -1435,7 +1435,8 @@ public function testIndexPathFormStillResolvesRegisterSchemaToNumericId(): void * Exercises lines 1643-1657 (webhook error catch block). * Uses a fresh controller with a custom webhookService mock. */ - public function testCreateContinuesWhenWebhookFails(): void { + #[\PHPUnit\Framework\Attributes\DataProvider('webhookFailures')] + public function testCreateContinuesWhenWebhookFails(\Throwable $webhookException): void { $this->setupAdminUser(); $registerEntity = $this->createMagicMappedRegister(1, 'reg', []); @@ -1447,9 +1448,6 @@ public function testCreateContinuesWhenWebhookFails(): void { $this->objectService->method('getCurrentSchemaEntity')->willReturn($schemaEntity); // Create a fresh webhookService mock with interceptRequest throwing. - // Note: the controller's catch block uses `Exception` which resolves to OCP\DB\Exception - // due to the `use OCP\DB\Exception;` import at the top of ObjectsController. - $webhookException = new \OCP\DB\Exception('Webhook down'); $failingWebhookService = $this->createMock(WebhookService::class); $failingWebhookService->method('interceptRequest') ->willThrowException($webhookException); @@ -1485,11 +1483,25 @@ public function testCreateContinuesWhenWebhookFails(): void { $this->objectService->method('getSchema')->willReturn(2); $this->objectService->method('saveObject')->willReturn($objectEntity); + $this->logger->expects($this->once())->method('error') + ->with(message: '[ObjectsController] Webhook interception failed', context: $this->anything()); + $result = $controller->create('1', '2', $this->objectService); $this->assertSame(201, $result->getStatus()); } + /** + * @return array + */ + public static function webhookFailures(): array { + return [ + 'database' => [new \OCP\DB\Exception('Webhook down')], + 'other exception' => [new \RuntimeException('Webhook down')], + 'error' => [new \TypeError('Webhook down')], + ]; + } + // ========================================================================= // index() magic mapper — OrganisationService error catch (lines 1053-1056) // ========================================================================= diff --git a/tests/Unit/Controller/ObjectsControllerTest.php b/tests/Unit/Controller/ObjectsControllerTest.php index 28f1c5265f1a..904cdb666dec 100644 --- a/tests/Unit/Controller/ObjectsControllerTest.php +++ b/tests/Unit/Controller/ObjectsControllerTest.php @@ -1006,26 +1006,43 @@ public function testLogsReturns404WhenObjectNotFound(): void { $this->assertSame(404, $result->getStatus()); } - public function testLogsThrowsWhenFindFails(): void { + /** + * @return array + */ + public static function logsLookupFailures(): array { + return [ + 'database' => [new DBException('Connection lost'), 1], + 'other' => [new Exception('Not found'), 1], + 'plain miss' => [new \OCP\AppFramework\Db\DoesNotExistException('Gone'), 0], + ]; + } + + #[\PHPUnit\Framework\Attributes\DataProvider('logsLookupFailures')] + public function testLogsAnswers404WhenFindFails(Exception $failure, int $errorLines): void { // The stored history is the administrator's; a reader gets the redacted one (ObjectsControllerLogsRedactionTest). $this->setupAdminUser(); $this->request->method('getParams')->willReturn([]); $this->objectService->method('setSchema')->willReturnSelf(); $this->objectService->method('setRegister')->willReturnSelf(); - $this->objectService->method('getSchema')->willReturn(1); - $this->objectService->method('getRegister')->willReturn(1); - $this->objectService->method('find') - ->willThrowException(new Exception('Not found')); + $this->objectService->method('find')->willThrowException($failure); + $this->logger->expects($this->exactly($errorLines))->method('error'); - // logs() catches Exception from find and returns 404 - try { - $result = $this->controller->logs('uuid-123', 'reg1', 'schema1', $this->objectService); - $this->assertSame(404, $result->getStatus()); - } catch (Exception $e) { - // If exception propagates, that is also valid behavior - $this->assertSame('Not found', $e->getMessage()); - } + $result = $this->controller->logs('uuid-123', 'reg1', 'schema1', $this->objectService); + + $this->assertSame(404, $result->getStatus()); + $this->assertSame(['message' => 'Object not found'], $result->getData()); + } + + public function testLogsLeavesAnExternalSourceFailureToTheMiddleware(): void { + $this->setupAdminUser(); + $failure = new \OCA\OpenRegister\Service\ObjectSource\DbalObjectSourceException('source down', 503); + $this->objectService->method('setSchema')->willReturnSelf(); + $this->objectService->method('setRegister')->willReturnSelf(); + $this->objectService->method('find')->willThrowException($failure); + + $this->expectExceptionObject($failure); + $this->controller->logs('uuid-123', 'reg1', 'schema1', $this->objectService); } // --- import() register-level additional tests --- diff --git a/tests/Unit/Controller/fixtures/objects-bulk-routes-golden.json b/tests/Unit/Controller/fixtures/objects-bulk-routes-golden.json index 6e28c7ae5ad3..d7473b88835a 100644 --- a/tests/Unit/Controller/fixtures/objects-bulk-routes-golden.json +++ b/tests/Unit/Controller/fixtures/objects-bulk-routes-golden.json @@ -47,6 +47,17 @@ "getVectorizationStatistics": [ null ] + }, + { + "error": [ + "[ObjectsController] Vectorization route failed", + { + "error": "no way" + }, + [ + "error" + ] + ] } ], "status": 500, @@ -776,6 +787,17 @@ ], 25 ] + }, + { + "error": [ + "[ObjectsController] Vectorization route failed", + { + "error": "no way" + }, + [ + "error" + ] + ] } ], "status": 500, From 479e0d94cf345ca194af706bcb89a6af4f51f90f Mon Sep 17 00:00:00 2001 From: Ruben van der Linde Date: Fri, 6 Nov 2026 08:16:42 +0100 Subject: [PATCH 2/2] fix(objects): import RuntimeException Assisted-by: ClaudeCode:claude-opus-5-5 --- lib/Controller/ObjectsController.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lib/Controller/ObjectsController.php b/lib/Controller/ObjectsController.php index 5b3227c525be..0f8f1deb4af2 100644 --- a/lib/Controller/ObjectsController.php +++ b/lib/Controller/ObjectsController.php @@ -106,6 +106,7 @@ use Psr\Container\ContainerInterface; use Psr\Container\NotFoundExceptionInterface; use Psr\Log\LoggerInterface; +use RuntimeException; use Symfony\Component\Uid\Uuid; /** @@ -6417,7 +6418,7 @@ public function downloadFiles( unlink($zipInfo['path']); } - throw new \RuntimeException('Failed to read ZIP file content'); + throw new RuntimeException('Failed to read ZIP file content'); } // Clean up temporary file after reading.