Skip to content
Merged
34 changes: 25 additions & 9 deletions src/Connection/ConnectionInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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.
*
Expand Down Expand Up @@ -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.
Expand Down
205 changes: 205 additions & 0 deletions src/Connection/IdleSession.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,205 @@
<?php

namespace DirectoryTree\ImapEngine\Connection;

use Carbon\Carbon;
use Carbon\CarbonInterface;
use DirectoryTree\ImapEngine\Collections\ResponseCollection;
use DirectoryTree\ImapEngine\Connection\Responses\ContinuationResponse;
use DirectoryTree\ImapEngine\Connection\Responses\Response;
use DirectoryTree\ImapEngine\Connection\Responses\TaggedResponse;
use DirectoryTree\ImapEngine\Connection\Responses\UntaggedResponse;
use DirectoryTree\ImapEngine\Exceptions\ImapCommandException;
use DirectoryTree\ImapEngine\Exceptions\ImapConnectionClosedException;
use DirectoryTree\ImapEngine\Exceptions\ImapConnectionTimedOutException;
use Generator;
use LogicException;

class IdleSession
{
/**
* Whether the session still owns the connection.
*/
protected bool $active = true;

/**
* Whether the server has acknowledged IDLE with a continuation.
*/
protected bool $ready = false;

/**
* Whether response consumption has started.
*/
protected bool $started = false;

/**
* Updates not yet delivered to the caller.
*
* @var UntaggedResponse[]
*/
protected array $pending = [];

/**
* The deadline for receiving updates or finishing the IDLE exchange.
*/
protected ?CarbonInterface $deadline = null;

/**
* Create an IDLE session on the connection.
*/
public function __construct(
/**
* The IDLE command used to match completion and report errors.
*/
protected ImapCommand $command,
/**
* The connection used for the IDLE exchange.
*/
protected ConnectionInterface $connection,
) {}

/**
* Determine whether this session still owns the connection.
*/
public function active(): bool
{
return $this->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<int, UntaggedResponse>
*/
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;
}
}
66 changes: 33 additions & 33 deletions src/Connection/ImapConnection.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*/
Expand Down Expand Up @@ -174,6 +179,9 @@ protected function getDefaultSocketOptions(string $transport, array $proxy = [],
*/
public function disconnect(): void
{
$this->idle?->invalidate();
$this->idle = null;

$this->stream->close();
}

Expand Down Expand Up @@ -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);

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

Expand All @@ -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;
}
Expand All @@ -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');
Expand Down Expand Up @@ -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;
}
Expand All @@ -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();
Expand All @@ -900,4 +892,12 @@ protected function nextReply(): Data|Token|Response|null

return $reply;
}

/**
* {@inheritDoc}
*/
public function stream(): StreamInterface
{
return $this->stream;
}
}
Loading
Loading