Lines 98.36% 60 / 61
Functions and Methods 80.00% 4 / 5
Classes and Traits 0.00% 0 / 1
Name Lines Functions and Methods CRAP Classes and Traits
IpcCodec 98.36% 60 / 61 80.00% 4 / 5 18 0.00% 0 / 1
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 createForWorkerBootstrap 100.00% 1 / 1 100.00% 1 / 1 1
 createIpcWireMapper 100.00% 29 / 29 100.00% 1 / 1 1
 encodeMessage 88.88% 8 / 9 0.00% 0 / 1 3.01
 decodeMessage 100.00% 21 / 21 100.00% 1 / 1 12
1<?php
2
3declare(strict_types=1);
4
5namespace Stewart\Runtime\Ipc\Wire;
6
7use JsonException;
8use Stewart\Contracts\Exception\StewartException;
9use Stewart\Contracts\Exposure\ExposedEntityKey;
10use Stewart\Runtime\Exception\TransportError;
11use Stewart\Runtime\Exception\TransportException;
12use Stewart\Runtime\Ipc\Message\Bootstrap;
13use Stewart\Runtime\Json\ClassShapeReader;
14use Stewart\Runtime\Json\Collection\ValueConverterCollection;
15use Stewart\Runtime\Json\DurationConverter;
16use Stewart\Runtime\Json\EpochInstantConverter;
17use Stewart\Runtime\Json\StringIdentifierConverter;
18use Stewart\Runtime\Json\WireMapper;
19use Stewart\Runtime\Model\CorrelationId;
20use Stewart\Runtime\Model\ResourceScope;
21use Stewart\Runtime\Model\SubscriptionId;
22use Stewart\Support\Json\JsonDecoder;
23use Throwable;
24
25final readonly class IpcCodec
26{
27    public const int PROTOCOL_VERSION = 35;
28
29    private const string UNKNOWN_TYPE = '?';
30
31    public function __construct(
32        private WireMapper $ipcWireMapper,
33        private IpcMessageCatalog $messageCatalog,
34    ) {}
35
36    /** @throws TransportException */
37    public static function createForWorkerBootstrap(): self
38    {
39        return new self(self::createIpcWireMapper(), IpcMessageCatalog::scanMessageDirectory());
40    }
41
42    public static function createIpcWireMapper(): WireMapper
43    {
44        $entityIds = StringIdentifierConverter::createForEntityIds();
45        $instants = new EpochInstantConverter();
46        $contexts = new EventContextConverter();
47        $states = new EntityStateConverter($entityIds, $instants, $contexts);
48
49        return new WireMapper(new ClassShapeReader(ValueConverterCollection::keyedByHandledClass([
50            $instants,
51            new DurationConverter(),
52            new SelectorConverter(),
53            new MqttMessageConverter(),
54            new TriggerSpecConverter(),
55            new ExceptionDetailsConverter(),
56            new ExposedStateConverter(),
57            new TimeOfDayConverter(),
58            new DateTimeImmutableConverter(),
59            $contexts,
60            $states,
61            new StateUpdateConverter($entityIds, $instants, $contexts, $states),
62            $entityIds,
63            StringIdentifierConverter::createForAppIds(),
64            StringIdentifierConverter::createForAreaIds(),
65            StringIdentifierConverter::createForFloorIds(),
66            StringIdentifierConverter::createForLabelIds(),
67            StringIdentifierConverter::createForDeviceIds(),
68            new StringIdentifierConverter(SubscriptionId::class, 'a subscription id', SubscriptionId::fromString(...)),
69            new StringIdentifierConverter(CorrelationId::class, 'a correlation id', CorrelationId::fromString(...)),
70            new StringIdentifierConverter(ExposedEntityKey::class, 'an exposed entity key', ExposedEntityKey::tryFromString(...)),
71            new WorkerIdConverter(),
72            new StringIdentifierConverter(ResourceScope::class, 'an app id or "@shared"', ResourceScope::tryFromWireValue(...)),
73        ])));
74    }
75
76    /** @throws TransportException */
77    public function encodeMessage(object $message): string
78    {
79        $tag = $this->messageCatalog->findTagForClass($message::class) ?? throw TransportException::createForReason(
80            TransportError::MessageTypeMissing,
81            messageClass: $message::class,
82        );
83
84        try {
85            return '{"t":"' . $tag . '","m":' . $this->ipcWireMapper->encodeObject($message) . '}';
86        } catch (TransportException $e) {
87            throw $e;
88        } catch (JsonException|StewartException $e) {
89            throw TransportException::createForReason(TransportError::Unencodable, $e, messageClass: $message::class);
90        }
91    }
92
93    /** @throws TransportException */
94    public function decodeMessage(string $frame): object
95    {
96        try {
97            $data = JsonDecoder::decodeJson($frame);
98        } catch (JsonException $e) {
99            throw TransportException::createForReason(TransportError::UndecodableFrame, $e, messageType: self::UNKNOWN_TYPE, reason: $e->getMessage());
100        }
101
102        $tag = \is_array($data) && \is_string($data['t'] ?? null) ? $data['t'] : self::UNKNOWN_TYPE;
103        $body = \is_array($data) ? ($data['m'] ?? null) : null;
104        $class = $this->messageCatalog->findClassForTag($tag);
105
106        if ($class === null || !\is_array($body)) {
107            throw TransportException::createForReason(
108                TransportError::UndecodableFrame,
109                messageType: $tag,
110                reason: $class === null ? 'unknown message type' : 'the frame has no message body',
111            );
112        }
113
114        if ($class === Bootstrap::class && ($body['protocol'] ?? null) !== self::PROTOCOL_VERSION) {
115            throw TransportException::createForReason(
116                TransportError::ProtocolMismatch,
117                expected: self::PROTOCOL_VERSION,
118                actual: \is_int($body['protocol'] ?? null) ? $body['protocol'] : 0,
119            );
120        }
121
122        try {
123            return $this->ipcWireMapper->decodeObject($class, $body);
124        } catch (Throwable $e) {
125            throw TransportException::createForReason(TransportError::UndecodableFrame, $e, messageType: $tag, reason: $e->getMessage());
126        }
127    }
128}