53 lines
2.6 KiB
PHP
53 lines
2.6 KiB
PHP
<?php
|
|
namespace App\Services\PaymentHealth;
|
|
|
|
use RuntimeException;
|
|
|
|
class StateStore
|
|
{
|
|
private $handle;
|
|
public function __construct(private string $path) {}
|
|
|
|
public function acquire(): bool
|
|
{
|
|
$dir=dirname($this->path);
|
|
$newDirectory=!is_dir($dir);$parent=dirname($dir);while(!is_dir($parent)&&dirname($parent)!==$parent)$parent=dirname($parent);
|
|
if ($newDirectory && !mkdir($dir,0700,true) && !is_dir($dir)) throw new RuntimeException('state_directory_failed');
|
|
if($newDirectory&&function_exists('posix_geteuid')&&posix_geteuid()===0){chown($dir,fileowner($parent));chgrp($dir,filegroup($parent));}
|
|
if (is_link($dir) || is_link($this->path) || is_link($this->path.'.lock')) throw new RuntimeException('unsafe_state_path');
|
|
$this->handle=fopen($this->path.'.lock','c+');
|
|
if (!$this->handle) throw new RuntimeException('state_lock_failed');
|
|
chmod($this->path.'.lock',0600);
|
|
$this->inheritOwner($this->path.'.lock');
|
|
return flock($this->handle,LOCK_EX|LOCK_NB);
|
|
}
|
|
public function read(): array
|
|
{
|
|
if (!is_file($this->path)) return ['version'=>1,'channels'=>[],'events'=>[],'budget'=>[]];
|
|
$value=json_decode(file_get_contents($this->path),true,512,JSON_THROW_ON_ERROR);
|
|
if (!is_array($value) || ($value['version']??null)!==1 || !is_array($value['channels']??null) || !is_array($value['events']??null) || !is_array($value['budget']??null)) throw new RuntimeException('invalid_health_state');
|
|
return $value;
|
|
}
|
|
public function save(array $state): void
|
|
{
|
|
$temp=$this->path.'.'.bin2hex(random_bytes(6)).'.tmp';
|
|
try {
|
|
$data=json_encode($state,JSON_UNESCAPED_UNICODE|JSON_THROW_ON_ERROR);
|
|
$h=fopen($temp,'x');if (!$h) throw new RuntimeException('state_write_failed');
|
|
chmod($temp,0600);$this->inheritOwner($temp);
|
|
try {if (fwrite($h,$data)!==strlen($data)) throw new RuntimeException('short_state_write');fflush($h);if(function_exists('fsync'))fsync($h);}finally{fclose($h);}
|
|
if (!rename($temp,$this->path)) throw new RuntimeException('state_rename_failed');
|
|
} finally {if(is_file($temp))unlink($temp);}
|
|
}
|
|
private function inheritOwner(string $file):void
|
|
{
|
|
if(function_exists('posix_geteuid')&&posix_geteuid()===0){chown($file,fileowner(dirname($this->path)));chgrp($file,filegroup(dirname($this->path)));}
|
|
}
|
|
public function release(): void
|
|
{
|
|
if(is_resource($this->handle)){flock($this->handle,LOCK_UN);fclose($this->handle);}
|
|
$this->handle=null;
|
|
}
|
|
public function __destruct(){ $this->release(); }
|
|
}
|