Skip to content

Commit 2764b3b

Browse files
authored
Fix/http lifecycle (#2)
* fix: support for HTTP services lifecycle API * style: remove unnecessary comments
1 parent 1b8c97e commit 2764b3b

File tree

10 files changed

+83
-46
lines changed

10 files changed

+83
-46
lines changed

examples/services/grpc/src/main.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,13 +12,13 @@ use helloworld::{HelloReply, HelloRequest};
1212

1313
#[derive(Clone)]
1414
pub struct MyGreeter {
15-
ctx: Box<Arc<mikros::FutureMutex<Context>>>
15+
ctx: Arc<mikros::FutureMutex<Context>>
1616
}
1717

1818
impl MyGreeter {
1919
pub fn new(ctx: Arc<mikros::FutureMutex<Context>>) -> Self {
2020
Self {
21-
ctx: Box::new(ctx)
21+
ctx: ctx.clone()
2222
}
2323
}
2424
}
@@ -38,6 +38,7 @@ impl Greeter for MyGreeter {
3838
message: format!("Hello, {}!", request.into_inner().name),
3939
};
4040

41+
self.ctx.lock().await.value += 1;
4142
Ok(Response::new(reply))
4243
}
4344
}

examples/services/http/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ version = "0.1.0"
44
edition = "2021"
55

66
[dependencies]
7+
async-trait = "0.1.83"
78
axum = "0.7.7"
89
mikros = { path = "../../../" }
910
tokio = { version = "1.41.1", features = ["full"] }

examples/services/http/src/main.rs

Lines changed: 44 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
1+
use std::any::Any;
12
use std::sync::Arc;
23

34
use axum::extract::State;
45
use axum::routing::get;
6+
use futures::lock::Mutex;
57
use mikros::FutureMutex;
68
use mikros::http::ServiceState;
79
use mikros::service::builder::ServiceBuilder;
10+
use mikros::service::lifecycle::Lifecycle;
811

912
#[derive(Clone, Default)]
1013
pub struct AppState {
@@ -17,6 +20,39 @@ impl AppState {
1720
}
1821
}
1922

23+
#[async_trait::async_trait]
24+
impl Lifecycle for AppState {
25+
async fn on_start(&mut self) -> mikros::errors::Result<()> {
26+
println!("service on_start");
27+
self.value = 42;
28+
Ok(())
29+
}
30+
31+
async fn on_finish(&self) -> mikros::errors::Result<()> {
32+
println!("service on_finish");
33+
Ok(())
34+
}
35+
}
36+
37+
#[derive(Clone)]
38+
pub struct AppLifecycle {
39+
state: Arc<Mutex<dyn Any + Send + Sync>>,
40+
}
41+
42+
#[async_trait::async_trait]
43+
impl Lifecycle for AppLifecycle {
44+
async fn on_start(&mut self) -> mikros::errors::Result<()> {
45+
println!("service on_start");
46+
self.state.lock().await.downcast_mut::<AppState>().unwrap().value = 42;
47+
Ok(())
48+
}
49+
50+
async fn on_finish(&self) -> mikros::errors::Result<()> {
51+
println!("service on_finish");
52+
Ok(())
53+
}
54+
}
55+
2056
// Handler method for the first endpoint
2157
async fn handler_one(State(state): State<Arc<FutureMutex<ServiceState>>>) -> String {
2258
println!("Handler One");
@@ -47,9 +83,15 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
4783
.route("/one", get(handler_one))
4884
.route("/two", get(handler_two));
4985

50-
let state = AppState::default();
86+
//let state = Arc::new(Mutex::new(Box::new(AppState::default()) as Box<dyn Any + Send + Sync>));
87+
let state = Arc::new(Mutex::new(AppState::default()));
88+
// let lifecycle = Arc::new(Mutex::new(AppLifecycle { state: state.clone(), }));
89+
5190
let svc = ServiceBuilder::default()
52-
.http_with_state(api, Box::new(state))
91+
//.http_with_lifecycle_and_state(api, lifecycle.clone(), state.clone())
92+
.http_with_lifecycle_and_state(api, state.clone(), state.clone())
93+
// .http_with_lifecycle(api, Box::new(state))
94+
// .http_with_state(api, Box::new(state))
5395
// .http(api)
5496
.build();
5597

examples/services/native/src/main.rs

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,14 @@
11
mod service;
22

3-
extern crate mikros;
4-
5-
use std::sync::Arc;
6-
7-
use mikros::FutureMutex;
83
use mikros::service::builder::{ServiceBuilder};
94
use service::Service as AppService;
105

116
#[tokio::main]
127
async fn main() {
13-
let s = Arc::new(FutureMutex::new(AppService::new()));
8+
let s = AppService::new();
149
let svc = ServiceBuilder::default()
15-
.script(s.clone())
16-
.native(s.clone())
10+
// .script(Box::new(s))
11+
.native(Box::new(s))
1712
.build();
1813

1914
match svc {

src/http/mod.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ pub struct ServiceState {
3636
/// }
3737
/// ```
3838
///
39-
pub app_state: Option<Arc<Mutex<Box<dyn Any + Send + Sync>>>>,
39+
pub app_state: Option<Arc<Mutex<dyn Any + Send + Sync>>>,
4040
}
4141

4242
impl ServiceState {
@@ -47,9 +47,9 @@ impl ServiceState {
4747
}
4848
}
4949

50-
pub(crate) fn new_with_state(context: &Context, internal_state: Arc<Mutex<Box<dyn Any + Send + Sync>>>) -> Self {
50+
pub(crate) fn new_with_state(context: &Context, internal_state: Arc<Mutex<dyn Any + Send + Sync>>) -> Self {
5151
let mut s = Self::new(context);
52-
s.app_state = Some(internal_state);
52+
s.app_state = Some(internal_state.clone());
5353
s
5454
}
5555

src/service/builder.rs

Lines changed: 10 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -38,20 +38,14 @@ impl ServiceBuilder {
3838

3939
/// Initializes the native service type with the required structure
4040
/// implementing its API.
41-
pub fn native<S>(mut self, svc: Arc<Mutex<S>>) -> Self
42-
where
43-
S: NativeService + 'static
44-
{
41+
pub fn native(mut self, svc: Box<dyn NativeService>) -> Self {
4542
self.servers.insert(definition::ServiceKind::Native.to_string(), Box::new(Native::new(svc)));
4643
self
4744
}
4845

4946
/// Initializes the script service type with the required structure
5047
/// implementing its API.
51-
pub fn script<S>(mut self, svc: Arc<Mutex<S>>) -> Self
52-
where
53-
S: ScriptService + 'static
54-
{
48+
pub fn script(mut self, svc: Box<dyn ScriptService>) -> Self {
5549
self.servers.insert(definition::ServiceKind::Script.to_string(), Box::new(Script::new(svc)));
5650
self
5751
}
@@ -75,7 +69,7 @@ impl ServiceBuilder {
7569
/// Initializes the gRPC service type with the required structure
7670
/// implementing its API and another with implementing the Lifecycle
7771
/// API.
78-
pub fn grpc_with_lifecycle<S, B>(mut self, server: S, lifecycle: Arc<Mutex<B>>) -> Self
72+
pub fn grpc_with_lifecycle<S, L>(mut self, server: S, lifecycle: Arc<Mutex<L>>) -> Self
7973
where
8074
S: tonic::codegen::Service<Request<BoxBody>, Response = Response<BoxBody>, Error = Infallible>
8175
+ NamedService
@@ -84,7 +78,7 @@ impl ServiceBuilder {
8478
+ Sync
8579
+ 'static,
8680
S::Future: Send + 'static,
87-
B: Lifecycle + 'static
81+
L: Lifecycle + 'static
8882
{
8983
self.servers.insert(definition::ServiceKind::Grpc.to_string(), Box::new(Grpc::new_with_lifecycle(server, lifecycle)));
9084
self
@@ -111,7 +105,10 @@ impl ServiceBuilder {
111105
/// Initializes the HTTP service type with the required structure
112106
/// implementing the service endpoint handlers. It also receives an
113107
/// object that will be passed inside the handlers state.
114-
pub fn http_with_state(mut self, router: Router<Arc<Mutex<ServiceState>>>, state: Box<dyn Any + Send + Sync>) -> Self {
108+
pub fn http_with_state<S>(mut self, router: Router<Arc<Mutex<ServiceState>>>, state: Arc<Mutex<S>>) -> Self
109+
where
110+
S: Any + Send + Sync
111+
{
115112
self.servers.insert(definition::ServiceKind::Http.to_string(), Box::new(Http::new_with_state(router, state)));
116113
self
117114
}
@@ -120,9 +117,10 @@ impl ServiceBuilder {
120117
/// implementing the service endpoint handlers and another with
121118
/// implementing the Lifecycle API. It also receives an object that
122119
/// will be passed inside the handlers state.
123-
pub fn http_with_lifecycle_and_state<L>(mut self, router: Router<Arc<Mutex<ServiceState>>>, lifecycle: Arc<Mutex<L>>, state: Box<dyn Any + Send + Sync>) -> Self
120+
pub fn http_with_lifecycle_and_state<L, S>(mut self, router: Router<Arc<Mutex<ServiceState>>>, lifecycle: Arc<Mutex<L>>, state: Arc<Mutex<S>>) -> Self
124121
where
125122
L: Lifecycle + 'static,
123+
S: Any + Send + Sync
126124
{
127125
self.servers.insert(definition::ServiceKind::Http.to_string(), Box::new(Http::new_with_lifecycle_and_state(router, lifecycle, state)));
128126
self

src/service/grpc/mod.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ use crate::service::lifecycle::Lifecycle;
2121
pub(crate) struct Grpc<S> {
2222
port: i32,
2323
server: S,
24-
lifecycle: Option<Box<Arc<Mutex<dyn Lifecycle>>>>,
24+
lifecycle: Option<Arc<Mutex<dyn Lifecycle>>>,
2525
}
2626

2727
impl<S> Grpc<S>
@@ -34,11 +34,11 @@ where
3434
+ 'static,
3535
S::Future: Send + 'static,
3636
{
37-
pub(crate) fn new_with_lifecycle<B: Lifecycle + 'static>(server: S, lifecycle: Arc<Mutex<B>>) -> Self {
37+
pub(crate) fn new_with_lifecycle<L: Lifecycle + 'static>(server: S, lifecycle: Arc<Mutex<L>>) -> Self {
3838
Self {
3939
port: 0,
4040
server,
41-
lifecycle: Some(Box::new(lifecycle)),
41+
lifecycle: Some(lifecycle.clone()),
4242
}
4343
}
4444

src/service/http/mod.rs

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,8 @@ use crate::{definition, env, errors as merrors, plugin};
1717
pub(crate) struct Http {
1818
port: i32,
1919
router: Router<Arc<Mutex<ServiceState>>>,
20-
lifecycle: Option<Box<Arc<Mutex<dyn Lifecycle>>>>,
21-
app_state: Option<Arc<Mutex<Box<dyn Any + Send + Sync>>>>,
20+
lifecycle: Option<Arc<Mutex<dyn Lifecycle>>>,
21+
app_state: Option<Arc<Mutex<dyn Any + Send + Sync>>>,
2222
}
2323

2424
impl Http {
@@ -36,23 +36,23 @@ impl Http {
3636
L: Lifecycle + 'static,
3737
{
3838
let mut s = Self::new(router);
39-
s.lifecycle = Some(Box::new(lifecycle));
39+
s.lifecycle = Some(lifecycle.clone());
4040
s
4141
}
4242

43-
pub fn new_with_state(router: Router<Arc<Mutex<ServiceState>>>, state: Box<dyn Any + Send + Sync>) -> Self {
43+
pub fn new_with_state(router: Router<Arc<Mutex<ServiceState>>>, state: Arc<Mutex<dyn Any + Send + Sync>>) -> Self {
4444
let mut s = Self::new(router);
45-
s.app_state = Some(Arc::new(Mutex::new(state)));
45+
s.app_state = Some(state.clone());
4646
s
4747
}
4848

49-
pub fn new_with_lifecycle_and_state<L>(router: Router<Arc<Mutex<ServiceState>>>, lifecycle: Arc<Mutex<L>>, state: Box<dyn Any + Send + Sync>) -> Self
49+
pub fn new_with_lifecycle_and_state<L>(router: Router<Arc<Mutex<ServiceState>>>, lifecycle: Arc<Mutex<L>>, state: Arc<Mutex<dyn Any + Send + Sync>>) -> Self
5050
where
5151
L: Lifecycle + 'static,
5252
{
5353
let mut s = Self::new(router);
54-
s.lifecycle = Some(Box::new(lifecycle));
55-
s.app_state = Some(Arc::new(Mutex::new(state)));
54+
s.lifecycle = Some(lifecycle.clone());
55+
s.app_state = Some(state.clone());
5656
s
5757
}
5858
}

src/service/native/mod.rs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
11
use std::collections::HashMap;
2-
use std::sync::{Arc};
2+
use std::sync::Arc;
33

44
use futures::lock::Mutex;
55
use logger::fields::FieldValue;
66
use tokio::sync::watch;
77

8-
use crate::{definition, env, errors as merrors, plugin};
98
use crate::service::context::Context;
109
use crate::service::lifecycle::Lifecycle;
10+
use crate::{definition, env, errors as merrors, plugin};
1111

1212
#[async_trait::async_trait]
1313
pub trait NativeService: NativeServiceClone + Lifecycle + Send + Sync {
@@ -43,13 +43,13 @@ impl Clone for Box<dyn NativeService> {
4343

4444
#[derive(Clone)]
4545
pub(crate) struct Native {
46-
svc: Box<Arc<Mutex<dyn NativeService>>>,
46+
svc: Arc<Mutex<Box<dyn NativeService>>>,
4747
}
4848

4949
impl Native {
50-
pub fn new<S: NativeService + 'static>(svc: Arc<Mutex<S>>) -> Self {
50+
pub fn new(svc: Box<dyn NativeService>) -> Self {
5151
Self {
52-
svc: Box::new(svc),
52+
svc: Arc::new(Mutex::new(svc)),
5353
}
5454
}
5555
}

src/service/script/mod.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -36,13 +36,13 @@ impl Clone for Box<dyn ScriptService> {
3636

3737
#[derive(Clone)]
3838
pub(crate) struct Script {
39-
svc: Box<Arc<Mutex<dyn ScriptService>>>,
39+
svc: Arc<Mutex<Box<dyn ScriptService>>>,
4040
}
4141

4242
impl Script {
43-
pub fn new<S: ScriptService + 'static>(svc: Arc<Mutex<S>>) -> Self {
43+
pub fn new(svc: Box<dyn ScriptService>) -> Self {
4444
Self {
45-
svc: Box::new(svc),
45+
svc: Arc::new(Mutex::new(svc)),
4646
}
4747
}
4848
}

0 commit comments

Comments
 (0)