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

Create common traits, types and mocks for the local node - #20

Merged
Jannis merged 8 commits into
masterfrom
jannis/local-node-skeleton
May 9, 2018
Merged

Jannis merged 8 commits into
masterfrom
jannis/local-node-skeleton

Conversation

@Jannis

@Jannis Jannis commented May 4, 2018

Copy link
Copy Markdown
Contributor

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:

  1. Common traits and types for most system components of the local node, in thegraph/src/common. These are
    • Data Source Provider
    • Schema Provider
    • Store
    • Query Runner
    • GraphQL Server
  2. A bunch of opaque types for things like Query, QueryResult, events etc. We will build these out more as we develop the functionality they are involved in.
  3. Mock implementations of the above system components in thegraph/src/mock.
  4. A basic thegraph-local-node that 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:

  • Subscription Manager
  • Data Source
  • Data Source Runtime

@Jannis Jannis added the enhancement New feature or request label May 4, 2018
@Jannis Jannis added this to the Free Service milestone May 4, 2018
@Jannis Jannis self-assigned this May 4, 2018
@Jannis
Jannis requested review from Zerim, adklempner, fordN and yanivtal May 4, 2018 13:26
@Jannis
Jannis force-pushed the jannis/local-node-skeleton branch from 022ab64 to 2171334 Compare May 4, 2018 14:36
@Jannis
Jannis force-pushed the jannis/local-node-skeleton branch from 9cfabf8 to c8fd2cb Compare May 4, 2018 14:51
Jannis Pohlmann added 2 commits May 4, 2018 18:51
@Jannis
Jannis force-pushed the jannis/local-node-skeleton branch from c8fd2cb to 05944f4 Compare May 4, 2018 16:52
Comment thread Cargo.toml
members = [
"thegraph",
"thegraph-standalone-node",
"thegraph-local-node",

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.

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.

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 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),

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.

For my own learning... what is the static lifetime annotation accomplishing in these event enums?

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.

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.

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.

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",

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.

Why are we passing a string with these events. Is this meant to identify the data source?

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.

It's just a placeholder for the moment. We'll add data source information soon.

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.

👍

fn generate_mock_schema_events(&mut self) {
let sink = self.schema_event_sink.clone().unwrap();
sink.clone()
.send(SchemaEvent::SchemaAdded("First schema"))

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.

Same question. Is the string here just for testing/ debugging purposes?

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.

Placeholder, yup.

/// 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.

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.

Will we never listen on DataSourceProvider from more than one place?

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.

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 Sender in to the constructor from the outside (which would also create the Receiver), 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 . the DataSourceProvider.

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.

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.

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> {

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.

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'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.

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.

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>;

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.

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.

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 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).

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, 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.

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.

Not quite. These futures are "tasks" and they are the ones being spawned. ;)

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.

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 {

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.

This isn't already taken care of by the futures library?

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.

Nope, this is a special error for our FnOnce-style approach to obtaining an event stream from components like DataSourceProvider.

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. 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>>>>,

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.

For my own learning... could you explain the rationale behind the Arc<Mutex<Option<...>>>?

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.

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.

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.

Fantastic explanation, thank you :)


impl Store for MockStore {
fn get(&self, _key: StoreKey) -> Result<Entity, ()> {
unimplemented!();

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.

This is neat.

register_panic_handler();

// Start the node
tokio::run(future::lazy(|| {

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.

Lazy futures, nice!

tokio::spawn({
schema_stream
.forward(schema_sink.sink_map_err(|e| {
panic!("Failed to send schema event to schema provider: {:?}", e);

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 like that we're handling these sorts of errors at the top level, where we're doing our wiring. Looks clean!

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.

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();

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.

Interesting... can only be called once, but then the stream can still have multiple consumers?

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.

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 Zerim 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.

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. 👍

@Jannis
Jannis merged commit 202e5ac into master May 9, 2018
@Jannis
Jannis deleted the jannis/local-node-skeleton branch May 9, 2018 10:14
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")

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.

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?

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.

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.

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

3 participants