Lines 100.00% 123 / 123
Functions and Methods 100.00% 16 / 16
Classes and Traits 100.00% 1 / 1
Name Lines Functions and Methods CRAP Classes and Traits
Client 100.00% 123 / 123 100.00% 16 / 16 52 100.00% 1 / 1
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 enter 100.00% 36 / 36 100.00% 1 / 1 10
 askForThePlayer 100.00% 2 / 2 100.00% 1 / 1 1
 subscribe 100.00% 1 / 1 100.00% 1 / 1 1
 character 100.00% 1 / 1 100.00% 1 / 1 1
 run 100.00% 15 / 15 100.00% 1 / 1 6
 send 100.00% 1 / 1 100.00% 1 / 1 1
 wait 100.00% 8 / 8 100.00% 1 / 1 4
 execute 100.00% 13 / 13 100.00% 1 / 1 5
 receive 100.00% 19 / 19 100.00% 1 / 1 8
 listen 100.00% 13 / 13 100.00% 1 / 1 5
 close 100.00% 1 / 1 100.00% 1 / 1 1
 server 100.00% 1 / 1 100.00% 1 / 1 1
 awaiting 100.00% 1 / 1 100.00% 1 / 1 1
 recognize 100.00% 6 / 6 100.00% 1 / 1 3
 hear 100.00% 4 / 4 100.00% 1 / 1 3
1<?php
2
3declare(strict_types=1);
4
5namespace Lorekeeper\Client;
6
7use Closure;
8use Lorekeeper\Client\Command\Command;
9use Lorekeeper\Client\Command\Inventory\LoadPlayerInventoryCommand;
10use Lorekeeper\Client\Command\Map\JoinInitialMapCommand;
11use Lorekeeper\Client\Command\Session\LoadPlayerDataCommand;
12use Lorekeeper\Client\Command\Session\LoginCommand;
13use Lorekeeper\Client\Command\Session\PolicyFileRequestCommand;
14use Lorekeeper\Client\Script\Await;
15use Lorekeeper\Client\Script\Disconnected;
16use Lorekeeper\Client\Script\Failed;
17use Lorekeeper\Client\Script\Instruction;
18use Lorekeeper\Client\Script\Pause;
19use Lorekeeper\Client\Script\Script;
20use Lorekeeper\Client\Script\Send;
21use Lorekeeper\Client\Script\Stopped;
22use Lorekeeper\Client\Script\TimedOut;
23use Lorekeeper\Client\Session\Entrance;
24use Lorekeeper\Client\Session\GameLogin;
25use Lorekeeper\Server\Event\Event;
26use Lorekeeper\Server\Event\Events;
27use Lorekeeper\Server\Event\Map\MovedToMapEvent;
28use Lorekeeper\Server\Event\Session\ConnectionEstablishedEvent;
29use Lorekeeper\Server\Event\Session\LoginFailedEvent;
30use Lorekeeper\Server\Event\Session\LoginSucceededEvent;
31use Lorekeeper\Server\Exception\MalformedEventException;
32use Lorekeeper\Server\Message\Message;
33use Lorekeeper\Server\Server;
34use Psl\Async;
35use Psl\Async\CancellationTokenInterface;
36use Psl\Async\Exception\CancelledException;
37use Psl\Async\NullCancellationToken;
38use Psl\DateTime\Duration;
39use Psl\DateTime\Timestamp;
40use RuntimeException;
41
42/**
43 * @mago-expect lint:cyclomatic-complexity
44 * @mago-expect lint:kan-defect
45 * @mago-expect lint:too-many-methods
46 */
47final class Client
48{
49    /** @var list<Closure(Event): void> */
50    private array $subscribers = [];
51
52    public function __construct(
53        private readonly Connection $connection,
54        private readonly Character $me,
55    ) {}
56
57    /** @throws CancelledException */
58    public static function enter(
59        Connection $connection,
60        GameLogin $login,
61        CancellationTokenInterface $stop = new NullCancellationToken(),
62    ): self|LoginFailedEvent|TimedOut|Disconnected|Stopped {
63        $entrance = new Entrance($login->player);
64        $hear = static function (Message $message) use ($entrance): void {
65            foreach (self::recognize($message) as $event) {
66                $entrance->hear($event);
67            }
68        };
69
70        try {
71            $connection->send(new PolicyFileRequestCommand());
72            $policy = self::receive($connection, self::awaiting(ConnectionEstablishedEvent::class), $stop, $hear);
73            if ($policy instanceof TimedOut) {
74                return $policy;
75            }
76
77            $connection->send(new LoginCommand($login->player, $login->token, $login->version));
78            /** @var LoginSucceededEvent|LoginFailedEvent|TimedOut $logged */
79            $logged = self::receive(
80                $connection,
81                self::awaiting(LoginSucceededEvent::class, LoginFailedEvent::class),
82                $stop,
83                $hear,
84            );
85            if (!$logged instanceof LoginSucceededEvent) {
86                return $logged;
87            }
88
89            $connection->send(new JoinInitialMapCommand());
90            /** @var MovedToMapEvent|TimedOut $arrival */
91            $arrival = self::receive($connection, self::awaiting(MovedToMapEvent::class), $stop, $hear);
92            if ($arrival instanceof TimedOut) {
93                return $arrival;
94            }
95
96            self::askForThePlayer($connection, $arrival, $logged);
97            $missing = $entrance->missing();
98            while ($missing !== []) {
99                $heard = self::receive($connection, new Await($missing, Duration::seconds(15)), $stop, $hear);
100                if ($heard instanceof TimedOut) {
101                    return $heard;
102                }
103
104                $missing = $entrance->missing();
105            }
106
107            return new self($connection, $entrance->character());
108        } catch (PeerClosedException $closed) {
109            return new Disconnected($closed->getMessage());
110        } catch (CancelledException $cancelled) {
111            if (!$stop->isCancelled()) {
112                throw $cancelled;
113            }
114
115            return new Stopped();
116        }
117    }
118
119    /** @throws PeerClosedException */
120    private static function askForThePlayer(
121        Connection $connection,
122        MovedToMapEvent $arrival,
123        LoginSucceededEvent $logged,
124    ): void {
125        $connection->send(new LoadPlayerInventoryCommand($arrival->areaId, $logged->spawnId));
126        $connection->send(new LoadPlayerDataCommand($arrival->areaId, $logged->spawnId));
127    }
128
129    /** @param Closure(Event): void $subscriber */
130    public function subscribe(Closure $subscriber): void
131    {
132        $this->subscribers[] = $subscriber;
133    }
134
135    public function character(): Character
136    {
137        return $this->me;
138    }
139
140    /**
141     * @template TResult
142     *
143     * @param Script<TResult> $script
144     *
145     * @return TResult|Disconnected|Stopped
146     */
147    public function run(Script $script, CancellationTokenInterface $stop = new NullCancellationToken()): mixed
148    {
149        $steps = $script->run($this->me);
150
151        try {
152            while ($steps->valid()) {
153                $stop->throwIfCancelled();
154                $instruction = $steps->current();
155                $answer = $this->execute($instruction, $stop);
156
157                $steps->send($answer);
158            }
159        } catch (PeerClosedException $closed) {
160            return new Disconnected($closed->getMessage());
161        } catch (CancelledException $cancelled) {
162            if (!$stop->isCancelled()) {
163                throw $cancelled;
164            }
165
166            return new Stopped();
167        } catch (RuntimeException $broke) {
168            return new Failed($broke->getMessage());
169        }
170
171        return $steps->getReturn();
172    }
173
174    /** @throws PeerClosedException */
175    public function send(Command $command): void
176    {
177        $this->connection->send($command);
178    }
179
180    public function wait(
181        Duration $duration,
182        CancellationTokenInterface $stop = new NullCancellationToken(),
183    ): null|Disconnected|Stopped {
184        try {
185            $this->listen(new Pause($duration), $stop);
186        } catch (PeerClosedException $closed) {
187            return new Disconnected($closed->getMessage());
188        } catch (CancelledException $cancelled) {
189            if (!$stop->isCancelled()) {
190                throw $cancelled;
191            }
192
193            return new Stopped();
194        }
195
196        return null;
197    }
198
199    /** @throws PeerClosedException */
200    private function execute(Instruction $instruction, CancellationTokenInterface $stop): null|Event|TimedOut
201    {
202        if ($instruction instanceof Pause) {
203            $this->listen($instruction, $stop);
204
205            return null;
206        }
207
208        if ($instruction instanceof Send) {
209            $this->connection->send($instruction->command);
210
211            return (
212                $instruction->await === null
213                    ? null
214                    : self::receive($this->connection, $instruction->await, $stop, $this->hear(...))
215            );
216        }
217
218        if ($instruction instanceof Await) {
219            return self::receive($this->connection, $instruction, $stop, $this->hear(...));
220        }
221
222        return null;
223    }
224
225    /**
226     * @param Closure(Message): void $hear
227     *
228     * @throws PeerClosedException
229     * @throws CancelledException
230     */
231    private static function receive(
232        Connection $connection,
233        Await $await,
234        CancellationTokenInterface $stop,
235        Closure $hear,
236    ): Event|TimedOut {
237        $deadline = Timestamp::monotonic()->plus($await->timeout);
238
239        while (true) {
240            $left = $deadline->since(Timestamp::monotonic());
241            if (!$left->isPositive()) {
242                return new TimedOut($await);
243            }
244
245            try {
246                $message = $connection->receive(
247                    new Async\LinkedCancellationToken(new Async\TimeoutCancellationToken($left), $stop),
248                );
249            } catch (CancelledException $cancelled) {
250                if ($stop->isCancelled()) {
251                    throw $cancelled;
252                }
253
254                return new TimedOut($await);
255            }
256
257            if ($message->isNone()) {
258                continue;
259            }
260
261            $hear($message->unwrap());
262
263            foreach ($await->events as $event) {
264                $heard = Events::read($event, $message->unwrap());
265                if ($heard->isSome()) {
266                    return $heard->unwrap();
267                }
268            }
269        }
270    }
271
272    /** @throws PeerClosedException */
273    private function listen(Pause $pause, CancellationTokenInterface $stop): void
274    {
275        $deadline = Timestamp::monotonic()->plus($pause->duration);
276
277        while (true) {
278            $left = $deadline->since(Timestamp::monotonic());
279            if (!$left->isPositive()) {
280                return;
281            }
282
283            try {
284                $message = $this->connection->receive(
285                    new Async\LinkedCancellationToken(new Async\TimeoutCancellationToken($left), $stop),
286                );
287            } catch (CancelledException $cancelled) {
288                if ($stop->isCancelled()) {
289                    throw $cancelled;
290                }
291
292                return;
293            }
294
295            $message->apply($this->hear(...));
296        }
297    }
298
299    public function close(): void
300    {
301        $this->connection->close();
302    }
303
304    public function server(): ?Server
305    {
306        return $this->connection->server();
307    }
308
309    /**
310     * @param class-string<Event> $event
311     * @param class-string<Event> ...$more
312     */
313    private static function awaiting(string $event, string ...$more): Await
314    {
315        return new Await([$event, ...array_values($more)], Duration::seconds(15));
316    }
317
318    /**
319     * @throws MalformedEventException
320     *
321     * @return list<Event>
322     */
323    private static function recognize(Message $message): array
324    {
325        $events = [];
326        foreach (Events::recognize($message) as $event) {
327            if (!$event instanceof Event) {
328                throw $event;
329            }
330
331            $events[] = $event;
332        }
333
334        return $events;
335    }
336
337    /** @throws MalformedEventException */
338    private function hear(Message $message): void
339    {
340        foreach (self::recognize($message) as $event) {
341            $this->me->hear($event);
342            foreach ($this->subscribers as $subscriber) {
343                $subscriber($event);
344            }
345        }
346    }
347}