프로덕션 레퍼런스: 액터
프로덕션 레퍼런스: 액터 (Production Reference: Actors)
PHP 액터를 프로덕션에서 실행하는 방법을 알아봐요.
출처: Dapr 문서
본문
프록시 모드 (Proxy modes)
액터 프록시를 처리하는 네 가지 모드가 있어요. 각 모드는 개발과 프로덕션에서 저울질(weigh)해야 할 서로 다른 트레이드오프를 제시해요.
<?php
\Dapr\Actors\Generators\ProxyFactory::GENERATED;
\Dapr\Actors\Generators\ProxyFactory::GENERATED_CACHED;
\Dapr\Actors\Generators\ProxyFactory::ONLY_EXISTING;
\Dapr\Actors\Generators\ProxyFactory::DYNAMIC;
이것은 dapr.actors.proxy.generation 구성 키로 설정할 수 있어요.
- GENERATED
- GENERATED_CACHED
- ONLY_EXISTING
- DYNAMIC
GENERATED 모드는 기본 모드예요. 이 모드에서는 매 요청마다 클래스가 생성되고 eval로 실행돼요. 주로 개발용이고 프로덕션에서는 사용하면 안 돼요.
GENERATED_CACHED는 ProxyModes::GENERATED와 같지만 클래스가 tmp 파일에 저장되어 매 요청마다 다시 생성할 필요가 없어요. 캐시된 클래스를 언제 업데이트해야 하는지 모르기 때문에 개발에서 사용하는 것은 권장되지 않지만, 파일을 수동으로 생성할 수 없는 경우를 위해 제공돼요.
ONLY_EXISTING 모드에서는 프록시 클래스가 존재하지 않으면 예외가 발생해요. 프로덕션에서 코드를 생성하고 싶지 않을 때 유용해요. 클래스가 생성되어 사전/자동 로드되도록 해야 해요.
프록시 생성하기 (Generating proxies)
ONLY_EXISTING 모드를 활용하려면 컴포저 스크립트를 만들어서 필요할 때 프록시를 생성할 수 있어요.
ProxyCompiler.php를 만들어요.
<?php
class ProxyCompiler {
private const PROXIES = [
MyActorInterface::class,
MyOtherActorInterface::class,
];
private const PROXY_LOCATION = __DIR__.'/proxies/';
public static function compile() {
try {
$app = \Dapr\App::create();
foreach(self::PROXIES as $interface) {
$output = $app->run(function(\DI\FactoryInterface $factory) use ($interface) {
return \Dapr\Actors\Generators\FileGenerator::generate($interface, $factory);
});
$reflection = new ReflectionClass($interface);
$dapr_type = $reflection->getAttributes(\Dapr\Actors\Attributes\DaprType::class)[0]->newInstance()->type;
$filename = 'dapr_proxy_'.$dapr_type.'.php';
file_put_contents(self::PROXY_LOCATION.$filename, $output);
echo "Compiled: $interface";
}
} catch (Exception $ex) {
echo "Failed to generate proxy for $interface\n{$ex->getMessage()} on line {$ex->getLine()} in {$ex->getFile()}\n";
}
}
}
그다음 생성된 프록시를 위한 psr-4 오토로더와 composer.json의 스크립트를 추가해요:
{
"autoload": {
"psr-4": {
"Dapr\\Proxies\\": "path/to/proxies"
}
},
"scripts": {
"compile-proxies": "ProxyCompiler::compile"
}
}
그리고 마지막으로 dapr이 생성된 프록시만 사용하도록 구성해요:
<?php
// in config.php
return [
'dapr.actors.proxy.generation' => ProxyFactory::ONLY_EXISTING,
];
DYNAMIC 모드에서는 프록시가 인터페이스 계약을 충족하지만, 실제로 인터페이스 자체를 구현하지는 않아요(instanceof가 false가 된다는 뜻). 이 모드는 PHP의 몇 가지 특성을 활용해서 동작하며, 코드를 eval하거나 생성할 수 없는 경우를 위해 존재해요.
요청 (Requests)
액터 프록시를 만드는 것은 어떤 모드에서든 매우 저렴해요. 액터 프록시 객체를 만들 때는 요청이 발생하지 않아요. 프록시 객체에서 메서드를 호출하면, 여러분이 구현한 메서드만 액터 구현이 처리해요.
get_id()는 로컬에서 처리되고, get_reminder(), delete_reminder() 등은 daprd가 처리해요.
액터 구현 (Actor implementation)
PHP의 모든 액터 구현은 \Dapr\Actors\IActor를 구현하고 \Dapr\Actors\ActorTrait 트레이트를 사용해야 해요. 이렇게 하면 빠른 리플렉션과 몇 가지 단축키를 사용할 수 있어요. \Dapr\Actors\Actor 추상 기본 클래스를 사용하면 이 작업을 대신 해주지만, 기본 동작을 재정의해야 한다면 인터페이스를 구현하고 트레이트를 사용해서 직접 할 수 있어요.
활성화와 비활성화 (Activation and deactivation)
액터가 활성화되면 토큰 파일이 임시 디렉터리에 기록돼요(기본적으로 Linux에서는 '/tmp/dapr_' + sha256(concat(Dapr type, id)), Windows에서는 '%temp%/dapr_' + sha256(concat(Dapr type, id))). 이것은 액터가 비활성화되거나 호스트가 종료될 때까지 유지돼요. 이렇게 하면 Dapr이 호스트에서 액터를 활성화할 때 on_activation이 정확히 한 번만 호출될 수 있어요.
성능 (Performance)
php-fpm과 nginx, 또는 Windows의 IIS를 사용하는 프로덕션 구성에서 액터 메서드 호출은 매우 빨라요. 액터가 매 요청마다 구성되긴 하지만, 액터 상태 키는 각 요청 중에 호출되지 않고 필요할 때만(ondemand) 로드돼요.
하지만 각 키를 개별적으로 로드하는 데는 약간의 오버헤드가 있어요. 데이터 배열을 상태에 저장하면 이 문제를 완화할 수 있는데, 사용성이 약간 줄어드는 대신 속도를 얻어요. 처음부터 이렇게 하는 것은 권장하지 않고, 필요할 때 최적화로 사용하는 것이 좋아요.
상태 버전 관리 (Versioning state)
ActorState 객체의 변수 이름은 저장소의 키 이름과 직접 대응돼요. 즉 변수의 타입이나 이름을 변경하면 오류가 발생할 수 있다는 뜻이에요. 이를 피하려면 상태 객체를 버전 관리해야 할 수 있어요. 이렇게 하려면 상태가 로드되고 저장되는 방식을 재정의해야 해요. 접근 방법은 여러 가지가 있는데, 한 가지 해결책은 이런 식일 수 있어요:
<?php
class VersionedState extends \Dapr\Actors\ActorState {
/**
* @var int The current version of the state in the store. We give a default value of the current version.
* However, it may be in the store with a different value.
*/
public int $state_version = self::VERSION;
/**
* @var int The current version of the data
*/
private const VERSION = 3;
/**
* Call when your actor activates.
*/
public function upgrade() {
if($this->state_version < self::VERSION) {
$value = parent::__get($this->get_versioned_key('key', $this->state_version));
// update the value after updating the data structure
parent::__set($this->get_versioned_key('key', self::VERSION), $value);
$this->state_version = self::VERSION;
$this->save_state();
}
}
// if you upgrade all keys as needed in the method above, you don't need to walk the previous
// keys when loading/saving and you can just get the current version of the key.
private function get_previous_version(int $version): int {
return $this->has_previous_version($version) ? $version - 1 : $version;
}
private function has_previous_version(int $version): bool {
return $version >= 0;
}
private function walk_versions(int $version, callable $callback, callable $predicate): mixed {
$value = $callback($version);
if($predicate($value) || !$this->has_previous_version($version)) {
return $value;
}
return $this->walk_versions($this->get_previous_version($version), $callback, $predicate);
}
private function get_versioned_key(string $key, int $version) {
return $this->has_previous_version($version) ? $version.$key : $key;
}
public function __get(string $key): mixed {
return $this->walk_versions(
self::VERSION,
fn($version) => parent::__get($this->get_versioned_key($key, $version)),
fn($value) => isset($value)
);
}
public function __isset(string $key): bool {
return $this->walk_versions(
self::VERSION,
fn($version) => parent::__isset($this->get_versioned_key($key, $version)),
fn($isset) => $isset
);
}
public function __set(string $key,mixed $value): void {
// optional: you can unset previous versions of the key
parent::__set($this->get_versioned_key($key, self::VERSION), $value);
}
public function __unset(string $key) : void {
// unset this version and all previous versions
$this->walk_versions(
self::VERSION,
fn($version) => parent::__unset($this->get_versioned_key($key, $version)),
fn() => false
);
}
}
최적화할 부분이 많고, 이 코드를 프로덕션에서 그대로(verbatim) 사용하는 것은 좋지 않지만, 어떻게 동작하는지 대략적인 감은 잡을 수 있어요. 많이 사용자의 사용 사례에 달려 있기 때문에 SDK에 이런 게 없는 거예요. 예를 들어 이 예제 구현에서는 업그레이드 중 버그가 있을 수 있는 경우를 위해 이전 값을 유지해요. 이전 값을 유지하면 업그레이드를 다시 실행할 수 있지만, 이전 값을 삭제하고 싶을 수도 있어요.