├── .gitignore ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── src └── lib.rs └── tests └── test_actor.rs /.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "kabuki" 3 | version = "0.0.1" 4 | authors = ["Carl Lerche "] 5 | description = "Name reservation" 6 | license = "MIT" 7 | 8 | [dependencies] 9 | futures = "0.1" 10 | tokio-core = "0.1" 11 | futures-threadpool = "0.1" 12 | futures-mpsc = "0.1" 13 | 14 | [dependencies.futures-spawn] 15 | version = "0.1" 16 | default-features = false 17 | features = ["use_std", "tokio"] 18 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2016 Carl Lerche 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2016 Carl Lerche 2 | 3 | Permission is hereby granted, free of charge, to any 4 | person obtaining a copy of this software and associated 5 | documentation files (the "Software"), to deal in the 6 | Software without restriction, including without 7 | limitation the rights to use, copy, modify, merge, 8 | publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software 10 | is furnished to do so, subject to the following 11 | conditions: 12 | 13 | The above copyright notice and this permission notice 14 | shall be included in all copies or substantial portions 15 | of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 18 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 19 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 21 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 22 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 23 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 24 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 25 | DEALINGS IN THE SOFTWARE. 26 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Kabuki 2 | 3 | Actor library built on top of the Tokio platform. 4 | 5 | ## Overview 6 | 7 | Kabuki provides a simple way to structure concurrent applications built for 8 | the Tokio / Futures platform. It is based on the [actor 9 | model](https://en.wikipedia.org/wiki/Actor_model). An actor is a small unit 10 | of computation that is used to manage state and resources. It receives 11 | messages from other actors and performs some kind of action based on that 12 | input. This way, instead of having state and resources accessed 13 | concurrently, only a single thread access it and concurrent access is 14 | handled through message passing. 15 | 16 | ## Motivation 17 | 18 | [Tokio](https://docs.rs/tokio-core/0.1.2/tokio_core/reactor/index.html) and 19 | [Futures](https://docs.rs/futures/0.1.7/futures/task/index.html) provide a 20 | lightweight task primitive. However, it leaves the details of managing 21 | concurrency up to the developer. 22 | 23 | ## Usage 24 | 25 | First, add this to your `Cargo.toml`: 26 | 27 | ```toml 28 | [dependencies] 29 | kabuki = { git = "https://github.com/carllerche/kabuki" } 30 | ``` 31 | 32 | Next, add this to your crate: 33 | 34 | ```rust 35 | extern crate kabuki; 36 | ``` 37 | 38 | And then, use kabuki! 39 | 40 | # License 41 | 42 | `kabuki` is primarily distributed under the terms of both the MIT license and 43 | the Apache License (Version 2.0), with portions covered by various BSD-like 44 | licenses. 45 | 46 | See LICENSE-APACHE, and LICENSE-MIT for details. 47 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! Actor library built on top of the Tokio platform. 2 | //! 3 | //! Kabuki provides a simple way to structure concurrent applications built for 4 | //! the Tokio / Futures platform. It is based on the [actor 5 | //! model](https://en.wikipedia.org/wiki/Actor_model). An actor is a small unit 6 | //! of computation that is used to manage state and resources. It receives 7 | //! messages from other actors and performs some kind of action based on that 8 | //! input. This way, instead of having state and resources accessed 9 | //! concurrently, only a single thread access it and concurrent access is 10 | //! handled through message passing. 11 | //! 12 | //! # Motivation 13 | //! 14 | //! [Tokio](https://docs.rs/tokio-core/0.1.2/tokio_core/reactor/index.html) and 15 | //! [Futures](https://docs.rs/futures/0.1.7/futures/task/index.html) provide a 16 | //! lightweight task primitive. However, it leaves the details of managing 17 | //! concurrency up to the developer. 18 | 19 | #![deny(missing_docs)] 20 | 21 | // TODO: 22 | // - Use UnparkEvent once in-flight passes some threshold 23 | // - Conditionally depend on tokio-core 24 | 25 | #[macro_use] 26 | extern crate futures; 27 | extern crate futures_spawn; 28 | extern crate futures_mpsc; 29 | extern crate tokio_core; 30 | 31 | use futures::{Future, Stream, IntoFuture, Async, AsyncSink, Sink, Poll}; 32 | use futures::sync::oneshot; 33 | use futures_spawn::Spawn; 34 | use futures_mpsc as mpsc; 35 | 36 | use std::mem; 37 | use std::marker::PhantomData; 38 | 39 | /// A value that manages state and responds to messages 40 | pub trait Actor { 41 | /// The message sent to the actor 42 | type Request; 43 | 44 | /// The response sent back from the actor 45 | type Response; 46 | 47 | /// The response error 48 | type Error; 49 | 50 | /// The internal response future. This will remain on the actor's task and 51 | /// will be polled to completion before being sent back to the caller. 52 | type Future: IntoFuture; 53 | 54 | /// Poll the `Actor` to see if it has completed processing. 55 | /// 56 | /// Allows the actor to advance its internal state without receiving a 57 | /// message. For example, if the actor sets a timeout, the task 58 | /// managing the actor will get notified and this function will be called. 59 | fn poll(&mut self, state: ActorState) -> Async<()> { 60 | if state == ActorState::Listening { 61 | Async::NotReady 62 | } else { 63 | Async::Ready(()) 64 | } 65 | } 66 | 67 | /// Indicates that the actor is ready to process the next inbox message 68 | /// 69 | /// Before the `ActorCell` attempts to read a message off the inbox, it will 70 | /// call this function. If the actor value is not ready to process a new 71 | /// message, the cell will wait until it is. 72 | fn poll_ready(&mut self) -> Async<()> { 73 | Async::Ready(()) 74 | } 75 | 76 | /// Process an inbound message and return a response. 77 | /// 78 | /// The response future will be polled until the value is realized and the 79 | /// response value will be sent back to the sender of the message. 80 | fn call(&mut self, req: Self::Request) -> Self::Future; 81 | } 82 | 83 | /// An actor implemented by a closure. 84 | pub struct ActorFn { 85 | f: F, 86 | _ty: PhantomData T>, // don't impose Sync on T 87 | } 88 | 89 | /// The return value of `ActorRef::call` 90 | pub struct ActorFuture { 91 | state: CallState, 92 | } 93 | 94 | /// Tracks the state of the actor 95 | #[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)] 96 | pub enum ActorState { 97 | /// Listening for inbound messages 98 | Listening, 99 | /// Inbox is closed 100 | Finalizing, 101 | } 102 | 103 | /// Internal representation of the actor state 104 | enum ActorStatePriv { 105 | Listening, 106 | Finalizing, 107 | Shutdown, 108 | } 109 | 110 | enum CallState { 111 | Waiting(oneshot::Receiver>), 112 | Error(CallError), 113 | Consumed, 114 | } 115 | 116 | /// Builds an actor 117 | pub struct Builder { 118 | // Inbox capacity 119 | inbox: usize, 120 | // Max number of in-flight requests 121 | in_flight: usize, 122 | } 123 | 124 | /// Manages the runtime state of an `Actor`. 125 | pub struct ActorCell { 126 | // The actor value 127 | actor: A, 128 | 129 | // Current state of the actor 130 | state: ActorStatePriv, 131 | 132 | // The actors inbox 133 | rx: mpsc::Receiver>, 134 | 135 | // A slab of futures that are being executed. Each slot in this vector is 136 | // either an active future or a pointer to the next empty slot. This is used 137 | // to get O(1) deallocation in the slab and O(1) allocation. 138 | // 139 | // The `next_future` field is the next slot in the `futures` array that's a 140 | // `Slot::Next` variant. If it points to the end of the array then the array 141 | // is full. 142 | futures: Vec>>, 143 | next_future: usize, 144 | 145 | // Number of active futures running in the `futures` slab 146 | active: usize, 147 | 148 | // Maximum number of in-flight futures 149 | max: usize, 150 | } 151 | 152 | /// Handle to an actor, used to send messages 153 | pub struct ActorRef { 154 | tx: mpsc::Sender>, 155 | } 156 | 157 | /// Used to represent `call` errors 158 | pub enum CallError { 159 | /// The actor's inbox is full 160 | Full(T), 161 | /// The actor has shutdown 162 | Disconnected(T), 163 | /// The actor aborted processing the request for some reason 164 | Aborted, 165 | } 166 | 167 | struct Envelope { 168 | arg: T, 169 | ret: oneshot::Sender>, 170 | } 171 | 172 | struct Processing { 173 | future: ::Future, 174 | ret: Option>>, 175 | } 176 | 177 | // Stores in-flight responses 178 | enum Slot { 179 | Next(usize), 180 | Data(T), 181 | } 182 | 183 | /// Returns an `Actor` backed by the given closure. 184 | pub fn actor_fn(f: F) -> ActorFn 185 | where F: FnMut(T) -> U, 186 | U: IntoFuture, 187 | { 188 | ActorFn { 189 | f: f, 190 | _ty: PhantomData, 191 | } 192 | } 193 | 194 | /* 195 | * 196 | * ===== impl Builder ===== 197 | * 198 | */ 199 | 200 | impl Builder { 201 | /// Returns a new actor `Builder` with default settings 202 | pub fn new() -> Builder { 203 | Builder { 204 | inbox: 1024, 205 | in_flight: 16, 206 | } 207 | } 208 | 209 | /// Sets the actor's inbox queue capacity. 210 | /// 211 | /// The default value is 1024. 212 | pub fn inbox_capacity(mut self, n: usize) -> Self { 213 | self.inbox = n; 214 | self 215 | } 216 | 217 | /// Sets the max number of in-flight requests the actor can process 218 | /// concurrently. 219 | /// 220 | /// The default value is 16 221 | pub fn max_in_flight(mut self, n: usize) -> Self { 222 | self.in_flight = n; 223 | self 224 | } 225 | 226 | /// Spawn a new actor 227 | pub fn spawn(self, s: &S, actor: A) 228 | -> ActorRef 229 | where A: Actor, 230 | S: Spawn>, 231 | { 232 | let (tx, rx) = self.pair(actor); 233 | s.spawn_detached(rx); 234 | tx 235 | } 236 | 237 | /// Spawn the given closure as an actor 238 | pub fn spawn_fn(self, s: &S, f: F) 239 | -> ActorRef 240 | where F: FnMut(T) -> U, 241 | U: IntoFuture, 242 | S: Spawn>>, 243 | { 244 | self.spawn(s, actor_fn(f)) 245 | } 246 | 247 | fn pair(self, actor: A) 248 | -> (ActorRef, ActorCell) 249 | where A: Actor, 250 | { 251 | // TODO: respect inbox bound 252 | let (tx, rx) = mpsc::channel(self.inbox); 253 | 254 | let tx = ActorRef { tx: tx }; 255 | let rx = ActorCell::new(actor, rx, self.in_flight); 256 | 257 | (tx, rx) 258 | } 259 | } 260 | 261 | /* 262 | * 263 | * ===== impl ActorFn ===== 264 | * 265 | */ 266 | 267 | impl Actor for ActorFn 268 | where F: FnMut(T) -> U, 269 | U: IntoFuture, 270 | { 271 | type Request = T; 272 | type Response = U::Item; 273 | type Error = U::Error; 274 | type Future = U; 275 | 276 | fn call(&mut self, req: Self::Request) -> Self::Future { 277 | (self.f)(req) 278 | } 279 | } 280 | 281 | /* 282 | * 283 | * ===== impl ActorRef ===== 284 | * 285 | */ 286 | 287 | impl ActorRef 288 | where E: From>, 289 | { 290 | /// Returns `Async::Ready` when the actor can accept a new request 291 | pub fn poll_ready(&mut self) -> Async<()> { 292 | self.tx.poll_ready() 293 | } 294 | 295 | /// Send a request to the actor 296 | pub fn call(&mut self, request: T) -> ActorFuture { 297 | let (tx, rx) = oneshot::channel(); 298 | 299 | let envelope = Envelope { 300 | arg: request, 301 | ret: tx, 302 | }; 303 | 304 | // TODO: impl the send 305 | let state = match self.tx.start_send(envelope) { 306 | Ok(AsyncSink::Ready) => { 307 | CallState::Waiting(rx) 308 | } 309 | Ok(AsyncSink::NotReady(request)) => { 310 | let Envelope { arg, .. } = request; 311 | CallState::Error(CallError::Full(arg)) 312 | } 313 | Err(err) => { 314 | let Envelope { arg, .. } = err.into_inner(); 315 | CallState::Error(CallError::Disconnected(arg)) 316 | } 317 | }; 318 | 319 | ActorFuture { state: state } 320 | } 321 | } 322 | 323 | impl Clone for ActorRef { 324 | fn clone(&self) -> Self { 325 | ActorRef { tx: self.tx.clone() } 326 | } 327 | } 328 | 329 | /* 330 | * 331 | * ===== impl ActorFuture ===== 332 | * 333 | */ 334 | 335 | impl Future for ActorFuture 336 | where E: From>, 337 | { 338 | type Item = U; 339 | type Error = E; 340 | 341 | fn poll(&mut self) -> Poll { 342 | match self.state { 343 | CallState::Waiting(ref mut rx) => { 344 | match rx.poll() { 345 | Ok(Async::Ready(Ok(v))) => Ok(Async::Ready(v)), 346 | Ok(Async::Ready(Err(e))) => Err(e), 347 | Ok(Async::NotReady) => Ok(Async::NotReady), 348 | Err(_) => Err(CallError::Aborted.into()), 349 | } 350 | } 351 | _ => { 352 | match mem::replace(&mut self.state, CallState::Consumed) { 353 | CallState::Waiting(_) => unreachable!(), 354 | CallState::Error(e) => Err(e.into()), 355 | CallState::Consumed => panic!("polled after complete"), 356 | } 357 | } 358 | } 359 | } 360 | } 361 | 362 | /* 363 | * 364 | * ===== impl ActorCell ===== 365 | * 366 | */ 367 | 368 | impl ActorCell { 369 | fn new(actor: A, 370 | rx: mpsc::Receiver>, 371 | max_in_flight: usize) 372 | -> ActorCell 373 | { 374 | ActorCell { 375 | actor: actor, 376 | state: ActorStatePriv::Listening, 377 | rx: rx, 378 | futures: vec![], 379 | next_future: 0, 380 | active: 0, 381 | max: max_in_flight, 382 | } 383 | } 384 | 385 | fn poll_pending(&mut self) -> Async<()> { 386 | let mut ret = Async::Ready(()); 387 | 388 | // TODO: Make this less terrible :) 389 | for i in 0..self.futures.len() { 390 | // Poll the future 391 | match self.futures[i] { 392 | Slot::Data(ref mut f) => { 393 | if !f.poll().is_ready() { 394 | ret = Async::NotReady; 395 | continue; 396 | } 397 | } 398 | _ => continue, 399 | } 400 | 401 | // At this point, the future is complete, so reclaim the spot 402 | self.remove_processing(i); 403 | } 404 | 405 | ret 406 | } 407 | 408 | fn poll_actor(&mut self) -> Async<()> { 409 | if !self.state.is_running() { 410 | return Async::Ready(()); 411 | } 412 | 413 | // Poke the actor 414 | if self.actor.poll(self.state.as_pub()).is_ready() { 415 | // Shutdown the actor 416 | self.state = ActorStatePriv::Shutdown; 417 | self.rx.close(); 418 | return Async::Ready(()); 419 | } 420 | 421 | // As long as the actor can accept new messages... 422 | while self.is_call_ready() { 423 | match self.rx.poll() { 424 | Ok(Async::Ready(Some(msg))) => { 425 | let Envelope { arg, ret } = msg; 426 | let fut = self.actor.call(arg).into_future(); 427 | 428 | let mut processing = Processing { 429 | future: fut, 430 | ret: Some(ret), 431 | }; 432 | 433 | if processing.poll().is_ready() { 434 | // request done, move on to the next one 435 | continue; 436 | } 437 | 438 | self.push_processing(processing); 439 | } 440 | Ok(Async::Ready(None)) => { 441 | self.state = ActorStatePriv::Finalizing; 442 | return Async::Ready(()); 443 | } 444 | Ok(Async::NotReady) => { 445 | break; 446 | } 447 | Err(_) => { 448 | // TODO: can this happen? 449 | unimplemented!(); 450 | } 451 | } 452 | } 453 | 454 | Async::NotReady 455 | } 456 | 457 | fn is_call_ready(&mut self) -> bool { 458 | match self.state { 459 | ActorStatePriv::Listening => { 460 | self.active < self.max && self.actor.poll_ready().is_ready() 461 | } 462 | _ => false, 463 | } 464 | } 465 | 466 | fn push_processing(&mut self, processing: Processing) { 467 | debug_assert!(self.active < self.max); 468 | 469 | // If the `futures` slab is at capacity, grow by 1 470 | if self.next_future == self.futures.capacity() { 471 | debug_assert!(self.next_future < self.max); 472 | 473 | self.futures.reserve(1); 474 | self.futures.push(Slot::Next(self.next_future + 1)); 475 | } 476 | 477 | self.active += 1; 478 | 479 | match mem::replace(&mut self.futures[self.next_future], Slot::Data(processing)) { 480 | Slot::Next(next) => self.next_future = next, 481 | Slot::Data(_) => panic!(), 482 | } 483 | } 484 | 485 | fn remove_processing(&mut self, idx: usize) { 486 | self.active -= 1; 487 | self.futures[idx] = Slot::Next(self.next_future); 488 | self.next_future = idx; 489 | } 490 | } 491 | 492 | impl Future for ActorCell { 493 | type Item = (); 494 | type Error = (); 495 | 496 | fn poll(&mut self) -> Poll<(), ()> { 497 | let mut done = true; 498 | 499 | // Poll pending first futures first. This makes handling "max inflight" 500 | // simpler 501 | done &= self.poll_pending().is_ready(); 502 | done &= self.poll_actor().is_ready(); 503 | 504 | if done { 505 | debug_assert!(self.active == 0); 506 | Ok(Async::Ready(())) 507 | } else { 508 | Ok(Async::NotReady) 509 | } 510 | } 511 | } 512 | 513 | /* 514 | * 515 | * ===== impl Processing ===== 516 | * 517 | */ 518 | 519 | impl Processing { 520 | fn poll(&mut self) -> Async<()> { 521 | { 522 | // First, check to see if there is still interest on the receiving 523 | // the value 524 | let ret = self.ret.as_mut().unwrap(); 525 | 526 | if let Ok(Async::Ready(())) = ret.poll_cancel() { 527 | return Async::Ready(()); 528 | } 529 | } 530 | 531 | let ret = match self.future.poll() { 532 | Ok(Async::Ready(v)) => Ok(v), 533 | Ok(Async::NotReady) => return Async::NotReady, 534 | Err(e) => Err(e), 535 | }; 536 | 537 | self.ret.take().expect("return channel already consumed") 538 | .complete(ret); 539 | 540 | Async::Ready(()) 541 | } 542 | } 543 | 544 | /* 545 | * 546 | * ===== impl ActorStatePriv ===== 547 | * 548 | */ 549 | 550 | impl ActorStatePriv { 551 | fn is_running(&self) -> bool { 552 | match *self { 553 | ActorStatePriv::Shutdown => false, 554 | _ => true, 555 | } 556 | } 557 | 558 | fn as_pub(&self) -> ActorState { 559 | match *self { 560 | ActorStatePriv::Listening => ActorState::Listening, 561 | _ => ActorState::Finalizing, 562 | } 563 | } 564 | } 565 | 566 | /* 567 | * 568 | * ===== impl From ===== 569 | * 570 | */ 571 | 572 | impl From> for () { 573 | fn from(_: CallError) -> () { 574 | } 575 | } 576 | 577 | impl From> for ::std::io::Error { 578 | fn from(src: CallError) -> ::std::io::Error { 579 | use std::io; 580 | 581 | match src { 582 | CallError::Full(..) => io::Error::new(io::ErrorKind::Other, "actor inbox full"), 583 | CallError::Disconnected(..) => io::Error::new(io::ErrorKind::Other, "actor shutdown"), 584 | CallError::Aborted => io::Error::new(io::ErrorKind::Other, "actor aborted request"), 585 | } 586 | } 587 | } 588 | -------------------------------------------------------------------------------- /tests/test_actor.rs: -------------------------------------------------------------------------------- 1 | extern crate futures; 2 | extern crate tokio_core; 3 | extern crate kabuki; 4 | 5 | use futures::Future; 6 | use tokio_core::reactor; 7 | 8 | use std::sync::mpsc; 9 | use std::thread; 10 | use std::time::Duration; 11 | 12 | #[test] 13 | fn simple_request_response() { 14 | let mut core = reactor::Core::new().unwrap(); 15 | 16 | let mut tx = kabuki::Builder::new() 17 | .spawn_fn(&core.handle(), |msg| { 18 | assert_eq!(msg, "ping"); 19 | Ok::<&'static str, ()>("pong") 20 | }); 21 | 22 | let resp = tx.call("ping"); 23 | let resp = core.run(resp).unwrap(); 24 | 25 | assert_eq!("pong", resp); 26 | } 27 | 28 | #[test] 29 | fn multiple_request_response() { 30 | let mut core = reactor::Core::new().unwrap(); 31 | let (ch_tx, rx) = mpsc::channel(); 32 | 33 | let mut tx = kabuki::Builder::new() 34 | .spawn_fn(&core.handle(), move |msg| { 35 | ch_tx.send(msg).unwrap(); 36 | Ok::<&'static str, ()>("pong") 37 | }); 38 | 39 | let resp = tx.call("ping 1"); 40 | let resp = core.run(resp).unwrap(); 41 | 42 | assert_eq!("pong", resp); 43 | assert_eq!("ping 1", rx.recv().unwrap()); 44 | 45 | let resp = tx.call("ping 2"); 46 | let resp = core.run(resp).unwrap(); 47 | 48 | assert_eq!("pong", resp); 49 | assert_eq!("ping 2", rx.recv().unwrap()); 50 | } 51 | 52 | #[test] 53 | fn actor_ref_is_clone_and_send() { 54 | let mut core = reactor::Core::new().unwrap(); 55 | 56 | let mut tx = kabuki::Builder::new() 57 | .spawn_fn(&core.handle(), |msg| { 58 | Ok::<&'static str, ()>(msg) 59 | }); 60 | 61 | let th = { 62 | let mut tx = tx.clone(); 63 | thread::spawn(move || { 64 | tx.call("ping 1").wait().unwrap() 65 | }) 66 | }; 67 | 68 | thread::sleep(Duration::from_millis(100)); 69 | 70 | let resp = tx.call("ping 2"); 71 | let resp = core.run(resp).unwrap(); 72 | 73 | assert_eq!("ping 2", resp); 74 | assert_eq!("ping 1", th.join().unwrap()); 75 | } 76 | --------------------------------------------------------------------------------