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
15 changes: 15 additions & 0 deletions lib/Db/MailboxMapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down
31 changes: 23 additions & 8 deletions lib/Service/Search/MailSearch.php
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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);
}

/**
Expand Down
12 changes: 10 additions & 2 deletions lib/Service/Sync/ImapToDbSynchronizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand All @@ -70,6 +74,7 @@ public function __construct(
private MailManager $mailManager,
private TagMapper $tagMapper,
private NewMessagesClassifier $newMessagesClassifier,
private IDBConnection $db,
) {
$this->dispatcher = $dispatcher;
}
Expand Down Expand Up @@ -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);
}

/**
Expand Down
33 changes: 33 additions & 0 deletions tests/Integration/Db/MailboxMapperTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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();
}
}
105 changes: 90 additions & 15 deletions tests/Unit/Service/Search/MailSearchTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;

Expand Down Expand Up @@ -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,
Expand All @@ -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,
Expand All @@ -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())
Expand Down Expand Up @@ -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');
Expand Down Expand Up @@ -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;
}
}
Loading
Loading