mptc/
lib.rs

1#![forbid(unsafe_code)]
2
3pub mod server;
4pub mod signals;
5pub mod worker;
6
7pub use server::Server;
8
9/// How often does each component wake and check for shutdown, reload,
10/// etc. signals.
11pub const SIGNAL_POLL_INTERVAL: u64 = 3;
12
13/// Default minimum number of worker threads.
14pub const DEFAULT_MIN_WORKERS: usize = 5;
15
16/// Default maximum number of worker threads.
17pub const DEFAULT_MAX_WORKERS: usize = 256;
18
19/// Default maximum number of worker threads.
20pub const DEFAULT_MAX_WORKER_REQUESTS: usize = 1000;
21
22/// Default minimum number of idle workers to maintain.
23const DEFAULT_MIN_IDLE_WORKERS: usize = 1;
24
25/// By default, a worker will exit once it has handled this many requests.
26///
27/// A value of 0 means there is no max.
28pub const DEFAULT_MAX_WORKER_REQS: usize = 10_000;
29
30/// Models a single request to be passed to a worker for handling.
31pub trait Request: Send + std::any::Any {
32    /// Needed for downcasting a generic Request into the
33    /// specific type used by the implementor.
34    /// Example: fn as_any_mut(&mut self) -> &mut dyn Any { self }
35    fn as_any_mut(&mut self) -> &mut dyn std::any::Any;
36}
37
38/// Trait implemented by code that wishes to handle requests.
39pub trait RequestHandler: Send {
40    /// Called from within each worker thread just after spawning.
41    fn worker_start(&mut self) -> Result<(), String> {
42        Ok(())
43    }
44
45    /// Called from within each worker thread just before the thread exits.
46    fn worker_end(&mut self) -> Result<(), String> {
47        Ok(())
48    }
49
50    /// Process a single request.
51    ///
52    /// Returns Err of String if request processing failed.  The error
53    /// string will be logged.
54    fn process(&mut self, request: Box<dyn Request>) -> Result<(), String>;
55}
56
57pub trait RequestStream {
58    /// Returns the next incoming request in the stream.
59    ///
60    /// If the implementer wants the main server to periodically check
61    /// for signals, apply timeout logic in the implementation for
62    /// next() and simply return Ok(None) after waking and having
63    /// nothing to process.
64    fn next(&mut self) -> Result<Option<Box<dyn Request>>, String>;
65
66    /// Factory for creating new RequestHandler instances.
67    fn new_handler(&mut self) -> Box<dyn RequestHandler>;
68
69    /// Reload configuration data.
70    ///
71    /// If the RequestStream cannot reload, it should revert to its
72    /// previous state and continue functioning.  It should only return
73    /// an Err() if it cannot proceed.
74    /// SIGHUP
75    fn reload(&mut self) -> Result<(), String> {
76        Ok(())
77    }
78
79    /// Graceful shutdown request (SIGINT)
80    fn shutdown(&mut self) {}
81}