Lines 84.61% 22 / 26
Functions and Methods 66.66% 4 / 6
Classes and Traits 0.00% 0 / 1
Name Lines Functions and Methods CRAP Classes and Traits
FrameCodec 84.61% 22 / 26 66.66% 4 / 6 12.52 0.00% 0 / 1
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 createControlWireMapper 100.00% 1 / 1 100.00% 1 / 1 1
 encodeFrame 50.00% 3 / 6 0.00% 0 / 1 4.12
 decodeClientFrame 100.00% 3 / 3 100.00% 1 / 1 1
 decodeServerFrame 100.00% 3 / 3 100.00% 1 / 1 1
 decodeFrameOfType 91.66% 11 / 12 0.00% 0 / 1 5.01
1<?php
2
3declare(strict_types=1);
4
5namespace Stewart\Runtime\Control\Protocol\Codec;
6
7use JsonException;
8use Stewart\Contracts\Exception\StewartException;
9use Stewart\Runtime\Control\Protocol\Frame\Bye;
10use Stewart\Runtime\Control\Protocol\Frame\ClientFrame;
11use Stewart\Runtime\Control\Protocol\Frame\CommandResult;
12use Stewart\Runtime\Control\Protocol\Frame\Hello;
13use Stewart\Runtime\Control\Protocol\Frame\PauseAppRequest;
14use Stewart\Runtime\Control\Protocol\Frame\Rejected;
15use Stewart\Runtime\Control\Protocol\Frame\ReloadRequest;
16use Stewart\Runtime\Control\Protocol\Frame\RequestFailed;
17use Stewart\Runtime\Control\Protocol\Frame\ResetAppRequest;
18use Stewart\Runtime\Control\Protocol\Frame\RestartWorkerRequest;
19use Stewart\Runtime\Control\Protocol\Frame\ResumeAppRequest;
20use Stewart\Runtime\Control\Protocol\Frame\ServerFrame;
21use Stewart\Runtime\Control\Protocol\Frame\SnapshotFrame;
22use Stewart\Runtime\Control\Protocol\Frame\SnapshotRequest;
23use Stewart\Runtime\Control\Protocol\Frame\Welcome;
24use Stewart\Runtime\Exception\ControlError;
25use Stewart\Runtime\Exception\ControlException;
26use Stewart\Runtime\Json\ClassShapeReader;
27use Stewart\Runtime\Json\Collection\ValueConverterCollection;
28use Stewart\Runtime\Json\DurationConverter;
29use Stewart\Runtime\Json\IsoInstantConverter;
30use Stewart\Runtime\Json\WireMapper;
31use Stewart\Support\Exception\JsonShapeException;
32use Stewart\Support\Json\JsonDecoder;
33use Stewart\Support\Json\JsonEncoder;
34use Stewart\Support\Json\JsonShape;
35use Throwable;
36
37final readonly class FrameCodec
38{
39    private const int DEPTH = 32;
40
41    private const array CLIENT_FRAMES = [
42        'hello' => Hello::class,
43        'snapshot_request' => SnapshotRequest::class,
44        'pause_app' => PauseAppRequest::class,
45        'resume_app' => ResumeAppRequest::class,
46        'reset_app' => ResetAppRequest::class,
47        'restart_worker' => RestartWorkerRequest::class,
48        'reload' => ReloadRequest::class,
49    ];
50
51    private const array SERVER_FRAMES = [
52        'welcome' => Welcome::class,
53        'snapshot' => SnapshotFrame::class,
54        'rejected' => Rejected::class,
55        'command_result' => CommandResult::class,
56        'request_failed' => RequestFailed::class,
57        'bye' => Bye::class,
58    ];
59
60    public function __construct(private WireMapper $controlWireMapper) {}
61
62    public static function createControlWireMapper(): WireMapper
63    {
64        return new WireMapper(new ClassShapeReader(ValueConverterCollection::keyedByHandledClass([new IsoInstantConverter(), new DurationConverter()])));
65    }
66
67    /** @throws ControlException */
68    public function encodeFrame(ClientFrame|ServerFrame $frame): string
69    {
70        $type = array_search($frame::class, self::CLIENT_FRAMES + self::SERVER_FRAMES, true);
71
72        if ($type === false) {
73            throw ControlException::createForReason(ControlError::FrameClassUnknown, frameClass: $frame::class);
74        }
75
76        try {
77            return JsonEncoder::encodeToJson(['type' => $type, ...(array) $this->controlWireMapper->normalizeObject($frame)], self::DEPTH) . "\n";
78        } catch (JsonException|StewartException $e) {
79            throw ControlException::createForReason(ControlError::FrameUnencodable, $e, frameClass: $frame::class);
80        }
81    }
82
83    /** @throws ControlException|StewartException */
84    public function decodeClientFrame(string $line): ClientFrame
85    {
86        $frame = $this->decodeFrameOfType($line, self::CLIENT_FRAMES, 'a client frame type');
87        \assert($frame instanceof ClientFrame);
88
89        return $frame;
90    }
91
92    /** @throws ControlException|StewartException */
93    public function decodeServerFrame(string $line): ServerFrame
94    {
95        $frame = $this->decodeFrameOfType($line, self::SERVER_FRAMES, 'a server frame type');
96        \assert($frame instanceof ServerFrame);
97
98        return $frame;
99    }
100
101    /**
102     * @param array<string, class-string> $frames
103     * @throws ControlException|StewartException
104     */
105    private function decodeFrameOfType(string $line, array $frames, string $expected): object
106    {
107        try {
108            $data = JsonDecoder::decodeJson($line, self::DEPTH);
109        } catch (JsonException $e) {
110            throw ControlException::createForReason(ControlError::FrameNotJson, $e);
111        }
112
113        if (!\is_array($data)) {
114            throw ControlException::createForReason(ControlError::FrameNotAnObject, actualType: get_debug_type($data));
115        }
116
117        $type = JsonShape::requireString($data, 'type');
118        $class = $frames[$type] ?? throw JsonShapeException::unexpectedValue('type', $expected, $type);
119
120        try {
121            return $this->controlWireMapper->decodeObject($class, $data);
122        } catch (StewartException $e) {
123            throw $e;
124        } catch (Throwable $e) {
125            throw ControlException::createForReason(ControlError::FrameUndecodable, $e, frameType: $type);
126        }
127    }
128}