Lines 100.00% 43 / 43
Functions and Methods 100.00% 10 / 10
Classes and Traits 100.00% 1 / 1
Name Lines Functions and Methods CRAP Classes and Traits
StateCacheSync 100.00% 43 / 43 100.00% 10 / 10 21 100.00% 1 / 1
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 seedFromSnapshot 100.00% 7 / 7 100.00% 1 / 1 2
 awaitFirstSeed 100.00% 4 / 4 100.00% 1 / 1 2
 isOlderThan 100.00% 1 / 1 100.00% 1 / 1 1
 replaceWithResyncedStates 100.00% 4 / 4 100.00% 1 / 1 1
 applyStateUpdates 100.00% 5 / 5 100.00% 1 / 1 2
 countEntities 100.00% 1 / 1 100.00% 1 / 1 1
 buildResyncChanges 100.00% 9 / 9 100.00% 1 / 1 6
 hasChanged 100.00% 3 / 3 100.00% 1 / 1 4
 buildResyncChange 100.00% 8 / 8 100.00% 1 / 1 1
1<?php
2
3declare(strict_types=1);
4
5namespace Stewart\Runtime\Worker;
6
7use Amp\Cancellation;
8use Amp\CancelledException;
9use Amp\DeferredFuture;
10use Psr\Log\LoggerInterface;
11use Stewart\Contracts\Entity\EntityId;
12use Stewart\Contracts\State\Collection\EntityStateCollection;
13use Stewart\Contracts\State\EntityState;
14use Stewart\Contracts\State\StateChange;
15use Stewart\Contracts\State\StateChangeOrigin;
16use Stewart\Contracts\Time\Instant;
17use Stewart\Runtime\State\StateCache;
18use Stewart\Support\State\Collection\StateChangeCollection;
19use Stewart\Support\State\Collection\StateUpdateCollection;
20
21final class StateCacheSync
22{
23    private int $revision = 0;
24
25    private bool $seeded = false;
26
27    /** @var DeferredFuture<null> */
28    private readonly DeferredFuture $firstSeed;
29
30    public function __construct(
31        private readonly StateCache $stateCache,
32        private readonly LoggerInterface $logger,
33    ) {
34        $this->firstSeed = new DeferredFuture();
35    }
36
37    public function seedFromSnapshot(EntityStateCollection $states, int $revision): void
38    {
39        $this->stateCache->replaceAll($states);
40        $this->revision = $revision;
41
42        if ($this->seeded) {
43            return;
44        }
45
46        $this->seeded = true;
47
48        $this->logger->debug('State cache seeded', ['entities' => $this->stateCache->count(), 'revision' => $revision]);
49
50        $this->firstSeed->complete();
51    }
52
53    public function awaitFirstSeed(Cancellation $cancellation): bool
54    {
55        try {
56            $this->firstSeed->getFuture()->await($cancellation);
57        } catch (CancelledException) {
58            return false;
59        }
60
61        return true;
62    }
63
64    public function isOlderThan(int $revision): bool
65    {
66        return $revision > $this->revision;
67    }
68
69    public function replaceWithResyncedStates(EntityStateCollection $states, int $revision, Instant $resyncedAt): StateChangeCollection
70    {
71        $reconstructed = $this->buildResyncChanges($this->stateCache->getAllStates(), $states, $resyncedAt);
72
73        $this->stateCache->replaceAll($states);
74        $this->revision = $revision;
75
76        return $reconstructed;
77    }
78
79    public function applyStateUpdates(StateUpdateCollection $updates): StateChangeCollection
80    {
81        $changes = [];
82
83        foreach ($updates as $update) {
84            $changes[] = $update->toStateChange($this->stateCache->find($update->entityId));
85            $this->stateCache->applyUpdate($update);
86        }
87
88        return StateChangeCollection::fromList($changes);
89    }
90
91    public function countEntities(): int
92    {
93        return $this->stateCache->count();
94    }
95
96    private function buildResyncChanges(EntityStateCollection $before, EntityStateCollection $after, Instant $resyncedAt): StateChangeCollection
97    {
98        $changes = [];
99
100        foreach ($after as $state) {
101            $previous = $before->find($state->entityId);
102
103            if ($previous === null || $this->hasChanged($previous, $state)) {
104                $changes[] = $this->buildResyncChange($state->entityId, $previous, $state, $resyncedAt);
105            }
106        }
107
108        foreach ($before as $state) {
109            if ($after->find($state->entityId) === null) {
110                $changes[] = $this->buildResyncChange($state->entityId, $state, null, $resyncedAt);
111            }
112        }
113
114        return StateChangeCollection::fromList($changes);
115    }
116
117    private function hasChanged(EntityState $before, EntityState $after): bool
118    {
119        // HA bumps last_updated on any write; the fallback covers states without it.
120        if ($before->lastUpdatedAt !== null && $after->lastUpdatedAt !== null) {
121            return !$before->lastUpdatedAt->equals($after->lastUpdatedAt);
122        }
123
124        return $before->state !== $after->state || $before->attributes !== $after->attributes;
125    }
126
127    private function buildResyncChange(EntityId $entityId, ?EntityState $from, ?EntityState $to, Instant $resyncedAt): StateChange
128    {
129        return new StateChange(
130            entityId: $entityId,
131            from: $from,
132            to: $to,
133            firedAt: $to->lastUpdatedAt ?? $resyncedAt,
134            context: null,
135            origin: StateChangeOrigin::Resync,
136        );
137    }
138}