/**
  * @dataProvider getConnectors
  *
  * @param array $config
  */
 public function testInsert(array $config)
 {
     Coroutine\create(function () use($config) {
         $factory = new ManagerFactory();
         $database = $factory->create($config);
         $time = time();
         (yield $database->table("test")->insert(["text" => $time]));
         $row = (yield $database->table("test")->select()->where("text = ?", $time)->first());
         $this->assertEqualsAfterDelay(0.5, $row["text"], $time);
     })->done();
     Loop\run();
 }
예제 #2
0
 /**
  * @param string $subscriptionId
  * @param string $streamId
  * @param array $processedStreamIds
  * @param string $message
  * @param int $action
  *
  * @return Coroutine\Coroutine
  */
 function failAsync(string $subscriptionId, string $streamId, array $processedStreamIds, string $message, int $action) : Coroutine\Coroutine
 {
     return Coroutine\create([$this, 'fail'], $subscriptionId, $streamId, $processedStreamIds, $message, $action);
 }
예제 #3
0
}
require $autoloadPath;
use Icicle\Concurrent\Exception\{ChannelException, SerializationException};
use Icicle\Concurrent\Sync\{ChannelledStream, Internal\ExitFailure, Internal\ExitSuccess};
use Icicle\Concurrent\Worker\{BasicEnvironment, Internal\TaskRunner};
use Icicle\Coroutine;
use Icicle\Loop;
use Icicle\Stream;
Coroutine\create(function () {
    $channel = new ChannelledStream(Stream\stdin(), Stream\stdout());
    $environment = new BasicEnvironment();
    $runner = new TaskRunner($channel, $environment);
    try {
        $result = new ExitSuccess(yield from $runner->run());
    } catch (Throwable $exception) {
        $result = new ExitFailure($exception);
    }
    // Attempt to return the result.
    try {
        try {
            return yield from $channel->send($result);
        } catch (SerializationException $exception) {
            // Serializing the result failed. Send the reason why.
            return yield from $channel->send(new ExitFailure($exception));
        }
    } catch (ChannelException $exception) {
        // The result was not sendable! The parent context must have died or killed the context.
        return 0;
    }
})->done();
Loop\run();
예제 #4
0
    print "Demonstrating how alive the parent is for the {$i}th time.\n";
});

Coroutine\create(function () {
    // Create a new child thread that does some blocking stuff.
    $context = Thread::spawn(function () {
        printf("\$this: %s\n", get_class($this));

        printf("Received the following from parent: %s\n", (yield $this->receive()));

        print "Sleeping for 3 seconds...\n";
        sleep(3); // Blocking call in thread.

        yield $this->send('Data sent from child.');

        print "Sleeping for 2 seconds...\n";
        sleep(2); // Blocking call in thread.

        yield 42;
    });

    print "Waiting 2 seconds to send start data...\n";
    yield Coroutine\sleep(2);

    yield $context->send('Start data');

    printf("Received the following from child: %s\n", (yield $context->receive()));
    printf("Thread ended with value %d!\n", (yield $context->join()));
})->cleanup([$timer, 'stop'])->done();

Loop\run();
예제 #5
0
<?php

require dirname(__DIR__) . '/vendor/autoload.php';
use Icicle\Coroutine;
use Icicle\Loop;
use nntp\Client;
Coroutine\create(function () {
    $client = (yield from Client::connect('localhost', 1190));
    //$client = yield from Client::connect('news.php.net', 119);
    //var_dump(yield from $client->getGroups());
    $group = (yield from $client->setCurrentGroup('meta'));
    $c = min(1, $group->count());
    for ($i = 0; $i < $c; ++$i) {
        $article = (yield from $client->getArticleHeaders());
        var_dump($article);
        if ($i + 1 < $c) {
            yield from $client->next();
        }
    }
    var_dump(yield from $client->getArticle());
    yield from $client->close();
})->done();
Loop\run();
예제 #6
0
#!/usr/bin/env php
<?php 
require dirname(__DIR__) . '/vendor/autoload.php';
use Icicle\Concurrent\Worker\DefaultWorkerFactory;
use Icicle\Coroutine;
use Icicle\Examples\Concurrent\BlockingTask;
use Icicle\Loop;
Coroutine\create(function () {
    $factory = new DefaultWorkerFactory();
    $worker = $factory->create();
    $worker->start();
    $result = (yield from $worker->enqueue(new BlockingTask('file_get_contents', 'https://google.com')));
    printf("Read %d bytes\n", strlen($result));
    $code = (yield from $worker->shutdown());
    printf("Code: %d\n", $code);
})->done();
Loop\run();
예제 #7
0
파일: read.php 프로젝트: mhwk/spray-ouro
<?php

use Spray\Ouro\Client\Connection;
use Spray\Ouro\Transport\Message\EventRecord;
use Icicle\Awaitable;
use Icicle\Coroutine;
use Icicle\Loop;
error_reporting(-1);
ini_set('display_errors', 1);
chdir(__DIR__);
require 'vendor/autoload.php';
$coroutine = Coroutine\create(function () {
    $connection = Connection::connect('eventstore:2113', 'admin', 'changeit');
    (yield $connection->readStreamEventsForwardAsync('bar', function (EventRecord $record) {
        var_dump($record->getEventNumber());
    }));
});
$coroutine->capture(function (Throwable $e) {
    echo sprintf("%s on line %s in file %s\n%s\n", $e->getMessage(), $e->getLine(), $e->getFile(), $e->getTraceAsString());
});
Loop\run();
예제 #8
0
<?php

use Icicle\Coroutine;
use Icicle\Loop;
use Spray\Ouro\Client\Connection;
use Spray\Ouro\Client\IConnectToPersistentSubscriptionAsync;
use Spray\Ouro\Transport\Message\EventRecord;
error_reporting(-1);
ini_set('display_errors', 1);
chdir(__DIR__);
require 'vendor/autoload.php';
Coroutine\create(function () {
    /** @var IConnectToPersistentSubscriptionAsync $connection */
    $connection = Connection::connect('eventstore:2113', 'admin', 'changeit');
    (yield $connection->subscribePersistentAsync('saanka', 'bar', 50, function (EventRecord $record) {
        var_dump($record->getEventNumber());
    }));
});
Loop\run();
예제 #9
0
 /**
  * @inheritdoc
  *
  * @param string $key
  * @param mixed $value
  *
  * @return PromiseInterface
  *
  * @resolve mixed
  */
 public function set($key, $value)
 {
     $deferred = new Deferred();
     Loop\queue(function () use($deferred, $key, $value) {
         if ($this->busy($deferred, $key)) {
             $this->wait($deferred, $key);
         } else {
             Coroutine\create(function () use($deferred, $key, $value) {
                 $this->busy[$key] = $deferred;
                 if (is_callable($value)) {
                     $fork = Fork::spawn($value);
                     $value = (yield $fork->join());
                 }
                 $this->cache[$key] = $value;
                 unset($this->busy[$key]);
                 if (isset($this->waiting[$key])) {
                     while (count($this->waiting[$key])) {
                         /** @var Deferred $next */
                         $next = array_shift($this->waiting[$key]);
                         $next->resolve($value);
                     }
                 }
                 $deferred->resolve($value);
             });
         }
     });
     return $deferred->getPromise();
 }
예제 #10
0
파일: write.php 프로젝트: mhwk/spray-ouro
<?php

use Spray\Ouro\Client\Connection;
use Spray\Ouro\Transport\Message\NewEvent;
use Icicle\Awaitable;
use Icicle\Coroutine;
use Icicle\Loop;
use Ramsey\Uuid\Uuid;
error_reporting(-1);
ini_set('display_errors', 1);
chdir(__DIR__);
require 'vendor/autoload.php';
$coroutine = Coroutine\create(function () {
    $connection = Connection::connect('eventstore:2113', 'admin', 'changeit');
    for ($i = 0; $i < 100; $i++) {
        (yield $connection->writeEventsAsync('bar', -2, [new NewEvent(Uuid::uuid4(), 'Bar', ['foo' => 'bar'], ['foo' => 'bar']), new NewEvent(Uuid::uuid4(), 'Bar', ['foo' => 'bar'], ['foo' => 'bar'])]));
    }
});
$coroutine->capture(function (Throwable $e) {
    echo sprintf("%s on line %s in file %s\n%s\n", $e->getMessage(), $e->getLine(), $e->getFile(), $e->getTraceAsString());
});
Loop\run();
예제 #11
0
 public function testStampedeProtection()
 {
     Coroutine\create(function () {
         $cache = new MemoryDriver();
         file_put_contents(__DIR__ . "/stampede", 1);
         $factory = function () use(&$counter) {
             $count = (int) file_get_contents(__DIR__ . "/stampede");
             file_put_contents(__DIR__ . "/stampede", ++$count);
             (yield $count);
         };
         $cache->set("counter", $factory);
         $cache->set("counter", $factory);
         $cache->set("counter", $factory);
         $cache->get("counter");
         $cache->get("counter");
         // resolve the first "counter" value
         (yield $cache->get("counter"));
         // fetch the second "counter" value from the cache memory store
         $actual = (yield $cache->get("counter"));
         // first check to see that the count stored in the filesystem
         // is correct...
         Loop\timer(0.5, function () {
             $count = (int) file_get_contents(__DIR__ . "/stampede");
             $this->assertEquals(2, $count);
             unlink(__DIR__ . "/stampede");
         });
         // then check to see that the count stored in the cache
         // is correct...
         $this->assertEqualsAfterDelay(2, $actual);
     })->done();
     Loop\run();
 }
예제 #12
0
<?php

require __DIR__ . "/../vendor/autoload.php";
use AsyncPHP\Icicle\Database\ManagerFactory;
use Icicle\Coroutine;
use Icicle\Loop;
Coroutine\create(function () {
    $factory = new ManagerFactory();
    $manager = $factory->create(require __DIR__ . "/config.php");
    try {
        (yield $manager->table("test")->select()->where("text = ?", "foo")->limit(1, 2)->orderBy("text desc")->get());
        (yield $manager->table("test")->insert(["text" => "bar"]));
        (yield $manager->table("test")->where("text = ?", "bar")->update(["text" => "foo"]));
        (yield $manager->table("test")->where("text = ?", "bar")->delete());
    } catch (Exception $e) {
        die($e->getMessage());
    }
});
Loop\run();
예제 #13
0
    {
        $this->callable = $callable;
        $this->args = $args;
    }
    public function run(Environment $environment)
    {
        ($this->callable)(...$this->args);
    }
}
function wait()
{
    $sleep = rand(1, 200) / 100;
    echo "Sleep {$sleep} seconds\n";
    sleep($sleep);
    echo "Awake\n";
    return true;
}
Coroutine\create(function () {
    $pool = new DefaultPool();
    $pool->start();
    $coroutines = [];
    for ($i = 0; $i < 50; $i++) {
        $coroutines[] = Coroutine\create(function () use($pool) {
            $result = (yield from $pool->enqueue(new CallableTask('wait')));
            return $result;
        });
    }
    (yield Awaitable\all($coroutines));
    return yield from $pool->shutdown();
})->done();
Loop\run();
예제 #14
0
 /**
  * @return PromiseInterface
  */
 public function delete()
 {
     return Coroutine\create(function () {
         $builder = $this->builder->delete();
         $builder = $this->applyOperationsTo($builder);
         list($statement, $values) = $builder->build();
         (yield $this->connector->query($statement, $values));
     });
 }
예제 #15
0
<?php

require __DIR__ . "/../vendor/autoload.php";
use AsyncPHP\Icicle\Database\Connector\DoormanConnector;
use Icicle\Coroutine;
use Icicle\Loop;
Coroutine\create(function () {
    $connector = new DoormanConnector();
    $connector->connect(require __DIR__ . "/config.php");
    try {
        (yield $connector->query("insert into test (text) values (:text)", ["text" => "foo"]));
    } catch (Exception $e) {
        print $e->getMessage();
    }
    while (true) {
        $result = (yield $connector->query("select * from test where text = :text", ["text" => "foo"]));
        print print_r($result, true) . "\n";
    }
});
Loop\run();
예제 #16
0
    exit(1);
}

require $autoloadPath;

use Icicle\Concurrent\Sync\Channel;
use Icicle\Concurrent\Sync\Internal\ExitFailure;
use Icicle\Concurrent\Sync\Internal\ExitSuccess;
use Icicle\Concurrent\Worker\Environment;
use Icicle\Concurrent\Worker\Internal\TaskRunner;
use Icicle\Coroutine;
use Icicle\Loop;
use Icicle\Stream;

Coroutine\create(function () {
    $channel = new Channel(Stream\stdin(), Stream\stdout());
    $environment = new Environment();

    $runner = new TaskRunner($channel, $environment);

    try {
        $result = new ExitSuccess(yield $runner->run());
    } catch (Exception $exception) {
        $result = new ExitFailure($exception);
    }

    yield $channel->send($result);
})->done();

Loop\run();
예제 #17
0
#!/usr/bin/env php
<?php 
require dirname(__DIR__) . '/vendor/autoload.php';
use Icicle\Concurrent\Forking\Fork;
use Icicle\Coroutine;
use Icicle\Loop;
Coroutine\create(function () {
    $context = Fork::spawn(function () {
        print "Child sleeping for 4 seconds...\n";
        sleep(4);
        yield from $this->send('Data sent from child.');
        print "Child sleeping for 2 seconds...\n";
        sleep(2);
        return 42;
    });
    $timer = Loop\periodic(1, function () use($context) {
        static $i;
        $i = $i ? ++$i : 1;
        print "Demonstrating how alive the parent is for the {$i}th time.\n";
    });
    try {
        printf("Received the following from child: %s\n", yield from $context->receive());
        printf("Child ended with value %d!\n", yield from $context->join());
    } catch (Exception $e) {
        print "Error from child!\n";
        print $e . "\n";
    } finally {
        $timer->stop();
    }
});
Loop\run();
예제 #18
0
use Icicle\Awaitable;
use Icicle\Concurrent\Worker\DefaultPool;
use Icicle\Coroutine;
use Icicle\Examples\Concurrent\BlockingTask;
use Icicle\Loop;
Coroutine\create(function () {
    $pool = new DefaultPool();
    $pool->start();
    $coroutines = [];
    $coroutines[] = Coroutine\create(function () use($pool) {
        $url = 'https://google.com';
        $result = (yield from $pool->enqueue(new BlockingTask('file_get_contents', $url)));
        printf("Read from %s: %d bytes\n", $url, strlen($result));
    });
    $coroutines[] = Coroutine\create(function () use($pool) {
        $url = 'https://icicle.io';
        $result = (yield from $pool->enqueue(new BlockingTask('file_get_contents', $url)));
        printf("Read from %s: %d bytes\n", $url, strlen($result));
    });
    $coroutines[] = Coroutine\create(function () use($pool) {
        $url = 'https://github.com';
        $result = (yield from $pool->enqueue(new BlockingTask('file_get_contents', $url)));
        printf("Read from %s: %d bytes\n", $url, strlen($result));
    });
    (yield Awaitable\all($coroutines));
    return yield from $pool->shutdown();
})->done();
Loop\periodic(0.1, function () {
    printf(".\n");
})->unreference();
Loop\run();