You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/tests/AdministratorTelegramChanne...

374 lines
13 KiB
PHP

<?php
// In-memory contract: no application bootstrap, database or Telegram network.
namespace App\Models {
final class User
{
public static array $rows = [];
public function __construct(
public int $id,
public int $is_admin = 1,
public int $enable = 1
) {}
public static function find($id): ?self
{
return self::$rows[(int) $id] ?? null;
}
}
final class Configurations
{
public static array $rows = [];
public static int $transactions = 0;
public static int $locks = 0;
public static bool $failReads = false;
public function __construct(public string $name = '', public string $value = '{}') {}
public static function where($key, $value): \AdministratorTelegramChannelQuery
{
return new \AdministratorTelegramChannelQuery((string) $value);
}
public function getConnection(): \AdministratorTelegramChannelConnection
{
return new \AdministratorTelegramChannelConnection();
}
public function save(): bool
{
self::$rows[$this->name] = clone $this;
return true;
}
}
}
namespace App\Services {
final class Config
{
public static string $superAdministrators = '1';
public static function get(string $key, mixed $default = null): mixed
{
return $key === 'super_admin' ? self::$superAdministrators : $default;
}
}
final class TicketTelegramConfig
{
public const BINDING = 'ticket_telegram_binding';
public static bool $enabled = true;
public static bool $failRuntime = false;
public static string $token = '123456789:' . 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA';
public static function runtime(bool $requireEnabled = true): array
{
if ($requireEnabled && !self::$enabled) {
throw new \RuntimeException('disabled');
}
return ['bot_token' => self::$token];
}
public static function runtimeForDelivery(): ?array
{
if (self::$failRuntime) {
throw new \RuntimeException('synthetic configuration database failure');
}
return self::$enabled ? ['bot_token' => self::$token] : null;
}
}
}
namespace {
use App\Models\Configurations;
use App\Models\User;
use App\Services\TicketTelegramConfig;
use App\Services\Telegram\AdministratorTelegramChannel;
use App\Services\Telegram\AdministratorTelegramLocalUnavailable;
use App\Services\Telegram\AdministratorTelegramPreflightException;
use App\Services\Telegram\AdministratorTelegramRateLimiter;
use App\Services\Telegram\AdministratorTelegramRemoteEffectUnknown;
use App\Services\Telegram\AdministratorTelegramTransport;
require dirname(__DIR__) . '/app/Services/Telegram/AdministratorTelegramDestination.php';
require dirname(__DIR__) . '/app/Services/Telegram/AdministratorTelegramDeliveryChannel.php';
require dirname(__DIR__) . '/app/Services/Telegram/AdministratorTelegramTransport.php';
require dirname(__DIR__) . '/app/Services/Telegram/AdministratorTelegramPreflightException.php';
require dirname(__DIR__) . '/app/Services/Telegram/AdministratorTelegramLocalUnavailable.php';
require dirname(__DIR__) . '/app/Services/Telegram/AdministratorTelegramRemoteEffectUnknown.php';
require dirname(__DIR__) . '/app/Services/Telegram/AdministratorTelegramRateBacklog.php';
require dirname(__DIR__) . '/app/Services/Telegram/AdministratorTelegramRateLimiter.php';
require dirname(__DIR__) . '/app/Services/Telegram/DatabaseAdministratorTelegramRateGate.php';
final class AdministratorTelegramChannelFakeRateLimiter
implements AdministratorTelegramRateLimiter
{
public int $calls = 0;
public mixed $hook = null;
public function acquire(
\App\Services\Telegram\AdministratorTelegramDestination $destination
): void {
$this->calls++;
if (is_callable($this->hook)) {
($this->hook)();
}
}
}
final class AdministratorTelegramChannelConnection
{
public function transaction(callable $callback): mixed
{
Configurations::$transactions++;
try {
return $callback();
} finally {
Configurations::$transactions--;
}
}
}
final class AdministratorTelegramChannelQuery
{
public function __construct(private readonly string $name) {}
public function lockForUpdate(): self
{
if (Configurations::$transactions !== 1) {
throw new RuntimeException('lock outside transaction');
}
Configurations::$locks++;
return $this;
}
public function first(): ?Configurations
{
if (Configurations::$failReads) {
throw new RuntimeException('synthetic binding database failure');
}
$row = Configurations::$rows[$this->name] ?? null;
return $row === null ? null : clone $row;
}
}
final class AdministratorTelegramChannelFakeTransport
implements AdministratorTelegramTransport
{
public array $calls = [];
public bool $fail = false;
public function sendMessage(
string $botToken,
string $chatId,
string $text,
array $options = []
): int {
$this->calls[] = compact('botToken', 'chatId', 'text', 'options');
if ($this->fail) {
throw new AdministratorTelegramRemoteEffectUnknown(
'synthetic transport failure'
);
}
return 9001;
}
}
require dirname(__DIR__) . '/app/Services/Telegram/TelegramBotApiTransport.php';
require dirname(__DIR__) . '/app/Services/Telegram/AdministratorTelegramChannel.php';
$assert = static function (bool $condition, string $message): void {
if (!$condition) {
fwrite(STDERR, $message . PHP_EOL);
exit(1);
}
};
$expectFailure = static function (callable $callback, string $message) use ($assert): void {
try {
$callback();
} catch (Throwable $exception) {
return;
}
$assert(false, $message);
};
$setBinding = static function (array $state): void {
Configurations::$rows[TicketTelegramConfig::BINDING] = new Configurations(
TicketTelegramConfig::BINDING,
json_encode($state, JSON_THROW_ON_ERROR)
);
};
User::$rows[1] = new User(1);
$transport = new AdministratorTelegramChannelFakeTransport();
$rateLimiter = new AdministratorTelegramChannelFakeRateLimiter();
$channel = new AdministratorTelegramChannel($transport, $rateLimiter);
$setBinding(['bound_admin_id' => 1, 'chat_id' => '123456']);
$destination = $channel->currentDestination();
$assert($destination !== null
&& $destination->administratorId === 1
&& $destination->chatId === '123456'
&& preg_match('/^[a-f0-9]{32}$/D', $destination->bindingGeneration) === 1
&& Configurations::$locks === 1
&& Configurations::$transactions === 0,
'Legacy binding was not upgraded atomically with a valid generation.');
$messageId = $channel->send($destination, 'Test alert', [
'disable_web_page_preview' => 'true',
]);
$assert($messageId === 9001 && count($transport->calls) === 1
&& $rateLimiter->calls === 1
&& $transport->calls[0]['chatId'] === '123456'
&& $transport->calls[0]['botToken'] === TicketTelegramConfig::$token,
'Authoritative destination was not sent exactly once.');
$rateLimiter->hook = static function () use ($setBinding): void {
$setBinding([
'bound_admin_id' => 1,
'chat_id' => '654321',
'binding_generation' => bin2hex(random_bytes(16)),
]);
};
$postWaitFailure = null;
try {
$channel->send($destination, 'Rebound while waiting');
} catch (Throwable $exception) {
$postWaitFailure = $exception;
}
$assert($postWaitFailure instanceof AdministratorTelegramPreflightException
&& $postWaitFailure->reason
=== AdministratorTelegramPreflightException::DESTINATION_CHANGED
&& count($transport->calls) === 1,
'Post-gate rebind reached the stale Telegram destination.');
$rateLimiter->hook = null;
$setBinding([
'bound_admin_id' => 1,
'chat_id' => '123456',
'binding_generation' => $destination->bindingGeneration,
]);
$rateLimiter->hook = static function (): void {
TicketTelegramConfig::$enabled = false;
};
$postWaitFailure = null;
try {
$channel->send($destination, 'Disabled while waiting');
} catch (Throwable $exception) {
$postWaitFailure = $exception;
}
$assert($postWaitFailure instanceof AdministratorTelegramPreflightException
&& $postWaitFailure->reason
=== AdministratorTelegramPreflightException::CHANNEL_UNAVAILABLE
&& count($transport->calls) === 1,
'Post-gate disable reached Telegram.');
TicketTelegramConfig::$enabled = true;
$rateLimiter->hook = null;
$expectFailure(
fn () => $channel->send($destination, 'Unsafe', ['parse_mode' => 'HTML']),
'Unknown Telegram option was accepted.'
);
$assert(count($transport->calls) === 1,
'Rejected Telegram options reached the network transport.');
$setBinding([
'bound_admin_id' => 1,
'chat_id' => '654321',
'binding_generation' => bin2hex(random_bytes(16)),
]);
$expectFailure(
fn () => $channel->send($destination, 'Stale destination'),
'A stale binding generation was sent after rebind.'
);
$assert(count($transport->calls) === 1,
'A stale destination reached the Telegram transport.');
$setBinding([
'bound_admin_id' => 1,
'chat_id' => '123456',
'binding_generation' => $destination->bindingGeneration,
]);
TicketTelegramConfig::$enabled = false;
$assert($channel->currentDestination() === null,
'Disabled Telegram configuration still exposed a destination.');
$assert($channel->boundDestination()?->equals($destination) === true,
'Disabling outbound Telegram hid the retained administrator binding.');
$expectFailure(
fn () => $channel->send($destination, 'Disabled channel'),
'Disabled Telegram configuration still sent a message.'
);
TicketTelegramConfig::$enabled = true;
$assert(count($transport->calls) === 1,
'Disabled Telegram configuration reached the transport.');
TicketTelegramConfig::$failRuntime = true;
$localFailure = null;
try {
$channel->currentDestination();
} catch (Throwable $exception) {
$localFailure = $exception;
}
$assert($localFailure instanceof AdministratorTelegramLocalUnavailable,
'Configuration infrastructure failure was collapsed into disabled.');
try {
$channel->send($destination, 'Local configuration failure');
} catch (Throwable $exception) {
$localFailure = $exception;
}
$assert($localFailure instanceof AdministratorTelegramLocalUnavailable
&& count($transport->calls) === 1,
'Local configuration failure reached transport or became remote unknown.');
TicketTelegramConfig::$failRuntime = false;
Configurations::$failReads = true;
try {
$channel->send($destination, 'Local binding failure');
} catch (Throwable $exception) {
$localFailure = $exception;
}
$assert($localFailure instanceof AdministratorTelegramLocalUnavailable
&& count($transport->calls) === 1,
'Binding read failure reached transport or became remote unknown.');
Configurations::$failReads = false;
$transport->fail = true;
$remoteFailure = null;
try {
$channel->send($destination, 'Unknown-effect send');
} catch (Throwable $exception) {
$remoteFailure = $exception;
}
$assert($remoteFailure instanceof AdministratorTelegramRemoteEffectUnknown,
'Transport failure was not classified as remote-effect unknown.');
$assert(count($transport->calls) === 2,
'A transport failure was internally retried.');
$transport->fail = false;
$setBinding([
'bound_admin_id' => 1,
'chat_id' => '654321',
'binding_generation' => bin2hex(random_bytes(16)),
]);
$preflightFailure = null;
try {
$channel->send($destination, 'Known preflight failure');
} catch (Throwable $exception) {
$preflightFailure = $exception;
}
$assert($preflightFailure instanceof AdministratorTelegramPreflightException
&& count($transport->calls) === 2,
'Destination change was not classified before the remote request.');
User::$rows[1]->enable = 0;
$assert($channel->currentDestination() === null,
'Disabled administrator remained an eligible destination.');
User::$rows[1]->enable = 1;
\App\Services\Config::$superAdministrators = '2';
$assert($channel->currentDestination() === null,
'Removed super administrator remained an eligible destination.');
echo "Administrator Telegram channel tests passed.\n";
}