Skip to content
Merged
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
41 changes: 27 additions & 14 deletions src/FreeDSx/Socket/Timeout/BlockingSelectEnforcer.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,37 +48,25 @@ public function write(
$write = [$stream];
$read = [];
$except = [];
error_clear_last();
$ready = @stream_select(
$read,
$write,
$except,
$timeout,
);

if ($ready === false) {
$this->throwWriteError();
}
// The write itself decides whether the socket is still usable.
if ($ready === 0) {
throw new WriteTimeoutException(sprintf(
'The write operation timed out after %d seconds.',
$timeout,
));
}

error_clear_last();
$written = @fwrite(
$remaining = $this->writeRemaining(
$stream,
$remaining,
);
if ($written === false) {
$this->throwWriteError();
}

$remaining = substr(
$remaining,
$written,
);
}
} finally {
@stream_set_blocking(
Expand All @@ -87,4 +75,29 @@ public function write(
);
}
}

/**
* Writes what is left and returning what still has to go out.
*
* @param resource $stream
*/
private function writeRemaining(
$stream,
string $remaining,
): string {
error_clear_last();
$written = @fwrite(
$stream,
$remaining,
);

if ($written === false) {
$this->throwWriteError();
}

return substr(
$remaining,
$written,
);
}
}
61 changes: 61 additions & 0 deletions tests/unit/Timeout/BlockingSelectEnforcerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,67 @@ public function test_it_throws_when_the_peer_stops_reading(): void
);
}

public function test_a_signal_arriving_while_it_waits_does_not_abort_the_send(): void
{
$this->requireFillableSocket();

if (!function_exists('pcntl_async_signals')) {
self::markTestSkipped('The pcntl extension is required to interrupt the wait.');
}

[$local, $remote] = $this->createSocketPair();
$this->fillSocket($local);

pcntl_async_signals(true);
pcntl_signal(
SIGALRM,
static function () use ($remote): void {
// Frees room so the interrupted send can carry on once it resumes.
stream_set_blocking($remote, false);

while (fread($remote, 65536) !== '') {
}
},
);
pcntl_alarm(1);

try {
$this->subject->write(
$local,
'payload',
10,
);
} finally {
pcntl_alarm(0);
pcntl_signal(SIGALRM, SIG_DFL);
}

stream_set_blocking($remote, false);
$drained = '';

while (($chunk = fread($remote, 65536)) !== '' && $chunk !== false) {
$drained .= $chunk;
}

self::assertStringEndsWith(
'payload',
$drained,
);
}

/**
* @param resource $stream
*/
private function fillSocket($stream): void
{
stream_set_blocking($stream, false);

while (@fwrite($stream, str_repeat('x', 65536)) > 0) {
}

stream_set_blocking($stream, true);
}

/**
* @return array{0: resource, 1: resource}
*/
Expand Down
Loading