Lines 86.66% 26 / 30
Functions and Methods 81.81% 18 / 22
Classes and Traits 0.00% 0 / 1
Name Lines Functions and Methods CRAP Classes and Traits
WorkerHaContext 86.66% 26 / 30 81.81% 18 / 22 29.86 0.00% 0 / 1
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 forApp 100.00% 1 / 1 100.00% 1 / 1 1
 getState 100.00% 1 / 1 100.00% 1 / 1 1
 getEntity 100.00% 1 / 1 100.00% 1 / 1 1
 requireState 100.00% 2 / 2 100.00% 1 / 1 1
 getHeldStateDuration 100.00% 2 / 2 100.00% 1 / 1 2
 hasHeldStateFor 100.00% 2 / 2 100.00% 1 / 1 2
 getHistory 100.00% 1 / 1 100.00% 1 / 1 1
 listStates 66.66% 2 / 3 0.00% 0 / 1 3.33
 watchStateChanges 100.00% 1 / 1 100.00% 1 / 1 2
 waitForState 100.00% 1 / 1 100.00% 1 / 1 1
 getRegistry 100.00% 1 / 1 100.00% 1 / 1 1
 watchEvents 100.00% 1 / 1 100.00% 1 / 1 1
 watchTrigger 100.00% 1 / 1 100.00% 1 / 1 1
 callAction 100.00% 1 / 1 100.00% 1 / 1 1
 callActionForResponse 100.00% 1 / 1 100.00% 1 / 1 1
 fireEvent 100.00% 1 / 1 100.00% 1 / 1 1
 wasCausedByStewart 100.00% 1 / 1 100.00% 1 / 1 1
 publish 100.00% 4 / 4 100.00% 1 / 1 2
 watchTopic 0.00% 0 / 1 0.00% 0 / 1 2
 watchConnection 0.00% 0 / 1 0.00% 0 / 1 2
 isConnected 0.00% 0 / 1 0.00% 0 / 1 2
1<?php
2
3declare(strict_types=1);
4
5namespace Stewart\Runtime\Worker;
6
7use Stewart\Contracts\Action\ActionName;
8use Stewart\Contracts\Action\ActionResponse;
9use Stewart\Contracts\Action\ActionTargetSource;
10use Stewart\Contracts\App\AppId;
11use Stewart\Contracts\Entity\Entity;
12use Stewart\Contracts\Entity\EntityId;
13use Stewart\Contracts\Event\HaEvent;
14use Stewart\Contracts\EventStream;
15use Stewart\Contracts\Exception\StateException;
16use Stewart\Contracts\Exception\TopicError;
17use Stewart\Contracts\Exception\TopicException;
18use Stewart\Contracts\HaContext;
19use Stewart\Contracts\History\EntityStateHistory;
20use Stewart\Contracts\History\HistoryQuery;
21use Stewart\Contracts\Registry\EntityFilter;
22use Stewart\Contracts\Registry\Registry;
23use Stewart\Contracts\Selector\Collection\SelectorCollection;
24use Stewart\Contracts\Selector\Selector;
25use Stewart\Contracts\State\Collection\EntityStateCollection;
26use Stewart\Contracts\State\EntityState;
27use Stewart\Contracts\State\EventContext;
28use Stewart\Contracts\State\StateChange;
29use Stewart\Contracts\StateChangeStream;
30use Stewart\Contracts\Time\Clock;
31use Stewart\Contracts\Time\Duration;
32use Stewart\Contracts\Trigger\Collection\HaTriggerCollection;
33use Stewart\Contracts\Trigger\HaTrigger;
34use Stewart\Runtime\Exception\TransportException;
35use Stewart\Runtime\Model\ResourceScope;
36use Stewart\Runtime\Registry\RegistryCache;
37use Stewart\Runtime\State\StateCache;
38use Stewart\Runtime\Worker\Context\ActionCaller;
39use Stewart\Runtime\Worker\Context\DispatchStreams;
40use Stewart\Runtime\Worker\Context\EventFirer;
41use Stewart\Runtime\Worker\Context\HistoryReader;
42use Stewart\Runtime\Worker\Context\TopicPublisher;
43use Stewart\Support\State\StewartIdentity;
44use Stewart\Support\Wire\ActionFields;
45use Stewart\Support\Wire\EventPayload;
46use Stewart\Support\Wire\EventTypeSelector;
47use Stewart\Support\Wire\TopicPayload;
48use Stewart\Support\Wire\TriggerSpec;
49
50final readonly class WorkerHaContext implements HaContext
51{
52    public function __construct(
53        private StateCache $states,
54        private RegistryCache $registry,
55        private ConnectionStatus $connection,
56        private ActionCaller $actions,
57        private HistoryReader $history,
58        private EventFirer $eventFires,
59        private DispatchStreams $streams,
60        private TopicPublisher $topics,
61        private StewartIdentity $identity,
62        private Clock $clock,
63        private ResourceScope $resourceScope,
64    ) {}
65
66    public function forApp(AppId $appId): self
67    {
68        return new self($this->states, $this->registry, $this->connection, $this->actions, $this->history, $this->eventFires, $this->streams, $this->topics, $this->identity, $this->clock, ResourceScope::forApp($appId));
69    }
70
71    public function getState(EntityId|string $entityId): ?EntityState
72    {
73        return $this->states->find(EntityId::fromStringOrId($entityId));
74    }
75
76    public function getEntity(EntityId|string $entityId): Entity
77    {
78        return new Entity($this, EntityId::fromStringOrId($entityId));
79    }
80
81    public function requireState(EntityId|string $entityId): EntityState
82    {
83        $id = EntityId::fromStringOrId($entityId);
84
85        return $this->states->find($id) ?? throw StateException::entityNotFound($id);
86    }
87
88    public function getHeldStateDuration(EntityId|string $entityId): ?Duration
89    {
90        $changedAt = $this->getState($entityId)?->lastChangedAt;
91
92        return $changedAt === null ? null : $this->clock->getNow()->elapsedSince($changedAt);
93    }
94
95    public function hasHeldStateFor(EntityId|string $entityId, Duration $duration): bool
96    {
97        $held = $this->getHeldStateDuration($entityId);
98
99        return $held !== null && !$duration->isLongerThan($held);
100    }
101
102    public function getHistory(EntityId|string $entityId, HistoryQuery $query): EntityStateHistory
103    {
104        return $this->history->fetchHistory($this->resourceScope, EntityId::fromStringOrId($entityId), $query);
105    }
106
107    public function listStates(string|EntityId|Selector|SelectorCollection|EntityFilter|null $selector = null): EntityStateCollection
108    {
109        if ($selector instanceof EntityFilter) {
110            return $this->states->getAllStates()->filterByEntityFilter($selector, $this->registry);
111        }
112
113        return $this->states->filterBySelector($selector === null ? null : Selector::fromSpec($selector));
114    }
115
116    public function watchStateChanges(string|EntityId|Selector|SelectorCollection|EntityFilter $selector): StateChangeStream
117    {
118        return $this->streams->watchStateChanges($this->resourceScope, $selector instanceof EntityFilter ? $selector : Selector::fromSpec($selector));
119    }
120
121    public function waitForState(EntityId|string $entityId, string $state, ?Duration $timeout = null): ?EntityState
122    {
123        return $this->getEntity($entityId)->waitForState($state, $timeout);
124    }
125
126    public function getRegistry(): Registry
127    {
128        return $this->registry;
129    }
130
131    public function watchEvents(string|Selector|SelectorCollection $eventType): EventStream
132    {
133        return $this->streams->watchEvents($this->resourceScope, EventTypeSelector::fromSpec($eventType));
134    }
135
136    public function watchTrigger(HaTrigger|HaTriggerCollection|array $trigger, array $variables = []): EventStream
137    {
138        return $this->streams->watchTrigger($this->resourceScope, TriggerSpec::fromSpec($trigger, $variables));
139    }
140
141    public function callAction(string $action, array $data = [], ?ActionTargetSource $target = null): EventContext
142    {
143        return $this->actions->callAction($this->resourceScope, new ActionName($action), ActionFields::fromFieldsDroppingNulls($data), $target?->toActionTarget());
144    }
145
146    public function callActionForResponse(string $action, array $data = [], ?ActionTargetSource $target = null): ActionResponse
147    {
148        return $this->actions->callActionForResponse($this->resourceScope, new ActionName($action), ActionFields::fromFieldsDroppingNulls($data), $target?->toActionTarget());
149    }
150
151    public function fireEvent(string $eventType, array $data = []): EventContext
152    {
153        return $this->eventFires->fireEvent($this->resourceScope, new EventPayload($eventType, $data));
154    }
155
156    public function wasCausedByStewart(StateChange|EntityState|HaEvent $subject): bool
157    {
158        return $this->identity->wasCausedByStewart($subject);
159    }
160
161    public function publish(string $topic, bool|int|float|string|array|null $payload = null): void
162    {
163        $topicPayload = new TopicPayload($payload);
164
165        try {
166            $this->topics->publish($this->resourceScope, $topic, $topicPayload);
167        } catch (TransportException $e) {
168            throw TopicException::createForReason(TopicError::PublishFailed, $e, topic: $topic);
169        }
170    }
171
172    public function watchTopic(string|Selector|SelectorCollection $topic): EventStream
173    {
174        return $this->streams->watchTopic($this->resourceScope, Selector::fromSpec($topic));
175    }
176
177    public function watchConnection(): EventStream
178    {
179        return $this->streams->watchConnection($this->resourceScope);
180    }
181
182    public function isConnected(): bool
183    {
184        return $this->connection->connected;
185    }
186}