Files
NextFloor/symcon/tests/webhook-lifecycle.php
T

172 lines
10 KiB
PHP

<?php
declare(strict_types=1);
// Exercise the actual module against a volatile, in-memory hook registry. This intentionally
// models startup/reload losing registrations; it is not a test against a running Symcon kernel.
const KR_READY = 10103;
const KR_INIT = 10102;
const IPS_KERNELSTARTED = 10001;
const KL_ERROR = 10205;
$kernelRunlevel = KR_INIT;
$nativeHooks = [];
function IPS_GetKernelRunlevel(): int { global $kernelRunlevel; return $kernelRunlevel; }
function check(bool $condition, string $message): void { if (!$condition) throw new RuntimeException($message); }
class IPSModuleStrict
{
protected int $InstanceID;
public array $attributes = [];
public array $properties = [];
public array $messages = [];
public array $timers = [];
public array $logs = [];
public int $status = 101;
public ?bool $registrationResult = true;
public bool $registrationThrows = false;
public array $registrationRunlevels = [];
public function __construct(int $id) { $this->InstanceID = $id; }
public function Create(): void {}
public function ApplyChanges(): void
{
global $nativeHooks;
$nativeHooks = array_filter($nativeHooks, fn(int $owner): bool => $owner !== $this->InstanceID);
}
public function MessageSink(int $time, int $sender, int $message, array $data): void {}
protected function RegisterPropertyString(string $name, string $value): void { $this->properties[$name] ??= $value; }
protected function RegisterAttributeString(string $name, string $value): void { $this->attributes[$name] ??= $value; }
protected function RegisterAttributeInteger(string $name, int $value): void { $this->attributes[$name] ??= $value; }
protected function ReadAttributeString(string $name): string { return $this->attributes[$name]; }
protected function WriteAttributeString(string $name, string $value): void { $this->attributes[$name] = $value; }
protected function ReadPropertyString(string $name): string { return $this->properties[$name]; }
protected function RegisterMessage(int $sender, int $message): void { $this->messages[] = [$sender, $message]; }
protected function RegisterTimer(string $name, int $interval, string $script): void { $this->timers[$name] = ['interval' => $interval, 'script' => $script]; }
protected function SetTimerInterval(string $name, int $interval): void
{
check(isset($this->timers[$name]), 'Timer must have been registered in Create');
$this->timers[$name]['interval'] = $interval;
}
protected function SetVisualizationType(int $type): void {}
protected function SetStatus(int $status): void { $this->status = $status; }
protected function LogMessage(string $message, int $type): void { $this->logs[] = [$message, $type]; }
protected function RegisterHook(string $path): ?bool
{
global $nativeHooks;
$this->registrationRunlevels[] = IPS_GetKernelRunlevel();
if ($this->registrationThrows) throw new RuntimeException('WebHook Control unavailable');
if ($this->registrationResult !== false) $nativeHooks['/hook/' . $path] = $this->InstanceID;
return $this->registrationResult;
}
}
require __DIR__ . '/../NextFloor/module.php';
$module = new NextFloor(12345);
$hook = '/hook/nextfloor/12345';
$module->Create();
check(($nativeHooks[$hook] ?? null) === 12345 && $module->status === 104, 'Create registers the native hook early without reporting the initializing kernel as ready');
check($module->registrationRunlevels === [KR_INIT], 'Create must register hooks during initialization, as required by the native lifecycle');
check(in_array([0, IPS_KERNELSTARTED], $module->messages, true), 'Module must listen for the completed kernel startup');
check(in_array([0, KR_READY], $module->messages, true), 'Module also restores its route as soon as the kernel becomes ready');
check($module->timers['WebHookRetry']['interval'] === 5000, 'Startup recovery must be scheduled');
$kernelRunlevel = KR_READY;
$nativeHooks = [];
$module->MessageSink(1, 0, KR_READY, []);
check(isset($nativeHooks[$hook]), 'KR_READY restores routes cleared after Create');
$nativeHooks = [];
$module->MessageSink(1, 0, IPS_KERNELSTARTED, []);
check(($nativeHooks[$hook] ?? null) === 12345 && $module->status === 102, 'Kernel startup must restore the instance hook');
check($module->timers['WebHookRetry']['interval'] === 30000, 'Successful registration keeps maintenance active for delayed resets');
$token = $module->attributes['AccessToken'];
$module->attributes['Building'] = '{"preserved_project":true}';
$module->properties['Title'] = ' Haus & Büro <West> ';
$nativeHooks = [];
$link = $module->OpenDesigner();
check(isset($nativeHooks[$hook]) && str_starts_with($link, 'link:' . $hook . '/designer?'), 'Opening the designer repairs a lost route before returning its URL');
$nativeHooks = [];
check(str_contains($module->GetVisualizationTile(), '<iframe') && isset($nativeHooks[$hook]), 'Opening a tile also repairs its route');
check(str_contains($module->GetVisualizationTile(), 'title="Haus &amp; Büro &lt;West&gt;"'), 'Tile iframe uses the escaped configured view name');
$module->ApplyChanges();
check(isset($nativeHooks[$hook]), 'ApplyChanges restores hooks after module reload');
for ($reload = 0; $reload < 3; $reload++) {
unset($nativeHooks[$hook]); // WebHook Control resets after our successful ApplyChanges.
$module->RetryWebHook();
check(isset($nativeHooks[$hook]) && $module->status === 102, 'Maintenance restores delayed hook loss without opening a designer or tile');
check($module->timers['WebHookRetry']['interval'] === 30000, 'Maintenance must survive every successful recovery');
}
$kernelRunlevel = KR_INIT;
$nativeHooks = [];
$module->Create();
$module->ApplyChanges();
check($module->status === 104, 'Restart initialization must not report ready');
$kernelRunlevel = KR_READY;
$module->MessageSink(2, 0, IPS_KERNELSTARTED, []);
check(isset($nativeHooks[$hook]) && $module->attributes['AccessToken'] === $token, 'A full restart restores the same route and retains the original access token');
$module->registrationResult = false;
$module->ApplyChanges();
check($module->status === 200 && !isset($nativeHooks[$hook]), 'A rejected registration must not report ready');
check($module->timers['WebHookRetry']['interval'] === 5000, 'Rejected registration must be retried');
$logCount = count($module->logs);
try {
$module->OpenDesigner();
throw new LogicException('Must not return a dead designer URL');
} catch (RuntimeException $error) {
check(str_contains($error->getMessage(), 'WebHook nicht verfügbar'), 'Designer must show a useful registration error');
}
check(count($module->logs) === $logCount, 'Identical retry errors must not flood the log');
check(!str_contains($module->GetVisualizationTile(), '<iframe'), 'Failure produces an explanatory tile, not a broken iframe');
$module->registrationResult = true;
$module->RetryWebHook();
check(isset($nativeHooks[$hook]) && $module->status === 102, 'Retry must recover after WebHook Control becomes available');
$module->registrationThrows = true;
check(str_contains($module->RepairWebHook(), 'WebHook Control unavailable'), 'Repair button reports the native registration exception');
$module->registrationThrows = false;
$module->registrationResult = null; // compatibility with older native return-void implementations
check(str_contains($module->RepairWebHook(), 'WebHook registriert:'), 'A native void return is not an explicit rejection');
check($module->attributes['AccessToken'] === $token && $module->attributes['Building'] === '{"preserved_project":true}', 'Repair must preserve project and access token');
$other = new NextFloor(54321);
$other->Create();
check(isset($nativeHooks[$hook]) && isset($nativeHooks['/hook/nextfloor/54321']), 'Instances must keep independent routes');
$kernelRunlevel = KR_INIT;
$earlyFailure = new NextFloor(34567);
$earlyFailure->registrationThrows = true;
$earlyFailure->Create();
check($earlyFailure->status === 104 && $earlyFailure->timers['WebHookRetry']['interval'] === 5000 && $earlyFailure->logs === [], 'An early startup registration failure waits and retries without an error log');
$kernelRunlevel = KR_READY;
$earlyFailure->registrationThrows = false;
$earlyFailure->RetryWebHook();
check(isset($nativeHooks['/hook/nextfloor/34567']) && $earlyFailure->status === 102, 'Unavailable early WebHook Control must recover automatically');
// Verify that returned URLs reach the real dispatcher, including Symcon's SCRIPT_NAME fallback.
parse_str((string) parse_url(substr($link, 5), PHP_URL_QUERY), $_GET);
$_SERVER['REQUEST_URI'] = $hook . '/designer';
$process = new ReflectionMethod($module, 'ProcessHookData');
ob_start();
$process->invoke($module);
$html = ob_get_clean();
check(str_contains($html, 'window.__NEXTFLOOR_SYMCON__=') && str_contains($html, 'assets/nextfloor-designer.js'), 'Designer route must serve its host page');
check(str_contains($html, '<title>Haus &amp; Büro &lt;West&gt;</title>'), 'Browser title uses the escaped configured view name');
preg_match('/window\.__NEXTFLOOR_SYMCON__=(.*?);<\/script>/s', $html, $hostConfig);
check(json_decode($hostConfig[1], true)['title'] === 'Haus & Büro <West>', 'Frontend receives the configured title as plain text');
$version = json_decode((string) file_get_contents(__DIR__ . '/../library.json'), true)['version'];
check(str_contains($html, 'nextfloor-designer.js?v=' . $version), 'A module update must invalidate the cached designer entry bundle');
unset($_SERVER['REQUEST_URI']);
$_SERVER['SCRIPT_NAME'] = $hook . '/designer';
ob_start();
$process->invoke($module);
$fallback = ob_get_clean();
check(str_contains($fallback, 'window.__NEXTFLOOR_SYMCON__='), 'Dispatcher must accept SCRIPT_NAME when REQUEST_URI is absent');
$_GET['token'] = 'wrong-token';
ob_start();
$process->invoke($module);
$unauthorized = ob_get_clean();
check(http_response_code() === 403 && str_contains($unauthorized, 'forbidden'), 'Recovery must not bypass hook authentication');
echo "OK: early registration, startup/update and delayed reset recovery, ongoing maintenance, titles, data preservation, routing and authentication\n";