Skip to content
Open
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
8 changes: 8 additions & 0 deletions config/config.sample.php
Original file line number Diff line number Diff line change
Expand Up @@ -2775,4 +2775,12 @@
* Defaults to ``true``
*/
'enable_lazy_objects' => true,

/**
* Delete previews older than a certain number of days to reduce storage usage.
* Less than one day is not allowed, so set it to 0 to disable the deletion.
*
* Defaults to ``0``.
*/
'preview_expiration_days' => 0,
];
38 changes: 38 additions & 0 deletions core/BackgroundJobs/ExpirePreviewsJob.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?php

declare(strict_types=1);

/*
* SPDX-FileCopyrightText: 2025 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

namespace OC\Core\BackgroundJobs;

use OC\Preview\PreviewService;
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\BackgroundJob\IJob;
use OCP\BackgroundJob\TimedJob;
use OCP\IConfig;

class ExpirePreviewsJob extends TimedJob {
public function __construct(
ITimeFactory $time,
private readonly IConfig $config,
private readonly PreviewService $service,
) {
parent::__construct($time);

$this->setTimeSensitivity(IJob::TIME_INSENSITIVE);
$this->setInterval(60 * 60 * 24);
}

protected function run($argument): void {
$days = $this->config->getSystemValueInt('preview_expiration_days');
if ($days <= 0) {
return;
}

$this->service->deleteExpiredPreviews($days);
}
}
1 change: 1 addition & 0 deletions lib/composer/composer/autoload_classmap.php
Original file line number Diff line number Diff line change
Expand Up @@ -1248,6 +1248,7 @@
'OC\\Core\\BackgroundJobs\\BackgroundCleanupUpdaterBackupsJob' => $baseDir . '/core/BackgroundJobs/BackgroundCleanupUpdaterBackupsJob.php',
'OC\\Core\\BackgroundJobs\\CheckForUserCertificates' => $baseDir . '/core/BackgroundJobs/CheckForUserCertificates.php',
'OC\\Core\\BackgroundJobs\\CleanupLoginFlowV2' => $baseDir . '/core/BackgroundJobs/CleanupLoginFlowV2.php',
'OC\\Core\\BackgroundJobs\\ExpirePreviewsJob' => $baseDir . '/core/BackgroundJobs/ExpirePreviewsJob.php',
'OC\\Core\\BackgroundJobs\\GenerateMetadataJob' => $baseDir . '/core/BackgroundJobs/GenerateMetadataJob.php',
'OC\\Core\\BackgroundJobs\\LookupServerSendCheckBackgroundJob' => $baseDir . '/core/BackgroundJobs/LookupServerSendCheckBackgroundJob.php',
'OC\\Core\\BackgroundJobs\\MovePreviewJob' => $baseDir . '/core/BackgroundJobs/MovePreviewJob.php',
Expand Down
1 change: 1 addition & 0 deletions lib/composer/composer/autoload_static.php
Original file line number Diff line number Diff line change
Expand Up @@ -1289,6 +1289,7 @@ class ComposerStaticInit749170dad3f5e7f9ca158f5a9f04f6a2
'OC\\Core\\BackgroundJobs\\BackgroundCleanupUpdaterBackupsJob' => __DIR__ . '/../../..' . '/core/BackgroundJobs/BackgroundCleanupUpdaterBackupsJob.php',
'OC\\Core\\BackgroundJobs\\CheckForUserCertificates' => __DIR__ . '/../../..' . '/core/BackgroundJobs/CheckForUserCertificates.php',
'OC\\Core\\BackgroundJobs\\CleanupLoginFlowV2' => __DIR__ . '/../../..' . '/core/BackgroundJobs/CleanupLoginFlowV2.php',
'OC\\Core\\BackgroundJobs\\ExpirePreviewsJob' => __DIR__ . '/../../..' . '/core/BackgroundJobs/ExpirePreviewsJob.php',
'OC\\Core\\BackgroundJobs\\GenerateMetadataJob' => __DIR__ . '/../../..' . '/core/BackgroundJobs/GenerateMetadataJob.php',
'OC\\Core\\BackgroundJobs\\LookupServerSendCheckBackgroundJob' => __DIR__ . '/../../..' . '/core/BackgroundJobs/LookupServerSendCheckBackgroundJob.php',
'OC\\Core\\BackgroundJobs\\MovePreviewJob' => __DIR__ . '/../../..' . '/core/BackgroundJobs/MovePreviewJob.php',
Expand Down
15 changes: 9 additions & 6 deletions lib/private/Preview/Db/PreviewMapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@

namespace OC\Preview\Db;

use DateInterval;
use DateTimeImmutable;
use OCP\AppFramework\Db\Entity;
use OCP\AppFramework\Db\QBMapper;
use OCP\DB\Exception;
Expand All @@ -25,6 +27,7 @@ class PreviewMapper extends QBMapper {
private const TABLE_NAME = 'previews';
private const LOCATION_TABLE_NAME = 'preview_locations';
private const VERSION_TABLE_NAME = 'preview_versions';
public const MAX_CHUNK_SIZE = 1000;

public function __construct(
IDBConnection $db,
Expand Down Expand Up @@ -168,19 +171,19 @@ public function getLocationId(string $bucket, string $objectStore): int {
}
}

public function deleteAll(): void {
$delete = $this->db->getQueryBuilder();
$delete->delete($this->getTableName());
}

/**
* @return \Generator<Preview>
*/
public function getPreviews(int $lastId, int $limit = 1000): \Generator {
public function getPreviews(int $lastId, int $limit = self::MAX_CHUNK_SIZE, ?int $maxAgeDays = null): \Generator {
$qb = $this->db->getQueryBuilder();
$this->joinLocation($qb)
->where($qb->expr()->gt('p.id', $qb->createNamedParameter($lastId, IQueryBuilder::PARAM_INT)))
->setMaxResults($limit);

if ($maxAgeDays !== null) {
$qb->andWhere($qb->expr()->lt('mtime', $qb->createNamedParameter((new DateTimeImmutable())->sub(new DateInterval('P' . $maxAgeDays . 'D'))->getTimestamp(), IQueryBuilder::PARAM_INT)));
}

return $this->yieldEntities($qb);

}
Expand Down
21 changes: 19 additions & 2 deletions lib/private/Preview/PreviewService.php
Original file line number Diff line number Diff line change
Expand Up @@ -85,15 +85,15 @@ public function getPreviewsForMimeTypes(array $mimeTypes): \Generator {
public function deleteAll(): void {
$lastId = 0;
while (true) {
$previews = $this->previewMapper->getPreviews($lastId, 1000);
$previews = $this->previewMapper->getPreviews($lastId, PreviewMapper::MAX_CHUNK_SIZE);
$i = 0;
foreach ($previews as $preview) {
$this->deletePreview($preview);
$i++;
$lastId = $preview->getId();
}

if ($i !== 1000) {
if ($i !== PreviewMapper::MAX_CHUNK_SIZE) {
break;
}
}
Expand All @@ -106,4 +106,21 @@ public function deleteAll(): void {
public function getAvailablePreviews(array $fileIds): array {
return $this->previewMapper->getAvailablePreviews($fileIds);
}

public function deleteExpiredPreviews(int $maxAgeDays): void {
$lastId = 0;
while (true) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do everything at once? If an admin suddenly sets preview_expiration_days to a very low value, there will need a lot of work to delete everything, so the cron might timeout at some point.

The fact that the background job runs regularly should be enough to lower the number of previews little by little. And we can also add a command to cleanup everything that won't be limited if needed.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure, but if it is limited to some value per run, then the job might not be able to catch up with deleting all expired previews.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sensitive defaults should be acceptable. Maybe increase the job frequency to make sure this works?

Copy link
Member

@CarlSchwan CarlSchwan Oct 9, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A common pattern we have elsewhere is to limit by time. e.g. max 1 hour running

$startTime = time();
		while (true) {
			$done = $this->doTheStuffWithLimit(1000);

                        if ($done) {
                            break;
                        }

			// Stop if execution time is more than one hour.
			if (time() - $startTime > 3600) {
				return;
			}

$previews = $this->previewMapper->getPreviews($lastId, PreviewMapper::MAX_CHUNK_SIZE, $maxAgeDays);
$i = 0;
foreach ($previews as $preview) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It might make sense to wrap this in a transation and delete by chunk to speed up a bit the process

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're right, I just copied from the deleteAll method which doesn't have that (probably because it will only be used by tests?)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, it's currently only used in tests

Copy link
Member Author

@provokateurin provokateurin Oct 9, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hm but with a transaction the DB and storage could get out of sync and I don't know how that is handled. What happens if the files are deleted, but the entries are still in the DB?

(Ok they can get out of sync without a transaction as well, but it would be limited to a single preview and not all expired ones)

Copy link
Member

@CarlSchwan CarlSchwan Oct 9, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Don't call rollback but just commit if something fails in the middle while removing a preview from the storage?

$this->deletePreview($preview);
$i++;
$lastId = $preview->getId();
}

if ($i !== PreviewMapper::MAX_CHUNK_SIZE) {
break;
}
}
}
}
2 changes: 2 additions & 0 deletions lib/private/Setup.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
use InvalidArgumentException;
use OC\Authentication\Token\PublicKeyTokenProvider;
use OC\Authentication\Token\TokenCleanupJob;
use OC\Core\BackgroundJobs\ExpirePreviewsJob;
use OC\Core\BackgroundJobs\GenerateMetadataJob;
use OC\Core\BackgroundJobs\MovePreviewJob;
use OC\Log\Rotate;
Expand Down Expand Up @@ -507,6 +508,7 @@ public static function installBackgroundJobs(): void {
$jobList->add(CleanupDeletedUsers::class);
$jobList->add(GenerateMetadataJob::class);
$jobList->add(MovePreviewJob::class);
$jobList->add(ExpirePreviewsJob::class);
}

/**
Expand Down
Loading