Skip to content

[WIP] Proof of proof of concept for Tide-global state #100

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
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
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ multipart = "0.15.3"
slog = "2.4.1"
slog-term = "2.4.0"
slog-async = "2.3.0"
lazy_static = "1.2.0"

[dependencies.path_table]
path = "path_table"
Expand Down
20 changes: 19 additions & 1 deletion src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,19 @@ use futures::{
prelude::*,
};
use hyper::service::Service;
use slog::{info, Logger};
use std::{
ops::{Deref, DerefMut},
sync::Arc,
};

use crate::{
body::Body,
config::{Config, Env},
extract::Extract,
middleware::{logger::RootLogger, RequestContext},
router::{Resource, RouteResult, Router},
typemap::STATE,
Middleware, Request, Response, RouteMatch,
};

Expand All @@ -30,14 +33,20 @@ pub struct App<Data> {
impl<Data: Clone + Send + Sync + 'static> App<Data> {
/// Set up a new app with some initial `data`.
pub fn new(data: Data) -> App<Data> {
let logger = RootLogger::new();
let logger = RootLogger::init();
let config = Config { env: Env::Dev };

let mut map = STATE.write().unwrap();
// store config in app state
map.insert(config);
let mut app = App {
data,
router: Router::new(),
};

// Add RootLogger as a default middleware
app.middleware(logger);

app
}

Expand Down Expand Up @@ -86,6 +95,15 @@ impl<Data: Clone + Send + Sync + 'static> App<Data> {
res
})
.compat();

let map = STATE.read().unwrap();
let logger = map.get::<Logger>().unwrap();
let config = map.get::<Config>().unwrap();

info!(
logger,
"Environment: {:?} Starting server on: {}", config.env, addr
);
hyper::rt::run(server);
}
}
Expand Down
14 changes: 14 additions & 0 deletions src/config.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
#[derive(Debug)]
pub(crate) enum Env {
Dev,
Prod,
Test,
Staging,
}

// NOTE: Example only!!
//
// Just to test if TypeMap works
pub(crate) struct Config {
pub(crate) env: Env,
}
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,15 @@

mod app;
pub mod body;
mod config;
mod endpoint;
mod extract;
pub mod head;
pub mod middleware;
mod request;
mod response;
mod router;
mod typemap;

pub use crate::{
app::{App, AppData},
Expand Down
25 changes: 17 additions & 8 deletions src/middleware/logger.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,24 +4,27 @@ use slog_term;

use futures::future::FutureObj;

use crate::{middleware::RequestContext, Middleware, Response};
use crate::{middleware::RequestContext, typemap::STATE, Middleware, Response};

/// Root logger for Tide. Wraps over logger provided by slog.SimpleLogger
///
/// Only used internally for now.
pub(crate) struct RootLogger {
// drain: dyn slog::Drain,
inner_logger: slog::Logger,
}
pub(crate) struct RootLogger;

impl RootLogger {
pub fn new() -> RootLogger {
pub fn init() -> RootLogger {
let decorator = slog_term::TermDecorator::new().build();
let drain = slog_term::CompactFormat::new(decorator).build().fuse();
let drain = slog_async::Async::new(drain).build().fuse();

let log = slog::Logger::root(drain, o!());
RootLogger { inner_logger: log }

let logger = RootLogger {};

// Store global logger instance.
STATE.write().unwrap().insert(log);

logger
}
}

Expand All @@ -36,7 +39,13 @@ impl<Data: Clone + Send> Middleware<Data> for RootLogger {

let res = await!(ctx.next());
let status = res.status();
info!(self.inner_logger, "{} {} {}", method, path, status.as_str());

let map = STATE.read().unwrap();

// Get global logger instance
let logger = map.get::<slog::Logger>().unwrap();

info!(logger, "{} {} {}", method, path, status.as_str());
res
},
))
Expand Down
11 changes: 11 additions & 0 deletions src/typemap.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
use std::sync::RwLock;

use http::Extensions;
use lazy_static::lazy_static;

lazy_static! {
pub(crate) static ref STATE: RwLock<Extensions> = {
let m = Extensions::new();
RwLock::new(m)
};
}