//! # Function tasks
//!
//! This module contains the trait definitions and implementations that are
//! necessary for accepting functions as tasks when using the
//! `turbo_tasks::function` macro.
//!
//! This system is inspired by Bevy's Systems and Axum's Handlers.
//!
//! The original principle is somewhat simple: a function is accepted if all
//! of its arguments implement `TaskInput` and its return type implements
//! `TaskOutput`. There are a few hoops one needs to jump through to make this
//! work, but they are described in this blog post:
//!
//!
//! However, there is an additional complication in our case: async methods
//! that accept a reference to the receiver as their first argument.
//!
//! This complication handled through our own version of the `async_trait`
//! crate, which allows us to target `async fn` as trait bounds. The naive
//! approach runs into many issues with lifetimes, hence the need for an
//! intermediate trait. However, this implementation doesn't support all async
//! methods (see commented out tests).
use std::{future::Future, marker::PhantomData, pin::Pin};
use anyhow::Result;
use super::{TaskInput, TaskOutput};
use crate::{RawVc, Vc, VcRead, VcValueType, magic_any::MagicAny};
pub type NativeTaskFuture = Pin> + Send>>;
pub trait TaskFn: Send + Sync + 'static {
fn functor(&self, this: Option, arg: &dyn MagicAny) -> Result;
}
pub trait IntoTaskFn {
type TaskFn: TaskFn;
fn into_task_fn(self) -> Self::TaskFn;
}
impl IntoTaskFn for F
where
F: TaskFnInputFunction,
Mode: TaskFnMode,
Inputs: TaskInputs,
{
type TaskFn = FunctionTaskFn;
fn into_task_fn(self) -> Self::TaskFn {
FunctionTaskFn {
task_fn: self,
mode: PhantomData,
inputs: PhantomData,
}
}
}
pub trait IntoTaskFnWithThis {
type TaskFn: TaskFn;
fn into_task_fn_with_this(self) -> Self::TaskFn;
}
impl IntoTaskFnWithThis for F
where
F: TaskFnInputFunctionWithThis,
Mode: TaskFnMode,
This: Sync + Send + 'static,
Inputs: TaskInputs,
{
type TaskFn = FunctionTaskFnWithThis;
fn into_task_fn_with_this(self) -> Self::TaskFn {
FunctionTaskFnWithThis {
task_fn: self,
mode: PhantomData,
this: PhantomData,
inputs: PhantomData,
}
}
}
pub struct FunctionTaskFn {
task_fn: F,
mode: PhantomData,
inputs: PhantomData,
}
impl TaskFn for FunctionTaskFn
where
F: TaskFnInputFunction,
Mode: TaskFnMode,
Inputs: TaskInputs,
{
fn functor(&self, _this: Option, arg: &dyn MagicAny) -> Result {
TaskFnInputFunction::functor(&self.task_fn, arg)
}
}
pub struct FunctionTaskFnWithThis<
F,
Mode: TaskFnMode,
This: Sync + Send + 'static,
Inputs: TaskInputs,
> {
task_fn: F,
mode: PhantomData,
this: PhantomData,
inputs: PhantomData,
}
impl TaskFn for FunctionTaskFnWithThis
where
F: TaskFnInputFunctionWithThis,
Mode: TaskFnMode,
This: Sync + Send + 'static,
Inputs: TaskInputs,
{
fn functor(&self, this: Option, arg: &dyn MagicAny) -> Result {
let Some(this) = this else {
panic!("Method needs a `self` argument");
};
TaskFnInputFunctionWithThis::functor(&self.task_fn, this, arg)
}
}
trait TaskFnInputFunction: Send + Sync + Clone + 'static {
fn functor(&self, arg: &dyn MagicAny) -> Result;
}
trait TaskFnInputFunctionWithThis:
Send + Sync + Clone + 'static
{
fn functor(&self, this: RawVc, arg: &dyn MagicAny) -> Result;
}
pub trait TaskInputs: Send + Sync + 'static {}
/// Modes to allow multiple `TaskFnInputFunction` blanket implementations on
/// `Fn`s. Even though the implementations are non-conflicting in practice, they
/// could be in theory (at least from with the compiler's current limitations).
/// Despite this, the compiler is still able to infer the correct mode from a
/// function.
pub trait TaskFnMode: Send + Sync + 'static {}
pub struct FunctionMode;
impl TaskFnMode for FunctionMode {}
pub struct AsyncFunctionMode;
impl TaskFnMode for AsyncFunctionMode {}
pub struct MethodMode;
impl TaskFnMode for MethodMode {}
pub struct AsyncMethodMode;
impl TaskFnMode for AsyncMethodMode {}
macro_rules! task_inputs_impl {
( $( $arg:ident )* ) => {
impl<$($arg,)*> TaskInputs for ($($arg,)*)
where
$($arg: TaskInput + 'static,)*
{}
}
}
/// Downcast, and clone all the arguments in the singular `arg` tuple.
///
/// This helper function for `task_fn_impl!()` reduces the amount of code inside the macro, and
/// gives the compiler more chances to dedupe monomorphized code across small functions with less
/// typevars.
fn get_args(arg: &dyn MagicAny) -> Result {
let value = arg.downcast_ref::().cloned();
#[cfg(debug_assertions)]
return anyhow::Context::with_context(value, || {
crate::native_function::debug_downcast_args_error_msg(std::any::type_name::(), arg)
});
#[cfg(not(debug_assertions))]
return anyhow::Context::context(value, "Invalid argument type");
}
// Helper function for `task_fn_impl!()`
async fn output_try_into_non_local_raw_vc(output: impl TaskOutput) -> Result {
// TODO: Potential future optimization: If we know we're inside a local task, we can avoid
// calling `to_non_local()` here, which might let us avoid constructing a non-local cell for the
// local task's return value. Flattening chains of `RawVc::LocalOutput` may still be useful to
// reduce traversal later.
output.try_into_raw_vc()?.to_non_local().await
}
macro_rules! task_fn_impl {
( $async_fn_trait:ident $arg_len:literal $( $arg:ident )* ) => {
impl TaskFnInputFunction for F
where
$($arg: TaskInput + 'static,)*
F: Fn($($arg,)*) -> Output + Send + Sync + Clone + 'static,
Output: TaskOutput + 'static,
{
#[allow(non_snake_case)]
fn functor(&self, arg: &dyn MagicAny) -> Result {
let task_fn = self.clone();
let ($($arg,)*) = get_args::<($($arg,)*)>(arg)?;
Ok(Box::pin(async move {
let output = (task_fn)($($arg,)*);
output_try_into_non_local_raw_vc(output).await
}))
}
}
impl TaskFnInputFunction for F
where
$($arg: TaskInput + 'static,)*
F: Fn($($arg,)*) -> FutureOutput + Send + Sync + Clone + 'static,
FutureOutput: Future