Skip to content

Commit

Permalink
Add support for registering routes with a server type
Browse files Browse the repository at this point in the history
  • Loading branch information
photino committed Sep 17, 2023
1 parent 8b717e9 commit 70bda82
Show file tree
Hide file tree
Showing 15 changed files with 223 additions and 105 deletions.
4 changes: 4 additions & 0 deletions examples/actix-app/config/config.dev.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ version = "0.6.2"
[dirs]
uploads = "local/uploads"

[debug]
host = "127.0.0.1"
port = 6070

[main]
host = "127.0.0.1"
port = 6080
Expand Down
4 changes: 4 additions & 0 deletions examples/actix-app/config/config.prod.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ version = "0.6.2"
[dirs]
uploads = "local/uploads"

[debug]
host = "127.0.0.1"
port = 6070

[main]
host = "127.0.0.1"
port = 6080
Expand Down
1 change: 1 addition & 0 deletions examples/actix-app/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ use zino::prelude::*;
fn main() {
zino::Cluster::boot()
.register(router::routes())
.register_debug(router::debug_routes())
.spawn(schedule::jobs())
.run(schedule::async_jobs())
}
5 changes: 5 additions & 0 deletions examples/actix-app/src/router/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,11 @@ pub fn routes() -> Vec<RouterConfigure> {
user_router as RouterConfigure,
tag_router as RouterConfigure,
task_router as RouterConfigure,
]
}

pub fn debug_routes() -> Vec<RouterConfigure> {
vec![
stats_router as RouterConfigure,
]
}
Expand Down
4 changes: 4 additions & 0 deletions examples/axum-app/config/config.dev.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ version = "0.6.2"
[dirs]
uploads = "local/uploads"

[debug]
host = "127.0.0.1"
port = 6070

[main]
host = "127.0.0.1"
port = 6080
Expand Down
4 changes: 4 additions & 0 deletions examples/axum-app/config/config.prod.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ version = "0.6.2"
[dirs]
uploads = "local/uploads"

[debug]
host = "127.0.0.1"
port = 6070

[main]
host = "127.0.0.1"
port = 6080
Expand Down
1 change: 1 addition & 0 deletions examples/axum-app/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ use zino::prelude::*;
fn main() {
zino::Cluster::boot()
.register(router::routes())
.register_debug(router::debug_routes())
.spawn(schedule::jobs())
.run(schedule::async_jobs())
}
6 changes: 6 additions & 0 deletions examples/axum-app/src/router/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,12 @@ pub fn routes() -> Vec<Router> {
let router = Router::new().route("/task/execute", post(task::execute));
routes.push(router);

routes
}

pub fn debug_routes() -> Vec<Router> {
let mut routes = Vec::new();

// Stats controller.
let router = Router::new().route("/stats", get(stats::index));
routes.push(router);
Expand Down
20 changes: 19 additions & 1 deletion zino-core/src/application/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ pub trait Application {
/// Routes.
type Routes;

/// Registers routes.
/// Registers default routes.
fn register(self, routes: Self::Routes) -> Self;

/// Runs the application.
Expand Down Expand Up @@ -81,6 +81,24 @@ pub trait Application {
Self::boot()
}

/// Registers routes for debugger.
#[inline]
fn register_debug(self, routes: Self::Routes) -> Self
where
Self: Sized,
{
self.register_with("debug", routes)
}

/// Registers routes with a custom server type.
#[inline]
fn register_with(self, _server_type: &'static str, _routes: Self::Routes) -> Self
where
Self: Sized,
{
self
}

/// Gets the system’s information.
#[inline]
fn sysinfo() -> Map {
Expand Down
2 changes: 1 addition & 1 deletion zino-core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,11 @@
#![feature(async_fn_in_trait)]
#![feature(decl_macro)]
#![feature(doc_auto_cfg)]
#![feature(slice_first_last_chunk)]
#![feature(iter_intersperse)]
#![feature(lazy_cell)]
#![feature(let_chains)]
#![feature(result_option_inspect)]
#![feature(slice_first_last_chunk)]
#![forbid(unsafe_code)]

mod crypto;
Expand Down
20 changes: 11 additions & 9 deletions zino-core/src/response/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use crate::{
JsonValue, SharedString, Uuid,
};
use bytes::Bytes;
use http::header::{self, HeaderValue};
use http::header::{self, HeaderName, HeaderValue};
use http_body::Full;
use serde::Serialize;
use serde_json::value::RawValue;
Expand Down Expand Up @@ -95,7 +95,7 @@ pub struct Response<S = StatusCode> {
server_timing: ServerTiming,
/// Custom headers.
#[serde(skip)]
headers: Vec<(&'static str, String)>,
headers: Vec<(SharedString, String)>,
/// Phantom type of response code.
#[serde(skip)]
phantom: PhantomData<S>,
Expand Down Expand Up @@ -410,8 +410,8 @@ impl<S: ResponseCode> Response<S> {

/// Inserts a custom header.
#[inline]
pub fn insert_header(&mut self, name: &'static str, value: impl ToString) {
self.headers.push((name, value.to_string()));
pub fn insert_header(&mut self, name: impl Into<SharedString>, value: impl ToString) {
self.headers.push((name.into(), value.to_string()));
}

/// Gets a custome header with the given name.
Expand Down Expand Up @@ -481,7 +481,7 @@ impl<S: ResponseCode> Response<S> {

/// Returns the custom headers.
#[inline]
pub fn headers(&self) -> &[(&'static str, String)] {
pub fn headers(&self) -> &[(SharedString, String)] {
&self.headers
}

Expand Down Expand Up @@ -597,7 +597,7 @@ impl<S: ResponseCode> Response<S> {
}

/// Consumes `self` and returns the custom headers.
pub fn finalize(mut self) -> impl Iterator<Item = (&'static str, String)> {
pub fn finalize(mut self) -> Vec<(SharedString, String)> {
let request_id = self.request_id();
if !request_id.is_nil() {
self.insert_header("x-request-id", request_id.to_string());
Expand All @@ -611,7 +611,7 @@ impl<S: ResponseCode> Response<S> {
self.record_server_timing("total", None, Some(duration));
self.insert_header("server-timing", self.server_timing());

self.headers.into_iter()
self.headers
}
}

Expand Down Expand Up @@ -650,8 +650,10 @@ impl<S: ResponseCode> From<Response<S>> for FullResponse {
};

for (key, value) in response.finalize() {
if let Ok(header_value) = HeaderValue::try_from(value) {
res.headers_mut().insert(key, header_value);
if let Ok(header_name) = HeaderName::try_from(key.as_ref()) &&
let Ok(header_value) = HeaderValue::try_from(value)
{
res.headers_mut().insert(header_name, header_value);
}
}

Expand Down
32 changes: 24 additions & 8 deletions zino-core/src/state/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//! Application scoped state.

use crate::{application, crypto, encoding::base64, extension::TomlTableExt, helper};
use crate::{application, crypto, encoding::base64, extension::TomlTableExt, helper, SharedString};
use std::{
borrow::Cow,
env, fs,
Expand Down Expand Up @@ -95,38 +95,54 @@ impl<T> State<T> {
&mut self.data
}

/// Returns a list of listeners as `Vec<SocketAddr>`.
pub fn listeners(&self) -> Vec<SocketAddr> {
/// Returns a list of listeners.
pub fn listeners(&self) -> Vec<(SharedString, SocketAddr)> {
let config = self.config();
let mut listeners = Vec::new();

// Optional debug server
if let Some(debug_server) = config.get_table("debug") {
let debug_host = debug_server
.get_str("host")
.and_then(|s| s.parse::<IpAddr>().ok())
.expect("the `debug.host` field should be a str");
let debug_port = debug_server
.get_u16("port")
.expect("the `debug.port` field should be an integer");
listeners.push(("debug".into(), (debug_host, debug_port).into()));
}

// Main server
let (main_host, main_port) = if let Some(main) = config.get_table("main") {
let host = main
let (main_host, main_port) = if let Some(main_server) = config.get_table("main") {
let host = main_server
.get_str("host")
.and_then(|s| s.parse::<IpAddr>().ok())
.unwrap_or(Ipv4Addr::UNSPECIFIED.into());
let port = main.get_u16("port").unwrap_or(6080);
let port = main_server.get_u16("port").unwrap_or(6080);
(host, port)
} else {
(Ipv4Addr::UNSPECIFIED.into(), 6080)
};
listeners.push((main_host, main_port).into());
listeners.push(("main".into(), (main_host, main_port).into()));

// Optional standbys
if config.contains_key("standby") {
let standbys = config
.get_array("standby")
.expect("the `standby` field should be an array of tables");
for standby in standbys.iter().filter_map(|v| v.as_table()) {
let server_type = standby
.get_str("type")
.map(|s| s.to_owned().into())
.unwrap_or("standby".into());
let standby_host = standby
.get_str("host")
.and_then(|s| s.parse::<IpAddr>().ok())
.expect("the `standby.host` field should be a str");
let standby_port = standby
.get_u16("port")
.expect("the `standby.port` field should be an integer");
listeners.push((standby_host, standby_port).into());
listeners.push((server_type, (standby_host, standby_port).into()));
}
}

Expand Down
Loading

0 comments on commit 70bda82

Please sign in to comment.