2019-09-05 20:33:27 -07:00
< ? php
2024-03-12 22:39:16 -04:00
namespace App\Repositories\Daemon ;
2019-09-05 20:33:27 -07:00
2024-03-12 22:39:16 -04:00
use App\Models\Node ;
use App\Models\Server ;
2025-05-01 15:49:35 +02:00
use Illuminate\Http\Client\ConnectionException ;
2025-09-24 13:34:19 +02:00
use Illuminate\Http\Client\PendingRequest ;
2025-05-01 15:49:35 +02:00
use Illuminate\Http\Client\Response ;
2025-09-24 13:34:19 +02:00
use Illuminate\Support\Facades\Http ;
use Webmozart\Assert\Assert ;
2019-09-05 20:33:27 -07:00
abstract class DaemonRepository
{
2022-10-14 10:59:20 -06:00
protected ? Server $server ;
2019-09-05 20:33:27 -07:00
2022-10-14 10:59:20 -06:00
protected ? Node $node ;
2019-09-05 20:33:27 -07:00
/**
* Set the server model this request is stemming from .
2024-03-17 13:59:21 -04:00
*
* @ return static
2019-09-05 20:33:27 -07:00
*/
2024-03-17 13:59:21 -04:00
public function setServer ( Server $server ) : self
2019-09-05 20:33:27 -07:00
{
$this -> server = $server ;
$this -> setNode ( $this -> server -> node );
return $this ;
}
/**
* Set the node model this request is stemming from .
*/
2024-03-17 12:52:22 -04:00
public function setNode ( Node $node ) : static
2019-09-05 20:33:27 -07:00
{
$this -> node = $node ;
return $this ;
}
/**
* Return an instance of the Guzzle HTTP Client to be used for requests .
2025-03-03 14:41:19 -05:00
*
* @ param array < string , string > $headers
2019-09-05 20:33:27 -07:00
*/
2024-03-23 16:10:47 -04:00
public function getHttpClient ( array $headers = []) : PendingRequest
2019-09-05 20:33:27 -07:00
{
2019-09-05 21:16:36 -07:00
Assert :: isInstanceOf ( $this -> node , Node :: class );
2019-09-05 20:33:27 -07:00
2025-05-01 15:49:35 +02:00
return Http :: daemon ( $this -> node , $headers ) -> throwIf ( fn ( $condition ) => $this -> enforceValidNodeToken ( $condition ));
}
protected function enforceValidNodeToken ( Response | bool $condition ) : bool
{
if ( is_bool ( $condition )) {
return $condition ;
}
$header = $condition -> header ( 'User-Agent' );
2026-07-09 09:55:11 -04:00
throw_if ( empty ( $header ) ||
2025-05-01 15:49:35 +02:00
preg_match ( '/^Pelican Wings\/v(?:\d+\.\d+\.\d+|develop) \(id:(\w*)\)$/' , $header , $matches ) &&
2026-07-09 09:55:11 -04:00
array_get ( $matches , 1 , '' ) !== $this -> node -> daemon_token_id , new ConnectionException ( $condition -> effectiveUri () -> __toString () . ' does not match node token_id !' ));
2025-05-01 15:49:35 +02:00
return true ;
2019-09-05 20:33:27 -07:00
}
}