Files
provider_imap/lib/Service/Cache/MessageDeltaService.php
T
2026-10-07 21:21:14 -04:00

89 lines
3.0 KiB
PHP

<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: Sebastian Krupinski <krupinski01@gmail.com>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace KTXM\ProviderImap\Service\Cache;
use KTXF\Resource\Delta\Delta;
use KTXF\Resource\Delta\DeltaCollection;
use KTXM\ProviderImap\Stores\MailboxStore;
use KTXM\ProviderImap\Stores\MessageStore;
/**
* Answers "what changed since this signature?" for a cached mailbox.
*
* A signature is `<uidValidity>:<changeSeq>`. Read-only: harmonizing before
* answering is the caller's decision.
*/
class MessageDeltaService
{
public function __construct(
private readonly MailboxStore $mailboxStore,
private readonly MessageStore $messageStore,
) {}
/**
* Changes of a mailbox since a signature.
*
* - empty signature: the current signature and no changes, so the client gets a
* starting point; while the initial harmonization is incomplete the signature is
* `<uidValidity>:0`, so additions of the run in progress are not skipped
* - signature of another UIDVALIDITY, older than the purged tombstones, or not
* understood: a reset, answered as changes since 0 (every message is an addition)
* - otherwise: additions, modifications and deletions after the signature
*
* A mailbox that is not cached (or never harmonized) yields an empty delta.
*/
public function delta(string $serviceId, string $mailbox, string $signature): Delta
{
$state = $this->mailboxStore->state($serviceId, $mailbox);
if ($state['uidValidity'] === null) {
return new Delta();
}
$uidValidity = (int) $state['uidValidity'];
$current = self::signature($uidValidity, (int) $state['changeSeq']);
if ($signature === '') {
return new Delta(signature: $state['harmonizationComplete'] ? $current : self::signature($uidValidity, 0));
}
$since = self::since($signature, $uidValidity, (int) $state['purgedSeq'], (int) $state['changeSeq']) ?? 0;
$changes = $this->messageStore->changes($serviceId, $mailbox, $uidValidity, $since);
return new Delta(
new DeltaCollection(array_map('strval', $changes['additions'])),
new DeltaCollection(array_map('strval', $changes['modifications'])),
new DeltaCollection(array_map('strval', $changes['deletions'])),
$current,
);
}
public static function signature(int $uidValidity, int $changeSeq): string
{
return $uidValidity . ':' . $changeSeq;
}
/**
* The change sequence a signature refers to, or null when it needs a reset.
*/
private static function since(string $signature, int $uidValidity, int $purgedSeq, int $changeSeq): ?int
{
if (preg_match('/^(\d+):(\d+)$/', $signature, $matches) !== 1) {
return null;
}
$since = (int) $matches[2];
if ((int) $matches[1] !== $uidValidity || $since < $purgedSeq || $since > $changeSeq) {
return null;
}
return $since;
}
}