Lines
100.00%
8 / 8
Functions and Methods
100.00%
6 / 6
Classes and Traits
100.00%
1 / 1
| Name | Lines | Functions and Methods | CRAP | Classes and Traits | ||||||
|---|---|---|---|---|---|---|---|---|---|---|
| ClientSession | 100.00% | 8 / 8 | 100.00% | 6 / 6 | 6 | 100.00% | 1 / 1 | |||
| __construct | 100.00% | 2 / 2 | 100.00% | 1 / 1 | 1 | |||||
| describePeer | 100.00% | 1 / 1 | 100.00% | 1 / 1 | 1 | |||||
| hasExpired | 100.00% | 1 / 1 | 100.00% | 1 / 1 | 1 | |||||
| readLine | 100.00% | 1 / 1 | 100.00% | 1 / 1 | 1 | |||||
| send | 100.00% | 1 / 1 | 100.00% | 1 / 1 | 1 | |||||
| close | 100.00% | 2 / 2 | 100.00% | 1 / 1 | 1 | |||||
| 1 | <?php | |
| 2 | ||
| 3 | declare(strict_types=1); | |
| 4 | ||
| 5 | namespace Stewart\Runtime\Control\Server; | |
| 6 | ||
| 7 | use Amp\ByteStream\BufferedReader; | |
| 8 | use Amp\ByteStream\StreamException; | |
| 9 | use Amp\Cancellation; | |
| 10 | use Amp\Socket\Socket; | |
| 11 | use Stewart\Runtime\Control\Protocol\Codec\FrameCodec; | |
| 12 | use Stewart\Runtime\Control\Protocol\Frame\ServerFrame; | |
| 13 | use Stewart\Runtime\Exception\ControlException; | |
| 14 | use Throwable; | |
| 15 | ||
| 16 | final readonly class ClientSession | |
| 17 | { | |
| 18 | private BufferedReader $reader; | |
| 19 | ||
| 20 | private string $deadlineSubscription; | |
| 21 | ||
| 22 | // Closing on the deadline aborts a pending write, which takes no cancellation. | |
| 23 | public function __construct( | |
| 24 | public int $id, | |
| 25 | private Socket $socket, | |
| 26 | private FrameCodec $codec, | |
| 27 | private Cancellation $deadline, | |
| 28 | ) { | |
| 29 | $this->reader = new BufferedReader($socket); | |
| 30 | $this->deadlineSubscription = $deadline->subscribe($socket->close(...)); | |
| 31 | } | |
| 32 | ||
| 33 | public function describePeer(): string | |
| 34 | { | |
| 35 | return $this->socket->getRemoteAddress()->toString(); | |
| 36 | } | |
| 37 | ||
| 38 | public function hasExpired(): bool | |
| 39 | { | |
| 40 | return $this->deadline->isRequested(); | |
| 41 | } | |
| 42 | ||
| 43 | /** | |
| 44 | * @param positive-int $limit | |
| 45 | * @throws Throwable | |
| 46 | */ | |
| 47 | public function readLine(int $limit): string | |
| 48 | { | |
| 49 | return rtrim($this->reader->readUntil("\n", $this->deadline, $limit), "\r\n"); | |
| 50 | } | |
| 51 | ||
| 52 | /** @throws ControlException|StreamException */ | |
| 53 | public function send(ServerFrame $frame): void | |
| 54 | { | |
| 55 | $this->socket->write($this->codec->encodeFrame($frame)); | |
| 56 | } | |
| 57 | ||
| 58 | public function close(): void | |
| 59 | { | |
| 60 | $this->deadline->unsubscribe($this->deadlineSubscription); | |
| 61 | $this->socket->close(); | |
| 62 | } | |
| 63 | } |