Trait spirit::extension::Extensible [−][src]
pub trait Extensible: Sized {
type Opts;
type Config;
type Ok;
const STARTED: bool;
Show 14 methods
fn before_config<F>(self, cback: F) -> Result<Self::Ok, AnyError>
where
F: FnOnce(&Self::Config, &Self::Opts) -> Result<(), AnyError> + Send + 'static;
fn config_validator<F>(self, f: F) -> Result<Self::Ok, AnyError>
where
F: FnMut(&Arc<Self::Config>, &Arc<Self::Config>, &Self::Opts) -> Result<Action, AnyError> + Send + 'static;
fn config_mutator<F>(self, f: F) -> Self
where
F: FnMut(&mut Self::Config) + Send + 'static;
fn on_config<F>(self, hook: F) -> Self
where
F: FnMut(&Self::Opts, &Arc<Self::Config>) + Send + 'static;
fn on_signal<F>(self, signal: c_int, hook: F) -> Result<Self::Ok, AnyError>
where
F: FnMut() + Send + 'static;
fn on_terminate<F>(self, hook: F) -> Self
where
F: FnOnce() + Send + 'static;
fn run_before<B>(self, body: B) -> Result<Self::Ok, AnyError>
where
B: FnOnce(&Arc<Spirit<Self::Opts, Self::Config>>) -> Result<(), AnyError> + Send + 'static;
fn run_around<W>(self, wrapper: W) -> Result<Self::Ok, AnyError>
where
W: FnOnce(&Arc<Spirit<Self::Opts, Self::Config>>, Box<dyn FnOnce() -> Result<(), AnyError> + Send>) -> Result<(), AnyError> + Send + 'static;
fn around_hooks<W>(self, wrapper: W) -> Self
where
W: HookWrapper;
fn with<E>(self, ext: E) -> Result<Self::Ok, AnyError>
where
E: Extension<Self::Ok>;
fn singleton<T: 'static>(&mut self) -> bool;
fn with_singleton<T>(self, singleton: T) -> Result<Self::Ok, AnyError>
where
T: Extension<Self::Ok> + 'static;
fn keep_guard<G: Any + Send>(self, guard: G) -> Self;
fn autojoin_bg_thread(self, autojoin: Autojoin) -> Self;
}
Expand description
An interface allowing to extend something with callbacks.
This describes the interface to registering various callbacks. This unifies the interaction
with Builder
and Spirit
, so there’s little difference between registering a callback
when setting things up and when everything is already running (but see notes at various
methods, sometimes there are subtle differences ‒ specifically, it is not possible to do some
things when the application already started).
In addition, this is also implemented on Result<Extensible, AnyError>
. This allows the caller
to postpone all error handling for later or even leave it up to the
Builder::run
to handle them.
Deadlocks
In general, it is not possible to register callbacks from within callbacks. Internally, the structures holding them are protected by a mutex which needs to be locked both when manipulating and running them. Such attempt to register a callback from within a callback will lead to a deadlock (this restriction might be lifted in the future).
Examples
use spirit::{Empty, Spirit};
use spirit::prelude::*;
// This creates a Builder
Spirit::<Empty, Empty>::new()
// This returns Result<Builder, AnyError>. But we don't handle the error here, it propagates
// further in the call chain.
.run_before(|_spirit| Ok(()))
// This run_before is on the Result<Builder, AnyError>. If the first one returned an error,
// nothing would happen and the error would thread on. So, this works like implicit .and_then,
// but without the inconvenience.
//
// (This also returns Result<Builder, AnyError>, not Result<Result<Builder, AnyError>,
// AnyError>). .run_before(|_spirit| Ok(()))
//
// This .run can handle both the errors from above and from inside, logging them and
// terminating if they happen.
.run(|spirit| {
// And this callback is registered onto the Spirit. Here, the run_before is started
// right away.
//
// Here it is more convenient to just propagate the error, because the .run will handle
// it.
spirit.run_before(|_spirit| Ok(()))?;
Ok(())
});
Associated Types
The command line options structure tied to this instance.
A lot of the callbacks take command line structure as specified by the caller. This makes the type available for users of the trait.
The configuration structure.
Similar to Opts
, this makes the type used to load configuration
available to the users of the trait.
Associated Constants
Required methods
A callback that is run after the building started and the command line is parsed, but even
before the first configuration is loaded. The configuration provided is either the one
provided to the builder, or a default one when called on the builder, but current
configuration when run on Spirit
.
This is run right away if called on Spirit
, unless it is already terminated. In such
case, the callback is dropped.
Adds another config validator to the chain.
The validators are there to check and possibly refuse a newly loaded configuration.
The callback is passed three parameters:
- The old configuration.
- The new configuration.
- The command line options.
The new configuration is handled in this order:
- First, config mutators are called (in order of their registration).
- Then all the config validators are called, in order of their registration. If any of them fails, the configuration is refused and failure actions returned by the successful validators are run.
- If successful, the success actions returned by validators are run.
- New configuration is stored.
- Config hooks are called, in order of registration.
The actions
Sometimes, the only way to validate a piece of config is to try it out ‒ like when you want to open a listening socket, you don’t know if the port is free. But you can’t activate and apply just yet, because something further down the configuration might still fail.
So, you open the socket (or create an error result) and store it into the success action to apply it later on. If something fails, the action is dropped and the socket closed.
The failure action lets you roll back (if it isn’t done by simply dropping the thing).
If the validation and application steps can be separated (you can check if something is OK
by just „looking“ at it ‒ like with a regular expression and using it can’t fail), you
don’t have to use them, just use verification and on_config
separately.
If called on the already started Spirit
, it is run right away. If it is
called on terminated one, it is dropped.
Examples
TODO
fn config_mutator<F>(self, f: F) -> Self where
F: FnMut(&mut Self::Config) + Send + 'static,
fn config_mutator<F>(self, f: F) -> Self where
F: FnMut(&mut Self::Config) + Send + 'static,
Adds a callback able to mutate the configuration while being loaded.
Config mutators are run (in order of their registration) before config validators and allow the callback to modify the configuration. Note that by the time it is called it is not yet determined if this configuration is valid. A config mutator should not use the configuration in any way, only tweak it (and possibly warn about having done so), but the tweaked configuration should be used by something else down the line.
If run on an already started Spirit
, this only registers the callback
but doesn’t call it. If run on terminated one, it is dropped.
Adds a callback for notification about new configurations.
The callback is called once a new configuration is loaded and successfully validated, so it can be directly used.
It is run right away on a started Spirit
, but it is dropped if it was
already terminated.
Adds a callback for reacting to a signal.
The Spirit
reacts to some signals itself, in its own service
thread. However, it is also possible to hook into any signals directly (well, any except
the ones that are [off limits][signal_hook::consts::FORBIDDEN]).
These are not run inside the real signal handler, but are delayed and run in the service thread. Therefore, restrictions about async-signal-safety don’t apply to the hook.
It is dropped if called on already terminated spirit.
Panics
This may panic in case the application runs without the background signal thread. See
SpiritBuilder::build
.
TODO: Threads, deadlocks
fn on_terminate<F>(self, hook: F) -> Self where
F: FnOnce() + Send + 'static,
fn on_terminate<F>(self, hook: F) -> Self where
F: FnOnce() + Send + 'static,
Adds a callback executed once the Spirit
decides to terminate.
This is called either when someone calls terminate
or when a termination signal is received.
Note that there are ways the application may terminate without calling these hooks ‒ for example terminating the main thread, or aborting.
If called on already started and terminated Spirit
, it is run right away.
Add a closure run before the main body.
The run
will first execute all closures submitted through
this method before running the real body. They are run in the order of registration.
The purpose of this is mostly integration with extensions ‒ they often need some last minute preparation.
In case of using only build
, the bodies are composed into
one object and returned as part of the App
.
If called on an already started Spirit
, it is run immediately and any
error returned from it is propagated.
If submitted to the Builder
, the first body to fail terminates the
processing and further bodies (including the main one) are skipped.
Examples
Spirit::<Empty, Empty>::new()
.run_before(|_spirit| {
println!("Run first");
Ok(())
}).run(|_spirit| {
println!("Run second");
Ok(())
});
Wrap the body run by the run
into this closure.
It is expected the wrapper executes the inner body as part of itself and propagates any returned error.
In case of multiple wrappers, the ones submitted later on are placed inside the sooner ones ‒ the first one is the outermost.
In case of using only build
, all the wrappers composed
together are returned as part of the result.
Panics
If called on the already started crate::Spirit
, this panics. It is part of the
interface to make it possible to write extensions that register a body wrapper as part of
an singleton, but assume the singleton would be plugged in by the time it is already
started.
Examples
Spirit::<Empty, Empty>::new()
.run_around(|_spirit, inner| {
println!("Run first");
inner()?;
println!("Run third");
Ok(())
}).run(|_spirit| {
println!("Run second");
Ok(())
});
fn around_hooks<W>(self, wrapper: W) -> Self where
W: HookWrapper,
fn around_hooks<W>(self, wrapper: W) -> Self where
W: HookWrapper,
Wrap the hooks inside the provided closure.
This is in a sense similar to the principle of run_around
, but
for all the hooks that are plugged into the spirit and run in the spirit thread. The other
difference is, these may be run multiple times (eg. there may be multiple enters and leaves
of the wrappers).
- This is run during the initial configuration load from
build
. - This is run during configuration reloading and signal handling from the background thread.
- If a new one is added to an already configured and running spirit, it’ll become effective during the next event handled by the background thread.
- This is not run as part of the/around the usual
run
(it is run as part of the initial configuration loading, but not around the actual application body; that one has its ownrun_around
). - This is not run as part of user-invoked methods such as
config_reload
.
This is meant to set up global/thread local context for the hooks in a similar way as
run_around
is for the application itself. It is expected
similar setup will go into both in case the context is needed not only for the application,
but for the callbacks/hooks/pipelines.
Same as with run_around
, later submitted wrappers are inserted
inside the older ones.
Expected functionality
- The wrapper is a function/closure of the form
FnMut(Box<dyn FnOnce() + '_>)
. That is, it is passed an inner closure without parameters or return value. The lifetime of the inner closure may be arbitrarily short (it’s impossible to store it for later). - The wrapper must call the inner closure. Failing to call it will lead to panics during runtime.
- The wrapper must be prepared to survive a panic from the inner body. It may be called again even after such panic happened.
Warning
- Calling this from within a callback might cause a deadlock.
- These are not dropped at
terminate
, like most other callbacks.
Apply an Extension
.
An extension is allowed to register arbitrary amount of callbacks.
Check if this is the first call with the given type.
Some helpers share common part. This common part makes sense to register just once, so this
can be used to check that. The first call with given type returns true
, any future ones
with the same type return false
.
The method has no direct effect on the future spirit constructed from the builder and works only as a note for future helpers that want to manipulate the builder.
A higher-level interface is the with_singleton
method.
Singletons registered into a Builder
are then inherited into the
Spirit
, therefore they can be registered once during the whole lifetime.
Examples
use spirit::{Empty, Spirit};
use spirit::prelude::*;
let mut builder = Spirit::<Empty, Empty>::new();
struct X;
struct Y;
assert!(builder.singleton::<X>());
assert!(!builder.singleton::<X>());
assert!(builder.singleton::<Y>());
Applies the first Extension
of the same type.
This applies the passed extension, but only if an extension with the type same hasn’t yet
been applied (or the singleton
called manually).
Note that different instances of the same type of an extension can act differently, but are
still considered the same type. This means the first instance wins. This is considered a
feature ‒ many other extensions need some environment to run in (like tokio
runtime). The
extensions try to apply a default configuration, but the user can apply a specific
configuration first.
fn keep_guard<G: Any + Send>(self, guard: G) -> Self
fn keep_guard<G: Any + Send>(self, guard: G) -> Self
Keeps a guard object until destruction.
Sometimes, some things (like, a logger that needs flushing, metrics collector handle) need
a guard that is destroyed at the end of application lifetime. However, the run
body
may terminate sooner than the application, therefore destroying the guards too soon.
By passing the ownership to Spirit
, the guard is destroyed together with the Spirit
itself.
Note that you may need to wait for the background thread or autojoin it.
The guards can be only added (there’s no way to remove or overwrite them later on).
fn autojoin_bg_thread(self, autojoin: Autojoin) -> Self
fn autojoin_bg_thread(self, autojoin: Autojoin) -> Self
Specifies if and when the background thread should be joined automatically.
The default is to terminate and autojoin at the end of the run
method.