<?phpnamespace Tests;use App\Alis\Machine;use App\Alis\SysVars;use JumPHP\Async\Task;use JumPHP\Bridge\JsBridge;use JumPHP\Http\Http;use JumPHP\Http\HttpResponse;use PHPUnit\Framework\TestCase;/** * The big files of a game are downloaded by parts below 2 MB (in the browser PHP never gets back the memory of a * bigger string: a film downloaded whole grew the page at each download, and the game slowed down). */final class DownloadTest extends TestCase{ public static function setUpBeforeClass(): void { class_exists(Machine::class); // loads the VM's functions (fn/_load.php) } public function testABigFileComesByPartsAndWhole(): void { $data = random_bytes(7 * SysVars::LAZY_PART + 12345); $http = new class (new JsBridge()) extends Http { public string $data = ''; public bool $honourRange = true; /** @var list<string> */ public array $asked = []; public function request(string $method, string $url, string|array|null $body = null, array $headers = [], ?float $timeout = null): Task { $task = new Task(); $range = $headers['Range'] ?? null; $this->asked[] = $range ?? 'all'; if ($range !== null && $this->honourRange && preg_match('/bytes=(\d+)-(\d+)/', $range, $m)) { $task->settle(new HttpResponse(206, substr($this->data, (int) $m[1], (int) $m[2] - (int) $m[1] + 1))); } else { $task->settle(new HttpResponse(200, $this->data)); } return $task; } }; $http->data = $data; $dir = sys_get_temp_dir() . '/alis-dl-' . getmypid(); @mkdir($dir); SysVars::$http = $http; SysVars::$lazy = ['film.dat' => [strlen($data), 'abc']]; SysVars::$lazyDev = ''; SysVars::$lazyBase = '/alis/play/private/lazy/robinson/'; SysVars::$fetching = SysVars::$lazyFailed = SysVars::$lazyLoaded = []; self::assertNull(\App\Alis\sys_lazy_file($dir, 'film.dat')); self::assertSame($data, file_get_contents("$dir/film.dat")); self::assertSame((int) ceil(strlen($data) / SysVars::LAZY_PART), count($http->asked), 'parts of LAZY_PART bytes'); self::assertSame([], SysVars::$fetching); self::assertFileDoesNotExist("$dir/film.dat.part"); // a server that ignores Range: the part asked is cut from the whole answer unlink("$dir/film.dat"); $http->honourRange = false; SysVars::$lazyLoaded = []; self::assertNull(\App\Alis\sys_lazy_file($dir, 'film.dat')); self::assertSame($data, file_get_contents("$dir/film.dat")); unlink("$dir/film.dat"); rmdir($dir); } public function testTheBigFilesComeFromThePlaygroundsExternals(): void { $server = sys_get_temp_dir() . '/alis-ext-' . getmypid(); $dir = "$server-game"; @mkdir($server, 0777, true); @mkdir($dir, 0777, true); $data = random_bytes(5 * SysVars::LAZY_PART + 777); file_put_contents("$server/intro.dat", $data); // the externals folder alis/robinson is a folder of this computer here (LocalTransport); in the browser the // playground's /alis/play/externals/ (HttpTransport), the same API $externals = new \JumPHP\Externals\Externals(); $externals->configure(['local' => ['alis/robinson' => $server], 'persist' => false]); SysVars::$externals = $externals; SysVars::$externalsDir = 'alis/robinson'; SysVars::$externalsOff = false; SysVars::$http = null; SysVars::$lazy = ['intro.dat' => [strlen($data), 'abc'], 'other.dat' => [10, 'def']]; SysVars::$lazyDev = ''; SysVars::$fetching = SysVars::$lazyFailed = SysVars::$lazyLoaded = []; // sys_lazy_file() only starts a download with an Http: a fake one that must not be asked SysVars::$http = new class (new JsBridge()) extends Http { public int $asked = 0; public function request(string $method, string $url, string|array|null $body = null, array $headers = [], ?float $timeout = null): Task { $this->asked++; $t = new Task(); $t->settle(new HttpResponse(404, '')); return $t; } }; for ($i = 0; $i < 50 && \App\Alis\sys_lazy_file($dir, 'intro.dat') === null && !isset(SysVars::$lazyFailed['intro.dat']); $i++) { usleep(1000); } self::assertSame($data, file_get_contents("$dir/intro.dat")); self::assertSame(0, SysVars::$http->asked, 'not from the private files'); self::assertFalse(SysVars::$externalsOff); // a file the externals do not have: the private files (here: 404, so it fails), and the next ones too self::assertNull(\App\Alis\sys_lazy_file($dir, 'other.dat')); for ($i = 0; $i < 10 && SysVars::$fetching !== []; $i++) { usleep(1000); } self::assertTrue(SysVars::$externalsOff); self::assertSame(1, SysVars::$http->asked); SysVars::$externals = null; foreach (["$dir/intro.dat", "$server/intro.dat"] as $f) { @unlink($f); } @rmdir($dir); @rmdir($server); } public function testTheBlocksOfAnExternalNameItsVersionSoTheBrowserKeepsThem(): void { $data = random_bytes(3000); $http = new class (new JsBridge(), $data) extends Http { /** @var list<string> */ public array $urls = []; public function __construct(JsBridge $bridge, private string $data) { parent::__construct($bridge); } public function request(string $method, string $url, string|array|null $body = null, array $headers = [], ?float $timeout = null): Task { $this->urls[] = $url; $t = new Task(); if (str_contains($url, '~stat')) { $t->settle(new HttpResponse(200, json_encode(['path' => 'alis/robinson/logo.dat', 'type' => 'file', 'size' => 3000, 'mtime' => 1, 'etag' => 'bb8-1']))); } elseif (preg_match('/bytes=(\d+)-(\d+)/', (string) ($headers['Range'] ?? ''), $m)) { $t->settle(new HttpResponse(206, substr($this->data, (int) $m[1], (int) $m[2] - (int) $m[1] + 1))); } else { $t->settle(new HttpResponse(404, '')); } return $t; } }; $externals = new \JumPHP\Externals\Externals(); $externals->configure(['persist' => false, 'block' => 4096]); (new \ReflectionProperty($externals, 'http'))->setValue($externals, new \JumPHP\Externals\HttpTransport($http, '/alis/play/externals/')); $read = null; $error = null; $externals->open('alis/robinson/logo.dat')->then( function ($file) use (&$read, &$error): void { $file->read(0, 3000)->then(function (string $b) use (&$read): void { $read = $b; }, function (\Throwable $e) use (&$error): void { $error = $e->getMessage(); }); }, function (\Throwable $e) use (&$error): void { $error = $e->getMessage(); }, ); self::assertNull($error); self::assertSame($data, $read); // the bytes are asked at an address that names the file's version: the playground lets the browser keep them self::assertContains('/alis/play/externals/alis/robinson/logo.dat?v=bb8-1&r=0', $http->urls); } public function testAFolderListedOnceOpensItsFilesWithoutAskingTheServerAgain(): void { $http = new class (new JsBridge()) extends Http { /** @var list<string> */ public array $urls = []; public function request(string $method, string $url, string|array|null $body = null, array $headers = [], ?float $timeout = null): Task { $this->urls[] = $url; $t = new Task(); $entry = ['path' => 'alis/robinson/a.dat', 'type' => 'file', 'size' => 10, 'mtime' => 1, 'etag' => 'a-1']; $t->settle(new HttpResponse(200, json_encode(str_contains($url, '~list') ? ['dir' => 'alis/robinson', 'entries' => [$entry]] : $entry))); return $t; } }; $externals = new \JumPHP\Externals\Externals(); $externals->configure(['persist' => false]); (new \ReflectionProperty($externals, 'http'))->setValue($externals, new \JumPHP\Externals\HttpTransport($http, '/alis/play/externals/')); $externals->list('alis/robinson'); $opened = null; $externals->open('alis/robinson/a.dat')->then(function ($f) use (&$opened): void { $opened = $f; }); self::assertNotNull($opened); self::assertSame(10, $opened->size()); self::assertSame([], array_values(array_filter($http->urls, static fn (string $u) => str_contains($u, '~stat'))), 'no ~stat after the list'); } public function testTheSmallFilesArePrefetchedInTheBackgroundOnce(): void { $files = ['a.als' => random_bytes(1000), 'b.dat' => random_bytes(300000)]; $http = new class (new JsBridge(), $files) extends Http { /** @var list<string> */ public array $urls = []; public function __construct(JsBridge $bridge, private array $files) { parent::__construct($bridge); } public function request(string $method, string $url, string|array|null $body = null, array $headers = [], ?float $timeout = null): Task { $this->urls[] = $url; $t = new Task(); $entries = []; foreach ($this->files as $n => $d) { $entries[] = ['path' => "alis/robinson/$n", 'type' => 'file', 'size' => strlen($d), 'mtime' => 1]; } if (str_contains($url, '~list')) { $t->settle(new HttpResponse(200, json_encode(['entries' => $entries]))); } elseif (preg_match('#robinson/([^?]+)\?#', $url, $m) && preg_match('/bytes=(\d+)-(\d+)/', (string) ($headers['Range'] ?? ''), $r)) { $t->settle(new HttpResponse(206, substr($this->files[$m[1]], (int) $r[1], (int) $r[2] - (int) $r[1] + 1))); } else { $t->settle(new HttpResponse(404, '')); } return $t; } }; $externals = new \JumPHP\Externals\Externals(); $externals->configure(['persist' => false]); (new \ReflectionProperty($externals, 'http'))->setValue($externals, new \JumPHP\Externals\HttpTransport($http, '/alis/play/externals/')); $var = sys_get_temp_dir() . '/alis-prefetch-' . getmypid(); @mkdir($var, 0777, true); SysVars::$storage = new \JumPHP\Save\Storage($var); SysVars::$externals = $externals; SysVars::$externalsDir = 'alis/robinson'; SysVars::$externalsOff = false; SysVars::$lazyDev = ''; SysVars::$fetching = SysVars::$lazyLoaded = []; SysVars::$lazy = ['a.als' => [1000, 'ha'], 'b.dat' => [300000, 'hb']]; $externals->list('alis/robinson'); \App\Alis\Prefetch::start('robinson'); self::assertSame(2, \App\Alis\Prefetch::left()); for ($i = 0; $i < 200 && \App\Alis\Prefetch::left() > 0; $i++) { \App\Alis\Prefetch::tick(0.1); } self::assertSame(0, \App\Alis\Prefetch::left()); $reads = array_values(array_filter($http->urls, static fn (string $u) => str_contains($u, '?v='))); self::assertCount(3, $reads, 'a.als in one part, b.dat in two (256 KB parts)'); self::assertSame(['a.als' => 'ha', 'b.dat' => 'hb'], json_decode((string) SysVars::$storage->read('alis-prefetch-robinson.json'), true)); // the next visit: nothing left to prefetch \App\Alis\Prefetch::start('robinson'); self::assertSame(0, \App\Alis\Prefetch::left()); \App\Alis\Prefetch::stop(); SysVars::$externals = null; }}