Files
2026-10-07 21:21:14 -04:00

66 lines
2.1 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 KTXM\ProviderImap\Providers\EntityResource;
use KTXM\ProviderImap\Stores\MailboxStore;
use KTXM\ProviderImap\Stores\MessageFileStore;
use KTXM\ProviderImap\Stores\MessageStore;
/**
* Writes fetched messages into the cache (content store + meta store).
*
* Shared by harmonization and by the cold list path, which caches the page it streams.
*/
class MessageIngestor
{
/** Maximum octets of BODY[TEXT] fetched per message for the cache; text past it is completed on open */
public const BODY_TEXT_LIMIT = 262144; // 256 KB
public function __construct(
private readonly MessageFileStore $fileStore,
private readonly MessageStore $messageStore,
private readonly MailboxStore $mailboxStore,
) {}
/**
* Cache messages of one mailbox generation.
*
* The content is written before the meta document, so an interruption leaves at
* most an orphaned file, never a meta document without content. Each message is
* stamped with its own change sequence, reserved per mailbox in one step.
*
* @return int[] UIDs that were cached
*/
public function ingest(string $tenantId, string $serviceId, int $uidValidity, EntityResource ...$entities): array
{
$byMailbox = [];
foreach ($entities as $entity) {
$byMailbox[(string) $entity->collection()][] = $entity;
}
$ingested = [];
foreach ($byMailbox as $mailbox => $group) {
$seq = $this->mailboxStore->reserveSequence($serviceId, (string) $mailbox, count($group));
foreach ($group as $entity) {
$uid = (int) $entity->identifier();
$this->fileStore->write($tenantId, $serviceId, (string) $mailbox, $uidValidity, $uid, $entity->toCacheContent());
$this->messageStore->upsert($tenantId, $serviceId, $uidValidity, $entity, $seq++);
$ingested[] = $uid;
}
}
return $ingested;
}
}