1
0
Fork 0
mirror of synced 2024-09-19 19:07:21 +12:00
appwrite/app/workers/deletes.php

732 lines
23 KiB
PHP
Raw Normal View History

<?php
2022-12-21 01:22:58 +13:00
require_once __DIR__ . '/../worker.php';
2022-11-22 03:24:52 +13:00
use Appwrite\Auth\Auth;
use Utopia\App;
use Utopia\Cache\Adapter\Filesystem;
use Utopia\Cache\Cache;
2021-07-14 07:24:52 +12:00
use Utopia\Database\Database;
use Utopia\Database\Document;
2021-07-13 09:57:37 +12:00
use Utopia\Database\Query;
2022-02-04 14:29:40 +13:00
use Executor\Executor;
2021-01-22 21:28:33 +13:00
use Utopia\Storage\Device\Local;
2020-12-19 03:08:28 +13:00
use Utopia\Abuse\Abuse;
use Utopia\Abuse\Adapters\TimeLimit;
use Utopia\CLI\Console;
use Utopia\Audit\Audit;
2022-11-22 03:24:52 +13:00
use Utopia\Database\DateTime;
2022-12-21 01:22:58 +13:00
use Utopia\Database\Validator\Authorization;
use Utopia\Queue\Message;
2022-12-21 01:22:58 +13:00
Authorization::disable();
Authorization::setDefaultStatus(false);
2020-12-19 21:08:03 +13:00
2022-12-21 01:22:58 +13:00
$server->job()
->inject('message')
->action(function (Message $message) {
$payload = $message->getPayload() ?? [];
2022-12-21 01:22:58 +13:00
if (empty($payload)) {
throw new Exception('Missing payload');
}
2022-12-21 01:22:58 +13:00
$project = new Document($payload['project'] ?? []);
$type = $payload['type'] ?? '';
switch (strval($type)) {
2020-12-19 03:05:15 +13:00
case DELETE_TYPE_DOCUMENT:
2022-12-21 01:22:58 +13:00
$document = new Document($payload['document'] ?? []);
2021-06-12 22:07:26 +12:00
switch ($document->getCollection()) {
Database layer (#3338) * database response model * database collection config * new database scopes * database service update * database execption codes * remove read write permission from database model * updating tests and fixing some bugs * server side tests are now passing * databases api * tests for database endpoint * composer update * fix error * formatting * formatting fixes * get database test * more updates to events and usage * more usage updates * fix delete type * fix test * delete database * more fixes * databaseId in attributes and indexes * more fixes * fix issues * fix index subquery * fix console scope and index query * updating tests as required * fix phpcs errors and warnings * updates to review suggestions * UI progress * ui updates and cleaning up * fix type * rework database events * update tests * update types * event generation fixed * events config updated * updating context to support multiple * realtime updates * fix ids * update context * validator updates * fix naming conflict * fix tests * fix lint errors * fix wprler and realtime tests * fix webhooks test * fix event validator and other tests * formatting fixes * removing leftover var_dumps * remove leftover comment * update usage params * usage metrics updates * update database usage * fix usage * specs update * updates to usage * fix UI and usage * fix lints * internal id fixes * fixes for internal Id * renaming services and related files * rename tests * rename doc link * rename readme * fix test name * tests: fixes for 0.15.x sync Co-authored-by: Torsten Dittmann <torsten.dittmann@googlemail.com>
2022-06-22 22:51:49 +12:00
case DELETE_TYPE_DATABASES:
2022-12-21 01:22:58 +13:00
deleteDatabase($document, $project);
Database layer (#3338) * database response model * database collection config * new database scopes * database service update * database execption codes * remove read write permission from database model * updating tests and fixing some bugs * server side tests are now passing * databases api * tests for database endpoint * composer update * fix error * formatting * formatting fixes * get database test * more updates to events and usage * more usage updates * fix delete type * fix test * delete database * more fixes * databaseId in attributes and indexes * more fixes * fix issues * fix index subquery * fix console scope and index query * updating tests as required * fix phpcs errors and warnings * updates to review suggestions * UI progress * ui updates and cleaning up * fix type * rework database events * update tests * update types * event generation fixed * events config updated * updating context to support multiple * realtime updates * fix ids * update context * validator updates * fix naming conflict * fix tests * fix lint errors * fix wprler and realtime tests * fix webhooks test * fix event validator and other tests * formatting fixes * removing leftover var_dumps * remove leftover comment * update usage params * usage metrics updates * update database usage * fix usage * specs update * updates to usage * fix UI and usage * fix lints * internal id fixes * fixes for internal Id * renaming services and related files * rename tests * rename doc link * rename readme * fix test name * tests: fixes for 0.15.x sync Co-authored-by: Torsten Dittmann <torsten.dittmann@googlemail.com>
2022-06-22 22:51:49 +12:00
break;
2021-10-26 13:14:55 +13:00
case DELETE_TYPE_COLLECTIONS:
2022-12-21 01:22:58 +13:00
deleteCollection($document, $project);
break;
2021-10-26 13:14:55 +13:00
case DELETE_TYPE_PROJECTS:
2022-12-21 01:22:58 +13:00
deleteProject($document);
break;
2021-10-26 13:14:55 +13:00
case DELETE_TYPE_FUNCTIONS:
2022-12-21 01:22:58 +13:00
deleteFunction($document, $project);
break;
case DELETE_TYPE_DEPLOYMENTS:
2022-12-21 01:22:58 +13:00
deleteDeployment($document, $project);
break;
2021-10-26 13:14:55 +13:00
case DELETE_TYPE_USERS:
2022-12-21 01:22:58 +13:00
deleteUser($document, $project);
break;
2021-10-26 13:14:55 +13:00
case DELETE_TYPE_TEAMS:
2022-12-21 01:22:58 +13:00
deleteMemberships($document, $project);
break;
2021-11-07 18:54:28 +13:00
case DELETE_TYPE_BUCKETS:
2022-12-21 01:22:58 +13:00
deleteBucket($document, $project);
2021-07-28 22:09:29 +12:00
break;
default:
2021-09-01 21:13:23 +12:00
Console::error('No lazy delete operation available for document of type: ' . $document->getCollection());
break;
}
2020-12-15 10:26:37 +13:00
break;
2020-12-22 07:15:52 +13:00
2020-12-28 06:57:35 +13:00
case DELETE_TYPE_EXECUTIONS:
2022-12-21 01:22:58 +13:00
deleteExecutionLogs($payload['datetime']);
2020-12-22 07:15:52 +13:00
break;
2020-12-19 03:05:15 +13:00
case DELETE_TYPE_AUDIT:
2022-12-21 01:22:58 +13:00
$datetime = $payload['datetime'] ?? null;
2022-07-12 03:12:41 +12:00
if (!empty($datetime)) {
2022-12-21 01:22:58 +13:00
deleteAuditLogs($datetime);
}
2022-12-21 01:22:58 +13:00
$document = new Document($payload['document'] ?? []);
2022-07-12 03:12:41 +12:00
if (!$document->isEmpty()) {
2022-12-21 01:22:58 +13:00
deleteAuditLogsByResource('document/' . $document->getId(), $project);
}
break;
2020-12-19 03:05:15 +13:00
case DELETE_TYPE_ABUSE:
2022-12-21 01:22:58 +13:00
deleteAbuseLogs($payload['datetime']);
break;
2021-02-05 23:57:43 +13:00
case DELETE_TYPE_REALTIME:
2022-12-21 01:22:58 +13:00
deleteRealtimeUsage($payload['datetime']);
break;
case DELETE_TYPE_SESSIONS:
2022-12-21 01:22:58 +13:00
deleteExpiredSessions();
break;
2021-02-05 23:57:43 +13:00
case DELETE_TYPE_CERTIFICATES:
2022-12-21 01:22:58 +13:00
$document = new Document($payload['document']);
deleteCertificates($document);
2021-02-05 23:57:43 +13:00
break;
2021-09-01 21:13:23 +12:00
case DELETE_TYPE_USAGE:
2022-12-21 01:22:58 +13:00
deleteUsageStats($payload['hourlyUsageRetentionDatetime']);
2021-09-06 21:39:36 +12:00
break;
2022-07-03 21:36:59 +12:00
2022-08-15 21:05:41 +12:00
case DELETE_TYPE_CACHE_BY_RESOURCE:
2022-12-21 01:22:58 +13:00
deleteCacheByResource($payload['resource']);
2022-08-15 21:05:41 +12:00
break;
case DELETE_TYPE_CACHE_BY_TIMESTAMP:
2022-12-21 01:22:58 +13:00
deleteCacheByDate($payload);
2022-07-03 21:36:59 +12:00
break;
2022-11-17 01:51:43 +13:00
case DELETE_TYPE_SCHEDULES:
2022-12-21 01:22:58 +13:00
deleteSchedules($payload['datetime']);
2022-11-17 01:51:43 +13:00
break;
2020-12-19 21:08:03 +13:00
default:
2021-09-01 21:13:23 +12:00
Console::error('No delete operation for type: ' . $type);
2020-12-19 21:08:03 +13:00
break;
2021-09-01 21:13:23 +12:00
}
2022-12-21 01:22:58 +13:00
});
2021-09-01 21:13:23 +12:00
2022-11-17 01:51:43 +13:00
/**
* @throws Exception
*/
2022-12-21 01:22:58 +13:00
function deleteSchedules(string $datetime): void
{
listByGroup(
'schedules',
[
Query::equal('region', [App::getEnv('_APP_REGION', 'default')]),
Query::equal('resourceType', ['function']),
Query::lessThanEqual('resourceUpdatedAt', $datetime),
Query::equal('active', [false]),
],
getConsoleDB(),
function (Document $document) {
$project = getConsoleDB()->getDocument('projects', $document->getAttribute('projectId'));
if ($project->isEmpty()) {
Console::warning('Unable to delete schedule for function ' . $document->getAttribute('resourceId'));
return;
}
2022-11-17 01:51:43 +13:00
2022-12-21 01:22:58 +13:00
$function = getProjectDB($project)->getDocument('functions', $document->getAttribute('resourceId'));
2022-11-17 01:51:43 +13:00
2022-12-21 01:22:58 +13:00
if ($function->isEmpty()) {
getConsoleDB()->deleteDocument('schedules', $document->getId());
Console::success('Deleting schedule for function ' . $document->getAttribute('resourceId'));
2022-11-17 01:51:43 +13:00
}
2022-12-21 01:22:58 +13:00
}
);
}
2022-11-17 01:51:43 +13:00
2022-07-03 21:36:59 +12:00
/**
* @param string $resource
2022-07-03 21:36:59 +12:00
*/
2022-12-21 01:22:58 +13:00
function deleteCacheByResource(string $resource): void
{
deleteCacheFiles([
Query::equal('resource', [$resource]),
]);
}
2022-08-15 21:05:41 +12:00
2022-12-21 01:22:58 +13:00
function deleteCacheByDate($payload): void
{
deleteCacheFiles([
Query::lessThan('accessedAt', $payload['datetime']),
]);
}
2022-08-15 21:05:41 +12:00
2022-12-21 01:22:58 +13:00
function deleteCacheFiles($query): void
{
deleteForProjectIds(function (Document $project) use ($query) {
$projectId = $project->getId();
$dbForProject = getProjectDB($project);
$cache = new Cache(
new Filesystem(APP_STORAGE_CACHE . DIRECTORY_SEPARATOR . 'app-' . $projectId)
);
deleteByGroup(
'cache',
$query,
$dbForProject,
function (Document $document) use ($cache, $projectId) {
$path = APP_STORAGE_CACHE . DIRECTORY_SEPARATOR . 'app-' . $projectId . DIRECTORY_SEPARATOR . $document->getId();
if ($cache->purge($document->getId())) {
Console::success('Deleting cache file: ' . $path);
} else {
Console::error('Failed to delete cache file: ' . $path);
2022-07-05 19:37:46 +12:00
}
2022-12-21 01:22:58 +13:00
}
);
});
}
2022-07-03 21:36:59 +12:00
Database layer (#3338) * database response model * database collection config * new database scopes * database service update * database execption codes * remove read write permission from database model * updating tests and fixing some bugs * server side tests are now passing * databases api * tests for database endpoint * composer update * fix error * formatting * formatting fixes * get database test * more updates to events and usage * more usage updates * fix delete type * fix test * delete database * more fixes * databaseId in attributes and indexes * more fixes * fix issues * fix index subquery * fix console scope and index query * updating tests as required * fix phpcs errors and warnings * updates to review suggestions * UI progress * ui updates and cleaning up * fix type * rework database events * update tests * update types * event generation fixed * events config updated * updating context to support multiple * realtime updates * fix ids * update context * validator updates * fix naming conflict * fix tests * fix lint errors * fix wprler and realtime tests * fix webhooks test * fix event validator and other tests * formatting fixes * removing leftover var_dumps * remove leftover comment * update usage params * usage metrics updates * update database usage * fix usage * specs update * updates to usage * fix UI and usage * fix lints * internal id fixes * fixes for internal Id * renaming services and related files * rename tests * rename doc link * rename readme * fix test name * tests: fixes for 0.15.x sync Co-authored-by: Torsten Dittmann <torsten.dittmann@googlemail.com>
2022-06-22 22:51:49 +12:00
/**
* @param Document $document database document
2022-08-13 19:57:04 +12:00
* @param Document $projectId
Database layer (#3338) * database response model * database collection config * new database scopes * database service update * database execption codes * remove read write permission from database model * updating tests and fixing some bugs * server side tests are now passing * databases api * tests for database endpoint * composer update * fix error * formatting * formatting fixes * get database test * more updates to events and usage * more usage updates * fix delete type * fix test * delete database * more fixes * databaseId in attributes and indexes * more fixes * fix issues * fix index subquery * fix console scope and index query * updating tests as required * fix phpcs errors and warnings * updates to review suggestions * UI progress * ui updates and cleaning up * fix type * rework database events * update tests * update types * event generation fixed * events config updated * updating context to support multiple * realtime updates * fix ids * update context * validator updates * fix naming conflict * fix tests * fix lint errors * fix wprler and realtime tests * fix webhooks test * fix event validator and other tests * formatting fixes * removing leftover var_dumps * remove leftover comment * update usage params * usage metrics updates * update database usage * fix usage * specs update * updates to usage * fix UI and usage * fix lints * internal id fixes * fixes for internal Id * renaming services and related files * rename tests * rename doc link * rename readme * fix test name * tests: fixes for 0.15.x sync Co-authored-by: Torsten Dittmann <torsten.dittmann@googlemail.com>
2022-06-22 22:51:49 +12:00
*/
2022-12-21 01:22:58 +13:00
function deleteDatabase(Document $document, Document $project): void
{
$databaseId = $document->getId();
$projectId = $project->getId();
Database layer (#3338) * database response model * database collection config * new database scopes * database service update * database execption codes * remove read write permission from database model * updating tests and fixing some bugs * server side tests are now passing * databases api * tests for database endpoint * composer update * fix error * formatting * formatting fixes * get database test * more updates to events and usage * more usage updates * fix delete type * fix test * delete database * more fixes * databaseId in attributes and indexes * more fixes * fix issues * fix index subquery * fix console scope and index query * updating tests as required * fix phpcs errors and warnings * updates to review suggestions * UI progress * ui updates and cleaning up * fix type * rework database events * update tests * update types * event generation fixed * events config updated * updating context to support multiple * realtime updates * fix ids * update context * validator updates * fix naming conflict * fix tests * fix lint errors * fix wprler and realtime tests * fix webhooks test * fix event validator and other tests * formatting fixes * removing leftover var_dumps * remove leftover comment * update usage params * usage metrics updates * update database usage * fix usage * specs update * updates to usage * fix UI and usage * fix lints * internal id fixes * fixes for internal Id * renaming services and related files * rename tests * rename doc link * rename readme * fix test name * tests: fixes for 0.15.x sync Co-authored-by: Torsten Dittmann <torsten.dittmann@googlemail.com>
2022-06-22 22:51:49 +12:00
2022-12-21 01:22:58 +13:00
$dbForProject = getProjectDB($project);
Database layer (#3338) * database response model * database collection config * new database scopes * database service update * database execption codes * remove read write permission from database model * updating tests and fixing some bugs * server side tests are now passing * databases api * tests for database endpoint * composer update * fix error * formatting * formatting fixes * get database test * more updates to events and usage * more usage updates * fix delete type * fix test * delete database * more fixes * databaseId in attributes and indexes * more fixes * fix issues * fix index subquery * fix console scope and index query * updating tests as required * fix phpcs errors and warnings * updates to review suggestions * UI progress * ui updates and cleaning up * fix type * rework database events * update tests * update types * event generation fixed * events config updated * updating context to support multiple * realtime updates * fix ids * update context * validator updates * fix naming conflict * fix tests * fix lint errors * fix wprler and realtime tests * fix webhooks test * fix event validator and other tests * formatting fixes * removing leftover var_dumps * remove leftover comment * update usage params * usage metrics updates * update database usage * fix usage * specs update * updates to usage * fix UI and usage * fix lints * internal id fixes * fixes for internal Id * renaming services and related files * rename tests * rename doc link * rename readme * fix test name * tests: fixes for 0.15.x sync Co-authored-by: Torsten Dittmann <torsten.dittmann@googlemail.com>
2022-06-22 22:51:49 +12:00
2022-12-21 01:22:58 +13:00
deleteByGroup('database_' . $document->getInternalId(), [], $dbForProject, function ($document) use ($project) {
deleteCollection($document, $project);
});
Database layer (#3338) * database response model * database collection config * new database scopes * database service update * database execption codes * remove read write permission from database model * updating tests and fixing some bugs * server side tests are now passing * databases api * tests for database endpoint * composer update * fix error * formatting * formatting fixes * get database test * more updates to events and usage * more usage updates * fix delete type * fix test * delete database * more fixes * databaseId in attributes and indexes * more fixes * fix issues * fix index subquery * fix console scope and index query * updating tests as required * fix phpcs errors and warnings * updates to review suggestions * UI progress * ui updates and cleaning up * fix type * rework database events * update tests * update types * event generation fixed * events config updated * updating context to support multiple * realtime updates * fix ids * update context * validator updates * fix naming conflict * fix tests * fix lint errors * fix wprler and realtime tests * fix webhooks test * fix event validator and other tests * formatting fixes * removing leftover var_dumps * remove leftover comment * update usage params * usage metrics updates * update database usage * fix usage * specs update * updates to usage * fix UI and usage * fix lints * internal id fixes * fixes for internal Id * renaming services and related files * rename tests * rename doc link * rename readme * fix test name * tests: fixes for 0.15.x sync Co-authored-by: Torsten Dittmann <torsten.dittmann@googlemail.com>
2022-06-22 22:51:49 +12:00
2022-12-21 01:22:58 +13:00
$dbForProject->deleteCollection('database_' . $document->getInternalId());
Database layer (#3338) * database response model * database collection config * new database scopes * database service update * database execption codes * remove read write permission from database model * updating tests and fixing some bugs * server side tests are now passing * databases api * tests for database endpoint * composer update * fix error * formatting * formatting fixes * get database test * more updates to events and usage * more usage updates * fix delete type * fix test * delete database * more fixes * databaseId in attributes and indexes * more fixes * fix issues * fix index subquery * fix console scope and index query * updating tests as required * fix phpcs errors and warnings * updates to review suggestions * UI progress * ui updates and cleaning up * fix type * rework database events * update tests * update types * event generation fixed * events config updated * updating context to support multiple * realtime updates * fix ids * update context * validator updates * fix naming conflict * fix tests * fix lint errors * fix wprler and realtime tests * fix webhooks test * fix event validator and other tests * formatting fixes * removing leftover var_dumps * remove leftover comment * update usage params * usage metrics updates * update database usage * fix usage * specs update * updates to usage * fix UI and usage * fix lints * internal id fixes * fixes for internal Id * renaming services and related files * rename tests * rename doc link * rename readme * fix test name * tests: fixes for 0.15.x sync Co-authored-by: Torsten Dittmann <torsten.dittmann@googlemail.com>
2022-06-22 22:51:49 +12:00
2022-12-21 01:22:58 +13:00
deleteAuditLogsByResource('database/' . $databaseId, $project);
}
Database layer (#3338) * database response model * database collection config * new database scopes * database service update * database execption codes * remove read write permission from database model * updating tests and fixing some bugs * server side tests are now passing * databases api * tests for database endpoint * composer update * fix error * formatting * formatting fixes * get database test * more updates to events and usage * more usage updates * fix delete type * fix test * delete database * more fixes * databaseId in attributes and indexes * more fixes * fix issues * fix index subquery * fix console scope and index query * updating tests as required * fix phpcs errors and warnings * updates to review suggestions * UI progress * ui updates and cleaning up * fix type * rework database events * update tests * update types * event generation fixed * events config updated * updating context to support multiple * realtime updates * fix ids * update context * validator updates * fix naming conflict * fix tests * fix lint errors * fix wprler and realtime tests * fix webhooks test * fix event validator and other tests * formatting fixes * removing leftover var_dumps * remove leftover comment * update usage params * usage metrics updates * update database usage * fix usage * specs update * updates to usage * fix UI and usage * fix lints * internal id fixes * fixes for internal Id * renaming services and related files * rename tests * rename doc link * rename readme * fix test name * tests: fixes for 0.15.x sync Co-authored-by: Torsten Dittmann <torsten.dittmann@googlemail.com>
2022-06-22 22:51:49 +12:00
/**
* @param Document $document teams document
2022-08-13 19:57:04 +12:00
* @param Document $project
*/
2022-12-21 01:22:58 +13:00
function deleteCollection(Document $document, Document $project): void
{
$collectionId = $document->getId();
$databaseId = $document->getAttribute('databaseId');
$databaseInternalId = $document->getAttribute('databaseInternalId');
2021-09-01 21:13:23 +12:00
2022-12-21 01:22:58 +13:00
$dbForProject = getProjectDB($project);
2022-12-21 01:22:58 +13:00
$dbForProject->deleteCollection('database_' . $databaseInternalId . '_collection_' . $document->getInternalId());
2022-12-21 01:22:58 +13:00
deleteByGroup('attributes', [
Query::equal('databaseId', [$databaseId]),
Query::equal('collectionId', [$collectionId])
], $dbForProject);
2022-12-21 01:22:58 +13:00
deleteByGroup('indexes', [
Query::equal('databaseId', [$databaseId]),
Query::equal('collectionId', [$collectionId])
], $dbForProject);
2022-12-21 01:22:58 +13:00
deleteAuditLogsByResource('database/' . $databaseId . '/collection/' . $collectionId, $project);
}
2021-08-27 23:37:52 +12:00
/**
2022-10-28 21:40:04 +13:00
* @param string $hourlyUsageRetentionDatetime
2021-08-27 23:37:52 +12:00
*/
2022-12-21 01:22:58 +13:00
function deleteUsageStats(string $hourlyUsageRetentionDatetime)
{
deleteForProjectIds(function (Document $project) use ($hourlyUsageRetentionDatetime) {
$dbForProject = getProjectDB($project);
// Delete Usage stats
deleteByGroup('stats', [
Query::lessThan('time', $hourlyUsageRetentionDatetime),
Query::equal('period', ['1h']),
], $dbForProject);
});
}
2021-07-14 07:24:52 +12:00
/**
* @param Document $document teams document
2022-08-13 19:57:04 +12:00
* @param Document $project
2021-07-14 07:24:52 +12:00
*/
2022-12-21 01:22:58 +13:00
function deleteMemberships(Document $document, Document $project): void
{
$teamId = $document->getAttribute('teamId', '');
// Delete Memberships
deleteByGroup('memberships', [
Query::equal('teamId', [$teamId])
], getProjectDB($project));
}
2021-07-14 07:24:52 +12:00
/**
* @param Document $document project document
*/
2022-12-21 01:22:58 +13:00
function deleteProject(Document $document): void
{
$projectId = $document->getId();
2022-12-21 01:22:58 +13:00
// Delete all DBs
getProjectDB($document)->delete($projectId);
2021-07-14 06:44:45 +12:00
2022-12-21 01:22:58 +13:00
// Delete all storage directories
$uploads = getFilesDevice($document->getId());
$cache = new Local(APP_STORAGE_CACHE . '/app-' . $document->getId());
2022-12-21 01:22:58 +13:00
$uploads->delete($uploads->getRoot(), true);
$cache->delete($cache->getRoot(), true);
}
2021-07-14 07:24:52 +12:00
/**
* @param Document $document user document
2022-08-13 19:57:04 +12:00
* @param Document $project
2021-07-14 07:24:52 +12:00
*/
2022-12-21 01:22:58 +13:00
function deleteUser(Document $document, Document $project): void
{
$userId = $document->getId();
$dbForProject = getProjectDB($project);
// Delete all sessions of this user from the sessions table and update the sessions field of the user record
deleteByGroup('sessions', [
Query::equal('userId', [$userId])
], $dbForProject);
$dbForProject->deleteCachedDocument('users', $userId);
// Delete Memberships and decrement team membership counts
deleteByGroup('memberships', [
Query::equal('userId', [$userId])
], $dbForProject, function (Document $document) use ($dbForProject) {
if ($document->getAttribute('confirm')) { // Count only confirmed members
$teamId = $document->getAttribute('teamId');
$team = $dbForProject->getDocument('teams', $teamId);
if (!$team->isEmpty()) {
$team = $dbForProject->updateDocument(
'teams',
$teamId,
// Ensure that total >= 0
$team->setAttribute('total', \max($team->getAttribute('total', 0) - 1, 0))
);
}
2022-12-21 01:22:58 +13:00
}
});
2022-04-27 23:06:53 +12:00
2022-12-21 01:22:58 +13:00
// Delete tokens
deleteByGroup('tokens', [
Query::equal('userId', [$userId])
], $dbForProject);
}
2021-07-14 07:24:52 +12:00
/**
2022-07-12 03:12:41 +12:00
* @param string $datetime
2021-07-14 07:24:52 +12:00
*/
2022-12-21 01:22:58 +13:00
function deleteExecutionLogs(string $datetime): void
{
deleteForProjectIds(function (Document $project) use ($datetime) {
$dbForProject = getProjectDB($project);
// Delete Executions
deleteByGroup('executions', [
Query::lessThan('$createdAt', $datetime)
], $dbForProject);
});
}
2020-12-15 10:26:37 +13:00
2022-12-21 01:22:58 +13:00
function deleteExpiredSessions(): void
{
$consoleDB = getConsoleDB();
2022-12-14 21:44:40 +13:00
2022-12-21 01:22:58 +13:00
deleteForProjectIds(function (Document $project) use ($consoleDB) {
$dbForProject = getProjectDB($project);
2022-12-14 21:44:40 +13:00
2022-12-21 01:22:58 +13:00
$project = $consoleDB->getDocument('projects', $project->getId());
$duration = $project->getAttribute('auths', [])['duration'] ?? Auth::TOKEN_EXPIRATION_LOGIN_LONG;
$expired = DateTime::addSeconds(new \DateTime(), -1 * $duration);
2022-12-14 21:44:40 +13:00
2022-12-21 01:22:58 +13:00
// Delete Sessions
deleteByGroup('sessions', [
Query::lessThan('$createdAt', $expired)
], $dbForProject);
});
}
/**
2022-07-12 03:12:41 +12:00
* @param string $datetime
*/
2022-12-21 01:22:58 +13:00
function deleteRealtimeUsage(string $datetime): void
{
deleteForProjectIds(function (Document $project) use ($datetime) {
$dbForProject = getProjectDB($project);
// Delete Dead Realtime Logs
deleteByGroup('realtime', [
Query::lessThan('timestamp', $datetime)
], $dbForProject);
});
}
2021-07-14 07:24:52 +12:00
/**
2022-07-12 03:12:41 +12:00
* @param string $datetime
* @throws Exception
2021-07-14 07:24:52 +12:00
*/
2022-12-21 01:22:58 +13:00
function deleteAbuseLogs(string $datetime): void
{
if (empty($datetime)) {
throw new Exception('Failed to delete audit logs. No datetime provided');
}
2022-12-21 01:22:58 +13:00
deleteForProjectIds(function (Document $project) use ($datetime) {
$projectId = $project->getId();
$dbForProject = getProjectDB($project);
$timeLimit = new TimeLimit("", 0, 1, $dbForProject);
$abuse = new Abuse($timeLimit);
$status = $abuse->cleanup($datetime);
if (!$status) {
throw new Exception('Failed to delete Abuse logs for project ' . $projectId);
}
});
}
2021-07-14 07:24:52 +12:00
/**
2022-07-12 03:12:41 +12:00
* @param string $datetime
* @throws Exception
2021-07-14 07:24:52 +12:00
*/
2022-12-21 01:22:58 +13:00
function deleteAuditLogs(string $datetime): void
{
if (empty($datetime)) {
throw new Exception('Failed to delete audit logs. No datetime provided');
}
2022-12-21 01:22:58 +13:00
deleteForProjectIds(function (Document $project) use ($datetime) {
$projectId = $project->getId();
$dbForProject = getProjectDB($project);
$audit = new Audit($dbForProject);
$status = $audit->cleanup($datetime);
if (!$status) {
throw new Exception('Failed to delete Audit logs for project' . $projectId);
}
});
}
/**
2022-07-12 03:12:41 +12:00
* @param string $resource
2022-08-13 19:57:04 +12:00
* @param Document $project
*/
2022-12-21 01:22:58 +13:00
function deleteAuditLogsByResource(string $resource, Document $project): void
{
$dbForProject = getProjectDB($project);
2022-12-21 01:22:58 +13:00
deleteByGroup(Audit::COLLECTION, [
Query::equal('resource', [$resource])
], $dbForProject);
}
2021-07-14 07:24:52 +12:00
/**
* @param Document $document function document
2022-08-13 19:57:04 +12:00
* @param Document $project
2021-07-14 07:24:52 +12:00
*/
2022-12-21 01:22:58 +13:00
function deleteFunction(Document $document, Document $project): void
{
$projectId = $project->getId();
$dbForProject = getProjectDB($project);
$functionId = $document->getId();
2022-12-21 01:22:58 +13:00
/**
* Delete Variables
*/
Console::info("Deleting variables for function " . $functionId);
deleteByGroup('variables', [
Query::equal('functionId', [$functionId])
], $dbForProject);
/**
2022-12-21 01:22:58 +13:00
* Delete Deployments
*/
2022-12-21 01:22:58 +13:00
Console::info("Deleting deployments for function " . $functionId);
$storageFunctions = getFunctionsDevice($projectId);
$deploymentIds = [];
deleteByGroup('deployments', [
Query::equal('resourceId', [$functionId])
], $dbForProject, function (Document $document) use ($storageFunctions, &$deploymentIds) {
$deploymentIds[] = $document->getId();
if ($storageFunctions->delete($document->getAttribute('path', ''), true)) {
2022-02-01 12:44:55 +13:00
Console::success('Deleted deployment files: ' . $document->getAttribute('path', ''));
} else {
Console::error('Failed to delete deployment files: ' . $document->getAttribute('path', ''));
}
2022-12-21 01:22:58 +13:00
});
2022-12-21 01:22:58 +13:00
/**
* Delete builds
*/
Console::info("Deleting builds for function " . $functionId);
$storageBuilds = getBuildsDevice($projectId);
foreach ($deploymentIds as $deploymentId) {
deleteByGroup('builds', [
2022-08-12 11:53:52 +12:00
Query::equal('deploymentId', [$deploymentId])
2022-12-21 01:22:58 +13:00
], $dbForProject, function (Document $document) use ($storageBuilds, $deploymentId) {
2022-12-18 20:35:16 +13:00
if ($storageBuilds->delete($document->getAttribute('path', ''), true)) {
Console::success('Deleted build files: ' . $document->getAttribute('path', ''));
2021-09-01 21:13:23 +12:00
} else {
2022-12-18 20:35:16 +13:00
Console::error('Failed to delete build files: ' . $document->getAttribute('path', ''));
}
});
2022-12-21 01:22:58 +13:00
}
/**
* Delete Executions
*/
Console::info("Deleting executions for function " . $functionId);
deleteByGroup('executions', [
Query::equal('functionId', [$functionId])
], $dbForProject);
// TODO: Request executor to delete runtime
}
/**
* @param Document $document deployment document
* @param Document $project
*/
function deleteDeployment(Document $document, Document $project): void
{
$projectId = $project->getId();
$dbForProject = getProjectDB($project);
$deploymentId = $document->getId();
$functionId = $document->getAttribute('resourceId');
2022-12-21 01:22:58 +13:00
/**
* Delete deployment files
*/
Console::info("Deleting deployment files for deployment " . $deploymentId);
$storageFunctions = getFunctionsDevice($projectId);
if ($storageFunctions->delete($document->getAttribute('path', ''), true)) {
Console::success('Deleted deployment files: ' . $document->getAttribute('path', ''));
} else {
Console::error('Failed to delete deployment files: ' . $document->getAttribute('path', ''));
}
2022-12-21 01:22:58 +13:00
/**
* Delete builds
*/
Console::info("Deleting builds for deployment " . $deploymentId);
$storageBuilds = getBuildsDevice($projectId);
deleteByGroup('builds', [
Query::equal('deploymentId', [$deploymentId])
], $dbForProject, function (Document $document) use ($storageBuilds) {
if ($storageBuilds->delete($document->getAttribute('path', ''), true)) {
Console::success('Deleted build files: ' . $document->getAttribute('path', ''));
2022-12-21 01:22:58 +13:00
} else {
Console::error('Failed to delete build files: ' . $document->getAttribute('path', ''));
2022-12-21 01:22:58 +13:00
}
});
// TODO: Request executor to delete runtime
}
2021-07-14 07:24:52 +12:00
/**
* @param Document $document to be deleted
* @param Database $database to delete it from
* @param callable $callback to perform after document is deleted
*
* @return bool
*/
2022-12-21 01:22:58 +13:00
function deleteById(Document $document, Database $database, callable $callback = null): bool
{
if ($database->deleteDocument($document->getCollection(), $document->getId())) {
Console::success('Deleted document "' . $document->getId() . '" successfully');
2022-12-21 01:22:58 +13:00
if (is_callable($callback)) {
$callback($document);
}
2022-12-21 01:22:58 +13:00
return true;
} else {
Console::error('Failed to delete document: ' . $document->getId());
return false;
}
2022-12-21 01:22:58 +13:00
}
2021-07-14 07:24:52 +12:00
/**
* @param callable $callback
*/
2022-12-21 01:22:58 +13:00
function deleteForProjectIds(callable $callback): void
{
// TODO: @Meldiron name of this method no longer matches. It does not delete, and it gives whole document
$count = 0;
$chunk = 0;
$limit = 50;
$projects = [];
$sum = $limit;
2020-12-22 07:15:52 +13:00
2022-12-21 01:22:58 +13:00
$executionStart = \microtime(true);
2021-09-01 21:13:23 +12:00
2022-12-21 01:22:58 +13:00
while ($sum === $limit) {
$projects = getConsoleDB()->find('projects', [Query::limit($limit), Query::offset($chunk * $limit)]);
2022-12-21 01:22:58 +13:00
$chunk++;
2021-08-27 16:37:15 +12:00
2022-12-21 01:22:58 +13:00
/** @var string[] $projectIds */
$sum = count($projects);
2022-12-21 01:22:58 +13:00
Console::info('Executing delete function for chunk #' . $chunk . '. Found ' . $sum . ' projects');
foreach ($projects as $project) {
$callback($project);
$count++;
}
2020-12-22 07:15:52 +13:00
}
2022-12-21 01:22:58 +13:00
$executionEnd = \microtime(true);
Console::info("Found {$count} projects " . ($executionEnd - $executionStart) . " seconds");
}
2021-07-13 09:57:37 +12:00
/**
* @param string $collection collectionID
* @param Query[] $queries
2021-07-14 07:24:52 +12:00
* @param Database $database
2021-07-13 09:57:37 +12:00
* @param callable $callback
*/
2022-12-21 01:22:58 +13:00
function deleteByGroup(string $collection, array $queries, Database $database, callable $callback = null): void
{
$count = 0;
$chunk = 0;
$limit = 50;
$results = [];
$sum = $limit;
2022-12-21 01:22:58 +13:00
$executionStart = \microtime(true);
2021-09-01 21:13:23 +12:00
2022-12-21 01:22:58 +13:00
while ($sum === $limit) {
$chunk++;
2022-12-21 01:22:58 +13:00
$results = $database->find($collection, \array_merge([Query::limit($limit)], $queries));
2022-01-29 13:52:06 +13:00
2022-12-21 01:22:58 +13:00
$sum = count($results);
2022-12-21 01:22:58 +13:00
Console::info('Deleting chunk #' . $chunk . '. Found ' . $sum . ' documents');
2022-12-21 01:22:58 +13:00
foreach ($results as $document) {
deleteById($document, $database, $callback);
$count++;
}
2022-12-21 01:22:58 +13:00
}
2022-12-21 01:22:58 +13:00
$executionEnd = \microtime(true);
2022-12-21 01:22:58 +13:00
Console::info("Deleted {$count} document by group in " . ($executionEnd - $executionStart) . " seconds");
}
2022-12-14 21:44:40 +13:00
/**
* @param string $collection collectionID
* @param Query[] $queries
* @param Database $database
* @param callable $callback
*/
2022-12-21 01:22:58 +13:00
function listByGroup(string $collection, array $queries, Database $database, callable $callback = null): void
{
$count = 0;
$chunk = 0;
$limit = 50;
$results = [];
$sum = $limit;
2022-12-14 21:44:40 +13:00
2022-12-21 01:22:58 +13:00
$executionStart = \microtime(true);
2022-12-14 21:44:40 +13:00
2022-12-21 01:22:58 +13:00
while ($sum === $limit) {
$chunk++;
2022-12-14 21:44:40 +13:00
2022-12-21 01:22:58 +13:00
$results = $database->find($collection, \array_merge([Query::limit($limit)], $queries));
2022-12-14 21:44:40 +13:00
2022-12-21 01:22:58 +13:00
$sum = count($results);
2022-12-14 21:44:40 +13:00
2022-12-21 01:22:58 +13:00
foreach ($results as $document) {
if (is_callable($callback)) {
$callback($document);
2022-12-14 21:44:40 +13:00
}
2022-12-21 01:22:58 +13:00
$count++;
2022-12-14 21:44:40 +13:00
}
2022-12-21 01:22:58 +13:00
}
2022-12-14 21:44:40 +13:00
2022-12-21 01:22:58 +13:00
$executionEnd = \microtime(true);
2022-12-14 21:44:40 +13:00
2022-12-21 01:22:58 +13:00
Console::info("Listed {$count} document by group in " . ($executionEnd - $executionStart) . " seconds");
}
2022-12-14 21:44:40 +13:00
2021-07-14 07:24:52 +12:00
/**
2022-05-24 02:54:50 +12:00
* @param Document $document certificates document
2021-07-14 07:24:52 +12:00
*/
2022-12-21 01:22:58 +13:00
function deleteCertificates(Document $document): void
{
$consoleDB = getConsoleDB();
2022-12-21 01:22:58 +13:00
// If domain has certificate generated
if (isset($document['certificateId'])) {
$domainUsingCertificate = $consoleDB->findOne('domains', [
Query::equal('certificateId', [$document['certificateId']])
]);
2022-12-21 01:22:58 +13:00
if (!$domainUsingCertificate) {
$mainDomain = App::getEnv('_APP_DOMAIN_TARGET', '');
if ($mainDomain === $document->getAttribute('domain')) {
$domainUsingCertificate = $mainDomain;
}
}
2022-12-21 01:22:58 +13:00
// If certificate is still used by some domain, mark we can't delete.
// Current domain should not be found, because we only have copy. Original domain is already deleted from database.
if ($domainUsingCertificate) {
Console::warning("Skipping certificate deletion, because a domain is still using it.");
return;
}
}
2021-02-05 22:05:26 +13:00
2022-12-21 01:22:58 +13:00
$domain = $document->getAttribute('domain');
$directory = APP_STORAGE_CERTIFICATES . '/' . $domain;
$checkTraversal = realpath($directory) === $directory;
2022-12-21 01:22:58 +13:00
if ($domain && $checkTraversal && is_dir($directory)) {
// Delete certificate document, so Appwrite is aware of change
if (isset($document['certificateId'])) {
$consoleDB->deleteDocument('certificates', $document['certificateId']);
2021-02-05 22:05:26 +13:00
}
2022-12-21 01:22:58 +13:00
// Delete files, so Traefik is aware of change
array_map('unlink', glob($directory . '/*.*'));
rmdir($directory);
Console::info("Deleted certificate files for {$domain}");
} else {
Console::info("No certificate files found for {$domain}");
2021-02-05 22:05:26 +13:00
}
2022-12-21 01:22:58 +13:00
}
2021-07-18 19:03:48 +12:00
2022-12-21 01:22:58 +13:00
function deleteBucket(Document $document, Document $project)
{
$projectId = $project->getId();
$dbForProject = getProjectDB($project);
$dbForProject->deleteCollection('bucket_' . $document->getInternalId());
2021-07-28 22:14:47 +12:00
2022-12-21 01:22:58 +13:00
$device = getFilesDevice($projectId);
2022-05-24 02:54:50 +12:00
2022-12-21 01:22:58 +13:00
$device->deletePath($document->getId());
2021-09-01 21:13:23 +12:00
}
2022-12-21 01:22:58 +13:00
$server->workerStart();
$server->start();