Skip to content

Instantly share code, notes, and snippets.

@chrisleavoy
Last active June 1, 2016 17:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save chrisleavoy/9c2386e3b408399c4ba2e5a4db055888 to your computer and use it in GitHub Desktop.
Save chrisleavoy/9c2386e3b408399c4ba2e5a4db055888 to your computer and use it in GitHub Desktop.
Amp\wait LogicException
<?php
require_once dirname(__DIR__) . '/vendor/autoload.php';
\Amp\run(function() {
$generator = resolve('google.ca', 8);
$old = \Amp\reactor();
\Amp\reactor(\Amp\driver());
$result = \Amp\wait(\Amp\resolve($generator));
\Amp\reactor($old);
// var_dump($result);
});
// ^works
function resolve($pluginName, $x)
{
$saneDefaults = [
'types' => \Amp\Dns\Record::A, 'server' => "8.8.8.{$x}", 'timeout' => 1000, 'tries' => 1,
'cache' => false
];
$result = (yield \Amp\Dns\resolve($pluginName, $saneDefaults));
yield new \Amp\CoroutineResult($result);
return;
}
function analyze($pluginName)
{
$x = rand(7,8);
$old = \Amp\reactor();
\Amp\reactor(\Amp\driver());
try {
$promise = \Amp\resolve(resolve($pluginName, $x));
$result = \Amp\wait($promise);
// FIXME: the above wait doesn't yield
} catch (\Exception $e) {
$result = "{$pluginName} timed out {$x}";
echo $result . "\n";
}
\Amp\reactor($old);
//$result = \Amp\wait($promise);
// ^ throws LogicException
return $result;
}
function analyzePlugin($pluginName)
{
// ideally not willing to change this function
$start = microtime(true);
echo("start $pluginName " . $start . "\n");
$r = analyze($pluginName);
echo("stop $pluginName " . (microtime(true) - $start) . "\n");
return $r;
}
function analyzePluginAsync($pluginName)
{
$deferred = new Amp\Deferred;
\Amp\immediately(function () use ($deferred, $pluginName) {
$deferred->succeed(analyzePlugin($pluginName));
});
return $deferred->promise();
}
function analyzePluginsAsync()
{
$registeredPlugins = ['google.ca', 'yahoo.com', 'textnow.com'];
$promises = [];
foreach ($registeredPlugins as $pluginName) {
$promises []= analyzePluginAsync($pluginName);
}
return \Amp\wait(\Amp\all($promises));
}
$start = microtime(true);
$result = analyzePluginsAsync();
echo "total: " . (microtime(true) - $start) . "\n";
// var_dump($result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment