Repository navigation
Create common traits, types and mocks for the local node - #20
Conversation
022ab64 to
2171334
Compare
9cfabf8 to
c8fd2cb
Compare
This should allow the service to be accessible from the outside.
c8fd2cb to
05944f4
Compare
| members = [ | ||
| "thegraph", | ||
| "thegraph-standalone-node", | ||
| "thegraph-local-node", |
There was a problem hiding this comment.
Not sure how I feel about "thegraph" being one word, though I understand the rationale for it. Maybe we should come up with a name for the Rust implementation of our client. More food for thought, nothing needs to change in this PR.
There was a problem hiding this comment.
I feel similar, but I wanted to be consistent with the thegraph library crate and the thegraph module. I'd rather not have to type and see the_graph::common::... everywhere but we can do that too. Let's discuss some time.
| #[derive(Debug)] | ||
| pub enum DataSourceProviderEvent { | ||
| /// A data source was added to the provider. | ||
| DataSourceAdded(&'static str), |
There was a problem hiding this comment.
For my own learning... what is the static lifetime annotation accomplishing in these event enums?
There was a problem hiding this comment.
Apart from a few cases where lifetime elision rules kick in (see https://doc.rust-lang.org/1.9.0/book/lifetimes.html#lifetime-elision), references need to be annotated with a lifetime. 'static means the reference lives for as long as the program runs. Essentially this means you can only put literal strings in that are known at compile time.
In this case, it's totally random. We'll replace the string with data source information that makes sense.
There was a problem hiding this comment.
Ah, makes sense. I missed this relevant section when I was looking earlier: https://doc.rust-lang.org/book/first-edition/lifetimes.html#static
| let sink = self.event_sink.clone().unwrap(); | ||
| sink.clone() | ||
| .send(DataSourceProviderEvent::DataSourceAdded( | ||
| "First data source", |
There was a problem hiding this comment.
Why are we passing a string with these events. Is this meant to identify the data source?
There was a problem hiding this comment.
It's just a placeholder for the moment. We'll add data source information soon.
| fn generate_mock_schema_events(&mut self) { | ||
| let sink = self.schema_event_sink.clone().unwrap(); | ||
| sink.clone() | ||
| .send(SchemaEvent::SchemaAdded("First schema")) |
There was a problem hiding this comment.
Same question. Is the string here just for testing/ debugging purposes?
| /// Common trait for data source providers. | ||
| pub trait DataSourceProvider { | ||
| /// Receiver from which others can read events emitted by the data source provider. | ||
| /// Can only be called once. Any consecutive call will result in a StreamError. |
There was a problem hiding this comment.
Will we never listen on DataSourceProvider from more than one place?
There was a problem hiding this comment.
We already are in thegraph-local-node.
This part was a little tricky. The problem is that you can only have one channel Receiver for any channel (unless you add dependencies that provide multi-reader/multi-writer channels). Due to ownership rules you can't store this Receiver in the DataSourceProvider. Instead, you have to either
- pass the corresponding
Senderin to the constructor from the outside (which would also create theReceiver), or - do it like I'm doing here—only allow the channel to be created once, or
- create a new
(sender, receiver)channel with every call and maintain a list of all senders inside . theDataSourceProvider.
I've been pondering them all. I don't like the first option because that would make it a constructor (and hence implementation) concern and it wouldn't be part of the trait. I'd be ok with the third option but it's a little annoying to have to manage many senders. I want to keep things simple.
The good news is: A Receiver (or rather, a Receiver that implements Stream) can clone and forward messages to other streams on the side, which is what we're doing in thegraph-local-node/src/main.rs. See https://docs.rs/futures/0.1.21/futures/stream/trait.Stream.html#method.forward also.
There was a problem hiding this comment.
Makes sense. I like #2, until we have a reason to make it more complicated, for instance sending different messages through different channels.
| } | ||
|
|
||
| /// Common trait for query runners that run queries against a [Store](../store/trait.Store.html). | ||
| pub trait QueryRunner<T> { |
There was a problem hiding this comment.
Why not require the QueryRunner trait to implement the Sender trait, as described here: https://doc.rust-lang.org/book/second-edition/ch19-03-advanced-traits.html#using-supertraits-to-require-one-traits-functionality-within-another-trait ?
There was a problem hiding this comment.
I'm not sure what you mean.
In order to obtain a response for an incoming request (e.g. HTTP), you need to turn that request into a response future. So the server can't just listen on a QueryRunner channel and handle any kind of result at arbitrary points in time—there needs to be a dedicated future for every request. This is why we're using oneshot::channel() for query results.
There was a problem hiding this comment.
Ah I see, I hadn't thought about the fact that it would be a separate future for each request, but that makes sense.
| fn query_stream(&mut self) -> Result<Receiver<Query<T>>, StreamError>; | ||
|
|
||
| /// Creates a new Tokio task that, when spawned, brings up the GraphQL server. | ||
| fn serve(&mut self) -> Result<Box<Future<Item = (), Error = ()> + Send>, GraphQLServerError>; |
There was a problem hiding this comment.
Can you explain the Result<Box<Future<Item = (), Error = ()> + Send? I'm familiar with Box, Result and union types, as well as the unit type, but this still looks strange to me.
There was a problem hiding this comment.
I know!
Every future has a result item type and an error type, denoted by the associated types Item and Error. Tokio has a notion of (potentially long-running) tasks. These are represented as futures that have empty tuples for Item and Error, hence the Future<Item = (), Error = ()>.
In this case we need the Send in order to pass that future on to the Tokio runtime, which I believe executes tasks in a thread pool; you can't send anything to a thread unless it satisfies the Send trait.
Instances of this future may have different sizes at runtime, so the compiler isn't sure about the size, that's why you put it in a Box (a pointer, which has a known, architecture-dependent size).
There was a problem hiding this comment.
I see, so these long living futures with the type <Future<Item = (), Error = ()> + Send act like an abstraction around simply using thread::spawn, but maybe are more performant since behind the scenes they are using a pooled threads and don't incur the cost of spinning up/ destroying threads. Sort of like how Goroutines are "thread-like" but don't map directly to threads either.
There was a problem hiding this comment.
Not quite. These futures are "tasks" and they are the ones being spawned. ;)
There was a problem hiding this comment.
Oh, yeah, but not with thread::spawn.
|
|
||
| /// Errors that can occur when obtaining an event stream from a system component. | ||
| #[derive(Debug)] | ||
| pub enum StreamError { |
There was a problem hiding this comment.
This isn't already taken care of by the futures library?
There was a problem hiding this comment.
Nope, this is a special error for our FnOnce-style approach to obtaining an event stream from components like DataSourceProvider.
There was a problem hiding this comment.
I see. The name StreamError is a bit misleading to me, but I understand what it means now.
| /// A mock [SchemaProvider](../common/schema/trait.SchemaProvider.html). | ||
| pub struct MockSchemaProvider { | ||
| schema_event_sink: Sender<SchemaEvent>, | ||
| event_sink: Arc<Mutex<Option<Sender<SchemaProviderEvent>>>>, |
There was a problem hiding this comment.
For my own learning... could you explain the rationale behind the Arc<Mutex<Option<...>>>?
There was a problem hiding this comment.
Sure :)
So we may or may not have created an outgoing event stream at the time the MockSchemaProvider starts processing incoming events. So we need an Option<Sender<...>> to handle Some vs None.
Processing incoming events takes place in a thread or Tokio task (executed on a thread pool). This means we need to protect access to the event_sink because both the processing thread/task and the event_stream() function may write/read to/from it. That protection is realized through a Mutex.
Now, the problem (as far as I understand it) is: you can't move the Mutex to another thread because you'll also need it in event_stream(). You can't clone it or anything either, so somehow you need to share the Mutex between two (or more) threads. That's what Arc does.
It's a pretty common scenario that you want something to be shared across threads. Arc gives you an atomic reference counter so the compiler knows when to drop the thing inside the Arc—every drop of the Arc itself reduces the reference counter, any clone of the Arc increases the reference counter, when it drops to zero, the thing inside the Arc is dropped.
tl;dr: Arc<Mutex<...>> is super common way to share data between threads and synchronize access to this data.
There was a problem hiding this comment.
Fantastic explanation, thank you :)
|
|
||
| impl Store for MockStore { | ||
| fn get(&self, _key: StoreKey) -> Result<Entity, ()> { | ||
| unimplemented!(); |
| register_panic_handler(); | ||
|
|
||
| // Start the node | ||
| tokio::run(future::lazy(|| { |
| tokio::spawn({ | ||
| schema_stream | ||
| .forward(schema_sink.sink_map_err(|e| { | ||
| panic!("Failed to send schema event to schema provider: {:?}", e); |
There was a problem hiding this comment.
I like that we're handling these sorts of errors at the top level, where we're doing our wiring. Looks clean!
There was a problem hiding this comment.
Yeah, ever since we wrote our first Go server, I've been liking the idea of creating all system components at the top level and then wiring them up there, too, so the system architecture is obvious at a glance.
| let mut graphql_server = mock::MockGraphQLServer::new(); | ||
|
|
||
| // Forward schema events from the data source provider to the schema provider | ||
| let schema_stream = data_source_provider.schema_event_stream().unwrap(); |
There was a problem hiding this comment.
Interesting... can only be called once, but then the stream can still have multiple consumers?
There was a problem hiding this comment.
Yes, forward is our friend. There are multi-reader/multi-writer channel crates out there but I want to stick to the bare metal as much as possible (apart from futures and tokio).
Zerim
left a comment
There was a problem hiding this comment.
This is looking great! I have a lot of questions, mostly due to my unfamiliarity with Rust, but I ran the code locally and everything checks out. I like how clean all our module code is, and how the messiness of wiring and error handling is all consolidated to our top level main. Also like how reactive the design is shaping up be. 👍
| fn main() { | ||
| // Set up Sentry, with release tracking and panic handling; | ||
| // fall back to an empty URL, which will result in no errors being reported | ||
| let sentry_url = env::var_os("THEGRAPH_SENTRY_URL") |
There was a problem hiding this comment.
Should sentry be part of the local node? If the idea is that people will be running this locally maybe the code for logging should be somewhere more free service specific?
There was a problem hiding this comment.
Unless they set the environment variable that defines the sentry URL, sentry will silently log nothing.
This allows us to catch bugs/crashes in the deployed local node, which is nice and will be relevant if we decide to host local nodes for projects for Alpha.
This resolves #1 and resolves #11. Once deployed, it will also resolve #15 (the subdomain is already set up, it's just waiting for a service to be launched on the standalone node pod on port 8000).
This PR includes the following:
thegraph/src/common. These areQuery,QueryResult, events etc. We will build these out more as we develop the functionality they are involved in.thegraph/src/mock.thegraph-local-nodethat wires up all mock components to provide some early validation of the architecture.Missing from this PR are traits and mock implementations for the following components: