1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529
use std::fmt; use std::future::Future; use std::pin::Pin; use std::sync::Arc; use futures::channel::oneshot::Sender as SyncSender; use crate::actor::{Actor, AsyncContext}; use crate::address::Addr; use crate::context::Context; use crate::fut::ActorFuture; use crate::WrapFuture; /// Describes how to handle messages of a specific type. /// /// Implementing `Handler` is a general way to handle incoming /// messages, streams, and futures. /// /// The type `M` is a message which can be handled by the actor. #[allow(unused_variables)] pub trait Handler<M> where Self: Actor, M: Message, { /// The type of value that this handler will return. /// /// Check the [MessageResponse] trait for some details /// on how a message can be responded to. type Result: MessageResponse<Self, M>; /// This method is called for every message received by this actor. fn handle(&mut self, msg: M, ctx: &mut Self::Context) -> Self::Result; } /// Represent message that can be handled by an actor. pub trait Message { /// The type of value that this message will resolved with if it is /// successful. type Result: 'static; } /// Allow users to use `Arc<M>` as a message without having to re-impl `Message` impl<M, R: 'static> Message for Arc<M> where M: Message<Result = R>, { type Result = R; } /// Allow users to use `Box<M>` as a message without having to re-impl `Message` impl<M, R: 'static> Message for Box<M> where M: Message<Result = R>, { type Result = R; } /// A helper type that implements the `MessageResponse` trait. /// /// # Examples /// ```rust, no_run /// use actix::prelude::*; /// /// #[derive(Message)] /// #[rtype(result = "Response")] /// struct Msg; /// /// struct Response; /// /// struct MyActor; /// /// impl Actor for MyActor { /// type Context = Context<Self>; /// } /// /// impl Handler<Msg> for MyActor { /// type Result = MessageResult<Msg>; /// /// fn handle(&mut self, _: Msg, _: &mut Context<Self>) -> Self::Result { /// MessageResult(Response {}) /// } /// } /// ``` pub struct MessageResult<M: Message>(pub M::Result); /// A specialized actor future for asynchronous message handling. /// /// Intended be used from when the future returned will, /// at some point, need to access Actor's internal state or context /// in order to finish. /// Check [ActorFuture] for available methods for accessing Actor's /// internal state. /// /// ## Note /// It's important to keep in mind that the provided `AsyncContext`, /// [Context], does not enforce the poll of any [ActorFuture] to be /// exclusive. Therefore, if other instances of [ActorFuture] are spawned /// into this Context **their execution won't necessarily be atomic**. /// /// # Examples /// ```rust, no_run /// use actix::prelude::*; /// /// #[derive(Message)] /// #[rtype(result = "Result<usize, ()>")] /// struct Msg; /// /// struct MyActor; /// /// impl Actor for MyActor { /// type Context = Context<Self>; /// } /// /// impl Handler<Msg> for MyActor { /// type Result = ResponseActFuture<Self, Result<usize, ()>>; /// /// fn handle(&mut self, _: Msg, _: &mut Context<Self>) -> Self::Result { /// Box::new( /// async { /// // Some async computation /// 42 /// } /// .into_actor(self) // converts future to ActorFuture /// .map(|res, _act, _ctx| { /// // Do some computation with actor's state or context /// Ok(res) /// }), /// ) /// } /// } /// ``` pub type ResponseActFuture<A, I> = Box<dyn ActorFuture<Output = I, Actor = A>>; /// A specialized future for asynchronous message handling. /// /// Intended be used for when the future returned doesn't /// need to access Actor's internal state or context to progress, either /// because it's completely agnostic to it, or because the required data has /// already been moved inside the future and it won't need Actor state to continue. /// /// # Examples /// ```rust, no_run /// use actix::prelude::*; /// /// #[derive(Message)] /// #[rtype(result = "Result<(), ()>")] /// struct Msg; /// /// struct MyActor; /// /// impl Actor for MyActor { /// type Context = Context<Self>; /// } /// /// impl Handler<Msg> for MyActor { /// type Result = ResponseFuture<Result<(), ()>>; /// /// fn handle(&mut self, _: Msg, _: &mut Context<Self>) -> Self::Result { /// Box::pin(async move { /// // Some async computation /// Ok(()) /// }) /// } /// } /// ``` pub type ResponseFuture<I> = Pin<Box<dyn Future<Output = I>>>; /// A trait that defines a message response channel. pub trait ResponseChannel<M: Message>: 'static { fn is_canceled(&self) -> bool; fn send(self, response: M::Result); } /// A trait which defines message responses. /// /// We offer implementation for some common language types, if you need /// to respond with a new type you can use [MessageResult]. /// /// If `Actor::Context` implements [AsyncContext] it's possible to handle /// the message asynchronously. /// For asynchronous message handling we offer two possible response types /// [ResponseFuture] and [ResponseActFuture]. /// - [ResponseFuture] should be used for when the future returned doesn't /// need to access Actor's internal state or context to progress, either /// because it's completely agnostic to it or because the required data has /// already been moved to it and it won't need Actor state to continue. /// - [ResponseActFuture] should be used from when the future returned /// will, at some point, need to access Actor's internal state or context /// in order to finish. pub trait MessageResponse<A: Actor, M: Message> { fn handle<R: ResponseChannel<M>>(self, ctx: &mut A::Context, tx: Option<R>); } impl<M: Message + 'static> ResponseChannel<M> for SyncSender<M::Result> where M::Result: Send, { fn is_canceled(&self) -> bool { SyncSender::is_canceled(self) } fn send(self, response: M::Result) { let _ = Self::send(self, response); } } impl<M: Message + 'static> ResponseChannel<M> for () { fn is_canceled(&self) -> bool { true } fn send(self, _: M::Result) {} } impl<A, M> MessageResponse<A, M> for MessageResult<M> where A: Actor, M: Message, { fn handle<R: ResponseChannel<M>>(self, _: &mut A::Context, tx: Option<R>) { if let Some(tx) = tx { tx.send(self.0); } } } impl<A, M, I: 'static, E: 'static> MessageResponse<A, M> for Result<I, E> where A: Actor, M: Message<Result = Self>, { fn handle<R: ResponseChannel<M>>(self, _: &mut A::Context, tx: Option<R>) { if let Some(tx) = tx { tx.send(self); } } } impl<A, M, I: 'static> MessageResponse<A, M> for Arc<I> where A: Actor, M: Message<Result = Arc<I>>, { fn handle<R: ResponseChannel<M>>(self, _: &mut A::Context, tx: Option<R>) { if let Some(tx) = tx { tx.send(self); } } } impl<A, M, I: 'static> MessageResponse<A, M> for Option<I> where A: Actor, M: Message<Result = Self>, { fn handle<R: ResponseChannel<M>>(self, _: &mut A::Context, tx: Option<R>) { if let Some(tx) = tx { tx.send(self); } } } impl<A, M, B> MessageResponse<A, M> for Addr<B> where A: Actor, M: Message<Result = Self>, B: Actor<Context = Context<B>>, { fn handle<R: ResponseChannel<M>>(self, _: &mut A::Context, tx: Option<R>) { if let Some(tx) = tx { tx.send(self); } } } impl<A, M, T: 'static> MessageResponse<A, M> for ResponseActFuture<A, T> where A: Actor, M: Message<Result = T>, A::Context: AsyncContext<A>, { fn handle<R: ResponseChannel<M>>(self, ctx: &mut A::Context, tx: Option<R>) { ctx.spawn(Box::new(Pin::from(self)).then(move |res, this, _| { if let Some(tx) = tx { tx.send(res); } async {}.into_actor(this) })); } } /// MessageResponse trait impl to enbale the use of any `I: 'static` with asynchronous /// message handling /// /// # Examples /// Usage with `Result<I,E>`: /// ``` /// # pub struct MyActorAsync {} /// # impl Actor for MyActorAsync { type Context = actix::Context<Self>; } /// # use actix::prelude::*; /// # use core::pin::Pin; /// # /// pub struct MyQuestion{} /// impl Message for MyQuestion { /// type Result = Result<u8,u8>; /// } /// impl Handler<MyQuestion> for MyActorAsync { /// type Result = ResponseFuture<Result<u8,u8>>; /// fn handle(&mut self, question: MyQuestion, _ctx: &mut Context<Self>) -> Self::Result { /// Box::pin(async {Ok(5)}) /// } /// } /// ``` /// Usage with `Option<I>`: /// ``` /// # pub struct MyActorAsync {} /// # impl Actor for MyActorAsync { type Context = actix::Context<Self>; } /// # use actix::prelude::*; /// # use core::pin::Pin; /// pub struct MyQuestion{} /// impl Message for MyQuestion { /// type Result = Option<u8>; /// } /// impl Handler<MyQuestion> for MyActorAsync { /// type Result = ResponseFuture<Option<u8>>; /// fn handle(&mut self, question: MyQuestion, _ctx: &mut Context<Self>) -> Self::Result { /// Box::pin(async {Some(5)}) /// } /// } /// ``` /// Usage with any `I: 'static`: /// ``` /// # pub struct MyActorAsync {} /// # impl Actor for MyActorAsync { type Context = actix::Context<Self>; } /// # use actix::prelude::*; /// # use core::pin::Pin; /// pub struct MyQuestion{} /// impl Message for MyQuestion { /// type Result = u8; /// } /// impl Handler<MyQuestion> for MyActorAsync { /// type Result = ResponseFuture<u8>; /// fn handle(&mut self, question: MyQuestion, _ctx: &mut Context<Self>) -> Self::Result { /// Box::pin(async {5}) /// } /// } /// ``` impl<A, M, I: 'static> MessageResponse<A, M> for ResponseFuture<I> where A: Actor, M::Result: Send, M: Message<Result = I>, A::Context: AsyncContext<A>, { fn handle<R: ResponseChannel<M>>(self, _: &mut A::Context, tx: Option<R>) { actix_rt::spawn(async move { let res = self.await; if let Some(tx) = tx { tx.send(res) } }); } } enum ResponseTypeItem<I, E> { Result(Result<I, E>), Fut(Box<dyn Future<Output = Result<I, E>> + Unpin>), } /// Helper type for representing different type of message responses pub struct Response<I, E> { item: ResponseTypeItem<I, E>, } impl<I, E> fmt::Debug for Response<I, E> { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { let mut fmt = fmt.debug_struct("Response"); match self.item { ResponseTypeItem::Result(_) => fmt.field("item", &"Result(_)".to_string()), ResponseTypeItem::Fut(_) => fmt.field("item", &"Fut(_)".to_string()), } .finish() } } impl<I, E> Response<I, E> { /// Creates an asynchronous response. pub fn fut<T>(fut: T) -> Self where T: Future<Output = Result<I, E>> + Unpin + 'static, { Self { item: ResponseTypeItem::Fut(Box::new(fut)), } } /// Creates a response. pub fn reply(val: Result<I, E>) -> Self { Self { item: ResponseTypeItem::Result(val), } } } impl<A, M, I: 'static, E: 'static> MessageResponse<A, M> for Response<I, E> where A: Actor, M: Message<Result = Result<I, E>>, A::Context: AsyncContext<A>, { fn handle<R: ResponseChannel<M>>(self, _: &mut A::Context, tx: Option<R>) { match self.item { ResponseTypeItem::Fut(fut) => { actix_rt::spawn(async move { if let Some(tx) = tx { tx.send(fut.await); } }); } ResponseTypeItem::Result(res) => { if let Some(tx) = tx { tx.send(res); } } } } } enum ActorResponseTypeItem<A, I, E> { Result(Result<I, E>), Fut(Box<dyn ActorFuture<Output = Result<I, E>, Actor = A>>), } /// A helper type for representing different types of message responses. pub struct ActorResponse<A, I, E> { item: ActorResponseTypeItem<A, I, E>, } impl<A, I, E> fmt::Debug for ActorResponse<A, I, E> { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { let mut fmt = fmt.debug_struct("ActorResponse"); match self.item { ActorResponseTypeItem::Result(_) => { fmt.field("item", &"Result(_)".to_string()) } ActorResponseTypeItem::Fut(_) => fmt.field("item", &"Fut(_)".to_string()), } .finish() } } impl<A: Actor, I, E> ActorResponse<A, I, E> { /// Creates a response. pub fn reply(val: Result<I, E>) -> Self { Self { item: ActorResponseTypeItem::Result(val), } } /// Creates an asynchronous response. pub fn r#async<T>(fut: T) -> Self where T: ActorFuture<Output = Result<I, E>, Actor = A> + 'static, { Self { item: ActorResponseTypeItem::Fut(Box::new(fut)), } } } impl<A, M, I: 'static, E: 'static> MessageResponse<A, M> for ActorResponse<A, I, E> where A: Actor, M: Message<Result = Result<I, E>>, A::Context: AsyncContext<A>, { fn handle<R: ResponseChannel<M>>(self, ctx: &mut A::Context, tx: Option<R>) { match self.item { ActorResponseTypeItem::Fut(fut) => { let fut = Box::new(Pin::from(fut)).then(move |res, this, _| { if let Some(tx) = tx { tx.send(res) } async {}.into_actor(this) }); ctx.spawn(fut); } ActorResponseTypeItem::Result(res) => { if let Some(tx) = tx { tx.send(res); } } } } } macro_rules! SIMPLE_RESULT { ($type:ty) => { impl<A, M> MessageResponse<A, M> for $type where A: Actor, M: Message<Result = $type>, { fn handle<R: ResponseChannel<M>>(self, _: &mut A::Context, tx: Option<R>) { if let Some(tx) = tx { tx.send(self); } } } }; } SIMPLE_RESULT!(()); SIMPLE_RESULT!(u8); SIMPLE_RESULT!(u16); SIMPLE_RESULT!(u32); SIMPLE_RESULT!(u64); SIMPLE_RESULT!(usize); SIMPLE_RESULT!(i8); SIMPLE_RESULT!(i16); SIMPLE_RESULT!(i32); SIMPLE_RESULT!(i64); SIMPLE_RESULT!(isize); SIMPLE_RESULT!(f32); SIMPLE_RESULT!(f64); SIMPLE_RESULT!(String); SIMPLE_RESULT!(bool);