BlueGit

projects-timfalken-com meteors

Files

meteors / server / lib / Store.php

Store.php

Store.php 23.0 KiB Download Raw
1<?php
2declare(strict_types=1);
3
4final class Store
5{
6 private PDO $pdo;
7 private int $txDepth = 0;
8
9 public function __construct(PDO $pdo)
10 {
11 $this->pdo = $pdo;
12 $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
13 $this->migrate();
14 }
15
16 public static function open(?string $dir = null): self
17 {
18 $dir = $dir ?? dataDir();
19 if (!is_dir($dir) && !mkdir($dir, 0775, true) && !is_dir($dir)) {
20 throw new RuntimeException('De datamap moet schrijfbaar zijn.');
21 }
22 $path = $dir . '/meteors.sqlite';
23 $pdo = new PDO('sqlite:' . $path, null, null, [
24 PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
25 PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
26 ]);
27 $pdo->exec('PRAGMA journal_mode = WAL');
28 $pdo->exec('PRAGMA foreign_keys = ON');
29 $pdo->exec('PRAGMA busy_timeout = 4000');
30 return new self($pdo);
31 }
32
33 private function migrate(): void
34 {
35 $this->pdo->exec(<<<'SQL'
36CREATE TABLE IF NOT EXISTS lobbies (
37 id TEXT PRIMARY KEY,
38 code TEXT UNIQUE NOT NULL,
39 host_id TEXT NOT NULL,
40 status TEXT NOT NULL DEFAULT 'waiting',
41 miss_chance REAL NOT NULL DEFAULT 0.30,
42 flight_duration REAL NOT NULL DEFAULT 1.2,
43 created INTEGER NOT NULL,
44 started INTEGER,
45 finished INTEGER
46);
47CREATE TABLE IF NOT EXISTS members (
48 lobby_id TEXT NOT NULL,
49 user_id TEXT NOT NULL,
50 name TEXT NOT NULL,
51 ready INTEGER NOT NULL DEFAULT 0,
52 eliminated INTEGER NOT NULL DEFAULT 0,
53 place INTEGER,
54 left_at INTEGER,
55 joined INTEGER NOT NULL,
56 last_seen INTEGER NOT NULL,
57 score INTEGER NOT NULL DEFAULT 0,
58 snapshot TEXT,
59 PRIMARY KEY (lobby_id, user_id)
60);
61CREATE TABLE IF NOT EXISTS shots (
62 id INTEGER PRIMARY KEY AUTOINCREMENT,
63 lobby_id TEXT NOT NULL,
64 from_user TEXT NOT NULL,
65 to_user TEXT,
66 color INTEGER NOT NULL,
67 client_id TEXT,
68 created REAL NOT NULL,
69 deliver_at REAL NOT NULL,
70 delivered INTEGER NOT NULL DEFAULT 0
71);
72CREATE INDEX IF NOT EXISTS shots_deliver ON shots (lobby_id, to_user, delivered, deliver_at);
73SQL);
74 }
75
76 public function transaction(callable $fn): mixed
77 {
78 if ($this->txDepth > 0) {
79 return $fn();
80 }
81 $this->pdo->beginTransaction();
82 $this->txDepth++;
83 try {
84 $result = $fn();
85 $this->pdo->commit();
86 $this->txDepth--;
87 return $result;
88 } catch (Throwable $e) {
89 $this->txDepth--;
90 if ($this->pdo->inTransaction()) {
91 $this->pdo->rollBack();
92 }
93 throw $e;
94 }
95 }
96
97 private function now(): int
98 {
99 return time();
100 }
101
102 private function nowf(): float
103 {
104 return microtime(true);
105 }
106
107 private function newId(): string
108 {
109 return bin2hex(random_bytes(12));
110 }
111
112 private function newCode(): string
113 {
114 $alphabet = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
115 $len = strlen($alphabet);
116 for ($attempt = 0; $attempt < 16; $attempt++) {
117 $code = '';
118 for ($i = 0; $i < 4; $i++) {
119 $code .= $alphabet[random_int(0, $len - 1)];
120 }
121 $exists = $this->pdo->prepare('SELECT 1 FROM lobbies WHERE code = ?');
122 $exists->execute([$code]);
123 if (!$exists->fetch()) {
124 return $code;
125 }
126 }
127 throw new RuntimeException('Kon geen unieke lobbycode maken.');
128 }
129
130 public function lobbyForUser(string $userId): ?array
131 {
132 $stmt = $this->pdo->prepare(
133 'SELECT l.* FROM lobbies l
134 JOIN members m ON m.lobby_id = l.id
135 WHERE m.user_id = ? AND m.left_at IS NULL
136 ORDER BY l.created DESC LIMIT 1'
137 );
138 $stmt->execute([$userId]);
139 $row = $stmt->fetch();
140 return $row ?: null;
141 }
142
143 public function getLobby(string $id): ?array
144 {
145 $stmt = $this->pdo->prepare('SELECT * FROM lobbies WHERE id = ?');
146 $stmt->execute([$id]);
147 $row = $stmt->fetch();
148 return $row ?: null;
149 }
150
151 public function getLobbyByCode(string $code): ?array
152 {
153 $code = strtoupper(preg_replace('/[^A-Za-z0-9]/', '', $code) ?? '');
154 $stmt = $this->pdo->prepare('SELECT * FROM lobbies WHERE code = ?');
155 $stmt->execute([$code]);
156 $row = $stmt->fetch();
157 return $row ?: null;
158 }
159
160 /** @return list<array> */
161 public function members(string $lobbyId, bool $includeLeft = false): array
162 {
163 $sql = 'SELECT * FROM members WHERE lobby_id = ?';
164 if (!$includeLeft) {
165 $sql .= ' AND left_at IS NULL';
166 }
167 $sql .= ' ORDER BY joined ASC';
168 $stmt = $this->pdo->prepare($sql);
169 $stmt->execute([$lobbyId]);
170 return $stmt->fetchAll();
171 }
172
173 public function createLobby(string $userId, string $name, float $missChance = METEORS_DEFAULT_MISS): array
174 {
175 return $this->transaction(function () use ($userId, $name, $missChance) {
176 $existing = $this->lobbyForUser($userId);
177 if ($existing && $existing['status'] !== 'finished') {
178 throw new RuntimeException('Je zit al in een lobby. Verlaat die eerst.');
179 }
180 if ($existing && $existing['status'] === 'finished') {
181 $this->leaveMember($existing['id'], $userId);
182 }
183 $id = $this->newId();
184 $code = $this->newCode();
185 $now = $this->now();
186 $miss = max(0.0, min(1.0, $missChance));
187 $this->pdo->prepare(
188 'INSERT INTO lobbies (id, code, host_id, status, miss_chance, flight_duration, created)
189 VALUES (?,?,?,?,?,?,?)'
190 )->execute([$id, $code, $userId, 'waiting', $miss, METEORS_FLIGHT_DURATION, $now]);
191 $this->pdo->prepare(
192 'INSERT INTO members (lobby_id, user_id, name, ready, joined, last_seen)
193 VALUES (?,?,?,0,?,?)'
194 )->execute([$id, $userId, $name, $now, $now]);
195 return $this->getLobby($id);
196 });
197 }
198
199 public function joinLobby(string $userId, string $name, string $code): array
200 {
201 return $this->transaction(function () use ($userId, $name, $code) {
202 $existing = $this->lobbyForUser($userId);
203 if ($existing && $existing['status'] !== 'finished') {
204 if (strcasecmp($existing['code'], $code) === 0) {
205 return $existing;
206 }
207 throw new RuntimeException('Je zit al in een andere lobby. Verlaat die eerst.');
208 }
209 $lobby = $this->getLobbyByCode($code);
210 if (!$lobby) {
211 throw new RuntimeException('Onbekende lobbycode.');
212 }
213 if ($lobby['status'] !== 'waiting') {
214 throw new RuntimeException('Deze lobby is al begonnen.');
215 }
216 $members = $this->members($lobby['id']);
217 if (count($members) >= METEORS_MAX_PLAYERS) {
218 throw new RuntimeException('Deze lobby is vol (maximaal ' . METEORS_MAX_PLAYERS . ' spelers).');
219 }
220 $now = $this->now();
221 $this->pdo->prepare(
222 'INSERT INTO members (lobby_id, user_id, name, ready, eliminated, place, left_at, joined, last_seen, score, snapshot)
223 VALUES (?,?,?,0,0,NULL,NULL,?,?,0,NULL)
224 ON CONFLICT(lobby_id, user_id) DO UPDATE SET
225 name = excluded.name,
226 ready = 0,
227 eliminated = 0,
228 place = NULL,
229 left_at = NULL,
230 joined = excluded.joined,
231 last_seen = excluded.last_seen,
232 score = 0,
233 snapshot = NULL'
234 )->execute([$lobby['id'], $userId, $name, $now, $now]);
235 return $this->getLobby($lobby['id']);
236 });
237 }
238
239 private function leaveMember(string $lobbyId, string $userId): void
240 {
241 $this->pdo->prepare(
242 'UPDATE members SET left_at = ?, ready = 0 WHERE lobby_id = ? AND user_id = ? AND left_at IS NULL'
243 )->execute([$this->now(), $lobbyId, $userId]);
244 $lobby = $this->getLobby($lobbyId);
245 if (!$lobby) {
246 return;
247 }
248 $remaining = $this->members($lobbyId);
249 if ($lobby['host_id'] === $userId) {
250 if ($remaining) {
251 $this->pdo->prepare('UPDATE lobbies SET host_id = ? WHERE id = ?')
252 ->execute([$remaining[0]['user_id'], $lobbyId]);
253 } elseif ($lobby['status'] === 'waiting') {
254 // Empty waiting lobby can stay; a later join by code still works until we want to close it.
255 }
256 }
257 if ($lobby['status'] === 'playing') {
258 $this->assignPlaceIfNeeded($lobbyId, $userId, true);
259 $this->maybeFinish($lobbyId);
260 }
261 }
262
263 public function leaveLobby(string $userId): void
264 {
265 $this->transaction(function () use ($userId) {
266 $lobby = $this->lobbyForUser($userId);
267 if (!$lobby) {
268 return;
269 }
270 $this->leaveMember($lobby['id'], $userId);
271 });
272 }
273
274 public function setReady(string $userId, bool $ready): array
275 {
276 return $this->transaction(function () use ($userId, $ready) {
277 $lobby = $this->lobbyForUser($userId);
278 if (!$lobby) {
279 throw new RuntimeException('Je zit niet in een lobby.');
280 }
281 if ($lobby['status'] !== 'waiting') {
282 throw new RuntimeException('Het spel is al begonnen.');
283 }
284 $this->pdo->prepare(
285 'UPDATE members SET ready = ?, last_seen = ? WHERE lobby_id = ? AND user_id = ? AND left_at IS NULL'
286 )->execute([$ready ? 1 : 0, $this->now(), $lobby['id'], $userId]);
287 return $this->getLobby($lobby['id']);
288 });
289 }
290
291 public function startGame(string $userId): array
292 {
293 return $this->transaction(function () use ($userId) {
294 $lobby = $this->lobbyForUser($userId);
295 if (!$lobby) {
296 throw new RuntimeException('Je zit niet in een lobby.');
297 }
298 if ($lobby['host_id'] !== $userId) {
299 throw new RuntimeException('Alleen de host kan het spel starten.');
300 }
301 if ($lobby['status'] !== 'waiting') {
302 throw new RuntimeException('Het spel is al begonnen.');
303 }
304 $members = $this->members($lobby['id']);
305 if (count($members) < 2) {
306 throw new RuntimeException('Er zijn minstens twee spelers nodig.');
307 }
308 foreach ($members as $m) {
309 if (!(int) $m['ready']) {
310 throw new RuntimeException('Niet iedereen is gereed.');
311 }
312 }
313 $this->pdo->prepare(
314 'UPDATE lobbies SET status = ?, started = ?, finished = NULL WHERE id = ?'
315 )->execute(['playing', $this->now(), $lobby['id']]);
316 $this->pdo->prepare(
317 'UPDATE members SET eliminated = 0, place = NULL, score = 0, snapshot = NULL
318 WHERE lobby_id = ? AND left_at IS NULL'
319 )->execute([$lobby['id']]);
320 $this->pdo->prepare('DELETE FROM shots WHERE lobby_id = ?')->execute([$lobby['id']]);
321 return $this->getLobby($lobby['id']);
322 });
323 }
324
325 /** @param list<array{client_id?:string,color?:int}> $shots */
326 public function recordShots(string $userId, array $shots): array
327 {
328 return $this->transaction(function () use ($userId, $shots) {
329 $lobby = $this->lobbyForUser($userId);
330 if (!$lobby || $lobby['status'] !== 'playing') {
331 return [];
332 }
333 $me = $this->member($lobby['id'], $userId);
334 if (!$me || (int) $me['eliminated']) {
335 return [];
336 }
337 $targets = [];
338 foreach ($this->members($lobby['id']) as $m) {
339 if ($m['user_id'] !== $userId && !(int) $m['eliminated']) {
340 $targets[] = $m;
341 }
342 }
343 $results = [];
344 $missChance = (float) $lobby['miss_chance'];
345 $flight = (float) $lobby['flight_duration'];
346 $now = $this->nowf();
347 $ins = $this->pdo->prepare(
348 'INSERT INTO shots (lobby_id, from_user, to_user, color, client_id, created, deliver_at, delivered)
349 VALUES (?,?,?,?,?,?,?,0)'
350 );
351 foreach ($shots as $shot) {
352 $color = isset($shot['color']) ? (int) $shot['color'] : -1;
353 $clientId = isset($shot['client_id']) ? (string) $shot['client_id'] : (string) ($shot['id'] ?? '');
354 $miss = $targets === [] || (mt_rand() / mt_getrandmax()) < $missChance;
355 $to = null;
356 $toName = null;
357 if (!$miss) {
358 $pick = $targets[random_int(0, count($targets) - 1)];
359 $to = $pick['user_id'];
360 $toName = $pick['name'];
361 }
362 $deliver = $now + $flight;
363 $ins->execute([$lobby['id'], $userId, $to, $color, $clientId, $now, $deliver]);
364 $results[] = [
365 'id' => (int) $this->pdo->lastInsertId(),
366 'client_id' => $clientId,
367 'miss' => $miss,
368 'target_id' => $to,
369 'target_name' => $toName,
370 'deliver_at' => $deliver,
371 'color' => $color,
372 'flight_duration' => $flight,
373 ];
374 }
375 return $results;
376 });
377 }
378
379 /** @return list<array> undelivered shots whose time has come, marked delivered. */
380 public function takeIncoming(string $lobbyId, string $userId): array
381 {
382 $now = $this->nowf();
383 $stmt = $this->pdo->prepare(
384 'SELECT * FROM shots
385 WHERE lobby_id = ? AND to_user = ? AND delivered = 0 AND deliver_at <= ?
386 ORDER BY deliver_at ASC, id ASC'
387 );
388 $stmt->execute([$lobbyId, $userId, $now]);
389 $rows = $stmt->fetchAll();
390 if (!$rows) {
391 return [];
392 }
393 $ids = array_column($rows, 'id');
394 $in = implode(',', array_fill(0, count($ids), '?'));
395 $this->pdo->prepare('UPDATE shots SET delivered = 1 WHERE id IN (' . $in . ')')->execute($ids);
396 $incoming = [];
397 foreach ($rows as $r) {
398 $incoming[] = [
399 'id' => (int) $r['id'],
400 'color' => (int) $r['color'],
401 'from_user' => $r['from_user'],
402 'client_id' => $r['client_id'],
403 ];
404 }
405 return $incoming;
406 }
407
408 public function updateSnapshot(string $userId, ?array $snapshot, ?int $score, bool $eliminated): void
409 {
410 $lobby = $this->lobbyForUser($userId);
411 if (!$lobby || $lobby['status'] !== 'playing') {
412 return;
413 }
414 $json = $snapshot !== null ? json_encode($snapshot, JSON_UNESCAPED_UNICODE) : null;
415 $fields = 'last_seen = ?';
416 $args = [$this->now()];
417 if ($json !== null) {
418 $fields .= ', snapshot = ?';
419 $args[] = $json;
420 }
421 if ($score !== null) {
422 $fields .= ', score = ?';
423 $args[] = $score;
424 }
425 $args[] = $lobby['id'];
426 $args[] = $userId;
427 $this->pdo->prepare(
428 "UPDATE members SET $fields WHERE lobby_id = ? AND user_id = ? AND left_at IS NULL"
429 )->execute($args);
430 if ($eliminated) {
431 $this->assignPlaceIfNeeded($lobby['id'], $userId, false);
432 $this->maybeFinish($lobby['id']);
433 }
434 }
435
436 public function member(string $lobbyId, string $userId): ?array
437 {
438 $stmt = $this->pdo->prepare(
439 'SELECT * FROM members WHERE lobby_id = ? AND user_id = ?'
440 );
441 $stmt->execute([$lobbyId, $userId]);
442 $row = $stmt->fetch();
443 return $row ?: null;
444 }
445
446 private function assignPlaceIfNeeded(string $lobbyId, string $userId, bool $leaving): void
447 {
448 $m = $this->member($lobbyId, $userId);
449 if (!$m || $m['place'] !== null) {
450 return;
451 }
452 $active = 0;
453 foreach ($this->members($lobbyId) as $row) {
454 if (!(int) $row['eliminated'] && $row['user_id'] !== $userId) {
455 $active++;
456 }
457 }
458 // First out gets last place = number of current (incl. this) non-left players.
459 $total = count($this->members($lobbyId));
460 $alreadyPlaced = 0;
461 foreach ($this->members($lobbyId, true) as $row) {
462 if ($row['place'] !== null && $row['left_at'] === null || ($row['place'] !== null && $row['user_id'] !== $userId)) {
463 if ($row['place'] !== null) {
464 $alreadyPlaced++;
465 }
466 }
467 }
468 $place = $active + 1; // remaining others + self → this player's place
469 $this->pdo->prepare(
470 'UPDATE members SET eliminated = 1, place = ? WHERE lobby_id = ? AND user_id = ?'
471 )->execute([$place, $lobbyId, $userId]);
472 }
473
474 public function maybeFinish(string $lobbyId): void
475 {
476 $lobby = $this->getLobby($lobbyId);
477 if (!$lobby || $lobby['status'] !== 'playing') {
478 return;
479 }
480 $alive = [];
481 foreach ($this->members($lobbyId) as $m) {
482 if (!(int) $m['eliminated']) {
483 $alive[] = $m;
484 }
485 }
486 if (count($alive) > 1) {
487 return;
488 }
489 if (count($alive) === 1) {
490 $winner = $alive[0];
491 if ($winner['place'] === null) {
492 $this->pdo->prepare(
493 'UPDATE members SET place = 1 WHERE lobby_id = ? AND user_id = ?'
494 )->execute([$lobbyId, $winner['user_id']]);
495 }
496 }
497 $this->pdo->prepare(
498 'UPDATE lobbies SET status = ?, finished = ? WHERE id = ?'
499 )->execute(['finished', $this->now(), $lobbyId]);
500 }
501
502 public function maybeResetLobby(string $lobbyId): void
503 {
504 $lobby = $this->getLobby($lobbyId);
505 if (!$lobby || $lobby['status'] !== 'finished') {
506 return;
507 }
508 $finished = (int) ($lobby['finished'] ?? 0);
509 if ($finished === 0 || time() < $finished + METEORS_PODIUM_SECONDS) {
510 return;
511 }
512 $this->pdo->prepare(
513 'UPDATE lobbies SET status = ?, started = NULL, finished = NULL WHERE id = ?'
514 )->execute(['waiting', $lobbyId]);
515 $this->pdo->prepare(
516 'UPDATE members SET ready = 0, eliminated = 0, place = NULL, snapshot = NULL, score = 0
517 WHERE lobby_id = ? AND left_at IS NULL'
518 )->execute([$lobbyId]);
519 $this->pdo->prepare('DELETE FROM shots WHERE lobby_id = ?')->execute([$lobbyId]);
520 }
521
522 /** Public view of a lobby for the given user, including incoming shots. */
523 public function viewFor(string $userId, ?array $snapshot = null, ?int $score = null, bool $eliminated = false, array $outgoing = []): array
524 {
525 return $this->transaction(function () use ($userId, $snapshot, $score, $eliminated, $outgoing) {
526 $touch = $this->lobbyForUser($userId);
527 if ($touch && $touch['status'] === 'finished') {
528 $this->maybeResetLobby($touch['id']);
529 }
530 if ($touch && $touch['status'] === 'playing') {
531 if ($snapshot !== null || $score !== null || $eliminated) {
532 $this->updateSnapshot($userId, $snapshot, $score, $eliminated);
533 } else {
534 $this->pdo->prepare(
535 'UPDATE members SET last_seen = ? WHERE lobby_id = ? AND user_id = ? AND left_at IS NULL'
536 )->execute([$this->now(), $touch['id'], $userId]);
537 }
538 }
539 $shotResults = [];
540 if ($outgoing && $touch && $touch['status'] === 'playing') {
541 $shotResults = $this->recordShots($userId, $outgoing);
542 }
543 $lobby = $this->lobbyForUser($userId);
544 if (!$lobby) {
545 return [
546 'lobby' => null,
547 'incoming' => [],
548 'shot_results' => $shotResults,
549 ];
550 }
551 $incoming = [];
552 if ($lobby['status'] === 'playing') {
553 $incoming = $this->takeIncoming($lobby['id'], $userId);
554 }
555 return [
556 'lobby' => $this->presentLobby($lobby, $userId),
557 'incoming' => $incoming,
558 'shot_results' => $shotResults,
559 ];
560 });
561 }
562
563 public function presentLobby(array $lobby, string $userId): array
564 {
565 $members = $this->members($lobby['id']);
566 $players = [];
567 foreach ($members as $m) {
568 $snap = null;
569 if (is_string($m['snapshot']) && $m['snapshot'] !== '') {
570 $decoded = json_decode($m['snapshot'], true);
571 $snap = is_array($decoded) ? $decoded : null;
572 }
573 $players[] = [
574 'id' => $m['user_id'],
575 'name' => $m['name'],
576 'ready' => (bool) (int) $m['ready'],
577 'eliminated' => (bool) (int) $m['eliminated'],
578 'place' => $m['place'] !== null ? (int) $m['place'] : null,
579 'is_host' => $m['user_id'] === $lobby['host_id'],
580 'is_me' => $m['user_id'] === $userId,
581 'score' => (int) $m['score'],
582 'snapshot' => $m['user_id'] === $userId ? null : $snap,
583 ];
584 }
585 $rankings = [];
586 if ($lobby['status'] === 'finished' || $lobby['finished']) {
587 $all = $this->members($lobby['id'], true);
588 foreach ($all as $m) {
589 if ($m['place'] !== null) {
590 $rankings[] = [
591 'place' => (int) $m['place'],
592 'id' => $m['user_id'],
593 'name' => $m['name'],
594 'score' => (int) $m['score'],
595 ];
596 }
597 }
598 usort($rankings, fn ($a, $b) => $a['place'] <=> $b['place']);
599 }
600 $allReady = $players !== [] && array_reduce($players, fn ($ok, $p) => $ok && $p['ready'], true);
601 return [
602 'id' => $lobby['id'],
603 'code' => $lobby['code'],
604 'status' => $lobby['status'],
605 'host_id' => $lobby['host_id'],
606 'miss_chance' => (float) $lobby['miss_chance'],
607 'flight_duration' => (float) $lobby['flight_duration'],
608 'players' => $players,
609 'all_ready' => $allReady,
610 'can_start' => $lobby['status'] === 'waiting' && $lobby['host_id'] === $userId && $allReady && count($players) >= 2,
611 'rankings' => $rankings,
612 'finished_at' => $lobby['finished'] !== null ? (int) $lobby['finished'] : null,
613 'podium_seconds' => METEORS_PODIUM_SECONDS,
614 ];
615 }
616}