diff --git a/src/Connection/ConnectionInterface.php b/src/Connection/ConnectionInterface.php index 24024101..db4dd00a 100644 --- a/src/Connection/ConnectionInterface.php +++ b/src/Connection/ConnectionInterface.php @@ -5,8 +5,12 @@ use DateTimeInterface; use DirectoryTree\ImapEngine\AppendResult; use DirectoryTree\ImapEngine\Collections\ResponseCollection; +use DirectoryTree\ImapEngine\Connection\Responses\Data\Data; +use DirectoryTree\ImapEngine\Connection\Responses\Response; use DirectoryTree\ImapEngine\Connection\Responses\TaggedResponse; use DirectoryTree\ImapEngine\Connection\Responses\UntaggedResponse; +use DirectoryTree\ImapEngine\Connection\Streams\StreamInterface; +use DirectoryTree\ImapEngine\Connection\Tokens\Token; use DirectoryTree\ImapEngine\Enums\ImapIdentifier; use DirectoryTree\ImapEngine\Fetch\ModifierInterface as FetchModifierInterface; use DirectoryTree\ImapEngine\FetchResult; @@ -36,6 +40,25 @@ public function disconnect(): void; */ public function connected(): bool; + /** + * Read and parse the next reply from the stream. + */ + public function read(): Data|Token|Response|null; + + /** + * Write a protocol line with CRLF, optionally redacting it from logs. + * + * This bypasses command tagging and the active IDLE guard. + */ + public function write(string $data, bool $sensitive = false): void; + + /** + * Get the underlying stream for low-level transport access. + * + * Direct IO bypasses parsing, logging, and connection state management. + */ + public function stream(): StreamInterface; + /** * Send a "LOGIN" command. * @@ -78,18 +101,11 @@ public function authenticate(string $mechanism, ?string $initial = null): Genera public function startTls(): void; /** - * Send an "IDLE" command. + * Send an "IDLE" command and return the session managing its responses. * * @see https://datatracker.ietf.org/doc/html/rfc9051#name-idle-command */ - public function idle(int $timeout): Generator; - - /** - * Send the DONE continuation to finish the current IDLE command. - * - * @see https://datatracker.ietf.org/doc/html/rfc9051#section-6.3.13 - */ - public function done(): void; + public function idle(): IdleSession; /** * Send a "NOOP" command. diff --git a/src/Connection/IdleSession.php b/src/Connection/IdleSession.php new file mode 100644 index 00000000..6918943f --- /dev/null +++ b/src/Connection/IdleSession.php @@ -0,0 +1,205 @@ +active; + } + + /** + * Invalidate the session when its connection is closed. + */ + public function invalidate(): void + { + $this->active = false; + $this->pending = []; + } + + /** + * Yield unsolicited updates until completion or the renewal deadline. + * + * Finish the session or disconnect before sending another command. + * + * @param int $timeout The renewal interval in seconds. + * @return Generator + */ + public function responses(int $timeout = 300): Generator + { + if ($this->started) { + throw new LogicException('IDLE responses may only be consumed once.'); + } + + $this->started = true; + $this->deadline = Carbon::now()->addSeconds(max($timeout, 1)); + + while ($this->active) { + if ($this->ready) { + if (Carbon::now()->greaterThanOrEqualTo($this->deadline)) { + return; + } + + if ($this->pending) { + yield array_shift($this->pending); + + continue; + } + } + + $response = $this->receive(); + + if ($response instanceof UntaggedResponse) { + $this->pending[] = $response; + } + } + } + + /** + * Finish IDLE and return updates not yet delivered to the caller. + * + * @param int $timeout The time allowed to complete the exchange, in seconds. + */ + public function finish(int $timeout = 30): ResponseCollection + { + if (! $this->active) { + return new ResponseCollection; + } + + // Completion has its own deadline, separate from the renewal interval. + $this->deadline = Carbon::now()->addSeconds($timeout); + + try { + while ($this->active && ! $this->ready) { + if (($response = $this->receive()) instanceof UntaggedResponse) { + $this->pending[] = $response; + } + } + + if ($this->active) { + $this->connection->write('DONE'); + } + + $responses = new ResponseCollection($this->pending); + + $this->pending = []; + + while ($this->active) { + if (($response = $this->receive()) instanceof UntaggedResponse) { + $responses->push($response); + } + } + + return $responses; + } catch (ImapConnectionTimedOutException $e) { + // A missing acknowledgement leaves the connection unusable. + $this->connection->disconnect(); + + throw $e; + } + } + + /** + * Read a response and advance the IDLE protocol state. + */ + protected function receive(): Response + { + $remaining = (int) ceil(Carbon::now()->diffInSeconds($this->deadline, false)); + + $this->connection->stream()->setTimeout(max(1, $remaining)); + + try { + if ($remaining <= 0) { + throw new ImapConnectionTimedOutException('IDLE session timed out'); + } + + $response = $this->connection->read(); + } catch (ImapConnectionTimedOutException $e) { + if (! $this->ready) { + $this->connection->disconnect(); + + throw new ImapConnectionClosedException('Timed out waiting for the IDLE continuation', previous: $e); + } + + throw $e; + } catch (ImapConnectionClosedException $e) { + $this->connection->disconnect(); + + throw $e; + } + + if ($response instanceof ContinuationResponse) { + $this->ready = true; + } elseif ($response instanceof TaggedResponse && $response->tag()->value === $this->command->tag()) { + $this->active = false; + + if (! $response->successful()) { + throw ImapCommandException::make($this->command, $response); + } + } elseif ($response instanceof UntaggedResponse && $response->type()->is('BYE')) { + $this->connection->disconnect(); + + throw new ImapConnectionClosedException((string) $response); + } + + return $response; + } +} diff --git a/src/Connection/ImapConnection.php b/src/Connection/ImapConnection.php index de00ba76..81f813ed 100644 --- a/src/Connection/ImapConnection.php +++ b/src/Connection/ImapConnection.php @@ -49,6 +49,11 @@ class ImapConnection implements ConnectionInterface */ protected ?Result $result = null; + /** + * The current IDLE session open on the connection. + */ + protected ?IdleSession $idle = null; + /** * The parser instance. */ @@ -174,6 +179,9 @@ protected function getDefaultSocketOptions(string $transport, array $proxy = [], */ public function disconnect(): void { + $this->idle?->invalidate(); + $this->idle = null; + $this->stream->close(); } @@ -202,6 +210,10 @@ public function login(string $user, string $password): TaggedResponse */ public function logout(): void { + if (! $this->connected()) { + return; + } + try { $this->send('LOGOUT', tag: $tag); @@ -631,37 +643,13 @@ public function noop(): TaggedResponse /** * {@inheritDoc} */ - public function idle(int $timeout): Generator + public function idle(): IdleSession { - $this->stream->setTimeout($timeout); - $this->send('IDLE', tag: $tag); - $this->assertNextResponse( - fn (Response $response) => $response instanceof ContinuationResponse, - fn (ContinuationResponse $response) => true, - fn (ContinuationResponse $response) => ImapCommandException::make(new ImapCommand('', 'IDLE'), $response), - ); - - while ($response = $this->nextReply()) { - yield $response; - } - } - - /** - * {@inheritDoc} - */ - public function done(): void - { - $this->write('DONE'); - - // After sending the DONE continuation, the server must respond with a - // tagged response to indicate that the IDLE command has been successfully - // terminated and the server is ready to accept further commands. - $this->assertNextResponse( - fn (Response $response) => $response instanceof TaggedResponse, - fn (TaggedResponse $response) => $response->successful(), - fn (TaggedResponse $response) => ImapCommandException::make(new ImapCommand('', 'DONE'), $response), + return $this->idle = new IdleSession( + new ImapCommand($tag, 'IDLE'), + $this, ); } @@ -672,6 +660,10 @@ public function done(): void */ public function send(string $name, array $tokens = [], ?string &$tag = null): void { + if ($this->idle?->active()) { + throw new LogicException('Finish the active IDLE session before sending another command.'); + } + if (! $tag) { $tag = 'TAG'.++$this->sequence; } @@ -693,9 +685,9 @@ public function send(string $name, array $tokens = [], ?string &$tag = null): vo } /** - * Write data to the connected stream. + * {@inheritDoc} */ - protected function write(string $data, bool $sensitive = false): void + public function write(string $data, bool $sensitive = false): void { if ($this->stream->fwrite($data."\r\n") === false) { throw new ImapStreamException('Failed to write data to stream'); @@ -866,7 +858,7 @@ protected function nextResponse(callable $filter): ?Response throw new LogicException('No parser instance set'); } - while ($response = $this->nextReply()) { + while ($response = $this->read()) { if (! $response instanceof Response) { continue; } @@ -882,9 +874,9 @@ protected function nextResponse(callable $filter): ?Response } /** - * Read the next reply from the stream. + * {@inheritDoc} */ - protected function nextReply(): Data|Token|Response|null + public function read(): Data|Token|Response|null { if (! $reply = $this->parser->next()) { $meta = $this->stream->meta(); @@ -900,4 +892,12 @@ protected function nextReply(): Data|Token|Response|null return $reply; } + + /** + * {@inheritDoc} + */ + public function stream(): StreamInterface + { + return $this->stream; + } } diff --git a/src/Folder.php b/src/Folder.php index 4fb79f72..600fc440 100644 --- a/src/Folder.php +++ b/src/Folder.php @@ -5,14 +5,11 @@ use Closure; use DirectoryTree\ImapEngine\Connection\ImapQueryBuilder; use DirectoryTree\ImapEngine\Connection\Responses\UntaggedResponse; -use DirectoryTree\ImapEngine\Enums\ImapIdentifier; -use DirectoryTree\ImapEngine\Exceptions\Exception; use DirectoryTree\ImapEngine\Exceptions\ImapCapabilityException; use DirectoryTree\ImapEngine\Selection\OptionInterface; use DirectoryTree\ImapEngine\Selection\Result; use DirectoryTree\ImapEngine\Support\Str; use Illuminate\Contracts\Support\Arrayable; -use Illuminate\Support\ItemNotFoundException; use JsonSerializable; class Folder implements Arrayable, FolderInterface, JsonSerializable @@ -95,7 +92,7 @@ public function messages(): MessageQuery /** * {@inheritDoc} */ - public function idle(callable $callback, ?callable $query = null, callable|int $timeout = 300): void + public function events(callable $callback, callable|int $timeout = 300, OptionInterface ...$options): void { if (! $this->mailbox->capabilities()->supports('IDLE')) { throw new ImapCapabilityException('Unable to IDLE. IMAP server does not support IDLE capability.'); @@ -106,37 +103,15 @@ public function idle(callable $callback, ?callable $query = null, callable|int $ $timeout = $timeout(...); } - // The message query to use when fetching messages. - $query ??= fn (MessageQuery $query) => $query; - - // Fetch the message by message number. - $fetch = fn (int $msgn) => ( - $query($this->messages())->findOrFail($msgn, ImapIdentifier::MessageNumber) - ); - - (new Idle(clone $this->mailbox, $this->path, $timeout))->await( - function (int $msgn) use ($callback, $fetch) { - if (! $this->mailbox->connected()) { - $this->mailbox->connect(); - } - - try { - $message = $fetch($msgn); - } catch (ItemNotFoundException) { - // The message wasn't found. We will skip - // it and continue awaiting new messages. - return; - } catch (Exception) { - // Something else happened. We will attempt - // reconnecting and re-fetching the message. - $this->mailbox->reconnect(); - - $message = $fetch($msgn); - } + (new Watch(clone $this->mailbox, $this->path, $timeout, $options))->await($callback); + } - $callback($message); - } - ); + /** + * {@inheritDoc} + */ + public function idle(callable $callback, ?callable $query = null, callable|int $timeout = 300, OptionInterface ...$options): void + { + (new Idle($this))->await($callback, $query, $timeout, ...$options); } /** @@ -144,19 +119,17 @@ function (int $msgn) use ($callback, $fetch) { */ public function poll(callable $callback, ?callable $query = null, callable|int $frequency = 60): void { + if (is_callable($frequency) && ! $frequency instanceof Closure) { + $frequency = $frequency(...); + } + (new Poll(clone $this->mailbox, $this->path, $frequency))->start( function (MessageInterface $message) use ($callback) { if (! $this->mailbox->connected()) { $this->mailbox->connect(); } - try { - $callback($message); - } catch (Exception) { - // Something unexpected happened. We will attempt - // reconnecting and continue polling for messages. - $this->mailbox->reconnect(); - } + return $callback($message); }, $query ?? fn (MessageQuery $query) => $query ); diff --git a/src/FolderInterface.php b/src/FolderInterface.php index 63fd1d02..e66cb155 100644 --- a/src/FolderInterface.php +++ b/src/FolderInterface.php @@ -2,6 +2,7 @@ namespace DirectoryTree\ImapEngine; +use DirectoryTree\ImapEngine\Idle\Events\EventInterface; use DirectoryTree\ImapEngine\Selection\OptionInterface; use DirectoryTree\ImapEngine\Selection\Result; @@ -45,12 +46,37 @@ public function is(FolderInterface $folder): bool; public function messages(): MessageQueryInterface; /** - * Begin idling on the current folder for the given timeout in seconds. + * Watch mailbox events on a dedicated connection. + * + * Events expose server responses without retrieving messages. + * + * Return false from the callback to stop. The timeout controls renewal, + * not the total watching duration. A callable timeout may return false + * or zero to stop between sessions. + * + * @param callable(EventInterface): mixed $callback + * @param callable|int $timeout The renewal interval in seconds, or a callable returning it. */ - public function idle(callable $callback, ?callable $query = null, callable|int $timeout = 300): void; + public function events(callable $callback, callable|int $timeout = 300, OptionInterface ...$options): void; + + /** + * Watch for new messages using IDLE, optionally customizing their query. + * + * Existing messages are excluded. Reconnects preserve the arrival cursor + * unless UID validity changes. Arrivals are fetched on count notifications. + * Return false from the callback to stop. Callback exceptions propagate. + * The timeout controls IDLE renewal, not the total watching duration. + * + * @param callable(MessageInterface): mixed $callback + * @param callable(MessageQueryInterface): MessageQueryInterface|null $query + */ + public function idle(callable $callback, ?callable $query = null, callable|int $timeout = 300, OptionInterface ...$options): void; /** * Begin polling for new messages at the given frequency in seconds. + * + * Return false from the callback to stop. Callback exceptions propagate. + * The polling connection is closed when polling stops. */ public function poll(callable $callback, ?callable $query = null, callable|int $frequency = 60): void; diff --git a/src/Idle.php b/src/Idle.php index 9be0f249..08858a23 100644 --- a/src/Idle.php +++ b/src/Idle.php @@ -2,172 +2,90 @@ namespace DirectoryTree\ImapEngine; -use Carbon\Carbon; -use Carbon\CarbonInterface; -use Closure; -use DirectoryTree\ImapEngine\Connection\Responses\UntaggedResponse; -use DirectoryTree\ImapEngine\Connection\Tokens\Atom; -use DirectoryTree\ImapEngine\Exceptions\Exception; -use DirectoryTree\ImapEngine\Exceptions\ImapConnectionClosedException; -use DirectoryTree\ImapEngine\Exceptions\ImapConnectionTimedOutException; -use Generator; +use DirectoryTree\ImapEngine\Idle\Events\EventInterface; +use DirectoryTree\ImapEngine\Idle\Events\FolderSelected; +use DirectoryTree\ImapEngine\Idle\Events\MessagesExist; +use DirectoryTree\ImapEngine\Selection\OptionInterface; +use DirectoryTree\ImapEngine\Selection\Result; class Idle { /** - * Constructor. + * The first UID that has not yet been delivered. */ - public function __construct( - protected Mailbox $mailbox, - protected string $folder, - protected Closure|int $timeout, - ) {} + protected ?int $nextUid = null; /** - * Destructor. + * The watching connection's latest folder selection. */ - public function __destruct() - { - $this->disconnect(); - } + protected ?Result $selection = null; /** - * Await new messages on the connection. + * Constructor. */ - public function await(callable $callback): void - { - $this->connect(); - - while ($ttl = $this->getNextTimeout()) { - try { - $this->listen($callback, $ttl); - } catch (ImapConnectionTimedOutException) { - $this->restart(); - } catch (ImapConnectionClosedException) { - $this->reconnect(); - } - } - } + public function __construct( + protected FolderInterface $folder + ) {} /** - * Start listening for new messages using the idle() generator. + * Await new messages, optionally customizing their query. + * + * @param callable(MessageInterface): mixed $callback + * @param (callable(MessageQueryInterface): MessageQueryInterface)|null $query */ - protected function listen(callable $callback, CarbonInterface $ttl): void + public function await(callable $callback, ?callable $query = null, callable|int $timeout = 300, OptionInterface ...$options): void { - // Iterate over responses yielded by the idle generator. - foreach ($this->idle($ttl) as $response) { - if (! $response instanceof UntaggedResponse) { - continue; - } + $this->folder->events(function (EventInterface $event) use ($callback, $query) { + if ($event instanceof FolderSelected) { + if ($this->selection === null || $this->selection->uidValidity() !== $event->selection()->uidValidity()) { + $this->nextUid = $event->selection()->uidNext() ?? $this->getNextUid(); + } - if (! $token = $response->tokenAt(2)) { - continue; + $this->selection = $event->selection(); } - if ($token instanceof Atom && $token->is('EXISTS')) { - $msgn = (int) $response->tokenAt(1)->value; - - $callback($msgn); - - $ttl = $this->getNextTimeout(); + if ($event instanceof MessagesExist) { + return $this->deliver($callback, $query); } - - if ($ttl === false) { - break; - } - - // If we've been idle too long, break out to restart the session. - if (Carbon::now()->greaterThanOrEqualTo($ttl)) { - $this->restart(); - - break; - } - } + }, $timeout, ...$options); } /** - * Get the folder to idle. + * Retrieve arrivals and deliver them in UID order. */ - protected function folder(): FolderInterface + protected function deliver(callable $callback, ?callable $query): ?bool { - return $this->mailbox->folders()->findOrFail($this->folder); - } + $current = $this->folder->select(true); - /** - * Issue a done command and restart the idle session. - */ - protected function restart(): void - { - try { - // Send DONE to terminate the current IDLE session gracefully. - $this->done(); - } catch (Exception) { - $this->reconnect(); + if ($this->selection->uidValidity() !== null && $current->uidValidity() !== $this->selection->uidValidity()) { + return null; } - } - /** - * Reconnect the client and restart the idle session. - */ - protected function reconnect(): void - { - $this->mailbox->disconnect(); + $messages = $this->folder->messages()->with(MessageData::flags()); - $this->connect(); - } + $messages = $query ? $query($messages) : $messages; - /** - * Connect the client and select the folder to idle. - */ - protected function connect(): void - { - $this->mailbox->connect(); + foreach ($messages->uid($this->nextUid.':*')->orderByUid()->cursor() as $message) { + // Reversed IMAP ranges can include an older UID when no arrivals exist. + if ($message->uid() < $this->nextUid) { + continue; + } - $this->mailbox->select($this->folder(), true); - } + if ($callback($message) === false) { + return false; + } - /** - * Disconnect the client. - */ - protected function disconnect(): void - { - try { - // Attempt to terminate IDLE gracefully. - $this->done(); - } catch (Exception) { - // Do nothing. + $this->nextUid = $message->uid() + 1; } - $this->mailbox->disconnect(); + return null; } /** - * End the current IDLE session. + * Determine the next UID from the folder's existing messages. */ - protected function done(): void + protected function getNextUid(): int { - $this->mailbox->connection()->done(); - } - - /** - * Begin a new IDLE session as a generator. - */ - protected function idle(CarbonInterface $ttl): Generator - { - yield from $this->mailbox->connection()->idle( - (int) Carbon::now()->diffInSeconds($ttl, true) - ); - } - - /** - * Get the next timeout as a Carbon instance. - */ - protected function getNextTimeout(): CarbonInterface|false - { - if (is_numeric($seconds = value($this->timeout))) { - return Carbon::now()->addSeconds(abs($seconds)); - } - - return false; + return ($this->folder->messages()->orderByUid('desc')->first()?->uid() ?? 0) + 1; } } diff --git a/src/Idle/Events/EventInterface.php b/src/Idle/Events/EventInterface.php new file mode 100644 index 00000000..5b78f279 --- /dev/null +++ b/src/Idle/Events/EventInterface.php @@ -0,0 +1,16 @@ +folder; + } + + /** + * Get the event type. + */ + public function type(): string + { + return 'SELECT'; + } + + /** + * Get the result of selecting the folder. + */ + public function selection(): Result + { + return $this->selection; + } +} diff --git a/src/Idle/Events/MessageExpunged.php b/src/Idle/Events/MessageExpunged.php new file mode 100644 index 00000000..66b70042 --- /dev/null +++ b/src/Idle/Events/MessageExpunged.php @@ -0,0 +1,14 @@ +response->type()->value; + } +} diff --git a/src/Idle/Events/MessageFetched.php b/src/Idle/Events/MessageFetched.php new file mode 100644 index 00000000..d505d0ec --- /dev/null +++ b/src/Idle/Events/MessageFetched.php @@ -0,0 +1,25 @@ +response->type()->value; + } + + /** + * Get the parsed message data from this FETCH response. + */ + public function changes(): FetchResult + { + return FetchResult::fromResponses(new ResponseCollection([$this->response])); + } +} diff --git a/src/Idle/Events/MessagesExist.php b/src/Idle/Events/MessagesExist.php new file mode 100644 index 00000000..1f578d09 --- /dev/null +++ b/src/Idle/Events/MessagesExist.php @@ -0,0 +1,14 @@ +response->type()->value; + } +} diff --git a/src/Idle/Events/MessagesVanished.php b/src/Idle/Events/MessagesVanished.php new file mode 100644 index 00000000..5da165bb --- /dev/null +++ b/src/Idle/Events/MessagesVanished.php @@ -0,0 +1,24 @@ +response)->uids(); + } + + /** + * Determine whether the server marked the VANISHED response as EARLIER. + */ + public function earlier(): bool + { + return Vanished::fromResponse($this->response)->earlier(); + } +} diff --git a/src/Idle/Events/ResponseEvent.php b/src/Idle/Events/ResponseEvent.php new file mode 100644 index 00000000..6c7e9096 --- /dev/null +++ b/src/Idle/Events/ResponseEvent.php @@ -0,0 +1,45 @@ +folder; + } + + /** + * Get the protocol response type. + */ + public function type(): string + { + return strtoupper( + $this->response->type() instanceof Number + ? $this->response->tokenAt(2)->value + : $this->response->type()->value + ); + } + + /** + * Get the original server response. + */ + public function response(): UntaggedResponse + { + return $this->response; + } +} diff --git a/src/Idle/Events/UnknownEvent.php b/src/Idle/Events/UnknownEvent.php new file mode 100644 index 00000000..7bd540e7 --- /dev/null +++ b/src/Idle/Events/UnknownEvent.php @@ -0,0 +1,5 @@ +process($this->uids()); } + /** + * {@inheritDoc} + */ + public function cursor(int $chunkSize = 10): Generator + { + $query = clone $this; + $uids = $query->uids(); + $chunkSize = max(1, $chunkSize); + + for ($page = 1; $page <= (int) ceil($uids->count() / $chunkSize); $page++) { + foreach ($query->limit($chunkSize, $page)->populate($uids) as $message) { + yield $message; + } + } + } + /** * {@inheritDoc} */ diff --git a/src/MessageQueryInterface.php b/src/MessageQueryInterface.php index d6b22397..7848a2e8 100644 --- a/src/MessageQueryInterface.php +++ b/src/MessageQueryInterface.php @@ -11,6 +11,7 @@ use DirectoryTree\ImapEngine\Enums\SortDirection; use DirectoryTree\ImapEngine\MessageData\FetchItemInterface; use DirectoryTree\ImapEngine\Pagination\LengthAwarePaginator; +use Generator; /** * @mixin ImapQueryBuilder @@ -94,6 +95,15 @@ public function firstOrFail(): MessageInterface; */ public function get(): MessageCollection; + /** + * Yield matching messages with at most the given number per FETCH request. + * + * The matching UIDs are loaded once. Query pagination is not applied. + * + * @return Generator + */ + public function cursor(int $chunkSize = 10): Generator; + /** * Get messages changed after the given modification sequence. * diff --git a/src/Poll.php b/src/Poll.php index 76d5617c..e47c8ec8 100644 --- a/src/Poll.php +++ b/src/Poll.php @@ -5,13 +5,20 @@ use Closure; use DirectoryTree\ImapEngine\Exceptions\Exception; use DirectoryTree\ImapEngine\Exceptions\ImapConnectionClosedException; +use DirectoryTree\ImapEngine\Selection\Result; +use Generator; class Poll { /** - * The last seen message UID. + * The first UID that has not yet been delivered. */ - protected ?int $lastSeenUid = null; + protected ?int $nextUid = null; + + /** + * The polling connection's latest folder selection. + */ + protected ?Result $selection = null; /** * Constructor. @@ -23,23 +30,33 @@ public function __construct( ) {} /** - * Destructor. + * Poll for new messages at a given frequency. */ - public function __destruct() + public function start(callable $callback, callable $query): void { - $this->disconnect(); + try { + foreach ($this->messages($query) as $message) { + if ($callback($message) === false) { + break; + } + } + } finally { + $this->disconnect(); + } } /** - * Poll for new messages at a given frequency. + * Yield arrivals, reconnecting when the polling connection is lost. + * + * @return Generator */ - public function start(callable $callback, callable $query): void + protected function messages(callable $query): Generator { $this->connect(); while ($frequency = $this->getNextFrequency()) { try { - $this->check($callback, $query); + yield from $this->check($query); } catch (ImapConnectionClosedException) { $this->reconnect(); } @@ -49,36 +66,33 @@ public function start(callable $callback, callable $query): void } /** - * Check for new messages since the last seen UID. + * Check for new messages since the last delivered UID. + * + * @return Generator */ - protected function check(callable $callback, callable $query): void + protected function check(callable $query): Generator { $folder = $this->folder(); - // If we don't have a last seen UID, we will fetch - // the last one in the folder as a starting point. - if (! $this->lastSeenUid) { - $this->lastSeenUid = $folder->messages() - ->first() - ?->uid() ?? 0; + $this->select($folder); - return; - } + $messages = $query($folder->messages()->with(MessageData::flags())) + ->uid($this->nextUid.':*') + ->orderByUid() + ->cursor(); - $query($folder->messages()) - ->uid($this->lastSeenUid + 1, INF) - ->each(function (MessageInterface $message) use ($callback) { - // Avoid processing the same message twice on subsequent polls. - // Some IMAP servers will always return the last seen UID in - // the search results regardless of given UID search range. - if ($this->lastSeenUid === $message->uid()) { - return; - } + foreach ($messages as $message) { + // Avoid processing the same message twice on subsequent polls. + // Some IMAP servers will always return the last seen UID in + // the search results regardless of given UID search range. + if ($message->uid() < $this->nextUid) { + continue; + } - $callback($message); + yield $message; - $this->lastSeenUid = $message->uid(); - }); + $this->nextUid = $message->uid() + 1; + } } /** @@ -106,7 +120,29 @@ protected function connect(): void { $this->mailbox->connect(); - $this->mailbox->select($this->folder(), true); + $this->select($this->folder()); + } + + /** + * Select the folder and reset the arrival cursor when UID validity changes. + */ + protected function select(FolderInterface $folder): void + { + $selection = $folder->select(true); + + if ($this->selection === null || $this->selection->uidValidity() !== $selection->uidValidity()) { + $this->nextUid = $selection->uidNext() ?? $this->getNextUid($folder); + } + + $this->selection = $selection; + } + + /** + * Determine the next UID from the folder's existing messages. + */ + protected function getNextUid(FolderInterface $folder): int + { + return ($folder->messages()->orderByUid('desc')->first()?->uid() ?? 0) + 1; } /** diff --git a/src/Testing/FakeFolder.php b/src/Testing/FakeFolder.php index 378690e2..76273a94 100644 --- a/src/Testing/FakeFolder.php +++ b/src/Testing/FakeFolder.php @@ -5,6 +5,8 @@ use DirectoryTree\ImapEngine\ComparesFolders; use DirectoryTree\ImapEngine\Exceptions\Exception; use DirectoryTree\ImapEngine\FolderInterface; +use DirectoryTree\ImapEngine\Idle\Events\EventInterface; +use DirectoryTree\ImapEngine\Idle\Events\FolderSelected; use DirectoryTree\ImapEngine\MailboxInterface; use DirectoryTree\ImapEngine\MessageQueryInterface; use DirectoryTree\ImapEngine\Selection\OptionInterface; @@ -22,6 +24,13 @@ class FakeFolder implements FolderInterface */ protected array $vanished = []; + /** + * The mailbox events to deliver while idling. + * + * @var EventInterface[] + */ + protected array $idleEvents = []; + /** * The next UID assigned to an appended message. */ @@ -107,10 +116,37 @@ public function messages(): MessageQueryInterface /** * {@inheritDoc} */ - public function idle(callable $callback, ?callable $query = null, callable|int $timeout = 300): void + public function events(callable $callback, callable|int $timeout = 300, OptionInterface ...$options): void + { + if (! is_numeric($seconds = is_callable($timeout) ? $timeout() : $timeout) || $seconds <= 0) { + return; + } + + $selection = new FolderSelected($this->path, $this->select(true, ...$options)); + + foreach ([$selection, ...$this->idleEvents] as $event) { + if ($callback($event) === false) { + break; + } + } + } + + /** + * {@inheritDoc} + */ + public function idle(callable $callback, ?callable $query = null, callable|int $timeout = 300, OptionInterface ...$options): void { - foreach ($this->messages as $message) { - $callback($message); + if (! is_numeric($seconds = is_callable($timeout) ? $timeout() : $timeout) || $seconds <= 0) { + return; + } + + $messages = $this->messages(); + $messages = $query ? $query($messages) : $messages; + + foreach ($messages->orderByUid()->cursor() as $message) { + if ($callback($message) === false) { + break; + } } } @@ -119,8 +155,17 @@ public function idle(callable $callback, ?callable $query = null, callable|int $ */ public function poll(callable $callback, ?callable $query = null, callable|int $frequency = 60): void { - foreach ($this->messages as $message) { - $callback($message); + if (! is_numeric($seconds = is_callable($frequency) ? $frequency() : $frequency) || $seconds <= 0) { + return; + } + + $messages = $this->messages(); + $messages = $query ? $query($messages) : $messages; + + foreach ($messages->orderByUid()->cursor() as $message) { + if ($callback($message) === false) { + break; + } } } @@ -239,6 +284,18 @@ public function setMessages(array $messages): FakeFolder return $this; } + /** + * Set the events delivered after the initial folder selection. + * + * @param EventInterface[] $events + */ + public function setIdleEvents(array $events): FakeFolder + { + $this->idleEvents = $events; + + return $this; + } + /** * Get the folder's fake messages. * diff --git a/src/Testing/FakeMessageQuery.php b/src/Testing/FakeMessageQuery.php index 22ef1eef..a2140654 100644 --- a/src/Testing/FakeMessageQuery.php +++ b/src/Testing/FakeMessageQuery.php @@ -21,6 +21,7 @@ use DirectoryTree\ImapEngine\QueriesMessages; use DirectoryTree\ImapEngine\UidOrder; use DirectoryTree\ImapEngine\Vanished; +use Generator; use Illuminate\Support\ItemNotFoundException; use InvalidArgumentException; @@ -48,6 +49,14 @@ public function get(): MessageCollection )); } + /** + * {@inheritDoc} + */ + public function cursor(int $chunkSize = 10): Generator + { + yield from $this->get(); + } + /** * {@inheritDoc} */ diff --git a/src/Watch.php b/src/Watch.php new file mode 100644 index 00000000..d0d25944 --- /dev/null +++ b/src/Watch.php @@ -0,0 +1,125 @@ +events() as $event) { + if ($callback($event) === false) { + break; + } + } + } finally { + $this->disconnect(); + } + } + + /** + * Yield folder selection and server response events without fetching messages. + * + * @return Generator + */ + protected function events(): Generator + { + $folder = null; + + while (is_numeric($seconds = value($this->timeout)) && $seconds > 0) { + $folder ??= $this->mailbox->folders()->findOrFail($this->folder); + + if (! $this->mailbox->selected($folder)) { + yield new FolderSelected($this->folder, $folder->select(true, ...$this->options)); + } + + $seconds = max((int) $seconds, 1); + + $session = $this->mailbox->connection()->idle(); + + try { + foreach ($session->responses($seconds) as $response) { + yield $this->toEvent($response); + } + } catch (ImapConnectionTimedOutException) { + // End the timed-out IDLE command before starting another. + } catch (ImapConnectionClosedException) { + $this->disconnect(); + + continue; + } + + try { + foreach ($session->finish($this->mailbox->config('timeout')) as $response) { + yield $this->toEvent($response); + } + } catch (ImapConnectionClosedException|ImapConnectionTimedOutException) { + $this->disconnect(); + } + } + } + + /** + * Convert an unsolicited response into a mailbox event. + */ + protected function toEvent(UntaggedResponse $response): ResponseEvent + { + $event = $response->type() instanceof Number + ? match (strtoupper($response->tokenAt(2)->value)) { + 'EXISTS' => MessagesExist::class, + 'FETCH' => MessageFetched::class, + 'EXPUNGE' => MessageExpunged::class, + default => UnknownEvent::class, + } + : match (strtoupper($response->type()->value)) { + 'VANISHED' => MessagesVanished::class, + default => UnknownEvent::class, + }; + + return new $event($this->folder, $response); + } + + /** + * Close the dedicated socket without sending commands during IDLE. + */ + protected function disconnect(): void + { + if ($this->mailbox->connected()) { + $this->mailbox->connection()->disconnect(); + } + + $this->mailbox->disconnect(); + } +} diff --git a/tests/Unit/Connection/IdleTest.php b/tests/Unit/Connection/IdleTest.php new file mode 100644 index 00000000..595f316f --- /dev/null +++ b/tests/Unit/Connection/IdleTest.php @@ -0,0 +1,288 @@ +timeouts[] = $seconds; + + return true; + } + }; + $stream->feed(['* OK Welcome', '+ idling', '* 4 EXISTS', 'TAG1 OK IDLE completed']); + $connection = new ImapConnection($stream); + + try { + $connection->connect('localhost'); + $session = $connection->idle(); + + if ($consume) { + $responses = $session->responses(300); + $responses->current(); + Carbon::setTestNow(Carbon::now()->addSeconds(301)); + } + + $stream->timeouts = []; + $timeout === null ? $session->finish() : $session->finish($timeout); + + expect($stream->timeouts)->not->toBeEmpty(); + expect(array_unique($stream->timeouts))->toBe([$expected]); + expect($session->active())->toBeFalse(); + $stream->assertWritten('DONE'); + } finally { + $connection->disconnect(); + Carbon::setTestNow(); + } +})->with([ + 'default before continuation' => [null, 30, false], + 'short before continuation' => [5, 5, false], + 'long before continuation' => [90, 90, false], + 'short after renewal deadline' => [5, 5, true], + 'long after renewal deadline' => [90, 90, true], +]); + +test('an idle session owns the connection until it finishes', function () { + $stream = new FakeStream; + $stream->open(); + $stream->feed(['* OK Welcome', '+ idling', '* 4 EXISTS', 'TAG1 OK IDLE completed', 'TAG2 OK NOOP completed']); + $connection = new ImapConnection($stream); + $connection->connect('localhost'); + $session = $connection->idle(); + + expect(fn () => $connection->noop())->toThrow(LogicException::class); + expect(fn () => $connection->idle())->toThrow(LogicException::class); + + $responses = $session->responses(); + $responses->current(); + + expect(fn () => $connection->noop())->toThrow(LogicException::class); + expect($session->active())->toBeTrue(); + expect($session->finish())->toBeEmpty(); + expect($session->active())->toBeFalse(); + expect($connection->noop()->successful())->toBeTrue(); +}); + +test('a session can finish before its responses are consumed', function () { + $stream = new FakeStream; + $stream->open(); + $stream->feed(['* OK Welcome', '* 4 EXISTS', '+ idling', '* 3 EXPUNGE', 'TAG1 OK IDLE completed']); + $connection = new ImapConnection($stream); + $connection->connect('localhost'); + $session = $connection->idle(); + + expect($session->finish()->map(fn ($response) => (string) $response)->all())->toBe([ + '* 4 EXISTS', '* 3 EXPUNGE', + ]); + expect(iterator_to_array($session->responses()))->toBeEmpty(); + $stream->assertWritten('DONE'); +}); + +test('a session rejects competing response consumers', function () { + $stream = new FakeStream; + $stream->open(); + $stream->feed(['* OK Welcome', '+ idling', '* 4 EXISTS']); + $connection = new ImapConnection($stream); + $connection->connect('localhost'); + $session = $connection->idle(); + $responses = $session->responses(); + $responses->current(); + + expect(fn () => $session->responses()->current())->toThrow(LogicException::class); + $connection->disconnect(); +}); + +test('a disconnected session cannot consume responses from a new session', function () { + $stream = new FakeStream; + $stream->open(); + $stream->feed(['* OK Welcome', '+ idling', '* 4 EXISTS']); + $connection = new ImapConnection($stream); + $connection->connect('localhost'); + $session = $connection->idle(); + $responses = $session->responses(); + $responses->current(); + $connection->disconnect(); + + $stream->feed(['* OK Welcome back', '+ idling', '* 5 EXISTS', 'TAG2 OK IDLE completed']); + $connection->connect('localhost'); + $nextSession = $connection->idle(); + + expect($session->active())->toBeFalse(); + expect($session->finish())->toBeEmpty(); + $responses->next(); + expect($responses->valid())->toBeFalse(); + expect($nextSession->finish()->map(fn ($response) => (string) $response)->all())->toBe(['* 5 EXISTS']); +}); + +test('a missing done acknowledgement invalidates the session and closes the connection', function () { + $stream = new FakeStream; + $stream->open(); + $stream->feed(['* OK Welcome', '+ idling', '* 4 EXISTS']); + $connection = new ImapConnection($stream); + $connection->connect('localhost'); + $session = $connection->idle(); + $responses = $session->responses(); + $responses->current(); + $stream->setMeta('timed_out', true); + + expect(fn () => $session->finish())->toThrow(ImapConnectionTimedOutException::class); + expect($session->active())->toBeFalse(); + expect($connection->connected())->toBeFalse(); + expect($session->finish())->toBeEmpty(); + $stream->assertWritten('DONE'); +}); + +test('idle preserves updates before continuation and while ending', function () { + $stream = new FakeStream; + $stream->open(); + $stream->feed([ + '* OK Welcome', + '* 4 EXISTS', + '+ idling', + '* 2 FETCH (FLAGS (\\Seen))', + '* 3 EXPUNGE', + '* VANISHED 8:9', + 'TAG1 OK IDLE completed', + 'TAG2 OK NOOP completed', + ]); + $connection = new ImapConnection($stream); + $connection->connect('localhost'); + $session = $connection->idle(); + $idle = $session->responses(30); + + expect((string) $idle->current())->toBe('* 4 EXISTS'); + $idle->next(); + expect((string) $idle->current())->toBe('* 2 FETCH (FLAGS (\\Seen))'); + + $pending = $session->finish(); + expect($pending->map(fn ($response) => (string) $response)->all())->toBe([ + '* 3 EXPUNGE', '* VANISHED 8:9', + ]); + expect($connection->noop()->successful())->toBeTrue(); + expect($session->finish())->toBeEmpty(); + $stream->assertWritten('DONE'); + $stream->assertWritten('TAG2 NOOP'); +}); + +test('idle rejection is reported immediately', function () { + $stream = new FakeStream; + $stream->open(); + $stream->feed(['* OK Welcome', 'TAG1 NO IDLE unavailable']); + $connection = new ImapConnection($stream); + $connection->connect('localhost'); + + $session = $connection->idle(); + + expect(fn () => iterator_to_array($session->responses(30)))->toThrow(ImapCommandException::class); + $stream->assertNotWritten('DONE'); +}); + +test('idle reports server shutdown as a closed connection', function () { + $stream = new FakeStream; + $stream->open(); + $stream->feed(['* OK Welcome', '+ idling', '* BYE Server shutting down']); + $connection = new ImapConnection($stream); + $connection->connect('localhost'); + + $session = $connection->idle(); + + expect(fn () => iterator_to_array($session->responses(30)))->toThrow(ImapConnectionClosedException::class); + expect($session->finish())->toBeEmpty(); +}); + +test('idle responses retain distinct generator keys across continuation', function () { + $stream = new FakeStream; + $stream->open(); + $stream->feed([ + '* OK Welcome', '* 4 EXISTS', '+ idling', '* 3 EXPUNGE', 'TAG1 OK IDLE completed', + ]); + $connection = new ImapConnection($stream); + $connection->connect('localhost'); + + $session = $connection->idle(); + $responses = iterator_to_array($session->responses(30)); + + expect(array_map(fn ($response) => (string) $response, $responses))->toBe([ + '* 4 EXISTS', '* 3 EXPUNGE', + ]); +}); + +test('idle can finish after a read timeout without losing queued changes', function () { + $stream = new FakeStream; + $stream->open(); + $stream->feed(['* OK Welcome', '+ idling', '* 4 EXISTS']); + $connection = new ImapConnection($stream); + $connection->connect('localhost'); + $session = $connection->idle(); + $idle = $session->responses(30); + $idle->current(); + $stream->setMeta('timed_out', true); + + expect(fn () => $idle->next())->toThrow(ImapConnectionTimedOutException::class); + + $stream->setMeta('timed_out', false); + $stream->feed(['* 3 EXPUNGE', 'TAG1 OK IDLE completed']); + + expect((string) $session->finish()->first())->toBe('* 3 EXPUNGE'); + $stream->assertWritten('DONE'); +}); + +test('a timeout before continuation closes the ambiguous session', function () { + $stream = new FakeStream; + $stream->open(); + $stream->feed('* OK Welcome'); + $connection = new ImapConnection($stream); + $connection->connect('localhost'); + $stream->setMeta('timed_out', true); + + $session = $connection->idle(); + + expect(fn () => iterator_to_array($session->responses(30)))->toThrow(ImapConnectionClosedException::class); + expect($connection->connected())->toBeFalse(); + expect($session->finish())->toBeEmpty(); + $stream->assertNotWritten('DONE'); +}); + +test('failed idle completion is surfaced by finish', function () { + $stream = new FakeStream; + $stream->open(); + $stream->feed(['* OK Welcome', '+ idling', '* 4 EXISTS', 'TAG1 NO IDLE failed']); + $connection = new ImapConnection($stream); + $connection->connect('localhost'); + $session = $connection->idle(); + $idle = $session->responses(30); + $idle->current(); + + expect(fn () => $session->finish())->toThrow(ImapCommandException::class); + expect($session->finish())->toBeEmpty(); +}); + +test('finish preserves pre-continuation updates not yet consumed by the generator', function () { + $stream = new FakeStream; + $stream->open(); + $stream->feed([ + '* OK Welcome', '* 4 EXISTS', '* 2 EXPUNGE', '+ idling', + '* 3 EXISTS', 'TAG1 OK IDLE completed', + ]); + $connection = new ImapConnection($stream); + $connection->connect('localhost'); + $session = $connection->idle(); + $idle = $session->responses(30); + + expect((string) $idle->current())->toBe('* 4 EXISTS'); + expect($session->finish()->map(fn ($response) => (string) $response)->all())->toBe([ + '* 2 EXPUNGE', '* 3 EXISTS', + ]); + $idle->next(); + expect($idle->valid())->toBeFalse(); +}); diff --git a/tests/Unit/Connection/ImapConnectionTest.php b/tests/Unit/Connection/ImapConnectionTest.php index 2ed9cf80..2096397a 100644 --- a/tests/Unit/Connection/ImapConnectionTest.php +++ b/tests/Unit/Connection/ImapConnectionTest.php @@ -4,10 +4,11 @@ use DirectoryTree\ImapEngine\Authentication; use DirectoryTree\ImapEngine\Authentication\XOAuth2; use DirectoryTree\ImapEngine\Connection\ImapConnection; +use DirectoryTree\ImapEngine\Connection\Loggers\LoggerInterface; +use DirectoryTree\ImapEngine\Connection\Responses\UntaggedResponse; use DirectoryTree\ImapEngine\Connection\Streams\FakeStream; use DirectoryTree\ImapEngine\Enums\ImapIdentifier; use DirectoryTree\ImapEngine\Exceptions\ImapCommandException; -use DirectoryTree\ImapEngine\Exceptions\ImapConnectionException; use DirectoryTree\ImapEngine\Exceptions\ImapConnectionFailedException; use DirectoryTree\ImapEngine\Fetch\ChangedSince; use DirectoryTree\ImapEngine\Fetch\ModifierInterface; @@ -15,6 +16,65 @@ use DirectoryTree\ImapEngine\StoreResult; use DirectoryTree\ImapEngine\Support\Str; +test('connection reads parsed replies and logs protocol lines with optional redaction', function () { + $stream = new FakeStream; + $stream->feed(['* OK Welcome', '* 4 EXISTS']); + $logger = new class implements LoggerInterface + { + public array $sent = []; + + public array $received = []; + + public function sent(string $message): void + { + $this->sent[] = $message; + } + + public function received(string $message): void + { + $this->received[] = $message; + } + }; + $connection = new ImapConnection($stream, $logger); + $connection->connect('localhost'); + + $connection->write('DONE'); + $connection->write('secret', sensitive: true); + $response = $connection->read(); + + expect($response)->toBeInstanceOf(UntaggedResponse::class); + expect((string) $response)->toBe('* 4 EXISTS'); + expect($logger->sent)->toBe(['DONE', '[redacted]']); + expect($logger->received)->toBe(['* OK Welcome', '* 4 EXISTS']); + $stream->assertWritten("DONE\r\n"); + $stream->assertWritten("secret\r\n"); + $connection->disconnect(); +}); + +test('connection exposes its underlying stream for transport settings', function (bool $result) { + $stream = new class($result) extends FakeStream + { + public ?int $timeout = null; + + public function __construct(protected bool $result) {} + + public function setTimeout(int $seconds): bool + { + $this->timeout = $seconds; + + return $this->result; + } + }; + $connection = new ImapConnection($stream); + + expect($connection->stream())->toBe($stream); + expect($connection->stream()->setTimeout(120))->toBe($result); + expect($stream->timeout)->toBe(120); +})->with([ + 'accepted' => true, + 'rejected' => false, +]); + test('connect success', function () { $stream = new FakeStream; @@ -183,13 +243,19 @@ $stream->feed([ '* OK Welcome to IMAP', + '+ idling', + '* 1 EXISTS', 'TAG1 OK Completed', ]); $connection = new ImapConnection($stream); $connection->connect('imap.example.com'); - $connection->done(); + $session = $connection->idle(); + $idle = $session->responses(30); + $idle->current(); + + expect($session->finish())->toBeEmpty(); $stream->assertWritten('DONE'); }); @@ -874,9 +940,7 @@ $connection = new ImapConnection($stream); $connection->connect('imap.example.com'); - expect(function () use ($connection) { - iterator_to_array($connection->idle(30)); - })->toThrow(ImapConnectionException::class); + expect(iterator_to_array($connection->idle()->responses(30)))->toBeEmpty(); $stream->assertWritten('TAG1 IDLE'); }); diff --git a/tests/Unit/FolderTest.php b/tests/Unit/FolderTest.php index c0210158..adb109ba 100644 --- a/tests/Unit/FolderTest.php +++ b/tests/Unit/FolderTest.php @@ -1,11 +1,193 @@ feed([ + '* OK Welcome', 'TAG1 OK LOGIN completed', + '* CAPABILITY IMAP4rev1 IDLE', 'TAG2 OK CAPABILITY completed', + '* OK [UIDVALIDITY 1]', '* OK [UIDNEXT 10]', 'TAG3 OK SELECT completed', + '* SEARCH 7 9', 'TAG4 OK SEARCH completed', + '* 2 FETCH (UID 7 FLAGS (\\Seen))', '* 3 FETCH (UID 9 FLAGS ())', 'TAG5 OK FETCH completed', + ]); + $watching = new FakeStream; + $watching->feed([ + '* OK Welcome', 'TAG1 OK LOGIN completed', + '* LIST () "/" "INBOX"', 'TAG2 OK LIST completed', + '* 1 EXISTS', '* OK [UIDVALIDITY 1]', '* OK [UIDNEXT 7]', 'TAG3 OK SELECT completed', + '+ idling', '* 3 EXISTS', + ]); + $mailbox = new class([$application, $watching]) extends Mailbox + { + public function __construct(protected array $streams) + { + parent::__construct(); + } + + public function connect(?ConnectionInterface $connection = null): void + { + parent::connect($connection ?? new ImapConnection(array_shift($this->streams))); + } + }; + $folder = new Folder($mailbox, 'INBOX'); + $received = []; + $uids = []; + + try { + if ($retrieve) { + $folder->idle(function (MessageInterface $message) use (&$uids) { + $uids[] = $message->uid(); + + return $message->uid() !== 9; + }, function (MessageQuery $query) { + return $query->seen(); + }); + } else { + $folder->events(function (EventInterface $event) use (&$received, $application) { + $received[] = $event::class; + $application->assertNotWritten('SELECT'); + $application->assertNotWritten('SEARCH'); + $application->assertNotWritten('FETCH'); + + return ! $event instanceof MessagesExist; + }); + } + + expect($received)->toBe($retrieve ? [] : [FolderSelected::class, MessagesExist::class]); + expect($uids)->toBe($retrieve ? [7, 9] : []); + expect($application->opened())->toBeTrue(); + expect($watching->opened())->toBeFalse(); + if ($retrieve) { + $application->assertWritten('UID FETCH'); + $application->assertWritten('SEEN'); + } else { + $application->assertNotWritten('UID FETCH'); + } + $watching->assertNotWritten('FETCH'); + $watching->assertNotWritten('LOGOUT'); + } finally { + $mailbox->connection()->disconnect(); + $mailbox->disconnect(); + } +})->with(['retrieve arrivals' => true, 'observe count only' => false]); + +test('folder idle preserves or replaces the arrival cursor after reconnecting', function (int $validity, int $uidNext, int $expectedUid) { + $application = new FakeStream; + $application->feed([ + '* OK Welcome', 'TAG1 OK LOGIN completed', + '* CAPABILITY IMAP4rev1 IDLE', 'TAG2 OK CAPABILITY completed', + "* OK [UIDVALIDITY {$validity}]", 'TAG3 OK SELECT completed', + "* SEARCH {$expectedUid}", 'TAG4 OK SEARCH completed', + "* 2 FETCH (UID {$expectedUid} FLAGS ())", 'TAG5 OK FETCH completed', + ]); + $watching = new FakeStream; + $watching->feed([ + '* OK Welcome', 'TAG1 OK LOGIN completed', + '* LIST () "/" "INBOX"', 'TAG2 OK LIST completed', + '* 1 EXISTS', '* OK [UIDVALIDITY 1]', '* OK [UIDNEXT 7]', 'TAG3 OK SELECT completed', + '+ idling', '* BYE Restarting', + ]); + $reconnected = new FakeStream; + $reconnected->feed([ + '* OK Welcome', 'TAG1 OK LOGIN completed', + '* 2 EXISTS', "* OK [UIDVALIDITY {$validity}]", "* OK [UIDNEXT {$uidNext}]", 'TAG2 OK SELECT completed', + '+ idling', '* 3 EXISTS', + ]); + $mailbox = new class([$application, $watching, $reconnected]) extends Mailbox + { + public function __construct(protected array $streams) + { + parent::__construct(); + } + + public function connect(?ConnectionInterface $connection = null): void + { + parent::connect($connection ?? new ImapConnection(array_shift($this->streams))); + } + }; + $folder = new Folder($mailbox, 'INBOX'); + $uids = []; + $attempts = 0; + + try { + $folder->idle(function (MessageInterface $message) use (&$uids) { + $uids[] = $message->uid(); + + return false; + }, timeout: function () use (&$attempts) { + return ++$attempts <= 2 ? 300 : false; + }); + + expect($uids)->toBe([$expectedUid]); + $start = $validity === 1 ? 7 : $uidNext; + $application->assertWritten("UID SEARCH UID {$start}:*"); + $watching->assertNotWritten('FETCH'); + $reconnected->assertNotWritten('FETCH'); + } finally { + $mailbox->connection()->disconnect(); + $mailbox->disconnect(); + } +})->with([ + 'same validity preserves the cursor' => [1, 10, 9], + 'changed validity replaces the cursor' => [2, 3, 3], +]); + +test('folder polling propagates callback exceptions', function (string $exceptionClass) { + $application = new FakeStream; + $application->feed(['* OK Welcome', 'TAG1 OK LOGIN completed']); + $polling = new FakeStream; + $polling->feed([ + '* OK Welcome', 'TAG1 OK LOGIN completed', + '* LIST () "/" "INBOX"', 'TAG2 OK LIST completed', + '* OK [UIDNEXT 2]', 'TAG3 OK SELECT completed', + '* LIST () "/" "INBOX"', 'TAG4 OK LIST completed', + '* OK [UIDNEXT 3]', 'TAG5 OK SELECT completed', + '* SEARCH 2', 'TAG6 OK SEARCH completed', + '* 2 FETCH (UID 2 FLAGS ())', 'TAG7 OK FETCH completed', + ]); + $mailbox = new class([$application, $polling]) extends Mailbox + { + public function __construct(protected array $streams) + { + parent::__construct(); + } + + public function connect(?ConnectionInterface $connection = null): void + { + parent::connect($connection ?? new ImapConnection(array_shift($this->streams))); + } + }; + $mailbox->connect(); + $folder = new Folder($mailbox, 'INBOX'); + $exception = new $exceptionClass('Application callback failed'); + + try { + expect(fn () => $folder->poll(function () use ($exception) { + throw $exception; + }, frequency: 1))->toThrow($exception); + } finally { + $mailbox->connection()->disconnect(); + $mailbox->disconnect(); + } +})->with([ + RuntimeException::class, + Exception::class, + ImapConnectionClosedException::class, +]); test('it examines a folder using the typed selection result', function () { $mailbox = Mailbox::make(); diff --git a/tests/Unit/IdleEventTest.php b/tests/Unit/IdleEventTest.php new file mode 100644 index 00000000..a482e4ad --- /dev/null +++ b/tests/Unit/IdleEventTest.php @@ -0,0 +1,203 @@ +open(); + $stream->feed([ + '* 10 EXISTS', + '* 3 EXPUNGE', + '* 2 FETCH (UID 42 FLAGS (\\Seen) MODSEQ (99))', + '* VANISHED (EARLIER) 7:9', + '* 4 FETCH (FLAGS (\\Flagged))', + ]); + $parser = new ImapParser(new ImapTokenizer($stream)); + + $exists = new MessagesExist('INBOX', $parser->next()); + expect($exists)->toBeInstanceOf(MessagesExist::class); + expect($exists->type())->toBe('EXISTS'); + expect($exists->count())->toBe(10); + expect($exists->folder())->toBe('INBOX'); + + $expunge = new MessageExpunged('INBOX', $parser->next()); + expect($expunge)->toBeInstanceOf(MessageExpunged::class); + expect($expunge->type())->toBe('EXPUNGE'); + expect($expunge->sequenceNumber())->toBe(3); + + $fetch = new MessageFetched('INBOX', $parser->next()); + expect($fetch)->toBeInstanceOf(MessageFetched::class); + expect($fetch->changes()->messages()[0]->uid())->toBe(42); + expect($fetch->sequenceNumber())->toBe(2); + + $vanished = new MessagesVanished('INBOX', $parser->next()); + expect($vanished)->toBeInstanceOf(MessagesVanished::class); + expect($vanished->type())->toBe('VANISHED'); + expect($vanished->uids())->toBe([7, 8, 9]); + expect($vanished->earlier())->toBeTrue(); + + $flags = new MessageFetched('INBOX', $parser->next()); + expect($flags)->toBeInstanceOf(MessageFetched::class); + expect($flags->changes()->messages()[0]->has('UID'))->toBeFalse(); + expect($flags->sequenceNumber())->toBe(4); + expect($flags->response())->not->toBeNull(); +}); + +test('selection events expose the reconciliation metadata', function () { + $event = new FolderSelected('INBOX', $selection = new Result(uidValidity: 777, uidNext: 43)); + + expect($event->type())->toBe('SELECT'); + expect($event->selection())->toBe($selection); + expect($event->selection()->uidValidity())->toBe(777); + expect($event->folder())->toBe('INBOX'); +}); + +test('watcher converts responses into typed events preserving response identity', function (string $line, string $class, string $type) { + $stream = new FakeStream; + $stream->open(); + $stream->feed($line); + $parser = new ImapParser(new ImapTokenizer($stream)); + $response = $parser->next(); + + $watch = new class(new Mailbox, 'Archive', 30) extends Watch + { + public function toEvent(UntaggedResponse $response): ResponseEvent + { + return parent::toEvent($response); + } + }; + $event = $watch->toEvent($response); + + expect($event)->toBeInstanceOf($class)->toBeInstanceOf(EventInterface::class); + expect($event->folder())->toBe('Archive'); + expect($event->type())->toBe($type); + expect($event->response())->toBe($response); +})->with([ + 'empty mailbox' => ['* 0 EXISTS', MessagesExist::class, 'EXISTS'], + 'fetch update' => ['* 2 FETCH (FLAGS (\\Seen))', MessageFetched::class, 'FETCH'], + 'expunged message' => ['* 3 EXPUNGE', MessageExpunged::class, 'EXPUNGE'], + 'vanished messages' => ['* VANISHED 7:9', MessagesVanished::class, 'VANISHED'], + 'numbered unmodeled response' => ['* 2 RECENT', UnknownEvent::class, 'RECENT'], + 'status response' => ['* OK [ALERT] Maintenance soon', UnknownEvent::class, 'OK'], + 'extension response' => ['* X-NOTICE changed', UnknownEvent::class, 'X-NOTICE'], +]); + +test('vanished events distinguish earlier changes from live changes', function (string $line, bool $earlier) { + $stream = new FakeStream; + $stream->open(); + $stream->feed($line); + $parser = new ImapParser(new ImapTokenizer($stream)); + + $event = new MessagesVanished('INBOX', $parser->next()); + + expect($event)->toBeInstanceOf(MessagesVanished::class); + expect($event->uids())->toBe([7, 8, 9, 12]); + expect($event->earlier())->toBe($earlier); +})->with([ + 'live removal' => ['* VANISHED 7:9,12', false], + 'checkpoint replay' => ['* VANISHED (EARLIER) 7:9,12', true], +]); + +test('fake folders let selection callbacks query configured messages without supplying events', function () { + $folder = new FakeFolder('INBOX', messages: [ + $first = new FakeMessage(7, flags: ['\\Seen']), + $second = new FakeMessage(8), + ]); + $received = []; + $messages = []; + + $folder->events(function (EventInterface $event) use ($folder, &$received, &$messages) { + $received[] = $event; + + if ($event instanceof FolderSelected) { + $messages = $folder->messages()->orderByUid()->get()->all(); + } + }); + + expect($received)->toHaveCount(1); + expect($received[0])->toBeInstanceOf(FolderSelected::class); + expect($received[0]->folder())->toBe('INBOX'); + expect($messages)->toBe([$first, $second]); +}); + +test('fake folder event callbacks can query messages explicitly', function () { + $message = new FakeMessage(7, flags: ['\\Seen']); + $event = new MessagesExist('INBOX', new UntaggedResponse([ + new Atom('*'), new Number('10'), new Atom('EXISTS'), + ])); + $folder = (new FakeFolder('INBOX', messages: [$message]))->setIdleEvents([$event]); + $received = []; + + $folder->events(function (EventInterface $event) use ($folder, &$received) { + if ($event instanceof MessagesExist) { + $folder->messages()->get()->each(function ($message) use (&$received) { + $received[] = $message; + }); + + return false; + } + }); + + expect($received)->toBe([$message]); + expect($event->folder())->toBe('INBOX'); + expect($event->type())->toBe('EXISTS'); + expect($event->count())->toBe(10); +}); + +test('fake folders deliver supplied events and stop when requested', function () { + $folder = (new FakeFolder('INBOX'))->setIdleEvents([ + $first = new FolderSelected('INBOX', new Result(uidNext: 2)), + new FolderSelected('INBOX', new Result(uidNext: 3)), + ]); + $received = []; + + $folder->events(function (EventInterface $event) use (&$received, $first) { + $received[] = $event; + + return $event !== $first; + }); + + expect($received)->toHaveCount(2); + expect($received[0])->toBeInstanceOf(FolderSelected::class); + expect($received[1])->toBe($first); +}); + +test('fake folder idle delivers configured messages and supports query customization and stopping', function () { + $folder = new FakeFolder('INBOX', messages: [new FakeMessage(9), $first = new FakeMessage(7)]); + $received = []; + $queried = false; + + $folder->idle(function (MessageInterface $message) use (&$received) { + $received[] = $message; + + return false; + }, function (MessageQueryInterface $query) use (&$queried) { + $queried = true; + + return $query->with(MessageData::flags()); + }); + + expect($queried)->toBeTrue(); + expect($received)->toBe([$first]); +}); diff --git a/tests/Unit/IdleTest.php b/tests/Unit/IdleTest.php new file mode 100644 index 00000000..7135cfb2 --- /dev/null +++ b/tests/Unit/IdleTest.php @@ -0,0 +1,76 @@ +connect($connection); + $folder = new class($mailbox, 'INBOX', $uidNext, $notifications) extends Folder + { + public function __construct(Mailbox $mailbox, string $path, protected ?int $uidNext, protected int $notifications) + { + parent::__construct($mailbox, $path); + } + + public function events(callable $callback, callable|int $timeout = 300, OptionInterface ...$options): void + { + $callback(new FolderSelected($this->path, new Result(uidValidity: 1, uidNext: $this->uidNext))); + + for ($i = 0; $i < $this->notifications; $i++) { + if ($callback(new MessagesExist($this->path, new UntaggedResponse([ + new Atom('*'), new Number('3'), new Atom('EXISTS'), + ]))) === false) { + break; + } + } + } + }; + $received = []; + + $folder->idle(function (MessageInterface $message) use (&$received) { + $received[] = $message->uid(); + }); + + expect($received)->toBe($expected); + $connection->stream()->assertNotWritten('BODY['); + $connection->disconnect(); +})->with([ + 'multiple arrivals and duplicate count notification' => [7, 2, [ + '* OK [UIDVALIDITY 1]', 'TAG2 OK SELECT completed', + '* SEARCH 7 9', 'TAG3 OK SEARCH completed', + '* 3 FETCH (UID 9 FLAGS ())', '* 2 FETCH (UID 7 FLAGS ())', 'TAG4 OK FETCH completed', + '* OK [UIDVALIDITY 1]', 'TAG5 OK SELECT completed', + '* SEARCH 9', 'TAG6 OK SEARCH completed', + '* 3 FETCH (UID 9 FLAGS ())', 'TAG7 OK FETCH completed', + ], [7, 9]], + 'message removed before fetch' => [7, 1, [ + '* OK [UIDVALIDITY 1]', 'TAG2 OK SELECT completed', + '* SEARCH 7', 'TAG3 OK SEARCH completed', 'TAG4 OK FETCH completed', + ], []], + 'application connection has different uid validity' => [7, 1, [ + '* OK [UIDVALIDITY 2]', 'TAG2 OK SELECT completed', + ], []], + 'missing uidnext snapshots existing messages' => [null, 1, [ + '* OK [UIDVALIDITY 1]', 'TAG2 OK SELECT completed', + '* SEARCH 2 6', 'TAG3 OK SEARCH completed', + '* OK [UIDVALIDITY 1]', 'TAG4 OK SELECT completed', + '* SEARCH 7', 'TAG5 OK SEARCH completed', + '* 3 FETCH (UID 7 FLAGS ())', 'TAG6 OK FETCH completed', + ], [7]], + 'initially empty folder delivers its first arrival' => [1, 1, [ + '* OK [UIDVALIDITY 1]', 'TAG2 OK SELECT completed', + '* SEARCH 1', 'TAG3 OK SEARCH completed', + '* 1 FETCH (UID 1 FLAGS ())', 'TAG4 OK FETCH completed', + ], [1]], +]); diff --git a/tests/Unit/MessageCursorTest.php b/tests/Unit/MessageCursorTest.php new file mode 100644 index 00000000..4b873305 --- /dev/null +++ b/tests/Unit/MessageCursorTest.php @@ -0,0 +1,39 @@ +connect($connection); + $query = (new Folder($mailbox, 'INBOX'))->messages()->with(MessageData::flags())->orderByUid()->limit(1, 3); + $cursor = $query->cursor(2); + $connection->stream()->assertNotWritten('SEARCH'); + $received = []; + + foreach ($cursor as $key => $message) { + $received[$key] = $message->uid(); + if ($stopEarly) { + break; + } + } + + expect($received)->toBe($stopEarly ? [1] : [1, 2, 3]); + expect($query->getLimit())->toBe(1); + expect($query->getPage())->toBe(3); + $connection->stream()->assertWritten('UID FETCH 1:2'); + if ($stopEarly) { + $connection->stream()->assertNotWritten('UID FETCH 3'); + } else { + $connection->stream()->assertWritten('UID FETCH 3'); + } + $connection->disconnect(); +})->with(['all batches' => false, 'early stop' => true]); diff --git a/tests/Unit/PollTest.php b/tests/Unit/PollTest.php new file mode 100644 index 00000000..83a98791 --- /dev/null +++ b/tests/Unit/PollTest.php @@ -0,0 +1,138 @@ +disconnected = true; + } + + protected function connect(): void {} + + protected function check(callable $query): Generator + { + yield new FakeMessage(1); + } + + protected function reconnect(): void + { + $this->reconnects++; + throw new RuntimeException('Unexpected reconnect'); + } + }; + $exception = new $exceptionClass('Callback failed'); + + expect(fn () => $poll->start(function () use ($exception) { + throw $exception; + }, fn ($query) => $query))->toThrow($exception); + expect($poll->reconnects)->toBe(0); + expect($poll->disconnected)->toBeTrue(); +})->with([RuntimeException::class, Exception::class, ImapConnectionClosedException::class]); + +test('poll still reconnects when retrieving messages loses the connection', function () { + $poll = new class(new Mailbox, 'INBOX', 1) extends Poll + { + public int $reconnects = 0; + + protected function connect(): void {} + + protected function check(callable $query): Generator + { + throw new ImapConnectionClosedException('Connection lost'); + } + + protected function reconnect(): void + { + $this->reconnects++; + $this->frequency = 0; + } + }; + + $poll->start(fn () => null, fn ($query) => $query); + + expect($poll->reconnects)->toBe(1); +}); + +test('poll stops and disconnects immediately when the callback returns false', function () { + $poll = new class(new Mailbox, 'INBOX', 60) extends Poll + { + public bool $disconnected = false; + + protected function connect(): void {} + + protected function check(callable $query): Generator + { + yield new FakeMessage(1); + throw new RuntimeException('Polling should have stopped'); + } + + protected function disconnect(): void + { + $this->disconnected = true; + } + }; + $received = []; + + $poll->start(function ($message) use (&$received) { + $received[] = $message->uid(); + + return false; + }, fn ($query) => $query); + + expect($received)->toBe([1]); + expect($poll->disconnected)->toBeTrue(); +}); + +test('poll preserves or resets its uid baseline when selecting again', function (int $validity, int $uidNext, array $expected) { + $connection = ImapConnection::fake([ + '* OK Welcome', 'TAG1 OK LOGIN completed', + '* OK [UIDVALIDITY 1]', '* OK [UIDNEXT 1]', 'TAG2 OK SELECT completed', + '* OK [UIDVALIDITY 1]', '* OK [UIDNEXT 4]', 'TAG3 OK SELECT completed', + '* SEARCH 3 1 2', 'TAG4 OK SEARCH completed', + '* 3 FETCH (UID 3 FLAGS ())', '* 1 FETCH (UID 1 FLAGS ())', '* 2 FETCH (UID 2 FLAGS ())', 'TAG5 OK FETCH completed', + "* OK [UIDVALIDITY {$validity}]", "* OK [UIDNEXT {$uidNext}]", 'TAG6 OK SELECT completed', + '* SEARCH 1 3 4', 'TAG7 OK SEARCH completed', + '* 1 FETCH (UID 1 FLAGS ())', '* 3 FETCH (UID 3 FLAGS ())', '* 4 FETCH (UID 4 FLAGS ())', 'TAG8 OK FETCH completed', + ]); + $mailbox = new Mailbox; + $mailbox->connect($connection); + $poll = new class($mailbox, 'INBOX', 1) extends Poll + { + public function initialize(): void + { + $this->select(new Folder($this->mailbox, $this->folder)); + } + + protected function folder(): FolderInterface + { + return new Folder($this->mailbox, $this->folder); + } + + public function read(): array + { + return iterator_to_array($this->check(fn ($query) => $query)); + } + }; + $poll->initialize(); + + expect(array_map(fn ($message) => $message->uid(), $poll->read()))->toBe([1, 2, 3]); + expect(array_map(fn ($message) => $message->uid(), $poll->read()))->toBe($expected); + $connection->disconnect(); +})->with([ + 'same validity excludes delivered and older UIDs' => [1, 5, [4]], + 'changed validity starts a new baseline' => [2, 3, [3, 4]], +]); diff --git a/tests/Unit/WatchTest.php b/tests/Unit/WatchTest.php new file mode 100644 index 00000000..f2219378 --- /dev/null +++ b/tests/Unit/WatchTest.php @@ -0,0 +1,258 @@ +open(); + $stream->feed([ + '* OK Welcome', 'TAG1 OK LOGIN completed', + '* LIST () "/" "INBOX"', 'TAG2 OK LIST completed', + '* 1 EXISTS', '* OK [UIDVALIDITY 777]', 'TAG3 OK SELECT completed', + '+ idling', '* 4 EXISTS', '* 2 FETCH (FLAGS (\\Seen))', '* 3 EXPUNGE', + ]); + $mailbox = new Mailbox; + $mailbox->connect(new ImapConnection($stream)); + $received = []; + + (new Watch($mailbox, 'INBOX', 30))->await(function (EventInterface $event) use (&$received) { + $received[] = $event; + + return ! $event instanceof MessageExpunged; + }); + + expect(array_map(fn (EventInterface $event) => $event::class, $received))->toBe([ + FolderSelected::class, MessagesExist::class, MessageFetched::class, MessageExpunged::class, + ]); + expect($received[0]->selection()->uidValidity())->toBe(777); + expect($received[1]->count())->toBe(4); + expect($stream->opened())->toBeFalse(); + $stream->assertNotWritten('FETCH'); + $stream->assertNotWritten('LOGOUT'); +}); + +test('callback connection exceptions propagate instead of causing a reconnect', function () { + $stream = new FakeStream; + $stream->open(); + $stream->feed([ + '* OK Welcome', 'TAG1 OK LOGIN completed', + '* LIST () "/" "INBOX"', 'TAG2 OK LIST completed', + 'TAG3 OK SELECT completed', '+ idling', '* 4 EXISTS', + ]); + $mailbox = new Mailbox; + $mailbox->connect(new ImapConnection($stream)); + $exception = new ImapConnectionClosedException('Application callback failed'); + + expect(fn () => (new Watch($mailbox, 'INBOX', 30))->await(function (EventInterface $event) use ($exception) { + if ($event instanceof MessagesExist) { + throw $exception; + } + }))->toThrow($exception); + + expect($stream->opened())->toBeFalse(); +}); + +test('watcher emits a fresh selection after reconnecting', function () { + $first = new FakeStream; + $first->open(); + $first->feed([ + '* OK Welcome', 'TAG1 OK LOGIN completed', + '* LIST () "/" "INBOX"', 'TAG2 OK LIST completed', + '* OK [UIDVALIDITY 777]', 'TAG3 OK SELECT completed', + '+ idling', '* BYE Restarting', + ]); + $second = new FakeStream; + $second->open(); + $second->feed([ + '* OK Welcome', 'TAG1 OK LOGIN completed', + '* OK [UIDVALIDITY 888]', 'TAG2 OK SELECT completed', + ]); + $mailbox = new class([new ImapConnection($first), new ImapConnection($second)]) extends Mailbox + { + public function __construct(protected array $connections) + { + parent::__construct(); + } + + public function connect(?ConnectionInterface $connection = null): void + { + parent::connect($connection ?? array_shift($this->connections)); + } + }; + $validities = []; + + (new Watch($mailbox, 'INBOX', 30))->await(function (EventInterface $event) use (&$validities) { + expect($event)->toBeInstanceOf(FolderSelected::class); + $validities[] = $event->selection()->uidValidity(); + + return count($validities) < 2; + }); + + expect($validities)->toBe([777, 888]); + expect($first->opened())->toBeFalse(); + expect($second->opened())->toBeFalse(); + $second->assertWritten('TAG2 SELECT "INBOX"'); + $second->assertNotWritten('LIST'); +}); + +test('watcher does not resolve the folder when stopped before starting', function (bool $callable) { + $mailbox = new class extends Mailbox + { + public function connect(?ConnectionInterface $connection = null): void + { + throw new LogicException('The stopped watcher must not connect.'); + } + }; + $received = []; + $timeout = $callable ? fn () => false : 0; + + (new Watch($mailbox, 'INBOX', $timeout))->await(function (EventInterface $event) use (&$received) { + $received[] = $event; + }); + + expect($received)->toBeEmpty(); +})->with([ + 'zero interval' => false, + 'stopped callback' => true, +]); + +test('watcher honors renewal intervals longer than 29 minutes', function () { + Carbon::setTestNow('2026-09-27 12:00:00'); + $stream = new FakeStream; + $stream->open(); + $stream->feed([ + '* OK Welcome', 'TAG1 OK LOGIN completed', + '* LIST () "/" "INBOX"', 'TAG2 OK LIST completed', + 'TAG3 OK SELECT completed', + '+ idling', '* 4 EXISTS', '* 5 EXISTS', '* 3 EXPUNGE', 'TAG4 OK IDLE completed', + '+ idling', '* 6 EXISTS', + ]); + $mailbox = new Mailbox; + $mailbox->connect(new ImapConnection($stream)); + $received = []; + + try { + (new Watch($mailbox, 'INBOX', 3600))->await(function (EventInterface $event) use ($stream, &$received) { + $received[] = $event::class; + + if ($event instanceof MessagesExist && $event->count() === 4) { + Carbon::setTestNow(Carbon::now()->addMinutes(30)); + } + + if ($event instanceof MessagesExist && $event->count() === 5) { + $stream->assertNotWritten('DONE'); + Carbon::setTestNow(Carbon::now()->addMinutes(31)); + } + + return ! ($event instanceof MessagesExist && $event->count() === 6); + }); + } finally { + Carbon::setTestNow(); + } + + expect($received)->toBe([ + FolderSelected::class, MessagesExist::class, MessagesExist::class, + MessageExpunged::class, MessagesExist::class, + ]); + $stream->assertWritten('DONE'); + $stream->assertWritten('TAG5 IDLE'); +}); + +test('watcher reads the mailbox timeout when finishing idle', function () { + Carbon::setTestNow('2026-09-27 12:00:00'); + $stream = new class extends FakeStream + { + public ?int $timeout = null; + + public function setTimeout(int $seconds): bool + { + $this->timeout = $seconds; + + return true; + } + }; + $stream->feed([ + '* OK Welcome', 'TAG1 OK LOGIN completed', + '* LIST () "/" "INBOX"', 'TAG2 OK LIST completed', + 'TAG3 OK SELECT completed', + '+ idling', '* 4 EXISTS', '* 3 EXPUNGE', 'TAG4 OK IDLE completed', + ]); + $mailbox = new class extends Mailbox + { + public int $timeout = 5; + + public function config(?string $key = null, mixed $default = null): mixed + { + return $key === 'timeout' ? $this->timeout : parent::config($key, $default); + } + }; + $completionTimeout = null; + + try { + $mailbox->connect(new ImapConnection($stream)); + + (new Watch($mailbox, 'INBOX', 30))->await(function (EventInterface $event) use ($mailbox, $stream, &$completionTimeout) { + if ($event instanceof MessagesExist) { + $mailbox->timeout = 90; + Carbon::setTestNow(Carbon::now()->addSeconds(31)); + } + + if ($event instanceof MessageExpunged) { + $completionTimeout = $stream->timeout; + + return false; + } + }); + + expect($completionTimeout)->toBe(90); + $stream->assertWritten('DONE'); + } finally { + $mailbox->disconnect(); + Carbon::setTestNow(); + } +}); + +test('watcher renews busy idle sessions and preserves queued updates', function () { + Carbon::setTestNow('2026-09-27 12:00:00'); + $stream = new FakeStream; + $stream->open(); + $stream->feed([ + '* OK Welcome', 'TAG1 OK LOGIN completed', + '* LIST () "/" "INBOX"', 'TAG2 OK LIST completed', + 'TAG3 OK SELECT completed', + '+ idling', '* 4 EXISTS', '* 3 EXPUNGE', 'TAG4 OK IDLE completed', + '+ idling', '* 5 EXISTS', + ]); + $mailbox = new Mailbox; + $mailbox->connect(new ImapConnection($stream)); + $received = []; + + try { + (new Watch($mailbox, 'INBOX', 30))->await(function (EventInterface $event) use (&$received) { + $received[] = $event::class; + + if ($event instanceof MessagesExist && $event->count() === 4) { + Carbon::setTestNow(Carbon::now()->addSeconds(31)); + } + + return ! ($event instanceof MessagesExist && $event->count() === 5); + }); + } finally { + Carbon::setTestNow(); + } + + expect($received)->toBe([FolderSelected::class, MessagesExist::class, MessageExpunged::class, MessagesExist::class]); + $stream->assertWritten('DONE'); + $stream->assertWritten('TAG5 IDLE'); +});