Skip to content

Commit

Permalink
New approach to dependency injection for 1.x
Browse files Browse the repository at this point in the history
  • Loading branch information
Diggsey committed Jul 1, 2023
1 parent e94a833 commit f8ebe14
Show file tree
Hide file tree
Showing 17 changed files with 840 additions and 822 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/toolchain.yml
Original file line number Diff line number Diff line change
Expand Up @@ -66,14 +66,14 @@ jobs:
args: --all-features

test_minimum:
name: Test (1.35.0)
name: Test (1.70.0)
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions-rs/toolchain@v1
with:
profile: minimal
toolchain: 1.35.0
toolchain: 1.70.0
override: true
- uses: actions-rs/cargo@v1
with:
Expand Down
21 changes: 17 additions & 4 deletions Cargo.toml
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"] }
10 changes: 0 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,3 @@
Simple dependency injection for Rust

[Documentation](https://docs.rs/aerosol/)

The two main exports of this crate are the `define_context!` and `define_interface!` macros.

Contexts are containers for multiple dependencies, allowing them to be passed around as one with relative ease. Interfaces are specialized traits which place constraints on contexts, indicating exactly what dependencies a context must provide.

Contexts are typically created at the top level of an application, as they specify exactly what concrete versions of all dependencies are going to be used. A single context is created with a precise set of depenencies, and is then threaded through the rest of the application as a generic parameter.

Interfaces are used at every level of an application, as they allow each piece of code to independently specify what dependencies are required. Interfaces can "inherit" the dependencies of other interfaces, with the idea being that this inheritance will form a tree, such that there will be some "root interface" which contains the union of all dependencies required by the whole application.

This pattern allows dependencies to be added or removed from any part of the application without having to modify the code at every level, to thread or un-thread the new or old dependencies through.
86 changes: 86 additions & 0 deletions src/async_.rs
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);
}
}
189 changes: 189 additions & 0 deletions src/async_constructible.rs
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;
}));
}
}
}
Loading

0 comments on commit f8ebe14

Please sign in to comment.