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
76 changes: 68 additions & 8 deletions lib/Controller/RegistersController.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
use OCA\OpenRegister\Service\ImportService;
use OCA\OpenRegister\Service\Configuration\GitHubHandler;
use OCA\OpenRegister\Service\OasService;
use OCA\OpenRegister\Service\Registers\RegisterCacheHandler;
use OCP\App\IAppManager;
use OCP\AppFramework\Controller;
use OCP\AppFramework\Db\DoesNotExistException;
Expand Down Expand Up @@ -171,6 +172,7 @@ class RegistersController extends Controller
* @param OasService $oasService OAS service for OpenAPI generation
* @param ContainerInterface $container Container for lazy loading services
* @param IGroupManager $groupManager Group manager for RBAC checks
* @param RegisterCacheHandler $registerCacheHandler Register cache handler (runtime-schema-api)
*
* @return void
*
Expand All @@ -194,7 +196,8 @@ public function __construct(
IAppManager $appManager,
OasService $oasService,
private readonly ContainerInterface $container,
private readonly IGroupManager $groupManager
private readonly IGroupManager $groupManager,
private readonly RegisterCacheHandler $registerCacheHandler
) {
$this->logger->debug(
message: '[RegistersController] Constructor started.',
Expand Down Expand Up @@ -445,7 +448,14 @@ public function create(): JSONResponse

try {
// Create a new register from the data.
return new JSONResponse(data: $this->registerService->createFromArray($data), statusCode: 201);
$register = $this->registerService->createFromArray($data);

// **CACHE INVALIDATION (runtime-schema-api)**: Drop the request-scoped
// find cache for the freshly-created ID so any follow-up read in the
// same PHP worker observes the new register.
$this->registerCacheHandler->invalidate(registerId: $register->getId());

return new JSONResponse(data: $register, statusCode: 201);
} catch (DBException $e) {
// Handle database constraint violations with user-friendly messages.
$constraintException = DatabaseConstraintException::fromDatabaseException(
Expand Down Expand Up @@ -533,25 +543,31 @@ public function update(int $id): JSONResponse
// Update the register with the provided data.
$updatedRegister = $this->registerService->updateFromArray(id: $id, data: $data);

// **CACHE INVALIDATION (runtime-schema-api)**: Drop the request-scoped
// find cache for the updated ID so any follow-up read in the same PHP
// worker observes the new register state (e.g. an added schema in schemas[]).
$this->registerCacheHandler->invalidate(registerId: $updatedRegister->getId());

// Log authorization and role changes.
try {
$auditService = $this->container->get(AuthorizationAuditService::class);

if (isset($data['authorization']) === true) {
$auditService->logRegisterAuthorizationChange(
$id,
$updatedRegister['title'] ?? '',
$updatedRegister->getTitle() ?? '',
$oldRegisterAuth,
$updatedRegister['authorization'] ?? null
$updatedRegister->getAuthorization()
);
}

if (isset($data['configuration']['roles']) === true) {
$configuration = $updatedRegister->getConfiguration();
$auditService->logRoleDefinitionChange(
$id,
$updatedRegister['title'] ?? '',
$updatedRegister->getTitle() ?? '',
$oldRegisterRoles,
$updatedRegister['configuration']['roles'] ?? null
$configuration['roles'] ?? null
);
}
} catch (\Throwable $e) {
Expand Down Expand Up @@ -624,11 +640,55 @@ public function patch(int $id): JSONResponse
*/
public function destroy(int $id): JSONResponse
{
// **DELETE SAFETY (runtime-schema-api)**: Count attached objects across
// every schema attached to this register. If N > 0 and ?force=true is
// not set, refuse with HTTP 409 so the caller sees a structured error
// containing the orphan count.
$forceParam = $this->request->getParam(key: 'force', default: null);
$force = (string) $forceParam === 'true' || $forceParam === true || $forceParam === '1';

try {
// Find the register by ID and delete it.
// Find the register first (validates existence + access).
$register = $this->registerService->find($id);

// Count objects still referencing this register across all schemas.
// Use getStatistics() (single-axis registerId path) — countSearchObjects()
// only returns a real count when BOTH register AND schema are present
// in the @self filter, and silently returns 0 on single-axis queries,
// which would let DELETE silently succeed on registers with objects.
$objectStats = $this->objectEntityMapper->getStatistics(registerId: $register->getId(), schemaId: null);
$objectCount = (int) $objectStats['total'];

if ($objectCount > 0 && $force === false) {
return new JSONResponse(
data: [
'error' => 'register-has-objects',
'objectCount' => $objectCount,
],
statusCode: 409
);
}

if ($objectCount > 0 && $force === true) {
// Force-delete with audit at WARNING level so operators can review.
$this->logger->warning(
message: '[RegistersController] Force-deleting register with attached objects',
context: [
'file' => __FILE__,
'line' => __LINE__,
'registerId' => $register->getId(),
'registerSlug' => $register->getSlug(),
'objectCount' => $objectCount,
]
);
}

$this->registerService->delete($register);

// **CACHE INVALIDATION (runtime-schema-api)**: Drop request-scoped
// find cache for the deleted register.
$this->registerCacheHandler->invalidate(registerId: $register->getId());

// Return an empty response.
return new JSONResponse(data: []);
} catch (DoesNotExistException $e) {
Expand All @@ -640,7 +700,7 @@ public function destroy(int $id): JSONResponse
} catch (Exception $e) {
// Return 500 for other errors.
return new JSONResponse(data: ['error' => $e->getMessage()], statusCode: 500);
}
}//end try
}//end destroy()

/**
Expand Down
68 changes: 60 additions & 8 deletions lib/Controller/SchemasController.php
Original file line number Diff line number Diff line change
Expand Up @@ -381,6 +381,12 @@ public function create(): JSONResponse
}
*/

// **CACHE INVALIDATION (runtime-schema-api)**: Drop in-memory + persistent
// schema cache for the freshly-created ID so any follow-up read in the same
// PHP worker observes the new schema. This is the create-side counterpart
// of the invalidations already wired into update() and destroy().
$this->schemaCacheService->invalidate(schemaId: $schema->getId());

return new JSONResponse(data: $schema, statusCode: 201);
} catch (DBException $e) {
// Handle database constraint violations with user-friendly messages.
Expand Down Expand Up @@ -514,8 +520,12 @@ public function update(int $id): JSONResponse
}
}

// **CACHE INVALIDATION**: Clear all schema-related caches when schema is updated.
$this->schemaCacheService->invalidateForSchemaChange(schemaId: $updatedSchema->getId(), operation: 'update');
// **CACHE INVALIDATION (runtime-schema-api)**: Clear all schema-related
// caches when a schema is updated. `invalidate()` is the runtime-schema-api
// entry point — it covers the legacy `invalidateForSchemaChange` cleanup AND
// drops the request-scoped find cache on the mapper itself so reads in the
// same worker observe the new state.
$this->schemaCacheService->invalidate(schemaId: $updatedSchema->getId());
$this->facetCacheSvc->invalidateForSchemaChange(
schemaId: $updatedSchema->getId(),
operation: 'update'
Expand Down Expand Up @@ -616,16 +626,58 @@ public function patch(int $id): JSONResponse
*/
public function destroy(int $id): JSONResponse
{
// **DELETE SAFETY (runtime-schema-api)**: Count attached objects FIRST.
// If N > 0 and ?force=true is not set, refuse with HTTP 409 so the caller
// gets a structured error containing the orphan count and can decide
// whether to escalate. A bare DELETE on a schema with objects is the
// canonical foot-gun that this guard closes.
$forceParam = $this->request->getParam(key: 'force', default: null);
$force = (string) $forceParam === 'true' || $forceParam === true || $forceParam === '1';

try {
// Find the schema by ID, delete it, and invalidate caches.
// Find the schema first (also validates existence and access).
$schemaToDelete = $this->schemaMapper->find(id: $id);

// Count objects still referencing this schema across all registers.
// Use getStatistics() (single-axis schemaId path) — countSearchObjects()
// only returns a real count when BOTH register AND schema are present
// in the @self filter, and silently returns 0 on single-axis queries,
// which would let DELETE silently succeed on schemas with objects.
$objectStats = $this->objectEntityMapper->getStatistics(registerId: null, schemaId: $schemaToDelete->getId());
$objectCount = (int) $objectStats['total'];

if ($objectCount > 0 && $force === false) {
// Refuse: structured 409 with the orphan count for the caller.
return new JSONResponse(
data: [
'error' => 'schema-has-objects',
'objectCount' => $objectCount,
],
statusCode: 409
);
}

if ($objectCount > 0 && $force === true) {
// Force-delete with audit trail at WARNING level: a misused force flag
// orphans every object referencing this schema, so log who did it.
$this->logger->warning(
message: '[SchemasController] Force-deleting schema with attached objects',
context: [
'file' => __FILE__,
'line' => __LINE__,
'schemaId' => $schemaToDelete->getId(),
'schemaSlug' => $schemaToDelete->getSlug(),
'objectCount' => $objectCount,
]
);
}

$this->schemaMapper->delete($schemaToDelete);

// **CACHE INVALIDATION**: Clear all schema-related caches when schema is deleted.
$this->schemaCacheService->invalidateForSchemaChange(
schemaId: $schemaToDelete->getId(),
operation: 'delete'
);
// **CACHE INVALIDATION (runtime-schema-api)**: invalidate() is the
// canonical entry point — covers in-memory, persistent cache table,
// AND the request-scoped find cache on the mapper.
$this->schemaCacheService->invalidate(schemaId: $schemaToDelete->getId());
$this->facetCacheSvc->invalidateForSchemaChange(
schemaId: $schemaToDelete->getId(),
operation: 'delete'
Expand Down
24 changes: 24 additions & 0 deletions lib/Db/RegisterMapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -343,6 +343,30 @@ public function find(
}//end try
}//end find()

/**
* Clear the request-scoped find cache for a specific register
*
* Used by the runtime-schema-api CRUD path to drop the in-memory
* cache entry after a mutation, so the next find() call re-reads
* from the database. Clears every cache key that referenced the
* given register (by id, uuid, slug) across both RBAC/multi-tenancy
* flag combinations.
*
* @param int $registerId The register ID to drop from the find cache.
*
* @return void
*/
public function clearFindCache(int $registerId): void
{
// Find every cache key whose value points at this register ID and unset.
foreach (array_keys($this->findCache) as $key) {
$cached = $this->findCache[$key];
if ($cached instanceof Register && $cached->getId() === $registerId) {
unset($this->findCache[$key]);
}
}
}//end clearFindCache()

/**
* Finds multiple registers by id
*
Expand Down
24 changes: 24 additions & 0 deletions lib/Db/SchemaMapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -317,6 +317,30 @@ public function find(
return $schema;
}//end find()

/**
* Clear the request-scoped find cache for a specific schema
*
* Used by the runtime-schema-api CRUD path to drop the in-memory
* cache entry after a mutation, so the next find() call re-reads
* from the database. Clears every cache key that referenced the
* given schema (by id, uuid, slug) across both RBAC/multi-tenancy
* flag combinations.
*
* @param int $schemaId The schema ID to drop from the find cache.
*
* @return void
*/
public function clearFindCache(int $schemaId): void
{
// Find every cache key whose value points at this schema ID and unset.
foreach (array_keys($this->findCache) as $key) {
$cached = $this->findCache[$key];
if ($cached instanceof Schema && $cached->getId() === $schemaId) {
unset($this->findCache[$key]);
}
}
}//end clearFindCache()

/**
* Finds multiple schemas by id
*
Expand Down
Loading
Loading