32 private static int $nextAsyncContextId = 1;
34 private readonly \Logger $logger;
37 private readonly \Closure $workerStartHook;
39 private readonly
int $asyncContextId;
45 private array $generatorRegisteredWorkers = [];
47 public function __construct(
51 int $asyncContextId =
null
53 $this->logger = new \PrefixedLogger($logger,
"AsyncGeneratorExecutor");
56 $this->asyncContextId = $asyncContextId ?? self::$nextAsyncContextId++;
58 $this->workerStartHook =
function(
int $workerId) :
void{
59 if(array_key_exists($workerId, $this->generatorRegisteredWorkers)){
60 $this->logger->debug(
"Worker $workerId with previously registered generator restarted, flagging as unregistered");
61 unset($this->generatorRegisteredWorkers[$workerId]);
64 $this->workerPool->addWorkerStartHook($this->workerStartHook);
67 private function registerGeneratorToWorker(
int $worker) :
void{
68 $this->logger->debug(
"Registering generator on worker $worker");
70 $this->generatorRegisteredWorkers[$worker] =
true;
73 private function unregisterGenerator() :
void{
74 foreach($this->workerPool->getRunningWorkers() as $i){
75 if(isset($this->generatorRegisteredWorkers[$i])){
79 $this->generatorRegisteredWorkers = [];
82 public function populate(
int $chunkX,
int $chunkZ, ?
Chunk $centerChunk, array $adjacentChunks, \Closure $onCompletion) : void{
84 $this->asyncContextId,
91 $workerId = $this->workerPool->selectWorker();
92 if(!isset($this->workerPool->getRunningWorkers()[$workerId]) && isset($this->generatorRegisteredWorkers[$workerId])){
93 $this->logger->debug(
"Selected worker $workerId previously had generator registered, but is now offline");
94 unset($this->generatorRegisteredWorkers[$workerId]);
96 if(!isset($this->generatorRegisteredWorkers[$workerId])){
97 $this->registerGeneratorToWorker($workerId);
99 $this->workerPool->submitTaskToWorker($task, $workerId);
102 public function shutdown() : void{
103 $this->unregisterGenerator();
104 $this->workerPool->removeWorkerStartHook($this->workerStartHook);