diff --git a/lib/Db/MailboxMapper.php b/lib/Db/MailboxMapper.php index faec77b867..c252bbcad7 100644 --- a/lib/Db/MailboxMapper.php +++ b/lib/Db/MailboxMapper.php @@ -279,6 +279,21 @@ public function unlockFromVanishedSync(Mailbox $mailbox): void { $this->update($mailbox); } + /** + * Mark the mailbox as not cached, whatever tokens the given entity holds + * + * @throws Exception + */ + public function clearSyncTokens(Mailbox $mailbox): void { + $query = $this->db->getQueryBuilder(); + $query->update($this->getTableName()) + ->set('sync_new_token', $query->createNamedParameter(null, IQueryBuilder::PARAM_NULL)) + ->set('sync_changed_token', $query->createNamedParameter(null, IQueryBuilder::PARAM_NULL)) + ->set('sync_vanished_token', $query->createNamedParameter(null, IQueryBuilder::PARAM_NULL)) + ->where($query->expr()->eq('id', $query->createNamedParameter($mailbox->getId(), IQueryBuilder::PARAM_INT))); + $query->executeStatement(); + } + public function deleteOrphans(): void { $qb1 = $this->db->getQueryBuilder(); $idsQuery = $qb1->select('m.id') diff --git a/lib/Service/Search/MailSearch.php b/lib/Service/Search/MailSearch.php index aacb4d3046..5381d98f5d 100644 --- a/lib/Service/Search/MailSearch.php +++ b/lib/Service/Search/MailSearch.php @@ -77,12 +77,7 @@ public function findMessages(Account $account, ?int $limit, ?string $userId, ?string $view): array { - if ($mailbox->hasLocks($this->timeFactory->getTime())) { - throw MailboxLockedException::from($mailbox); - } - if (!$mailbox->isCached()) { - throw MailboxNotCachedException::from($mailbox); - } + $this->assertCached($mailbox); $query = $this->filterStringParser->parse($filter); if ($cursor !== null) { @@ -100,16 +95,36 @@ public function findMessages(Account $account, $query->addFlag(Flag::not(Flag::DELETED)); } - return $this->previewEnhancer->process( + $accountUserId = $account->getUserId(); + $messages = $this->previewEnhancer->process( $account, $mailbox, - $this->messageMapper->findByIds($account->getUserId(), + $this->messageMapper->findByIds($accountUserId, $this->getIdsLocally($account, $mailbox, $query, $sortOrder, $limit), $sortOrder, ), true, $userId ); + // A sync may have reset the cache while the messages and their previews were read + $this->assertCached($this->mailManager->getMailbox($accountUserId, $mailbox->getId())); + + return $messages; + } + + /** + * @throws MailboxLockedException + * @throws MailboxNotCachedException + */ + private function assertCached(Mailbox $mailbox): void { + if ($mailbox->isCached()) { + return; + } + // Another process is filling the cache, so the client waits instead of starting an initial sync too + if ($mailbox->hasLocks($this->timeFactory->getTime())) { + throw MailboxLockedException::from($mailbox); + } + throw MailboxNotCachedException::from($mailbox); } /** diff --git a/lib/Service/Sync/ImapToDbSynchronizer.php b/lib/Service/Sync/ImapToDbSynchronizer.php index d2daab1925..1a88f0a848 100644 --- a/lib/Service/Sync/ImapToDbSynchronizer.php +++ b/lib/Service/Sync/ImapToDbSynchronizer.php @@ -38,7 +38,9 @@ use OCA\Mail\Service\MailManager; use OCA\Mail\Support\PerformanceLogger; use OCP\AppFramework\Db\DoesNotExistException; +use OCP\AppFramework\Db\TTransactional; use OCP\EventDispatcher\IEventDispatcher; +use OCP\IDBConnection; use Psr\Log\LoggerInterface; use Throwable; use function array_chunk; @@ -50,6 +52,8 @@ use function sprintf; class ImapToDbSynchronizer { + use TTransactional; + /** @var int */ public const MAX_NEW_MESSAGES = 5000; public const PARTIAL_SYNC_CHUNK_SIZE = 500; @@ -70,6 +74,7 @@ public function __construct( private MailManager $mailManager, private TagMapper $tagMapper, private NewMessagesClassifier $newMessagesClassifier, + private IDBConnection $db, ) { $this->dispatcher = $dispatcher; } @@ -160,12 +165,15 @@ public function clearCache(Account $account, */ private function resetCache(Account $account, Mailbox $mailbox): void { $id = $account->getId() . ':' . $mailbox->getName(); - $this->dbMapper->deleteAll($mailbox); + $this->atomicRetry(function () use ($mailbox): void { + $this->dbMapper->deleteAll($mailbox); + $this->mailboxMapper->clearSyncTokens($mailbox); + }, $this->db); $this->logger->debug("All messages of $id cleared"); + // Unlocking saves $mailbox, so it only gets the empty tokens once they are committed $mailbox->setSyncNewToken(null); $mailbox->setSyncChangedToken(null); $mailbox->setSyncVanishedToken(null); - $this->mailboxMapper->update($mailbox); } /** diff --git a/tests/Integration/Db/MailboxMapperTest.php b/tests/Integration/Db/MailboxMapperTest.php index f89fbc7a70..844604396c 100644 --- a/tests/Integration/Db/MailboxMapperTest.php +++ b/tests/Integration/Db/MailboxMapperTest.php @@ -12,6 +12,7 @@ use ChristophWurst\Nextcloud\Testing\DatabaseTransaction; use ChristophWurst\Nextcloud\Testing\TestCase; use OCA\Mail\Account; +use OCA\Mail\Db\Mailbox; use OCA\Mail\Db\MailboxMapper; use OCP\AppFramework\Db\DoesNotExistException; use OCP\AppFramework\Utility\ITimeFactory; @@ -191,4 +192,36 @@ public function testMailboxesWithTrailingSpace(): void { $resultB = $this->mapper->find($account, 'Test '); $this->assertSame('Test ', $resultB->getName()); } + + public function testClearSyncTokensOfAStaleEntityWithoutTokens(): void { + $account = $this->createMock(Account::class); + $account->method('getId')->willReturn(13); + $this->insertCachedMailbox('INBOX'); + $this->insertCachedMailbox('Sent'); + $stale = new Mailbox(); + $stale->setId($this->mapper->find($account, 'INBOX')->getId()); + + $this->mapper->clearSyncTokens($stale); + + $this->assertFalse($this->mapper->find($account, 'INBOX')->isCached()); + $this->assertTrue($this->mapper->find($account, 'Sent')->isCached()); + } + + private function insertCachedMailbox(string $name): void { + $qb = $this->db->getQueryBuilder(); + $qb->insert($this->mapper->getTableName()) + ->values([ + 'name' => $qb->createNamedParameter($name), + 'account_id' => $qb->createNamedParameter(13, IQueryBuilder::PARAM_INT), + 'sync_new_token' => $qb->createNamedParameter('VTEsVjE0Mjg1OTkxNDk='), + 'sync_changed_token' => $qb->createNamedParameter('VTEsVjE0Mjg1OTkxNDk='), + 'sync_vanished_token' => $qb->createNamedParameter('VTEsVjE0Mjg1OTkxNDk='), + 'delimiter' => $qb->createNamedParameter('.'), + 'messages' => $qb->createNamedParameter(0, IQueryBuilder::PARAM_INT), + 'unseen' => $qb->createNamedParameter(0, IQueryBuilder::PARAM_INT), + 'selectable' => $qb->createNamedParameter(true, IQueryBuilder::PARAM_BOOL), + 'name_hash' => $qb->createNamedParameter(md5($name)), + ]) + ->executeStatement(); + } } diff --git a/tests/Unit/Service/Search/MailSearchTest.php b/tests/Unit/Service/Search/MailSearchTest.php index b04244b925..284e4e4e76 100644 --- a/tests/Unit/Service/Search/MailSearchTest.php +++ b/tests/Unit/Service/Search/MailSearchTest.php @@ -11,6 +11,7 @@ use ChristophWurst\Nextcloud\Testing\TestCase; use OCA\Mail\Account; +use OCA\Mail\Contracts\IMailSearch; use OCA\Mail\Db\Mailbox; use OCA\Mail\Db\Message; use OCA\Mail\Db\MessageMapper; @@ -26,6 +27,8 @@ use PHPUnit\Framework\MockObject\MockObject; final class MailSearchTest extends TestCase { + private const NOW = 1_000_000; + /** @var FilterStringParser|MockObject */ private $filterStringParser; @@ -81,16 +84,87 @@ public function testFindMessagesNotCached(): void { ); } - public function testFindMessagesLocked(): void { + public function testFindMessagesNotCachedAndLocked(): void { $account = $this->createStub(Account::class); $mailbox = new Mailbox(); - $mailbox->setSyncNewLock(123); + $mailbox->setSyncNewLock(self::NOW); + $this->timeFactory->method('getTime')->willReturn(self::NOW); $this->expectException(MailboxLockedException::class); $this->search->findMessages( $account, $mailbox, - 'DESC', + IMailSearch::ORDER_NEWEST_FIRST, + null, + null, + null, + null, + null, + ); + } + + public function testFindMessagesNotCachedWithAnExpiredLock(): void { + $account = $this->createStub(Account::class); + $mailbox = new Mailbox(); + $mailbox->setSyncNewLock(self::NOW - Mailbox::LOCK_TIMEOUT); + $this->timeFactory->method('getTime')->willReturn(self::NOW); + $this->expectException(MailboxNotCachedException::class); + + $this->search->findMessages( + $account, + $mailbox, + IMailSearch::ORDER_NEWEST_FIRST, + null, + null, + null, + null, + null, + ); + } + + public function testFindMessagesOfACachedMailboxWhileItSyncs(): void { + $account = $this->createStub(Account::class); + $account->method('getUserId')->willReturn('admin'); + $mailbox = $this->createCachedMailbox(); + $mailbox->setSyncNewLock(self::NOW); + $this->timeFactory->method('getTime')->willReturn(self::NOW); + $message = new Message(); + $this->messageMapper->method('findByIds')->willReturn([$message]); + $this->previewEnhancer->method('process')->willReturnArgument(2); + + $messages = $this->search->findMessages( + $account, + $mailbox, + IMailSearch::ORDER_NEWEST_FIRST, + null, + null, + null, + null, + null, + ); + + $this->assertSame([$message], $messages); + } + + public function testFindMessagesWhileASyncResetsTheCache(): void { + $account = $this->createStub(Account::class); + $account->method('getUserId')->willReturn('admin'); + $mailbox = $this->createCachedMailbox(); + $this->timeFactory->method('getTime')->willReturn(self::NOW); + $this->previewEnhancer->method('process') + ->willReturnCallback(static function (Account $account, Mailbox $mailbox, array $messages): array { + $mailbox->setSyncNewLock(self::NOW); + $mailbox->setSyncNewToken(null); + $mailbox->setSyncChangedToken(null); + $mailbox->setSyncVanishedToken(null); + return $messages; + }); + $this->expectException(MailboxLockedException::class); + + $this->search->findMessages( + $account, + $mailbox, + IMailSearch::ORDER_NEWEST_FIRST, null, null, null, @@ -104,10 +178,7 @@ public function testNoFindMessages(): void { $account->expects($this->once()) ->method('getUserId') ->willReturn('admin'); - $mailbox = new Mailbox(); - $mailbox->setSyncNewToken('abc'); - $mailbox->setSyncChangedToken('def'); - $mailbox->setSyncVanishedToken('ghi'); + $mailbox = $this->createCachedMailbox(); $messages = $this->search->findMessages( $account, @@ -128,10 +199,7 @@ public function testFindFlagsLocally(): void { $account->expects($this->once()) ->method('getUserId') ->willReturn('admin'); - $mailbox = new Mailbox(); - $mailbox->setSyncNewToken('abc'); - $mailbox->setSyncChangedToken('def'); - $mailbox->setSyncVanishedToken('ghi'); + $mailbox = $this->createCachedMailbox(); $query = new SearchQuery(); $query->addFlag(Flag::is(Flag::SEEN)); $this->filterStringParser->expects($this->once()) @@ -169,10 +237,7 @@ public function testFindText(): void { $account->expects($this->once()) ->method('getUserId') ->willReturn('admin'); - $mailbox = new Mailbox(); - $mailbox->setSyncNewToken('abc'); - $mailbox->setSyncChangedToken('def'); - $mailbox->setSyncVanishedToken('ghi'); + $mailbox = $this->createCachedMailbox(); $query = new SearchQuery(); $query->addBody('my'); $query->addBody('search'); @@ -207,4 +272,14 @@ public function testFindText(): void { $this->assertCount(2, $messages); } + + private function createCachedMailbox(): Mailbox { + $mailbox = new Mailbox(); + $mailbox->setId(10); + $mailbox->setSyncNewToken('abc'); + $mailbox->setSyncChangedToken('def'); + $mailbox->setSyncVanishedToken('ghi'); + $this->mailManager->method('getMailbox')->with('admin', 10)->willReturn($mailbox); + return $mailbox; + } } diff --git a/tests/Unit/Service/Sync/ImapToDbSynchronizerTest.php b/tests/Unit/Service/Sync/ImapToDbSynchronizerTest.php index f580d2bef1..cc527e9a80 100644 --- a/tests/Unit/Service/Sync/ImapToDbSynchronizerTest.php +++ b/tests/Unit/Service/Sync/ImapToDbSynchronizerTest.php @@ -25,6 +25,7 @@ use OCA\Mail\Events\NewMessagesSynchronized; use OCA\Mail\Events\SynchronizationEvent; use OCA\Mail\Exception\ServiceException; +use OCA\Mail\Exception\UidValidityChangedException; use OCA\Mail\IMAP\MessageMapper as ImapMessageMapper; use OCA\Mail\IMAP\Sync\Synchronizer; use OCA\Mail\Model\IMAPMessage; @@ -34,7 +35,9 @@ use OCA\Mail\Service\Sync\ImapToDbSynchronizer; use OCA\Mail\Support\PerformanceLogger; use OCA\Mail\Support\PerformanceLoggerTask; +use OCP\DB\Exception as DBException; use OCP\EventDispatcher\IEventDispatcher; +use OCP\IDBConnection; use PHPUnit\Framework\MockObject\MockObject; use Psr\Log\LoggerInterface; use function array_fill; @@ -51,11 +54,14 @@ final class ImapToDbSynchronizerTest extends TestCase { private IEventDispatcher&MockObject $dispatcher; private PerformanceLogger&MockObject $performanceLogger; private MailManager&MockObject $mailManager; + private IDBConnection&MockObject $db; private ImapToDbSynchronizer $synchronizer; /** @var list UID chunks passed to findByIds, in call order */ private array $fetchedChunks = []; /** @var list permflags flag and message count of each updateBulk call */ private array $bulkUpdates = []; + /** @var list transaction and write steps of a cache reset, in call order */ + private array $resetSteps = []; protected function setUp(): void { parent::setUp(); @@ -69,6 +75,7 @@ protected function setUp(): void { $this->performanceLogger->method('startWithLogger') ->willReturn($this->createStub(PerformanceLoggerTask::class)); $this->mailManager = $this->createMock(MailManager::class); + $this->db = $this->createMock(IDBConnection::class); $this->synchronizer = new ImapToDbSynchronizer( $this->dbMapper, $this->protocolFactory, @@ -82,9 +89,48 @@ protected function setUp(): void { $this->mailManager, $this->createStub(TagMapper::class), $this->createStub(NewMessagesClassifier::class), + $this->db, ); } + public function testClearCacheDeletesTheMessagesAndTokensInOneTransaction(): void { + [$account, $mailbox] = $this->createAccountAndCachedMailbox(); + $this->recordResetSteps(); + + $this->synchronizer->clearCache($account, $mailbox); + + $this->assertSame(['begin', 'delete messages', 'clear tokens', 'commit'], $this->resetSteps); + } + + public function testClearCacheUnlocksWithoutSavingTheTokensOfARolledBackReset(): void { + [$account, $mailbox] = $this->createAccountAndCachedMailbox(); + $this->mailboxMapper->method('clearSyncTokens')->willThrowException(new DBException('update failed')); + $this->db->expects($this->once())->method('rollBack'); + $this->db->expects($this->never())->method('commit'); + $this->mailboxMapper->expects($this->once()) + ->method('unlockFromVanishedSync') + ->with($this->callback(static fn (Mailbox $mailbox): bool => $mailbox->isCached())); + $this->expectException(ServiceException::class); + + $this->synchronizer->clearCache($account, $mailbox); + } + + public function testUidValidityChangeResetsTheCacheInOneTransactionBeforeTheInitialSync(): void { + [$account, $mailbox, $client] = $this->createPartialSyncFixture(); + $this->imapSynchronizer->method('sync')->willThrowException(new UidValidityChangedException()); + $this->dbMapper->method('findHighestUid')->willReturn(null); + $this->imapMapper->method('findAll')->willReturn([ + 'messages' => [], + 'all' => true, + 'total' => 0, + ]); + $this->recordResetSteps(); + + $this->synchronizer->sync($account, $client, $mailbox, $this->createStub(LoggerInterface::class)); + + $this->assertSame(['begin', 'delete messages', 'clear tokens', 'commit', 'save cached mailbox'], $this->resetSteps); + } + public function testInitialSyncGetsSyncTokenFromCacheClient(): void { [$account, $mailbox] = $this->createAccountAndMailbox(); $capability = $this->createMock(Horde_Imap_Client_Data_Capability_Imap::class); @@ -386,13 +432,21 @@ private function createAccountAndMailbox(): array { } /** - * @return array{Account, Mailbox, Horde_Imap_Client_Socket&MockObject} + * @return array{Account, Mailbox} */ - private function createPartialSyncFixture(bool $qresync = false): array { + private function createAccountAndCachedMailbox(): array { [$account, $mailbox] = $this->createAccountAndMailbox(); $mailbox->setSyncNewToken('token'); $mailbox->setSyncChangedToken('token'); $mailbox->setSyncVanishedToken('token'); + return [$account, $mailbox]; + } + + /** + * @return array{Account, Mailbox, Horde_Imap_Client_Socket&MockObject} + */ + private function createPartialSyncFixture(bool $qresync = false): array { + [$account, $mailbox] = $this->createAccountAndCachedMailbox(); $capability = $this->createStub(Horde_Imap_Client_Data_Capability_Imap::class); $capability->method('isEnabled')->willReturnCallback(static fn (string $extension): bool => $qresync && $extension === 'QRESYNC'); $client = $this->createMock(Horde_Imap_Client_Socket::class); @@ -412,6 +466,25 @@ private function mockImapSync(array $newUids, array $changedUids, bool $hasQresy ->willReturn([$newUids, $changedUids, []]); } + private function recordResetSteps(): void { + $this->db->method('beginTransaction')->willReturnCallback(function (): void { + $this->resetSteps[] = 'begin'; + }); + $this->db->method('commit')->willReturnCallback(function (): void { + $this->resetSteps[] = 'commit'; + }); + $this->dbMapper->method('deleteAll')->willReturnCallback(function (): void { + $this->resetSteps[] = 'delete messages'; + }); + $this->mailboxMapper->method('clearSyncTokens')->willReturnCallback(function (): void { + $this->resetSteps[] = 'clear tokens'; + }); + $this->mailboxMapper->method('update')->willReturnCallback(function (Mailbox $mailbox): Mailbox { + $this->resetSteps[] = $mailbox->isCached() ? 'save cached mailbox' : 'save uncached mailbox'; + return $mailbox; + }); + } + private function recordBulkUpdates(): void { $this->dbMapper->method('updateBulk') ->willReturnCallback(function (Account $account, bool $permflagsEnabled, Message ...$messages): array {