presentkim / await-utils
await-generator utilities for axolotl-pm/PocketMine-MP: tick sleep and timeout, generator commands, awaitable promises
Requires
- php: ^8.4
- pocketmine/pocketmine-mp: ^5.0
- sof3/await-generator: ^3.6.1
Requires (Dev)
- axolotl-pm/pocketmine-mp: ^5.51
- phpstan/phpstan: ^2.1
- phpunit/phpunit: ^12.0
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
await-utils
A library for axolotl-pm/PocketMine-MP
Packagist ยท Changelog ยท Report a bug ยท Request a feature
Await::f2c(function() use ($player) : \Generator{ yield from AwaitSleep::sleep(AwaitSleep::seconds(1.5)); $answer = yield from AwaitSleep::timeout($this->askQuestion($player), AwaitSleep::seconds(30)); });
๐ Why await-utils?
Small helpers that every await-generator plugin ends up writing. They used to be three separate libraries (await-sleep, await-command, awaitable-promise) and are now one package with one namespace.
- Sleep and timeout :
AwaitSleep::sleep()waits ticks on the plugin scheduler,AwaitSleep::timeout()gives a generator a time limit and interrupts it when the limit is hit - Events and async tasks :
AwaitEvent::next()waits for an event,AwaitInteractwaits for a block or entity click,AwaitEvent::untilQuit()stops a flow when the player leaves,AwaitAsyncTask::submit()returns an AsyncTask result - Generator commands :
AwaitCommand::onExecute()is a generator, errors are reported to the sender - Awaitable promises :
AwaitablePromiseexposes a generator result as a promise withthen()/catch()/finally(), or back as a generator withawait()
๐ฆ Installation
composer require presentkim/await-utils
This also installs sof3/await-generator.
| Requirement | Version |
|---|---|
| Server | axolotl-pm/PocketMine-MP (fork of PocketMine-MP 5) |
| PHP | 8.4 or newer |
Using it in a plugin: plugins built from presentkim-pm/plugin-template bundle Composer libraries into the phar with shaded namespaces at release, so
composer requireis all a plugin needs.
Moving from await-sleep, await-command or awaitable-promise
Replace the package in composer.json and the namespace in your code. Class and method names are unchanged.
| Before | After |
|---|---|
presentkim/await-sleep, kim\present\awaitsleep\AwaitSleep, asleep() |
kim\present\awaitutils\AwaitSleep, asleep() |
presentkim/await-command, kim\present\awaitcommand\AwaitCommand |
kim\present\awaitutils\AwaitCommand |
presentkim/await-command, kim\present\awaitcommand\AwaitPluginCommand |
kim\present\awaitutils\AwaitPluginCommand |
presentkim/awaitable-promise, kim\present\awaitablepromise\AwaitablePromise |
kim\present\awaitutils\AwaitablePromise |
The message of the RuntimeException thrown by sleep() without registration is now AwaitSleep is not registered.
๐ Quick start
Sleep and timeout
Register your plugin once, so the helpers know which scheduler and listener owner to use. Every helper also takes an optional plugin argument, which is needed when several plugins share one unshaded copy of the library.
use kim\present\awaitutils\AwaitSleep; use kim\present\awaitutils\AwaitUtils; use kim\present\awaitutils\TimeoutException; use pocketmine\plugin\PluginBase; use SOFe\AwaitGenerator\Await; class TestPlugin extends PluginBase{ public function onLoad() : void{ AwaitUtils::register($this); } public function onEnable() : void{ Await::f2c(function() : \Generator{ yield from AwaitSleep::sleep(20); $this->getLogger()->info("After 20 ticks"); try{ $data = yield from AwaitSleep::timeout($this->loadData(), AwaitSleep::seconds(5)); }catch(TimeoutException){ $this->getLogger()->warning("Loading took more than 5 seconds"); } }); } }
- When the plugin that registered the scheduler is disabled, the scheduler cancels its tasks and the sleeping generators are never resumed (they are simply released). A tick count of 0 or less resumes on the next tick.
- When
timeout()runs out, the generator gets aRaceLostExceptionthrown in, so it can clean up in afinallyblock.
Events
use kim\present\awaitutils\AwaitEvent; use kim\present\awaitutils\AwaitSleep; use kim\present\awaitutils\PlayerQuitException; use kim\present\awaitutils\TimeoutException; use pocketmine\event\player\PlayerChatEvent; Await::f2c(function() use ($player) : \Generator{ $player->sendMessage("Type the name of your town in the chat (30 seconds)"); try{ $event = yield from AwaitEvent::untilQuit($player, AwaitSleep::timeout( AwaitEvent::next(PlayerChatEvent::class, fn(PlayerChatEvent $e) : bool => $e->getPlayer() === $player), AwaitSleep::seconds(30) )); }catch(TimeoutException){ $player->sendMessage("Too late"); return; }catch(PlayerQuitException){ return; // the player left, nothing to clean up } $this->createTown($player, $event->getMessage()); });
next()listens atMONITORpriority by default and resumes the generator inside the event call, so do not change the event there. Pass a lower priority (and cancel the event yourself) when you need to.- The listener is removed as soon as the generator gets the event, times out or is interrupted.
Clicks
use kim\present\awaitutils\AwaitInteract; $player->getInventory()->addItem(AwaitInteract::tagTool(VanillaItems::STICK()->setCustomName("Select a corner"), "corner")); $first = yield from AwaitInteract::block($player, tool: "corner"); $second = yield from AwaitInteract::block($player, tool: "corner"); $this->createArea($first->getBlock()->getPosition(), $second->getBlock()->getPosition()); $click = yield from AwaitInteract::entity($player, fn($e) : bool => $e->getEntity() instanceof Villager);
block() and entity() cancel the matching click by default so the tool does not break or use anything; pass
cancel: false to only watch it.
Async tasks
use kim\present\awaitutils\AwaitAsyncTask; final class HashTask extends AwaitAsyncTask{ public function __construct(private string $data){} public function onRun() : void{ $this->setResult(hash("sha256", $this->data)); } } $hash = yield from (new HashTask($data))->submit();
onCompletion() is used by AwaitAsyncTask and cannot be overridden. An exception in onRun() crashes the worker as
with any AsyncTask, so return failures through the result.
Generator commands
use kim\present\awaitutils\AwaitCommand; use pocketmine\command\CommandSender; class TestCommand extends AwaitCommand{ public function __construct(){ parent::__construct("test", "test command", "/test usage", ["t"]); } public function onExecute(CommandSender $sender, string $commandLabel, array $args) : \Generator{ $test = yield from TestFactory::getTestObject(); $sender->sendMessage("TestObject: " . $test->getName()); } }
- Extend
AwaitPluginCommandinstead when the command belongs to a plugin: it implementsPluginOwned, andgetOwningPlugin()is already available ininit(). throw new InvalidCommandSyntaxException()sends the command usage to the sender. Any other throwable is logged and the sender gets "An internal error occurred while attempting to perform this command".
Awaitable promises
use kim\present\awaitutils\AwaitablePromise as Promise; Promise::f2p(fn() => Something::getAsync()) ->then(function($result){ echo "SUCCESS: " . $result . PHP_EOL; }) ->catch(function(\RuntimeException $e){ echo "ERROR: " . $e->getMessage() . PHP_EOL; }, \RuntimeException::class) ->finally(function($resultOrThrowable){ echo "FINALLY" . PHP_EOL; }); $result = yield from Promise::r2p(Something::getSync())->await(); // throws when the promise was rejected
AwaitablePromise::all([...]) waits for every promise and keeps the keys, AwaitablePromise::any([...]) takes the first
that resolves and rejects with AllRejectedException only when all of them fail.
A throwable that nothing handles (no matching catch(), no finally() and no await()) is logged with GlobalLogger
when the AwaitablePromise is destroyed, so it never vanishes silently.
๐ API reference
All classes and functions are in kim\present\awaitutils.
| Member | Description |
|---|---|
AwaitUtils::register(Plugin $plugin) / unregister() / isRegistered() |
Default plugin of every helper (the last registered plugin wins) |
AwaitSleep::register() / unregister() / isRegistered() |
Same as the AwaitUtils methods, kept for 1.0 code |
AwaitSleep::sleep(int $ticks, ?Plugin $plugin = null) : Generator |
Resumes after $ticks ticks, throws RuntimeException if no plugin |
AwaitSleep::timeout(Generator $generator, int $ticks, ?Plugin $plugin = null) |
Returns the generator's result, throws TimeoutException after $ticks |
AwaitSleep::seconds(float $seconds) : int |
Seconds to ticks (20 per second), rounded |
asleep(), timeout(), seconds() |
Function shorthands of the three methods above |
AwaitEvent::next(string $event, ?Closure $filter = null, ?Plugin $plugin = null, int $priority = MONITOR, bool $handleCancelled = false) |
Returns the next event that passes the filter |
AwaitEvent::untilQuit(Player $player, Generator $generator, ?Plugin $plugin = null) |
Returns the generator's result, throws PlayerQuitException if the player leaves first |
AwaitInteract::block(Player $player, ?Closure $filter = null, ?string $tool = null, bool $cancel = true, ?Plugin $plugin = null) |
Returns the player's next PlayerInteractEvent |
AwaitInteract::entity(Player $player, ...) (same arguments) |
Returns the player's next PlayerEntityInteractEvent |
AwaitInteract::tagTool(Item $item, string $toolId) : Item / isTool(Item, string) |
Tag a copy of an item as a tool / check the tag |
AwaitAsyncTask::submit(?AsyncPool $pool = null) : Generator |
Submits the task and returns its result |
AwaitCommand::__construct(name, description = "", usage = null, aliases = []) |
Same arguments as Command |
AwaitCommand::onExecute(CommandSender, string $commandLabel, array $args) : Generator |
Abstract, the command body |
AwaitCommand::init() : void |
Optional hook called at the end of the constructor |
AwaitPluginCommand::__construct(Plugin $plugin, name, ...) |
AwaitCommand that implements PluginOwned |
AwaitablePromise::g2p(Generator) / f2p(callable) / r2p(mixed) |
Promise from a generator, a generator function, or a ready result |
then(Closure) / catch(Closure, string $class = "") / finally(Closure) |
Result handler / first matching throwable handler / both |
await() : Generator / getRealPromise() : Promise |
Back to a generator / the wrapped PocketMine promise |
AwaitablePromise::all(array) / any(array) |
All results with the same keys / the first result |
๐งช Development
composer install --ignore-platform-req='ext-*' composer test composer analyse # PHPStan
The server's native extensions are not needed for the tests, so ext-* requirements are ignored on install.
๐ License
Distributed under the MIT License. See LICENSE for more information.