Skip to content
Open
Show file tree
Hide file tree
Changes from 24 commits
Commits
Show all changes
38 commits
Select commit Hold shift + click to select a range
a2e0a0a
Extract HTTP-protocol specific code from Graph class
thekid Oct 1, 2017
3d687cf
Add factory to instantiate protocols
thekid Oct 1, 2017
59e7e88
Initial implementation of Bolt protocol
thekid Oct 1, 2017
c984437
Graph now accepts protocols
thekid Oct 1, 2017
c838a03
Rewrite newFixture() to pass a testing protocol
thekid Oct 1, 2017
1fd7b65
Restore PHPH 5.6 compatibility
thekid Oct 1, 2017
8aeaaa8
Remove debugging code
thekid Oct 1, 2017
df230c8
Add specialized exception for authentication failure
thekid Oct 1, 2017
da135c1
Add UnexpectedResponse exception class, base for all others
thekid Oct 1, 2017
02caa05
Extract record fetching into helper method
thekid Oct 1, 2017
a7fc0ec
Extract serialization from Bolt protocol class
thekid Oct 1, 2017
58956a9
Add serialization tests
thekid Oct 1, 2017
19c1eb8
Refrain from using `list()` as method name, causes syntax error in PH…
thekid Oct 1, 2017
a923aae
Fix int64 signedness
thekid Oct 1, 2017
d948734
QA: Simplify code inside is_int() branch in serialize()
thekid Oct 1, 2017
8fe26a3
Implement lists
thekid Oct 1, 2017
c458074
Implement floats
thekid Oct 1, 2017
f9445d3
Special case handling for empty strings
thekid Oct 1, 2017
675c2f8
Implement support for Path and UnboundRelationship structs
thekid Oct 1, 2017
b1526f9
Add support for Relationship struct
thekid Oct 1, 2017
5944cb1
Refactor struct fields -> members
thekid Oct 1, 2017
f8841c5
Fix byte order for signed shorts
thekid Oct 1, 2017
1e9d454
Fix byte order for signed shorts and doubles
thekid Oct 1, 2017
e56388c
Rename unserialize() parameter value -> input
thekid Oct 1, 2017
6842d52
Replace complicated int64 serialization with "q" pack specifier and e…
thekid Oct 2, 2017
53e0fbb
Greatly improve map tests performance (1.033 -> 0.772 seconds)
thekid Oct 2, 2017
ee2b033
Add tests for Protocol class
thekid Oct 2, 2017
16c112b
Implement message chunking
thekid Oct 2, 2017
0178734
Default HTTP port to 7474, and make passing "/db/data" optional
thekid Oct 2, 2017
c45abcc
Fix `Undefined variable: records` for empty results
thekid Oct 2, 2017
c96bac0
Refactor Bolt protocol to return untyped data
thekid Oct 3, 2017
e936774
Fix int16 endianness
thekid Oct 3, 2017
1d77aa8
Fix map-related tests
thekid Oct 3, 2017
547f766
Remove default port and path from connection DSN
thekid Oct 3, 2017
8ff66a3
Add Protocol::close()
thekid Oct 3, 2017
a3fd02e
Fix deserializing authentication errors
thekid Oct 3, 2017
a1c0d80
Ensure close() is called on destruction
thekid Oct 3, 2017
860c10e
Replace Socket::readBinary() with a local helper to read exact amount…
thekid Oct 3, 2017
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
125 changes: 125 additions & 0 deletions src/main/php/com/neo4j/BoltProtocol.class.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
<?php namespace com\neo4j;

use peer\Socket;
use peer\URL;

class BoltProtocol extends Protocol {
private $sock, $init, $serialization;

const PREAMBLE = "\x60\x60\xb0\x17";
const INIT = 0x01;
const ACK_FAILURE = 0x0e;
const RESET = 0x0f;
const RUN = 0x10;
const PULL_ALL = 0x3f;
const NODE = 0x4e;
const PATH = 0x50;
const RELATIONSHIP = 0x52;
const SUCCESS = 0x70;
const RECORD = 0x71;
const UNBOUNDRELATIONSHIP = 0x72;
const FAILURE = 0x7f;
const IGNORE = 0x7e;

/**
* Creates a new Neo4J graph connection
*
* @param peer.URL $endpoint
*/
public function __construct(URL $endpoint) {
$this->sock= new Socket($endpoint->getHost(), $endpoint->getPort(7687));
if ($user= $endpoint->getUser()) {
$this->init= ['scheme' => 'basic', 'principal' => $user, 'credentials' => $endpoint->getPassword()];
} else {
$this->init= ['scheme' => 'none'];
}
$this->serialization= new Serialization();
}

/** Sends a message */
private function send($signature, ... $args) {
$chunk= pack('cc', 0xb0 + sizeof($args), $signature);
foreach ($args as $arg) {
$chunk.= $this->serialization->serialize($arg);
}

$send= pack('n', strlen($chunk)).$chunk."\x00\x00";
$this->sock->write($send);
}

/** Receives one answer at a time */
private function receive() {
$chunk= '';
while ("\x00\x00" !== ($length= $this->sock->readBinary(2))) {
$chunk.= $this->sock->readBinary(unpack('n', $length)[1]);
}

return $this->serialization->unserialize($chunk);
}

/**
* Initialize communication
*
* @see https://boltprotocol.org/v1/#handshake
* @return void
* @throws com.neo4j.UnexpectedResponse
*/
private function init() {
$this->sock->write(self::PREAMBLE.pack('NNNN', 1, 0, 0, 0));
$protocol= unpack('N', $this->sock->readBinary(4));
if (0 === $protocol[1]) {
throw new UnexpectedResponse(['Protocol handshake failed, server does not support protocol version']);
}

$this->send(self::INIT, nameof($this), $this->init);
$res= $this->receive();
if (self::SUCCESS !== $res->signature) {
throw new CannotAuthenticate([$res->members['metadata']]);
}
}

/** @return [:var][] */
private function records() {
do {
$res= $this->receive();
if (self::RECORD === $res->signature) {
$records[]= ['row' => $res->members['fields'], 'meta' => null]; // FIXME: Fill meta

@thekid thekid Oct 1, 2017

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Either this should be transformed to the layout the REST API uses or the REST API should transform its data to typed structs.

$ xp -w '$g= new com\neo4j\Graph("http://...@localhost"); return $g->execute(["match (e:Employee{id:1549}) return e"])'
[[
  columns => ["e"]
  data => [[
    row => [[
      mail => "friebe@example.com"
      name => "Timm Friebe"
      modified => 1506689575857
      id => 1549
      user => "friebe"
      since => "2017-08-03"
    ]]
    meta => [[
      id => 27262
      type => "node"
      deleted => false
    ]]
  ]]
]]
$ xp -w '$g= new com\neo4j\Graph("bolt://...@localhost"); return $g->execute(["match (e:Employee{id:1549}) return e"])'
[[
  columns => ["e"]
  data => [[
    row => [com.neo4j.Struct<Node>@[
      identity => 27262
      labels => ["Employee"]
      properties => [
        mail => "friebe@example.com"
        name => "Timm Friebe"
        modified => 1506689575857
        id => 1549
        user => "friebe"
        since => "2017-08-03"
      ]
    ]]
    meta => null
  ]]
]]

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The REST API should transform its data to typed structs.

This should be kept for another pull request

}
} while (self::RECORD === $res->signature);
return $records;
}

/**
* Commits multiple statements using `transaction/commit` endpoint.
*
* @param [:var][] $payload
* @return [:var] Results
* @throws com.neo4j.UnexpectedResponse
*/
public function commit($payload) {
if (!$this->sock->isConnected()) {
$this->sock->connect();
$this->init();
}

$r= ['results' => [], 'errors' => []];
foreach ($payload['statements'] as $s) {
$this->send(self::RUN, $s['statement'], isset($s['parameters']) ? $s['parameters'] : []);

$res= $this->receive();
if (self::FAILURE === $res->signature) {
$r['errors'][]= $res->members['metadata'];
$this->send(self::ACK_FAILURE);
$this->receive();
} else if (self::IGNORE === $res->signature) {
$r['errors'][]= ['Ignored'];
$this->send(self::RESET);
$this->receive();
} else {
$this->send(self::PULL_ALL);
$r['results'][]= ['columns' => $res->members['metadata']['fields'], 'data' => $this->records()];
}
}
return $r;
}
}
8 changes: 8 additions & 0 deletions src/main/php/com/neo4j/CannotAuthenticate.class.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<?php namespace com\neo4j;

/**
* Indicates auhentication with the server failed
*/
class CannotAuthenticate extends UnexpectedResponse {

}
39 changes: 4 additions & 35 deletions src/main/php/com/neo4j/Graph.class.php
Original file line number Diff line number Diff line change
@@ -1,12 +1,5 @@
<?php namespace com\neo4j;

use peer\http\HttpConnection;
use peer\http\HttpRequest;
use peer\http\RequestData;
use text\json\Json;
use text\json\Format;
use text\json\StreamInput;

/**
* Neo4J interface using its HTTP API
*
Expand All @@ -15,40 +8,16 @@
* @test xp://com.neo4j.unittest.GraphTest
*/
class Graph implements \lang\Value {
private $conn, $cypher, $json, $base;
private $protocol, $cypher;

/**
* Creates a new Neo4J graph connection
*
* @param string|peer.URL|peer.http.HttpConnection $endpoint
* @param string|peer.URL|com.neo4j.Protocol $endpoint
*/
public function __construct($endpoint) {
$this->conn= $endpoint instanceof HttpConnection ? $endpoint : new HttpConnection($endpoint);
$this->protocol= $endpoint instanceof Protocol ? $endpoint : Protocol::forEndpoint($endpoint);
$this->cypher= new Cypher();
$this->json= Format::dense();
$this->base= rtrim($this->conn->getURL()->getPath(), '/');
}

/**
* Commits multiple statements using `transaction/commit` endpoint.
*
* @param [:var][] $payload
* @return [:var] Results
*/
protected function commit($payload) {
$req= $this->conn->create(new HttpRequest());
$req->setMethod('POST');
$req->setTarget($this->base.'/transaction/commit');
$req->setHeader('X-Stream', 'true');
$req->setHeader('Content-Type', 'application/json');
$req->setParameters(new RequestData(Json::of($payload, $this->json)));

$res= $this->conn->send($req);
if (200 !== $res->statusCode()) {
throw new QueryFailed(['Unexpected HTTP response status '.$res->statusCode()]);
}

return Json::read(new StreamInput($res->in()));
}

/**
Expand Down Expand Up @@ -103,7 +72,7 @@ public function execute($statements) {
$list[]= is_array($statement) ? $statement : ['statement' => $statement];
}

$response= $this->commit(['statements' => $list]);
$response= $this->protocol->commit(['statements' => $list]);
if (empty($response['errors'])) {
return $response['results'];
} else {
Expand Down
55 changes: 55 additions & 0 deletions src/main/php/com/neo4j/HttpProtocol.class.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
<?php namespace com\neo4j;

use peer\URL;
use peer\http\HttpConnection;
use peer\http\HttpRequest;
use peer\http\RequestData;
use text\json\Json;
use text\json\Format;
use text\json\StreamInput;
use io\IOException;

class HttpProtocol extends Protocol {
private $conn, $json, $base;

/**
* Creates a new Neo4J graph connection
*
* @param peer.URL $endpoint
*/
public function __construct(URL $endpoint) {
$this->conn= new HttpConnection($endpoint);
$this->json= Format::dense();
$this->base= rtrim($this->conn->getURL()->getPath(), '/');
}

/**
* Commits multiple statements using `transaction/commit` endpoint.
*
* @param [:var][] $payload
* @return [:var] Results
* @throws com.neo4j.UnexpectedResponse
*/
public function commit($payload) {
$req= $this->conn->create(new HttpRequest());
$req->setMethod('POST');
$req->setTarget($this->base.'/transaction/commit');
$req->setHeader('X-Stream', 'true');
$req->setHeader('Content-Type', 'application/json');
$req->setParameters(new RequestData(Json::of($payload, $this->json)));

try {
$res= $this->conn->send($req);
} catch (IOException $e) {
throw new QueryFailed(['I/O error'], $e);
}

if (200 === $res->statusCode()) {
return Json::read(new StreamInput($res->in()));
} else if (401 === $res->statusCode()) {
throw new CannotAuthenticate([$res->readData()]);

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should check for JSON and then deserialize the result into error messages instead of simply using the HTTP body as-is

} else {
throw new UnexpectedResponse(['Unexpected HTTP response status '.$res->statusCode(), $res->readData()]);
}
}
}
25 changes: 25 additions & 0 deletions src/main/php/com/neo4j/Protocol.class.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php namespace com\neo4j;

use lang\IllegalArgumentException;
use peer\URL;

abstract class Protocol {

/**
* Factory method
*
* @param peer.URL|string $endpoint
* @return self
*/
public static function forEndpoint($endpoint) {
$url= $endpoint instanceof URL ? $endpoint : new URL($endpoint);
switch ($url->getScheme()) {
case 'http': case 'https': return new HttpProtocol($url);
case 'bolt': return new BoltProtocol($url);
default: throw new IllegalArgumentException('Unsupported protocol "'.$url->getScheme().'"');
}
}

/** Commits a payload and returns records */
public abstract function commit($payload);
}
13 changes: 4 additions & 9 deletions src/main/php/com/neo4j/QueryFailed.class.php
Original file line number Diff line number Diff line change
@@ -1,13 +1,8 @@
<?php namespace com\neo4j;

use lang\XPException;
use lang\Throwable;
use util\Objects;
/**
* Indicates a Cypher query failed on the server
*/
class QueryFailed extends UnexpectedResponse {

class QueryFailed extends XPException {

/** Creates a new instance */
public function __construct(array $errors, Throwable $cause= null) {
parent::__construct('Query failed '.Objects::stringOf($errors), $cause);
}
}
Loading