server.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  1. <?php
  2. /**
  3. * Statum frontend demo backend.
  4. *
  5. * Run from this directory with PHP's built-in server. Because the realtime
  6. * channel is a long-lived Server-Sent Events connection, you MUST start the
  7. * server with several workers so an open SSE stream does not block other
  8. * requests:
  9. *
  10. * PHP_CLI_SERVER_WORKERS=5 php -S localhost:8000 server.php
  11. *
  12. * Then open http://localhost:8000/ in your browser (and a second tab to see
  13. * realtime pushes).
  14. *
  15. * This is a DEMO only: there is no real signing or encryption. Snapshots are
  16. * wrapped in trivial frames, and per-item action context is carried in the
  17. * action's `private` blob as plain base64. State lives in the PHP session so
  18. * that actions are stateful across requests. Realtime subscriptions are shared
  19. * between workers through small files in the system temp dir.
  20. */
  21. session_start();
  22. // Static product catalog used by the demo.
  23. $CATALOG = [
  24. ['id' => 1, 'name' => 'Widget', 'price' => 9.99, 'featured' => true, 'inStock' => true],
  25. ['id' => 2, 'name' => 'Gadget', 'price' => 19.99, 'featured' => false, 'inStock' => true],
  26. ['id' => 3, 'name' => 'Sprocket', 'price' => 4.50, 'featured' => false, 'inStock' => false],
  27. ['id' => 4, 'name' => 'Gizmo', 'price' => 29.99, 'featured' => true, 'inStock' => true],
  28. ];
  29. $TYPES = ['counter', 'products', 'cart', 'user', 'notice'];
  30. // ---------------------------------------------------------------------------
  31. // Helpers
  32. // ---------------------------------------------------------------------------
  33. /** Send a JSON array of Statum directives and stop. */
  34. function statum_respond(array $directives): void
  35. {
  36. header('Content-Type: application/vnd.statum+json');
  37. header('Cache-Control: no-store');
  38. echo json_encode($directives, JSON_PRETTY_PRINT);
  39. exit;
  40. }
  41. /** Wrap a snapshot in a trivial (unsigned) frame. The signature is a SHA256
  42. * hash of the content so that identical snapshots share a signature (used by
  43. * the client as an idempotency key) while distinct ones do not. */
  44. function frame(array $snapshot): array
  45. {
  46. $content = json_encode($snapshot);
  47. return [
  48. 'content' => $content,
  49. 'signer' => 'demo',
  50. 'signature' => base64_encode(hash('sha256', $content, true)),
  51. ];
  52. }
  53. /** Stable per-type slot key, kept in the session. */
  54. function key_for(string $type): string
  55. {
  56. if (!isset($_SESSION['keys'][$type])) {
  57. $_SESSION['keys'][$type] = 'k_' . $type;
  58. }
  59. return $_SESSION['keys'][$type];
  60. }
  61. /**
  62. * Build a snapshot for a type. Options:
  63. * - `always`: transmit_after == as_at, so the client sends the base64 frame on
  64. * every request (the always-send path).
  65. * - `stale`: transmit_after is set 10s in the future (with a far-future
  66. * invalid_after). The slot is fresh for 10s, after which the client must
  67. * pre-flight via /_statum/slots before each request. Load the page, wait ~10s,
  68. * then trigger an action to see the pre-flight request.
  69. */
  70. function make_snapshot(string $type, string $scope, array $public, array $opts = [], ?string $key = null): array
  71. {
  72. $now = time();
  73. $asAt = gmdate('Y-m-d\TH:i:s\Z', $now);
  74. if (!empty($opts['always'])) {
  75. $transmit = $asAt;
  76. } elseif (!empty($opts['stale'])) {
  77. $transmit = gmdate('Y-m-d\TH:i:s\Z', $now + 10);
  78. } else {
  79. $transmit = gmdate('Y-m-d\TH:i:s\Z', $now + 60);
  80. }
  81. return [
  82. 'as_at' => $asAt,
  83. 'slot' => ['key' => $key ?? key_for($type), 'scope' => $scope, 'type' => $type],
  84. 'transmit_after' => $transmit,
  85. 'invalid_after' => gmdate('Y-m-d\TH:i:s\Z', $now + 600),
  86. 'private' => $opts['private'] ?? '',
  87. 'public' => $public,
  88. ];
  89. }
  90. function set_dir(array $snapshot): array
  91. {
  92. return ['type' => 'set', 'snapshot_frame' => frame($snapshot)];
  93. }
  94. function clear_dir(string $key): array
  95. {
  96. return ['type' => 'clear', 'key' => $key];
  97. }
  98. function product_by_id($id): ?array
  99. {
  100. global $CATALOG;
  101. foreach ($CATALOG as $p) {
  102. if ((string)$p['id'] === (string)$id) return $p;
  103. }
  104. return null;
  105. }
  106. // ---------------------------------------------------------------------------
  107. // Public-data builders
  108. // ---------------------------------------------------------------------------
  109. function build_counter(): array
  110. {
  111. $v = $_SESSION['counter'] ?? 0;
  112. return [
  113. 'value' => $v,
  114. 'high' => $v > 5,
  115. 'increment' => ['uri' => '/api/counter/inc', 'method' => 'POST'],
  116. 'decrement' => ['uri' => '/api/counter/dec', 'method' => 'POST'],
  117. 'reset' => ['uri' => '/api/counter/reset', 'method' => 'POST'],
  118. 'add' => ['uri' => '/api/counter/add', 'method' => 'POST'],
  119. ];
  120. }
  121. function build_products(): array
  122. {
  123. global $CATALOG;
  124. $items = [];
  125. foreach ($CATALOG as $p) {
  126. $pid = (string)$p['id'];
  127. $items[] = [
  128. 'id' => $pid,
  129. 'name' => $p['name'],
  130. 'price' => $p['price'],
  131. 'featured' => $p['featured'],
  132. 'inStock' => $p['inStock'],
  133. // Per-item context rides in `private`; the client echoes it back
  134. // via the X-Statum-Private header (no stm-data expression needed).
  135. 'addToCartAction' => [
  136. 'uri' => '/api/cart/add',
  137. 'method' => 'POST',
  138. 'private' => base64_encode('id=' . $pid),
  139. ],
  140. ];
  141. }
  142. return ['items' => $items];
  143. }
  144. function build_cart(): array
  145. {
  146. $cart = $_SESSION['cart'] ?? [];
  147. $count = 0;
  148. $total = 0.0;
  149. $lines = [];
  150. foreach ($cart as $id => $qty) {
  151. $p = product_by_id($id);
  152. if (!$p) continue;
  153. $count += $qty;
  154. $total += $p['price'] * $qty;
  155. $lines[] = ['id' => (string)$id, 'name' => $p['name'], 'qty' => $qty, 'price' => $p['price']];
  156. }
  157. return [
  158. 'count' => $count,
  159. 'total' => round($total, 2),
  160. 'empty' => $count === 0,
  161. 'items' => $lines,
  162. 'checkoutAction' => ['uri' => '/api/cart/checkout', 'method' => 'POST'],
  163. 'clearAction' => ['uri' => '/api/cart/clear', 'method' => 'POST'],
  164. ];
  165. }
  166. function build_user(): array
  167. {
  168. $role = $_SESSION['role'] ?? 'guest';
  169. $names = ['guest' => 'Guest', 'member' => 'Member Mike', 'admin' => 'Admin Alice'];
  170. return [
  171. 'role' => $role,
  172. 'name' => $names[$role] ?? 'Guest',
  173. 'toggleAction' => ['uri' => '/api/user/toggle', 'method' => 'POST'],
  174. 'resetAllAction' => ['uri' => '/api/reset-all', 'method' => 'POST'],
  175. ];
  176. }
  177. function build_notice(): array
  178. {
  179. return [
  180. 'html' => $_SESSION['notice'] ?? '<em>No notice set.</em>',
  181. 'setAction' => ['uri' => '/api/notice/set', 'method' => 'POST'],
  182. 'failAction' => ['uri' => '/api/notice/fail', 'method' => 'POST'],
  183. ];
  184. }
  185. /** Build the snapshot for a type with its demo scope/options. */
  186. function snap(string $type): ?array
  187. {
  188. switch ($type) {
  189. case 'counter': return make_snapshot('counter', 'session', build_counter());
  190. case 'products': return make_snapshot('products', 'session', build_products());
  191. case 'cart': return make_snapshot('cart', 'session', build_cart(), ['always' => true]);
  192. case 'user': return make_snapshot('user', 'session', build_user(), ['stale' => true]);
  193. case 'notice': return make_snapshot('notice', 'flow', build_notice());
  194. }
  195. return null;
  196. }
  197. function all_directives(): array
  198. {
  199. global $TYPES;
  200. $dirs = [];
  201. foreach ($TYPES as $t) {
  202. $s = snap($t);
  203. if ($s) $dirs[] = set_dir($s);
  204. }
  205. return $dirs;
  206. }
  207. // ---------------------------------------------------------------------------
  208. // Realtime channel helpers (demo pub/sub via the filesystem)
  209. // ---------------------------------------------------------------------------
  210. /** A `set` directive wrapping an already-framed snapshot. */
  211. function set_dir_frame(array $frame): array
  212. {
  213. return ['type' => 'set', 'snapshot_frame' => $frame];
  214. }
  215. /** Directory holding per-channel subscription and event-log files. */
  216. function channel_dir(): string
  217. {
  218. $dir = rtrim(sys_get_temp_dir(), '/') . '/statum_demo';
  219. if (!is_dir($dir)) @mkdir($dir, 0777, true);
  220. return $dir;
  221. }
  222. function channel_subs_path(string $id): string { return channel_dir() . '/ch_' . $id . '.subs'; }
  223. function channel_events_path(string $id): string { return channel_dir() . '/ch_' . $id . '.events'; }
  224. function gen_channel_id(): string { return bin2hex(random_bytes(8)); }
  225. /** Read a channel's subscribed slot keys (empty array if unknown). */
  226. function read_channel_subs(string $id): array
  227. {
  228. $f = channel_subs_path($id);
  229. if (!is_file($f)) return [];
  230. $arr = json_decode((string)@file_get_contents($f), true);
  231. return is_array($arr) ? array_values($arr) : [];
  232. }
  233. /** Overwrite a channel's subscribed slot keys. */
  234. function set_channel_subs(string $id, array $subs): void
  235. {
  236. @file_put_contents(channel_subs_path($id), json_encode(array_values(array_unique($subs))), LOCK_EX);
  237. }
  238. /** Append one event to a channel's event log (a JSON line). */
  239. function append_channel_event(string $id, string $type, $data): void
  240. {
  241. $line = json_encode(['t' => $type, 'd' => $data]) . "\n";
  242. @file_put_contents(channel_events_path($id), $line, FILE_APPEND | LOCK_EX);
  243. }
  244. /** Channel ids currently subscribed to a given slot key. */
  245. function channels_subscribed_to(string $key): array
  246. {
  247. $ids = [];
  248. foreach ((array)glob(channel_dir() . '/ch_*.subs') as $f) {
  249. if (!is_file($f)) continue;
  250. $id = substr(basename($f), 3, -5); // ch_{ID}.subs
  251. if (in_array($key, read_channel_subs($id), true)) $ids[] = $id;
  252. }
  253. return $ids;
  254. }
  255. /** Push a `set` frame to every channel subscribed to a slot key. */
  256. function fanout_set(string $key, array $frame): void
  257. {
  258. foreach (channels_subscribed_to($key) as $id) append_channel_event($id, 'set', $frame);
  259. }
  260. /** Shared "live" broadcast value, stored on disk so all workers agree. */
  261. function live_path(): string { return channel_dir() . '/live.json'; }
  262. function live_read(): array
  263. {
  264. if (!is_file(live_path())) return ['text' => 'No live messages yet.', 'at' => ''];
  265. $d = json_decode((string)@file_get_contents(live_path()), true);
  266. return is_array($d) ? $d : ['text' => 'No live messages yet.', 'at' => ''];
  267. }
  268. /** Snapshot for the shared `live` slot (transient scope, fixed key `k_live`). */
  269. function snap_live(): array
  270. {
  271. $d = live_read();
  272. return make_snapshot('live', 'transient', [
  273. 'text' => $d['text'],
  274. 'at' => $d['at'],
  275. 'sendAction' => ['uri' => '/api/live/send', 'method' => 'POST'],
  276. 'muteAction' => ['uri' => '/api/live/mute', 'method' => 'POST'],
  277. 'resumeAction' => ['uri' => '/api/live/resume', 'method' => 'POST'],
  278. ], [], 'k_live');
  279. }
  280. /** The initial frame to push to a channel when it subscribes to a key. */
  281. function initial_frame_for_key(string $key): ?array
  282. {
  283. if ($key === 'k_live') return frame(snap_live());
  284. return null;
  285. }
  286. // ---------------------------------------------------------------------------
  287. // Router
  288. // ---------------------------------------------------------------------------
  289. $method = $_SERVER['REQUEST_METHOD'];
  290. $path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
  291. // Static assets.
  292. if ($path === '/statum.js') {
  293. header('Content-Type: application/javascript');
  294. readfile(__DIR__ . '/../js/statum.js');
  295. exit;
  296. }
  297. if ($path === '/_statum/worker.js') {
  298. header('Content-Type: application/javascript');
  299. readfile(__DIR__ . '/../js/statum-worker.js');
  300. exit;
  301. }
  302. // The page itself.
  303. if ($path === '/' || $path === '/index.html') {
  304. header('Content-Type: text/html; charset=utf-8');
  305. readfile(__DIR__ . '/index.html');
  306. exit;
  307. }
  308. // Landing page after a (post) checkout navigation.
  309. if ($path === '/api/checkout-done') {
  310. header('Content-Type: text/html; charset=utf-8');
  311. $order = htmlspecialchars($_GET['order'] ?? 'UNKNOWN');
  312. echo "<!doctype html><meta charset=utf-8><title>Checkout</title>" .
  313. "<body style='font-family:sans-serif;padding:2rem'>" .
  314. "<h1>Order $order placed</h1><p>This page was reached via a statum <code>post</code> directive.</p>" .
  315. "<p><a href='/'>Back to the demo</a></p>";
  316. exit;
  317. }
  318. // --- Statum endpoints -------------------------------------------------------
  319. if ($path === '/_statum/entrypoint') {
  320. $dirs = all_directives();
  321. $dirs[] = set_dir(snap_live()); // current broadcast + actions
  322. $dirs[] = ['type' => 'subscribe', 'key' => 'k_live']; // begin realtime delivery
  323. statum_respond($dirs);
  324. }
  325. if ($path === '/_statum/slots') {
  326. // Pre-flight target: refresh each type whose frame the client sent back.
  327. $body = json_decode(file_get_contents('php://input'), true);
  328. $dirs = [];
  329. if (is_array($body)) {
  330. foreach ($body as $fr) {
  331. $snap = json_decode($fr['content'] ?? 'null', true);
  332. $type = $snap['slot']['type'] ?? null;
  333. if ($type) {
  334. $s = snap($type);
  335. if ($s) $dirs[] = set_dir($s);
  336. }
  337. }
  338. }
  339. statum_respond($dirs);
  340. }
  341. // --- Realtime channel -------------------------------------------------------
  342. // Open the SSE stream. The first event carries the channel id; later events
  343. // are `set`/`clear` for the slots this channel has subscribed to (via PATCH).
  344. if ($path === '/_statum/channel' && $method === 'GET') {
  345. // Long-lived connection: release the session lock immediately so other
  346. // requests (served by other workers) for the same session are not blocked.
  347. session_write_close();
  348. @set_time_limit(0);
  349. @ini_set('zlib.output_compression', '0');
  350. while (ob_get_level() > 0) { @ob_end_flush(); }
  351. header('Content-Type: text/event-stream');
  352. header('Cache-Control: no-cache');
  353. header('X-Accel-Buffering: no');
  354. $id = gen_channel_id();
  355. set_channel_subs($id, []);
  356. @file_put_contents(channel_events_path($id), '');
  357. echo "event: channel\ndata: {$id}\n\n";
  358. flush();
  359. $offset = 0;
  360. $eventsFile = channel_events_path($id);
  361. while (!connection_aborted()) {
  362. clearstatcache(true, $eventsFile);
  363. $size = is_file($eventsFile) ? filesize($eventsFile) : 0;
  364. if ($size > $offset) {
  365. $fp = @fopen($eventsFile, 'rb');
  366. if ($fp) {
  367. fseek($fp, $offset);
  368. $chunk = (string)stream_get_contents($fp);
  369. $offset = (int)ftell($fp);
  370. fclose($fp);
  371. foreach (preg_split('/\r?\n/', trim($chunk)) as $line) {
  372. if ($line === '') continue;
  373. $ev = json_decode($line, true);
  374. if (!is_array($ev)) continue;
  375. if (($ev['t'] ?? '') === 'set') {
  376. echo 'event: set' . "\ndata: " . json_encode($ev['d']) . "\n\n";
  377. } elseif (($ev['t'] ?? '') === 'clear') {
  378. echo 'event: clear' . "\ndata: " . $ev['d'] . "\n\n";
  379. }
  380. }
  381. flush();
  382. }
  383. }
  384. echo ": ping\n\n"; // heartbeat keeps the stream alive
  385. flush();
  386. usleep(1000000);
  387. }
  388. // Client went away: drop this channel's files.
  389. @unlink(channel_subs_path($id));
  390. @unlink($eventsFile);
  391. exit;
  392. }
  393. // Manage a channel's subscriptions: {subscribe:[keys], unsubscribe:[keys]}.
  394. if (preg_match('#^/_statum/channel/([^/]+)$#', $path, $m) && $method === 'PATCH') {
  395. $id = $m[1];
  396. $body = json_decode((string)file_get_contents('php://input'), true);
  397. if (!is_array($body)) $body = [];
  398. $add = $body['subscribe'] ?? [];
  399. $rem = $body['unsubscribe'] ?? [];
  400. $subs = read_channel_subs($id);
  401. foreach ($add as $k) {
  402. if (!in_array($k, $subs, true)) $subs[] = $k;
  403. }
  404. $subs = array_values(array_diff($subs, $rem));
  405. set_channel_subs($id, $subs);
  406. // Push the current value of any newly-subscribed slot so a fresh client
  407. // sees the latest state right away.
  408. foreach ($add as $k) {
  409. $fr = initial_frame_for_key((string)$k);
  410. if ($fr !== null) append_channel_event($id, 'set', $fr);
  411. }
  412. http_response_code(204);
  413. exit;
  414. }
  415. // --- Actions ----------------------------------------------------------------
  416. if ($path === '/api/counter/inc' && $method === 'POST') {
  417. $_SESSION['counter'] = ($_SESSION['counter'] ?? 0) + 1;
  418. statum_respond([set_dir(snap('counter'))]);
  419. }
  420. if ($path === '/api/counter/dec' && $method === 'POST') {
  421. $_SESSION['counter'] = ($_SESSION['counter'] ?? 0) - 1;
  422. statum_respond([set_dir(snap('counter'))]);
  423. }
  424. if ($path === '/api/counter/reset' && $method === 'POST') {
  425. $_SESSION['counter'] = 0;
  426. statum_respond([set_dir(snap('counter'))]);
  427. }
  428. if ($path === '/api/counter/add' && $method === 'POST') {
  429. $amount = intval($_POST['amount'] ?? 1);
  430. $_SESSION['counter'] = ($_SESSION['counter'] ?? 0) + $amount;
  431. statum_respond([set_dir(snap('counter'))]);
  432. }
  433. if ($path === '/api/cart/add' && $method === 'POST') {
  434. $priv = $_SERVER['HTTP_X_STATUM_PRIVATE'] ?? '';
  435. $raw = base64_decode($priv, true) ?: '';
  436. if (preg_match('/id=([0-9]+)/', $raw, $m)) {
  437. $id = $m[1];
  438. $_SESSION['cart'][$id] = ($_SESSION['cart'][$id] ?? 0) + 1;
  439. }
  440. statum_respond([set_dir(snap('cart'))]);
  441. }
  442. if ($path === '/api/cart/clear' && $method === 'POST') {
  443. $_SESSION['cart'] = [];
  444. statum_respond([set_dir(snap('cart'))]);
  445. }
  446. if ($path === '/api/cart/checkout' && $method === 'POST') {
  447. // A `post` directive performs a full-page navigating form POST last.
  448. statum_respond([['type' => 'post', 'uri' => '/api/checkout-done', 'data' => ['order' => 'ORD-' . strtoupper(bin2hex(random_bytes(3)))]]]);
  449. }
  450. if ($path === '/api/user/toggle' && $method === 'POST') {
  451. $order = ['guest', 'member', 'admin'];
  452. $cur = array_search($_SESSION['role'] ?? 'guest', $order);
  453. $_SESSION['role'] = $order[($cur + 1) % count($order)];
  454. statum_respond([set_dir(snap('user'))]);
  455. }
  456. if ($path === '/api/notice/set' && $method === 'POST') {
  457. $_SESSION['notice'] = '<div class="ok"><strong>Notice:</strong> updated at ' . date('H:i:s') . '</div>';
  458. statum_respond([set_dir(snap('notice'))]);
  459. }
  460. if ($path === '/api/notice/fail' && $method === 'POST') {
  461. statum_respond([['type' => 'error', 'message' => 'Intentional failure.', 'code' => 'DEMO_FAIL', 'data' => ['at' => date('c')]]]);
  462. }
  463. if ($path === '/api/reset-all' && $method === 'POST') {
  464. $dirs = [];
  465. foreach ($TYPES as $t) {
  466. if (isset($_SESSION['keys'][$t])) $dirs[] = clear_dir($_SESSION['keys'][$t]);
  467. }
  468. session_unset();
  469. $dirs[] = ['type' => 'navigate', 'uri' => '/'];
  470. statum_respond($dirs);
  471. }
  472. // --- Live channel actions ---------------------------------------------------
  473. if ($path === '/api/live/send' && $method === 'POST') {
  474. $msg = trim((string)($_POST['msg'] ?? ''));
  475. if ($msg === '') $msg = '(empty message)';
  476. @file_put_contents(live_path(), json_encode(['text' => $msg, 'at' => date('H:i:s')]), LOCK_EX);
  477. $fr = frame(snap_live());
  478. fanout_set('k_live', $fr); // push to every subscribed tab via the channel
  479. statum_respond([
  480. set_dir_frame($fr), // immediate feedback (idempotent vs the push)
  481. ['type' => 'notify', 'kind' => 'success', 'message' => 'Broadcast to all tabs'],
  482. ]);
  483. }
  484. // Unsubscribing the only slot closes the realtime connection for this client.
  485. if ($path === '/api/live/mute' && $method === 'POST') {
  486. statum_respond([['type' => 'unsubscribe', 'key' => 'k_live']]);
  487. }
  488. // Re-subscribing reopens the connection; the PATCH initial-push re-sends the
  489. // current broadcast.
  490. if ($path === '/api/live/resume' && $method === 'POST') {
  491. statum_respond([['type' => 'subscribe', 'key' => 'k_live']]);
  492. }
  493. // Fallback 404.
  494. http_response_code(404);
  495. header('Content-Type: text/plain');
  496. echo "404 Not Found: $path";