Lines 100.00% 22 / 22
Functions and Methods 100.00% 4 / 4
Classes and Traits 100.00% 1 / 1
Name Lines Functions and Methods CRAP Classes and Traits
AppPlacement 100.00% 22 / 22 100.00% 4 / 4 9 100.00% 1 / 1
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 planWorkerSlots 100.00% 9 / 9 100.00% 1 / 1 3
 findHighestWeightWorker 100.00% 8 / 8 100.00% 1 / 1 3
 resolvePoolSize 100.00% 4 / 4 100.00% 1 / 1 2
1<?php
2
3declare(strict_types=1);
4
5namespace Stewart\Runtime\Broker;
6
7use Stewart\Contracts\App\AppId;
8use Stewart\Runtime\App\AppDefinition;
9use Stewart\Runtime\App\Collection\AppDefinitionCollection;
10use Stewart\Runtime\Broker\Collection\WorkerSlotCollection;
11use Stewart\Runtime\Config\StewartConfig;
12use Stewart\Runtime\Model\WorkerId;
13
14final readonly class AppPlacement
15{
16    public function __construct(private int $autoPoolSize) {}
17
18    public function planWorkerSlots(AppDefinitionCollection $apps, StewartConfig $config): WorkerSlotCollection
19    {
20        $poolSize = $this->resolvePoolSize($apps, $config->workers);
21        $byWorker = [];
22
23        foreach ($apps as $app) {
24            $byWorker[$app->worker ?? $this->findHighestWeightWorker($app->id, $poolSize)][] = $app;
25        }
26
27        ksort($byWorker);
28        $slots = [];
29
30        foreach ($byWorker as $workerId => $workerApps) {
31            $slots[] = new WorkerSlot(WorkerId::fromInt($workerId), AppDefinitionCollection::keyedByAppId($workerApps));
32        }
33
34        return WorkerSlotCollection::fromList($slots);
35    }
36
37    // Rendezvous hashing: an app moves only when the worker it wins is added or removed, never because of other apps.
38    private function findHighestWeightWorker(AppId $appId, int $poolSize): int
39    {
40        $chosen = 0;
41        $highestWeight = '';
42
43        for ($workerId = 0; $workerId < $poolSize; ++$workerId) {
44            $weight = hash('xxh3', $appId->value . "\0" . $workerId);
45
46            // strcmp, because > compares numeric-looking hex strings as numbers.
47            if (strcmp($weight, $highestWeight) > 0) {
48                $chosen = $workerId;
49                $highestWeight = $weight;
50            }
51        }
52
53        return $chosen;
54    }
55
56    private function resolvePoolSize(AppDefinitionCollection $apps, int $workers): int
57    {
58        if ($workers > 0) {
59            return $workers;
60        }
61
62        $highestPin = max([-1, ...$apps->mapToList(static fn(AppDefinition $app): int => $app->worker ?? -1)]);
63
64        return max(1, $this->autoPoolSize, $highestPin + 1);
65    }
66}