Lines 81.08% 30 / 37
Methods 54.54% 6 / 11
Classes 0.00% 0 / 1
Name Lines Methods CRAP
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 fetchSnapshot 100.00% 1 / 1 100.00% 1 / 1 1
 pauseApp 100.00% 1 / 1 100.00% 1 / 1 1
 resumeApp 100.00% 1 / 1 100.00% 1 / 1 1
 resetApp 100.00% 1 / 1 100.00% 1 / 1 1
 restartWorker 0.00% 0 / 1 0.00% 0 / 1 2
 requestReload 0.00% 0 / 1 0.00% 0 / 1 2
 sendRequest 75.00% 3 / 4 0.00% 0 / 1 2.06
 exchangeFrames 100.00% 17 / 17 100.00% 1 / 1 4
 readFrame 33.33% 1 / 3 0.00% 0 / 1 3.19
 expectWelcome 66.66% 4 / 6 0.00% 0 / 1 4.59
38final readonly class ControlClient
39{
40    private const int LINE_LIMIT = 4 * 1024 * 1024;
41
42    private const string CLIENT_NAME = 'stewart cli';
43
44    public function __construct(
45        private FrameCodec $codec,
46        private ProjectRoot $projectRoot,
47        private Deadlines $deadlines,
48        private SocketConnector $controlSocketConnector,
49    ) {}
50
51    /** @throws ControlException|Throwable */
52    public function fetchSnapshot(ControlTarget $target, Duration $timeout): RuntimeSnapshot
53    {
54        return $this->sendRequest($target, new SnapshotRequest(), SnapshotFrame::class, $timeout)->snapshot;
55    }
56
57    /** @throws ControlException|Throwable */
58    public function pauseApp(ControlTarget $target, AppId $appId, Duration $timeout): CommandResult
59    {
60        return $this->sendRequest($target, new PauseAppRequest($appId->value), CommandResult::class, $timeout);
61    }
62
63    /** @throws ControlException|Throwable */
64    public function resumeApp(ControlTarget $target, AppId $appId, Duration $timeout): CommandResult
65    {
66        return $this->sendRequest($target, new ResumeAppRequest($appId->value), CommandResult::class, $timeout);
67    }
68
69    /** @throws ControlException|Throwable */
70    public function resetApp(ControlTarget $target, AppId $appId, Duration $timeout): CommandResult
71    {
72        return $this->sendRequest($target, new ResetAppRequest($appId->value), CommandResult::class, $timeout);
73    }
74
75    /** @throws ControlException|Throwable */
76    public function restartWorker(ControlTarget $target, string $workerId, Duration $timeout): CommandResult
77    {
78        return $this->sendRequest($target, new RestartWorkerRequest($workerId), CommandResult::class, $timeout);
79    }
80
81    /** @throws ControlException|Throwable */
82    public function requestReload(ControlTarget $target, Duration $timeout): CommandResult
83    {
84        return $this->sendRequest($target, new ReloadRequest(), CommandResult::class, $timeout);
85    }
86
87    /**
88     * @template T of ServerFrame
89     * @param class-string<T> $responseClass
90     * @return T
91     * @throws ControlException|Throwable
92     */
93    private function sendRequest(ControlTarget $target, ClientFrame $request, string $responseClass, Duration $timeout): ServerFrame
94    {
95        $deadline = $this->deadlines->timeout($timeout);
96
97        try {
98            return $this->exchangeFrames($target, $request, $responseClass, $deadline);
99        } catch (CancelledException $e) {
100            throw ControlException::createForReason(ControlError::RequestTimedOut, $e, timeout: (string) $timeout);
101        }
102    }
103
104    /**
105     * @template T of ServerFrame
106     * @param class-string<T> $responseClass
107     * @return T
108     * @throws ControlException|Throwable
109     */
110    private function exchangeFrames(ControlTarget $target, ClientFrame $request, string $responseClass, Cancellation $deadline): ServerFrame
111    {
112        $socket = $this->controlSocketConnector->connect($target->address->resolveSocketAddress($this->projectRoot), null, $deadline);
113
114        try {
115            $socket->write($this->codec->encodeFrame(new Hello($target->token, self::CLIENT_NAME)));
116            $reader = new BufferedReader($socket);
117            $this->expectWelcome($this->readFrame($reader, $deadline));
118            $socket->write($this->codec->encodeFrame($request));
119            $response = $this->readFrame($reader, $deadline);
120
121            if ($response instanceof RequestFailed) {
122                throw ControlException::createForReason(ControlError::RequestFailed, reason: $response->reason, message: $response->message);
123            }
124
125            if (!$response instanceof $responseClass) {
126                throw ControlException::createForReason(ControlError::UnexpectedFrame, frameClass: $response::class, expectedFrameClass: $responseClass);
127            }
128
129            $bye = $this->readFrame($reader, $deadline);
130
131            return $bye instanceof Bye ? $response : throw ControlException::createForReason(
132                ControlError::UnexpectedFrame,
133                frameClass: $bye::class,
134                expectedFrameClass: Bye::class,
135            );
136        } finally {
137            $socket->close();
138        }
139    }
140
141    /** @throws ControlException|Throwable */
142    private function readFrame(BufferedReader $reader, Cancellation $deadline): ServerFrame
143    {
144        try {
145            return $this->codec->decodeServerFrame($reader->readUntil("\n", $deadline, self::LINE_LIMIT));
146        } catch (BufferException) {
147            throw ControlException::createForReason(ControlError::BrokerHungUp);
148        }
149    }
150
151    /** @throws ControlException */
152    private function expectWelcome(object $frame): void
153    {
154        if ($frame instanceof Rejected) {
155            throw ControlException::createForReason(ControlError::ConnectionRejected, reason: $frame->reason);
156        }
157
158        if (!$frame instanceof Welcome) {
159            throw ControlException::createForReason(ControlError::UnexpectedGreeting, frameClass: $frame::class);
160        }
161
162        if ($frame->protocol !== ControlProtocol::VERSION) {
163            throw ControlException::createForReason(ControlError::ProtocolMismatch, brokerProtocol: $frame->protocol, clientProtocol: ControlProtocol::VERSION);
164        }
165    }
166}