From ac41d76ef1fc103f930ccb4db25d3cca84b735f2 Mon Sep 17 00:00:00 2001 From: Baptiste Langlade Date: Sun, 5 Nov 2023 16:38:09 +0100 Subject: [PATCH] run http requests asynchronously --- composer.json | 2 +- proofs/functional.php | 52 ++++++++++++++++++++++++++++++++++++++++++- src/Task.php | 12 +++++++++- 3 files changed, 63 insertions(+), 3 deletions(-) diff --git a/composer.json b/composer.json index ac4f4ac..ea2ba0a 100644 --- a/composer.json +++ b/composer.json @@ -17,7 +17,7 @@ "require": { "php": "~8.2", "innmind/immutable": "~5.2", - "innmind/operating-system": "~4.0", + "innmind/operating-system": "~4.1", "innmind/filesystem": "~7.3" }, "autoload": { diff --git a/proofs/functional.php b/proofs/functional.php index 418143f..ac9a431 100644 --- a/proofs/functional.php +++ b/proofs/functional.php @@ -9,7 +9,15 @@ use Innmind\OperatingSystem\Factory; use Innmind\TimeContinuum\Earth\Period\Second; use Innmind\Filesystem\Name; -use Innmind\Url\Path; +use Innmind\Http\{ + Request, + Method, + ProtocolVersion, +}; +use Innmind\Url\{ + Url, + Path, +}; use Innmind\Immutable\Sequence; use Innmind\BlackBox\Set; @@ -229,4 +237,46 @@ static function($os) use ($assert, &$chunks) { ); }, ); + + yield test( + 'HTTP requests are handled asynchronously', + static function($assert) { + $order = []; + Forerunner::of(Factory::build())(null, Predetermined::of( + static function($os) use ($assert, &$order) { + $os + ->remote() + ->http()(Request::of( + Url::of('https://httpbin.org/delay/2'), + Method::get, + ProtocolVersion::v11, + )) + ->match( + static fn() => null, + static fn() => null, + ); + $order[] = 'first'; + }, + static function($os) use ($assert, &$order) { + $os + ->remote() + ->http()(Request::of( + Url::of('https://httpbin.org/delay/1'), + Method::get, + ProtocolVersion::v11, + )) + ->match( + static fn() => null, + static fn() => null, + ); + $order[] = 'second'; + }, + )); + + $assert->same( + ['second', 'first'], + $order, + ); + }, + ); }; diff --git a/src/Task.php b/src/Task.php index 765dc47..b940079 100644 --- a/src/Task.php +++ b/src/Task.php @@ -7,6 +7,10 @@ Factory, OperatingSystem, }; +use Innmind\TimeContinuum\Earth\{ + ElapsedPeriod, + Period\Millisecond, +}; /** * @template R @@ -46,7 +50,13 @@ public function start(OperatingSystem $synchronous): mixed $suspend, $config->streamCapabilities(), )) - ->haltProcessVia(Asynchronous\Halt::of($suspend)), + ->haltProcessVia(Asynchronous\Halt::of($suspend)) + ->withHttpHeartbeat( + ElapsedPeriod::of(10), // this is blocking the active task so it needs to be low + static fn() => $suspend(Suspend\Halt::of( // this allows to jump between tasks + Millisecond::of(1), + )), + ), ), ));