/** * Change the target owner * @param Deferred $deferred * @param TaskInterface $task * @return bool */ protected function processDeferred(Deferred $deferred, TaskInterface $task) { yield; /** @var Description $description */ $description = $task->getDescription(); try { $deferred->notify(new Notification("Changing '{$description->getTarget()}' owner to '{$description->getOwner()}'", Notification::PRIORITY_NORMAL)); if ($this->getFileSystem()->changeOwner($description->getTarget(), $description->getOwner())) { $deferred->resolve("Changed '{$description->getTarget()}' owner to '{$description->getOwner()}' successfully"); return; } } catch (\Exception $e) { // do noting, we reject below $deferred->reject("Failed to change the owner of {$description->getTarget()}: " . $e->getMessage()); return; } $deferred->reject("Failed to change the owner of {$description->getTarget()} to {$description->getOwner()}"); }
private function executeRequest($method, $uri, $body = null) { $deferred = new Deferred(); $request = $this->client->request($method, $this->buildUrl($uri), array('Content-Length' => strlen($body), 'Authorization' => 'Basic ' . base64_encode($this->options['user'] . ':' . $this->options['password']), 'Content-Type' => 'application/json')); $request->writeHead(); $request->on('error', function ($error) use($uri, $deferred) { $deferred->reject(sprintf('Error while doing the request on %s : %s', $uri, $error->getMessage())); }); $request->on('response', function (Response $response) use($deferred) { if ($response->getCode() < 200 || $response->getCode() >= 400) { $deferred->reject(sprintf('The response is not as expected (status code %s, message is %s)', $response->getCode(), $response->getReasonPhrase())); } $response->on('error', function ($error) use($deferred) { $deferred->reject($error->getMessage()); }); $data = (object) array('data' => ''); $response->on('data', function ($chunk) use($data) { $data->data .= $chunk; }); $response->on('end', function () use($deferred, $data) { $deferred->resolve($data->data); }); }); $request->end($body); return $deferred->promise(); }
protected function createInternalAsync($host, $docroot, $router) { $deferred = new Deferred(); $process = new BuiltinServer($host, $docroot, $router, $this->php); $process->start($this->loop); $process->on('exit', function ($code) use($deferred) { $this->stderr->write("Process exit with code {$code}\n"); $deferred->reject(); }); $process->stdin->close(); $process->stdout->close(); $process->stderr->on('data', function ($output) use($deferred) { $this->stderr->write($output); $deferred->reject(); }); $timer = new Deferred(); $this->loop->addTimer(0.05, function () use($timer, $process) { if (DIRECTORY_SEPARATOR === '\\') { // Pipes opened by proc_open() can break stream_select() loop in Windows. // This fix might do the trick... $process->stderr->close(); } $timer->resolve($process); }); return \React\Promise\race([$deferred->promise(), $timer->promise()])->then(null, function () use($process) { $process->terminate(); return new RejectedPromise(); }); }
public function doQuery($nameserver, $transport, $queryData, $name) { $parser = $this->parser; $loop = $this->loop; $response = new Message(); $deferred = new Deferred(); $retryWithTcp = function () use($nameserver, $queryData, $name) { return $this->doQuery($nameserver, 'tcp', $queryData, $name); }; $timer = $this->loop->addTimer($this->timeout, function () use(&$conn, $name, $deferred) { $conn->close(); $deferred->reject(new TimeoutException(sprintf("DNS query for %s timed out", $name))); }); $conn = $this->createConnection($nameserver, $transport); $conn->on('data', function ($data) use($retryWithTcp, $conn, $parser, $response, $transport, $deferred, $timer) { $responseReady = $parser->parseChunk($data, $response); if (!$responseReady) { return; } $timer->cancel(); if ($response->header->isTruncated()) { if ('tcp' === $transport) { $deferred->reject(new BadServerException('The server set the truncated bit although we issued a TCP request')); } else { $conn->end(); $deferred->resolve($retryWithTcp()); } return; } $conn->end(); $deferred->resolve($response); }); $conn->write($queryData); return $deferred->promise(); }
public function doQuery($nameserver, $queryData, $name) { $that = $this; $parser = $this->parser; $loop = $this->loop; $deferred = new Deferred(function ($_, $reject) use(&$conn, &$timer, $name) { $conn->close(); $timer->cancel(); $reject(new \RuntimeException(sprintf("DNS query for %s cancelled", $name))); }); $timer = $this->loop->addTimer($this->timeout, function () use(&$conn, $name, $deferred) { $conn->close(); $deferred->reject(new TimeoutException(sprintf("DNS query for %s timed out", $name))); }); $conn = $this->factory->createSender(); $conn->on('message', function ($data) use($conn, $parser, $deferred, $timer) { $response = new Message(); $responseReady = $parser->parseChunk($data, $response); $conn->close(); $timer->cancel(); if (!$responseReady) { $deferred->reject(new BadServerException('Invalid response received')); return; } if ($response->header->isTruncated()) { $deferred->reject(new BadServerException('The server set the truncated bit although we issued a TCP request')); return; } $deferred->resolve($response); }); $conn->send($queryData, $nameserver); return $deferred->promise(); }
/** * @param $channel * @param string $message * @return DeferredPromise */ public function call($channel, $message) { $loop = LoopFactory::create(); $factory = new StompFactory($loop); $client = $factory->createClient(); $deferred = new Deferred(); $timer = $loop->addTimer(2, function () use($deferred, $client) { $client->disconnect(); $deferred->reject(new RpcTimeIsOutException()); }); $client->connect()->then(function (StompClient $client) use($message, $channel, $loop, $deferred, $timer) { $rpcReceiver = function (Frame $frame) use($deferred, $timer, $client) { $timer->cancel(); $client->disconnect(); try { $deferred->resolve($frame); } catch (\Exception $e) { $deferred->reject($e); } }; $client->sendToTemp($channel, $message, [], $rpcReceiver); }, function () use($deferred, $client) { $client->disconnect(); $deferred->reject(new \RuntimeException('Error start rpc connection')); }); $loop->run(); return $deferred->promise(); }
public function testHttpError() { $d = new Deferred(); $d->reject(new RuntimeException('error')); $this->browser->expects($this->once())->method('get')->with($this->equalTo('http://a/path?key=mykey&hash=myhash&action=status'), array())->will($this->returnValue($d->promise())); $this->expectPromiseReject($this->client->status()); }
/** * {@inheritdoc} */ public function sendAsyncRequest(RequestInterface $request) { $requestStream = $this->buildReactRequest($request); $deferred = new Deferred(); $requestStream->on('error', function (\Exception $error) use($deferred, $request) { $deferred->reject(new RequestException($error->getMessage(), $request, $error)); }); $requestStream->on('response', function (ReactResponse $response = null) use($deferred, $requestStream, $request) { $bodyStream = null; $response->on('data', function ($data) use(&$bodyStream) { if ($data instanceof StreamInterface) { $bodyStream = $data; } else { $bodyStream->write($data); } }); $response->on('end', function (\Exception $error = null) use($deferred, $request, $response, &$bodyStream) { $bodyStream->rewind(); $psr7Response = $this->messageFactory->createResponse($response->getCode(), $response->getReasonPhrase(), $response->getHeaders(), $bodyStream, $response->getVersion()); if (null !== $error) { $deferred->reject(new HttpException($error->getMessage(), $request, $psr7Response, $error)); } else { $deferred->resolve($psr7Response); } }); }); $requestStream->end((string) $request->getBody()); $promise = new ReactPromiseAdapter($deferred->promise()); $this->loop->run(); return $promise; }
public function connect($timeout = 5) { if ($this->connectDeferred) { return $this->connectDeferred->promise(); } $this->connectionStatus = 'connecting'; $promise = new Deferred(); $client = $this; $loop = $this->loop; $this->connectDeferred = $promise; $this->connectDeferred->then(function () use($client) { $client->setConnectionStatus('connected'); }); $timer = $this->loop->addTimer($timeout, function () use($client, $promise) { $promise->reject(new ConnectionException('Connection timeout')); $client->resetConnectDeferred(); $client->setConnectionStatus('not-connected'); }); $this->on('connect', function ($client) use($timer, $promise) { $timer->cancel(); $promise->resolve($client); }); $frame = $this->packageCreator->connect($this->options['vhost'], $this->options['login'], $this->options['passcode']); $this->output->sendFrame($frame); return $this->connectDeferred->promise(); }
/** * {@inheritdoc} */ public function sendAsyncRequest(RequestInterface $request) { $reactRequest = $this->buildReactRequest($request); $deferred = new Deferred(); $reactRequest->on('error', function (\Exception $error) use($deferred, $request) { $deferred->reject(new RequestException($error->getMessage(), $request, $error)); }); $reactRequest->on('response', function (ReactResponse $reactResponse = null) use($deferred, $reactRequest, $request) { $bodyStream = $this->streamFactory->createStream(); $reactResponse->on('data', function ($data) use(&$bodyStream) { $bodyStream->write((string) $data); }); $reactResponse->on('end', function (\Exception $error = null) use($deferred, $request, $reactResponse, &$bodyStream) { $response = $this->buildResponse($reactResponse, $bodyStream); if (null !== $error) { $deferred->reject(new HttpException($error->getMessage(), $request, $response, $error)); } else { $deferred->resolve($response); } }); }); $reactRequest->end((string) $request->getBody()); $promise = new Promise($deferred->promise()); $promise->setLoop($this->loop); return $promise; }
public function loadEtcResolvConf($filename) { if (!file_exists($filename)) { return When::reject(new \InvalidArgumentException("The filename for /etc/resolv.conf given does not exist: {$filename}")); } try { $deferred = new Deferred(); $fd = fopen($filename, 'r'); stream_set_blocking($fd, 0); $contents = ''; $stream = new Stream($fd, $this->loop); $stream->on('data', function ($data) use(&$contents) { $contents .= $data; }); $stream->on('end', function () use(&$contents, $deferred) { $deferred->resolve($contents); }); $stream->on('error', function ($error) use($deferred) { $deferred->reject($error); }); return $deferred->promise(); } catch (\Exception $e) { return When::reject($e); } }
/** @internal */ public function go(Process $process) { $this->deferred = $deferred = new Deferred(); $this->process = $process; $buffered = null; $process->stdout->on('data', function ($data) use(&$buffered) { if ($data !== '') { $buffered .= $data; } }); $process->on('exit', function ($code) use($deferred) { if ($code !== 0) { $deferred->reject($code); } else { $deferred->resolve(); } }); $that = $this; $this->promise = $deferred->promise()->then(function () use(&$buffered, $that) { if ($buffered === null) { $buffered = true; } else { $buffered = $that->parseValue(trim($buffered)); } return $buffered; }); }
/** * @returns \React\Promise\Promise */ public function show() { $deferred = new Deferred(); $this->io->out('hello'); $deferred->reject(false); return $deferred->promise(); }
/** * {@inheritdoc} */ public function tick() { if (!$this->process->isRunning() && $this->outputBuffer->isEmpty()) { usleep(1000); if ($this->outputBuffer->isEmpty()) { if ($this->process->isSuccessful()) { $this->deferred->resolve(new MessageEvent($this, $this->process->getOutput())); } else { $this->deferred->reject(new MessageEvent($this, $this->process->getOutput())); } return; } } if (!$this->outputBuffer->isEmpty()) { $this->deferred->notify(new MessageEvent($this, $this->outputBuffer->dequeue()[1])); } }
protected function createPromiseRejected($value = null, $delay = 0.01) { $deferred = new Deferred(); $this->loop->addTimer($delay, function () use($deferred, $value) { $deferred->reject($value); }); return $deferred->promise(); }
public function __invoke($url, array $subProtocols = [], array $headers = []) { try { $request = $this->generateRequest($url, $subProtocols, $headers); } catch (\Exception $e) { return new RejectedPromise($e); } $connector = 'wss' === substr($url, 0, 3) ? $this->_secureConnector : $this->_connector; return $connector->create($request->getHost(), $request->getPort())->then(function (DuplexStreamInterface $stream) use($request, $subProtocols) { $futureWsConn = new Deferred(); $buffer = ''; $headerParser = function ($data, DuplexStreamInterface $stream) use(&$headerParser, &$buffer, $futureWsConn, $request, $subProtocols) { $buffer .= $data; if (false == strpos($buffer, "\r\n\r\n")) { return; } $stream->removeListener('data', $headerParser); $response = Response::fromMessage($buffer); if (101 !== $response->getStatusCode()) { $futureWsConn->reject($response); $stream->close(); return; } $acceptCheck = base64_encode(pack('H*', sha1($request->getHeader('Sec-WebSocket-Key') . RFC6455::GUID))); if ((string) $response->getHeader('Sec-WebSocket-Accept') !== $acceptCheck) { $futureWsConn->reject(new \DomainException("Could not verify Accept Key during WebSocket handshake")); $stream->close(); return; } $acceptedProtocol = $response->getHeader('Sec-WebSocket-Protocol'); if ((count($subProtocols) > 0 || null !== $acceptedProtocol) && !in_array((string) $acceptedProtocol, $subProtocols)) { $futureWsConn->reject(new \DomainException('Server did not respond with an expected Sec-WebSocket-Protocol')); $stream->close(); return; } $futureWsConn->resolve(new WebSocket($stream, $response, $request)); $futureWsConn->promise()->then(function (WebSocket $conn) use($stream) { $stream->emit('data', [$conn->response->getBody(), $stream]); }); }; $stream->on('data', $headerParser); $stream->write($request); return $futureWsConn->promise(); }); }
/** * create stream client socket connected to given address * * @param string $address * @return PromiseInterface to return a \Sockets\Stream * @uses RawFactory::createFromString() * @uses RawSocket::setBlocking() to turn on non-blocking mode * @uses RawSocket::connect() to initiate async connection * @uses LoopInterface::addWriteStream() to wait for connection result once * @uses RawSocket::assertAlive() to check connection result */ public function createClient($address) { $that = $this; $factory = $this->rawFactory; return $this->resolve($address)->then(function ($address) use($factory, $that) { $deferred = new Deferred(); $socket = $factory->createFromString($address, $scheme); if ($socket->getType() !== SOCK_STREAM) { $socket->close(); throw new Exception('Not a stream address scheme'); } $socket->setBlocking(false); try { // socket is nonblocking, so connect should emit EINPROGRESS $socket->connect($address); // socket is already connected immediately? $deferred->resolve(new Connection($socket, $that->getSocketLoop())); } catch (Exception $exception) { if ($exception->getCode() === SOCKET_EINPROGRESS) { // connection in progress => wait for the socket to become writable $that->getSocketLoop()->addWriteStream($socket->getResource(), function ($resource, $loop) use($deferred, $socket) { // only poll for writable event once $loop->removeWriteStream($resource); try { // assert that socket error is 0 (no TCP RST received) $socket->assertAlive(); } catch (Exception $e) { // error returned => connected failed $socket->close(); $deferred->reject(new Exception('Error while establishing connection', $e->getCode(), $e)); return; } // no error => connection established $deferred->resolve(new Connection($socket, $loop)); }); } else { // re-throw any other socket error $socket->close(); $deferred->reject($exception); } } return $deferred->promise(); }); }
protected function registerCancelTimer() { $this->cancel_timer = $this->loop->addTimer(0.5, function () { if (false == $this->isAllNeedsProvided()) { $this->deferred->reject(); } echo "resolving by timer\n"; $this->deferred->resolve($this->response); }); }
/** * Installs a handler which rejects the given deferred on stream close/end * * All bytes read until the close/end event will be passed in to the rejection handler * It will also remove all listeners defined in $listenrs from the stream. * * @param Stream $stream * @param Deferred $deferred * @param string &$buffer * @param array &$listeners */ function _install_incomplete_read_handler(Stream $stream, Deferred $deferred, &$buffer, array &$listeners) { $handler = function (Stream $stream) use($deferred, &$buffer, &$listeners) { _remove_listeners($stream, $listeners); $deferred->reject($buffer); }; $listeners['close'] = $handler; $listeners['end'] = $handler; $stream->on('close', $handler); $stream->on('end', $handler); }
public function testJsonRejectingPromiseWillEmitErrorAndCloseEvent() { $deferred = new Deferred(); $stream = $this->parser->parseJsonStream($deferred->promise()); $this->assertTrue($stream->isReadable()); $exception = new RuntimeException(); $stream->on('error', $this->expectCallableOnceWith($exception)); $stream->on('close', $this->expectCallableOnce()); $deferred->reject($exception); $this->assertFalse($stream->isReadable()); }
public function soapCall($name, $args) { try { $request = $this->encoder->encode($name, $args); } catch (\Exception $e) { $deferred = new Deferred(); $deferred->reject($e); return $deferred->promise(); } return $this->browser->send($request)->then(array($this, 'handleResponse'), array($this, 'handleError')); }
public function create($host, $port) { $deferred = new Deferred(); $resource = @stream_socket_client($this->path, $errno, $errstr, 1.0); if (!$resource) { $deferred->reject(new RuntimeException('Unable to connect to unix domain socket path: ' . $errstr, $errno)); } else { $deferred->resolve(new Stream($resource, $this->loop)); } return $deferred->promise(); }
/** * @param Route $route * @return Promise|PromiseInterface * @throws \InvalidArgumentException */ public function request(Route $route) { $deferred = new Deferred(); $request = $this->prepareRequest($this->gitter->token, $route); $this->logRequest($request); /** @var Promise $answer */ $answer = $this->client->send($request); $answer->then(function (ResponseInterface $response) use($deferred) { $this->logResponse($response); $data = json_decode((string) $response->getBody(), true); if (json_last_error() === JSON_ERROR_NONE) { $deferred->resolve($data); } else { $deferred->reject(new \InvalidArgumentException(json_last_error_msg() . ': ' . $response->getBody())); } }, function (\Throwable $throwable) use($deferred) { $deferred->reject($throwable); }); return $deferred->promise(); }
/** * @expectedException \OutOfBoundsException */ public function testThrowsWhenDerefFailure() { $called = false; $deferred = new Deferred(); $f = new FutureValue($deferred->promise(), function () use(&$called) { $called = true; }); $deferred->reject(new \OutOfBoundsException()); $f->wait(); $this->assertFalse($called); }
/** * Create the API Request * * @param string $apiUrl * @param Deferred $deferred * @return Request */ public function getApiRequest($apiUrl, $deferred) { return new Request(['url' => $apiUrl, 'resolveCallback' => function ($data, $headers, $code) use($deferred) { $cfps = $this->handleResponse($data, $headers, $code); if ($cfps === false) { $deferred->reject(); } else { $deferred->resolve($cfps); } }, 'rejectCallback' => [$deferred, 'reject']]); }
/** * Execute the given $command string in this shell instance * * @param string $command * @return Promise Promise<string> resolves with the command output or rejects with a RuntimeException * @see self::setBounding() */ public function execute($command) { $deferred = new Deferred(); if ($this->ending) { $deferred->reject(new RuntimeException('Shell is ending already')); } else { $this->pending[] = $deferred; $this->sendCommand($command); } return $deferred->promise(); }
public function probe(Stream $stream, $compression = false, $encryption = false) { $magic = Protocol::MAGIC; if ($compression) { $magic |= Protocol::FEATURE_COMPRESSION; } if ($encryption) { $magic |= Protocol::FEATURE_ENCRYPTION; } $binary = $this->binary; $stream->write($binary->writeUInt32($magic)); // list of supported protocol types (in order of preference) $types = array(Protocol::TYPE_DATASTREAM, Protocol::TYPE_LEGACY); // last item should get an END marker $last = array_pop($types); $types[] = $last | Protocol::TYPELIST_END; foreach ($types as $type) { $stream->write($binary->writeUInt32($type)); } $deferred = new Deferred(function ($resolve, $reject) use($stream) { $reject(new \RuntimeException('Cancelled')); }); $buffer = ''; $fn = function ($data) use(&$buffer, &$fn, $stream, $deferred, $binary) { $buffer .= $data; if (isset($buffer[4])) { $stream->removeListener('data', $fn); $deferred->reject(new \UnexpectedValueException('Expected 4 bytes response, received more data, is this a quassel core?', Prober::ERROR_PROTOCOL)); return; } if (isset($buffer[3])) { $stream->removeListener('data', $fn); $deferred->resolve($binary->readUInt32($buffer)); } }; $stream->on('data', $fn); $stream->on('close', function () use($deferred) { $deferred->reject(new \RuntimeException('Stream closed, does this (old?) server support probing?', Prober::ERROR_CLOSED)); }); return $deferred->promise(); }
/** * Make a directory as described in the task description * @param Deferred $deferred * @param TaskInterface $task * @return bool */ protected function processDeferred(Deferred $deferred, TaskInterface $task) { yield; /** @var Description $description */ $description = $task->getDescription(); $deferred->notify(new Notification("Moving '{$description->getFrom()}' to '{$description->getTo()}'", Notification::PRIORITY_NORMAL)); if ($this->getFileSystem()->move($description->getFrom(), $description->getTo())) { $deferred->resolve("Moved '{$description->getFrom()}' to '{$description->getTo()}'"); return; } $deferred->reject("Could not move '{$description->getFrom()}' to '{$description->getTo()}'"); }
/** * Check a file doesn't exist * @param Deferred $deferred * @param TaskInterface $task * @return bool */ protected function processDeferred(Deferred $deferred, TaskInterface $task) { yield; /** @var Description $description */ $description = $task->getDescription(); $deferred->notify(new Notification("Checking that file '{$description->getName()}' does not exist", Notification::PRIORITY_NORMAL)); if (!$this->getFileSystem()->isFile($description->getName())) { $deferred->resolve("File '{$description->getName()}' does not exist"); return; } $deferred->reject("File '{$description->getName()}' exists"); }
/** * Call curl_multi_add_handle(). * @param resource $ch * @param Deferred $deferred */ private function addImmediate($ch, Deferred $deferred = null) { $errno = curl_multi_add_handle($this->mh, $ch); if ($errno !== CURLM_OK) { // @codeCoverageIgnoreStart $msg = curl_multi_strerror($errno) . ": {$ch}"; $deferred && $deferred->reject(new \RuntimeException($msg)); return; // @codeCoverageIgnoreEnd } $this->added[(string) $ch] = $ch; $deferred && ($this->deferreds[(string) $ch] = $deferred); }