Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
92 changes: 79 additions & 13 deletions lib/Controller/ObjectsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand All @@ -105,6 +106,7 @@
use Psr\Container\ContainerInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Log\LoggerInterface;
use RuntimeException;
use Symfony\Component\Uid\Uuid;

/**
Expand Down Expand Up @@ -3484,7 +3486,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(
Expand Down Expand Up @@ -4472,7 +4474,7 @@ public function postPatch(
*
* @return JSONResponse JSON response with success or error.
*
* @throws Exception
* @throws \Exception
*
* @NoAdminRequired
* @NoCSRFRequired
Expand Down Expand Up @@ -4932,8 +4934,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.
Expand Down Expand Up @@ -6461,7 +6463,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.
Expand Down Expand Up @@ -6536,8 +6538,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()

Expand Down Expand Up @@ -6568,8 +6570,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()

Expand Down Expand Up @@ -6599,7 +6601,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()
Expand Down Expand Up @@ -6674,13 +6676,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: [
Expand All @@ -6697,6 +6702,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.
*
Expand Down
91 changes: 82 additions & 9 deletions tests/Unit/Controller/ObjectsControllerBulkRoutesGoldenTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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
Expand Down Expand Up @@ -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<string, array{0: \Throwable}>
*/
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<string, array{0: \Exception}>
*/
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);
}
Expand Down
20 changes: 16 additions & 4 deletions tests/Unit/Controller/ObjectsControllerCoverageTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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', []);
Expand All @@ -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);
Expand Down Expand Up @@ -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<string, array{0: \Throwable}>
*/
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)
// =========================================================================
Expand Down
Loading
Loading