-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
New approach to dependency injection for 1.x
- Loading branch information
Showing
17 changed files
with
840 additions
and
822 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,12 +1,25 @@ | ||
[package] | ||
name = "aerosol" | ||
version = "0.3.0" | ||
version = "1.0.0-alpha.1" | ||
authors = ["Diggory Blake <diggsey@googlemail.com>"] | ||
edition = "2018" | ||
description = "Dependency injection with compile-time guarantees" | ||
description = "Simple dependency injection for Rust" | ||
repository = "https://github.com/Diggsey/aerosol" | ||
license = "MIT OR Apache-2.0" | ||
|
||
[features] | ||
default = [] | ||
async = ["async-trait"] | ||
axum = ["dep:axum", "async", "tracing", "thiserror", "anyhow"] | ||
|
||
[dependencies] | ||
tt-call = "1.0" | ||
anyhow = "1" | ||
parking_lot = "0.12.1" | ||
anymap = { version = "1.0.0-beta.2", features = ["hashbrown"] } | ||
async-trait = { version = "0.1", optional = true } | ||
axum = { version = "0.6", optional = true } | ||
tracing = { version = "0.1", optional = true } | ||
thiserror = { version = "1.0", optional = true } | ||
anyhow = { version = "1.0", optional = true } | ||
|
||
[dev-dependencies] | ||
tokio = { version = "1.0", features = ["macros"] } |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,86 @@ | ||
use std::{ | ||
future::Future, | ||
marker::PhantomData, | ||
pin::Pin, | ||
task::{Context, Poll}, | ||
}; | ||
|
||
use crate::{ | ||
resource::{unwrap_resource, Resource}, | ||
slot::SlotDesc, | ||
state::Aerosol, | ||
}; | ||
|
||
pub(crate) struct WaitForSlot<T: Resource> { | ||
state: Aerosol, | ||
wait_index: Option<usize>, | ||
insert_placeholder: bool, | ||
phantom: PhantomData<fn() -> T>, | ||
} | ||
|
||
impl<T: Resource> Future for WaitForSlot<T> { | ||
type Output = Option<T>; | ||
|
||
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { | ||
let this = self.get_mut(); | ||
this.state | ||
.poll_for_slot(&mut this.wait_index, || cx.waker(), this.insert_placeholder) | ||
} | ||
} | ||
|
||
impl Aerosol { | ||
pub(crate) fn wait_for_slot_async<T: Resource>( | ||
&self, | ||
insert_placeholder: bool, | ||
) -> WaitForSlot<T> { | ||
WaitForSlot { | ||
state: self.clone(), | ||
wait_index: None, | ||
insert_placeholder, | ||
phantom: PhantomData, | ||
} | ||
} | ||
/// Tries to get an instance of `T` from the AppState. Returns `None` if there is no such instance. | ||
/// This function does not attempt to construct `T` if it does not exist. | ||
pub async fn try_get_async<T: Resource>(&self) -> Option<T> { | ||
match self.try_get_slot()? { | ||
SlotDesc::Filled(x) => Some(x), | ||
SlotDesc::Placeholder => self.wait_for_slot_async::<T>(false).await, | ||
} | ||
} | ||
/// Get an instance of `T` from the AppState, and panic if not found. | ||
/// This function does not attempt to construct `T` if it does not exist. | ||
pub async fn get_async<T: Resource>(&self) -> T { | ||
unwrap_resource(self.try_get_async().await) | ||
} | ||
} | ||
|
||
#[cfg(test)] | ||
mod tests { | ||
use super::*; | ||
|
||
#[tokio::test] | ||
async fn get_with() { | ||
let state = Aerosol::new().with(42); | ||
assert_eq!(state.get_async::<i32>().await, 42); | ||
} | ||
|
||
#[tokio::test] | ||
async fn get_inserted() { | ||
let state = Aerosol::new(); | ||
state.insert(42); | ||
assert_eq!(state.get_async::<i32>().await, 42); | ||
} | ||
|
||
#[tokio::test] | ||
async fn try_get_some() { | ||
let state = Aerosol::new().with(42); | ||
assert_eq!(state.try_get_async::<i32>().await, Some(42)); | ||
} | ||
|
||
#[tokio::test] | ||
async fn try_get_none() { | ||
let state = Aerosol::new().with("Hello"); | ||
assert_eq!(state.try_get_async::<i32>().await, None); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,189 @@ | ||
use std::error::Error; | ||
|
||
use async_trait::async_trait; | ||
|
||
use crate::{ | ||
resource::{unwrap_constructed, Resource}, | ||
slot::SlotDesc, | ||
state::Aerosol, | ||
ConstructibleResource, | ||
}; | ||
|
||
/// Implemented for resources which can be constructed asynchronously from other | ||
/// resources. Requires feature `async`. | ||
#[async_trait] | ||
pub trait AsyncConstructibleResource: Resource { | ||
/// Error type for when resource fails to be constructed. | ||
type Error: Error + Send + Sync; | ||
/// Construct the resource with the provided application state. | ||
async fn construct_async(aero: &Aerosol) -> Result<Self, Self::Error>; | ||
} | ||
|
||
#[async_trait] | ||
impl<T: ConstructibleResource> AsyncConstructibleResource for T { | ||
type Error = <T as ConstructibleResource>::Error; | ||
async fn construct_async(aero: &Aerosol) -> Result<Self, Self::Error> { | ||
Self::construct(aero) | ||
} | ||
} | ||
|
||
impl Aerosol { | ||
/// Try to get or construct an instance of `T` asynchronously. Requires feature `async`. | ||
pub async fn try_obtain_async<T: AsyncConstructibleResource>(&self) -> Result<T, T::Error> { | ||
match self.try_get_slot() { | ||
Some(SlotDesc::Filled(x)) => Ok(x), | ||
Some(SlotDesc::Placeholder) | None => match self.wait_for_slot_async::<T>(true).await { | ||
Some(x) => Ok(x), | ||
None => match T::construct_async(self).await { | ||
Ok(x) => { | ||
self.fill_placeholder::<T>(x.clone()); | ||
Ok(x) | ||
} | ||
Err(e) => { | ||
self.clear_placeholder::<T>(); | ||
Err(e) | ||
} | ||
}, | ||
}, | ||
} | ||
} | ||
/// Get or construct an instance of `T` asynchronously. Panics if unable. Requires feature `async`. | ||
pub async fn obtain_async<T: AsyncConstructibleResource>(&self) -> T { | ||
unwrap_constructed(self.try_obtain_async::<T>().await) | ||
} | ||
} | ||
|
||
#[cfg(test)] | ||
mod tests { | ||
use std::{convert::Infallible, time::Duration}; | ||
|
||
use super::*; | ||
|
||
#[derive(Debug, Clone)] | ||
struct Dummy; | ||
|
||
#[async_trait] | ||
impl AsyncConstructibleResource for Dummy { | ||
type Error = Infallible; | ||
|
||
async fn construct_async(_app_state: &Aerosol) -> Result<Self, Self::Error> { | ||
tokio::time::sleep(Duration::from_millis(100)).await; | ||
Ok(Self) | ||
} | ||
} | ||
|
||
#[tokio::test] | ||
async fn obtain() { | ||
let state = Aerosol::new(); | ||
state.obtain_async::<Dummy>().await; | ||
} | ||
|
||
#[tokio::test] | ||
async fn obtain_race() { | ||
let state = Aerosol::new(); | ||
let mut handles = Vec::new(); | ||
for _ in 0..100 { | ||
let state = state.clone(); | ||
handles.push(tokio::spawn(async move { | ||
state.obtain_async::<Dummy>().await; | ||
})); | ||
} | ||
for handle in handles { | ||
handle.await.unwrap(); | ||
} | ||
} | ||
|
||
#[derive(Debug, Clone)] | ||
struct DummyRecursive; | ||
|
||
#[async_trait] | ||
impl AsyncConstructibleResource for DummyRecursive { | ||
type Error = Infallible; | ||
|
||
async fn construct_async(aero: &Aerosol) -> Result<Self, Self::Error> { | ||
aero.obtain_async::<Dummy>().await; | ||
Ok(Self) | ||
} | ||
} | ||
|
||
#[tokio::test] | ||
async fn obtain_recursive() { | ||
let state = Aerosol::new(); | ||
state.obtain_async::<DummyRecursive>().await; | ||
} | ||
|
||
#[tokio::test] | ||
async fn obtain_recursive_race() { | ||
let state = Aerosol::new(); | ||
let mut handles = Vec::new(); | ||
for _ in 0..100 { | ||
let state = state.clone(); | ||
handles.push(tokio::spawn(async move { | ||
state.obtain_async::<DummyRecursive>().await; | ||
})); | ||
} | ||
} | ||
|
||
#[derive(Debug, Clone)] | ||
struct DummyCyclic; | ||
|
||
#[async_trait] | ||
impl AsyncConstructibleResource for DummyCyclic { | ||
type Error = Infallible; | ||
|
||
async fn construct_async(aero: &Aerosol) -> Result<Self, Self::Error> { | ||
aero.obtain_async::<DummyCyclic>().await; | ||
Ok(Self) | ||
} | ||
} | ||
|
||
#[tokio::test] | ||
#[should_panic(expected = "Cycle detected")] | ||
async fn obtain_cyclic() { | ||
let state = Aerosol::new(); | ||
state.obtain_async::<DummyCyclic>().await; | ||
} | ||
|
||
#[derive(Debug, Clone)] | ||
struct DummySync; | ||
|
||
impl ConstructibleResource for DummySync { | ||
type Error = Infallible; | ||
|
||
fn construct(_app_state: &Aerosol) -> Result<Self, Self::Error> { | ||
std::thread::sleep(Duration::from_millis(100)); | ||
Ok(Self) | ||
} | ||
} | ||
|
||
#[derive(Debug, Clone)] | ||
struct DummySyncRecursive; | ||
|
||
#[async_trait] | ||
impl AsyncConstructibleResource for DummySyncRecursive { | ||
type Error = Infallible; | ||
|
||
async fn construct_async(aero: &Aerosol) -> Result<Self, Self::Error> { | ||
aero.obtain_async::<DummySync>().await; | ||
Ok(Self) | ||
} | ||
} | ||
|
||
#[tokio::test] | ||
async fn obtain_sync_recursive() { | ||
let state = Aerosol::new(); | ||
state.obtain_async::<DummySyncRecursive>().await; | ||
} | ||
|
||
#[tokio::test] | ||
async fn obtain_sync_recursive_race() { | ||
let state = Aerosol::new(); | ||
let mut handles = Vec::new(); | ||
for _ in 0..100 { | ||
let state = state.clone(); | ||
handles.push(tokio::spawn(async move { | ||
state.obtain_async::<DummySyncRecursive>().await; | ||
})); | ||
} | ||
} | ||
} |
Oops, something went wrong.