private function doLoadKeyPair(string $path) : Generator { $privateExists = (yield exists("{$path}/private.pem")); $publicExists = (yield exists("{$path}/public.pem")); $lockExists = (yield exists("{$path}/key.lock")); if ($privateExists && $publicExists) { while ($lockExists) { (yield new Pause(500)); $lockExists = (yield exists("{$path}/key.lock")); } return new KeyPair((yield get("{$path}/private.pem")), (yield get("{$path}/public.pem"))); } $lock = new Lock("{$path}/key.lock"); try { $lock->acquire(); $gen = new OpenSSLKeyGenerator(); $keyPair = $gen->generate(4096); (yield put("{$path}/private.pem", $keyPair->getPrivate())); (yield put("{$path}/public.pem", $keyPair->getPublic())); return $keyPair; } catch (Exception $e) { do { (yield new Pause(500)); $lockExists = (yield exists("{$path}/key.lock")); } while ($lockExists); return new KeyPair((yield get("{$path}/private.pem")), (yield get("{$path}/public.pem"))); } finally { $lock->release(); unlink("{$path}/key.lock"); // do not yield in finally! } }