← 输入框|github.com|刷新
Skip to content

Parse GraphQL queries with serde_json and graphql_parser - #30

Merged
Jannis merged 19 commits into
masterfrom
jannis/parse-incoming-queries
May 10, 2018
Merged

Jannis merged 19 commits into
masterfrom
jannis/parse-incoming-queries

Conversation

@Jannis

@Jannis Jannis commented May 7, 2018 •

Copy link
Copy Markdown
Contributor

This PR depends on #29.

This resolves #23 by adding a more complete GraphQL server based on Hyper in a separate thegraph-hyper crate. This server asynchronously reads the request body, tries to parse it as JSON (using serde_json, then parses it into a GraphQL query document using graphql_parser and eventually feeds it into the system using its outgoing query stream.

A simple way to test this is to launch

cargo run -p thegraph-local-node

and (in another terminal) submit a query to the server:

curl \
    -X POST \
    -H "Content-Type: application/json" \
    --data '{ "query": "{ allUsers(first: 5) { name } allArticles(first: 10) { title  }" }' \
    http://localhost:8000/

In the server logs you should now see the following, demonstrating that the query is parsed and passed on to the query runner (from which this log message is printed):

May 07 19:44:59.256 INFO Running query, query: Query { document: Document { definitions: [Operation(SelectionSet(SelectionSet { span: (Pos(1:1), Pos(1:64)), items: [Field(Field { position: Pos(1:3), alias: None, name: "allUsers", arguments: [("first", Int(Number(5)))], directives: [], selection_set: SelectionSet { span: (Pos(1:22), Pos(1:29)), items: [Field(Field { position: Pos(1:24), alias: None, name: "name", arguments: [], directives: [], selection_set: SelectionSet { span: (Pos(1:24), Pos(1:24)), items: [] } })] } }), Field(Field { position: Pos(1:31), alias: None, name: "allArticles", arguments: [("first", Int(Number(10)))], directives: [], selection_set: SelectionSet { span: (Pos(1:54), Pos(1:62)), items: [Field(Field { position: Pos(1:56), alias: None, name: "title", arguments: [], directives: [], selection_set: SelectionSet { span: (Pos(1:56), Pos(1:56)), items: [] } })] } })] }))] }, result_sender: Sender { inner: Inner { complete: AtomicBool(false), data: Lock { locked: AtomicBool(false), data: UnsafeCell }, rx_task: Lock { locked: AtomicBool(false), data: UnsafeCell }, tx_task: Lock { locked: AtomicBool(false), data: UnsafeCell } } } }

This PR comes with the first

  • unit tests for request/response futures,
  • unit tests for the Hyper service for serving GraphQL requests, and
  • integration tests for the HyperGraphQLServer.

@Jannis Jannis added the enhancement New feature or request label May 7, 2018
@Jannis Jannis added this to the Free Service milestone May 7, 2018
@Jannis Jannis self-assigned this May 7, 2018
@Jannis
Jannis requested a review from a team May 7, 2018 17:54
@Jannis
Jannis force-pushed the jannis/parse-incoming-queries branch 2 times, most recently from dab5c59 to 787abf0 Compare May 8, 2018 14:34
Jannis Pohlmann added 13 commits May 9, 2018 13:48
We'll need these for parsing incoming GraphQL queries.
Also drop the request member for now. We should probably extract
everything we need from the client into a dedicated data structure
and pass that around as part of the query.
We will use this to report JSON parsing errors.
This server parses incoming JSON/GraphQL requests into queries that it then
passes on to the query runner.
It makes sense to treat errors that occur when starting up a GraphQL
server from those that occur when processing requests. To keep the
error type flexible for different server implementations, we're
using an associated type here.
This makes the GraphQLServer interface fully agnostic with regards
to how queries and query results are represented, parsed or served.
@Jannis
Jannis force-pushed the jannis/parse-incoming-queries branch from fb00f9e to 234733f Compare May 9, 2018 11:48
Jannis Pohlmann added 5 commits May 9, 2018 13:49
This makes running and testing the server a lot easier.
This is required for being able to obtain runtime handles to pass
to components so they can spawn tasks against the runtime.
These tests verify that making HTTP requests with valid/invalid
queries yield the correct HTTP responses. We'll build this out further
in the future.
This is required for the integration tests of thegraph-hyper. These
tests each launch an HTTP server and would fail trying to bind the
same address/port while running concurrently.

The tests run super fast right now, so this shouldn't be a problem
for a while.
@Jannis
Jannis force-pushed the jannis/parse-incoming-queries branch from 234733f to 618f969 Compare May 9, 2018 11:50
@Jannis Jannis changed the title [WIP] Parse incoming GraphQL queries using serde_json and graphql_parser Parse incoming GraphQL queries using serde_json and graphql_parser May 9, 2018
@Jannis
Jannis requested review from fordN and removed request for a team May 9, 2018 12:04
@Jannis
Jannis requested review from Zerim, adklempner and yanivtal May 9, 2018 12:04
@Jannis Jannis changed the title Parse incoming GraphQL queries using serde_json and graphql_parser Parse GraphQL queries with serde_json and graphql_parser May 9, 2018

@fordN fordN left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Looking really good! I asked a few questions that came to mind when reading through it, mostly for my own understanding.


impl GraphQLRequest {
/// Creates a new GraphQLRequest future based on an HTTP request and a result sender.
pub fn new(body: Chunk) -> Self {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

self here references an instance of the GraphQLRequest struct? didn't know you could use it like this.


// Ensure the JSON data is an object
let obj = json.as_object().ok_or_else(|| {
GraphQLServerError::ClientError(String::from("Request data is not an object"))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

does this need to be a String here? as opposed to a string slice

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I mainly did this to avoid dealing with lifetimes. Can take another look though.


// Create a one-shot channel to allow another part of the system
// to notify the service when the query has completed
let (sender, receiver) = oneshot::channel();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

oneshots seem to be an elegant way to communicate future traits

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Indeed :)

fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
let response = match self.result {
Ok(ref result) => {
let data = format!("{:?}", result);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

best way to format result?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Absolutely not. GraphQL mandates that the response be formatted in JSON, see http://facebook.github.io/graphql/October2016/#sec-Response. I'm already working on that.


impl fmt::Display for HyperGraphQLServeError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "OrphanError: No component set up to handle the queries")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

unclear about how this error message here is directly related to fmt::Display

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

i see now, this is just to format the error message when being displayed

match (req.method(), req.uri().path()) {
// POST / receives GraphQL queries
(&Method::POST, "/") => self.handle_graphql_query(req),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

more methods to come?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Definitely!

pub fn new(logger: &slog::Logger, runtime: Handle, store: S) -> Self {
let (sink, stream) = channel(100);
let runner = MockQueryRunner {
logger: logger.new(o!("component" => "MockQueryRunner")),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

what does the o! macro do?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

@Jannis
Jannis merged commit d4a8c64 into master May 10, 2018
@Jannis
Jannis deleted the jannis/parse-incoming-queries branch May 10, 2018 07:13
nabaruns pushed a commit to nabaruns/graph-node that referenced this pull request Jul 29, 2022
…assembly-script

Update -cli/ts for the new AssemblyScript version
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Parse incoming GraphQL queries

2 participants