Commit c93e3f0f authored by Benjamin Woodruff's avatar Benjamin Woodruff

callsites

parent fe4c6745
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
#![allow(clippy::needless_return)] // tokio macro-generated code doesn't respect this #![allow(clippy::needless_return)] // tokio macro-generated code doesn't respect this
use anyhow::Result; use anyhow::Result;
use turbo_tasks::{Completion, TryJoinIterExt, Vc, run_once}; use turbo_tasks::{Completion, StaticOrArc, TryJoinIterExt, Vc, run_once};
use turbo_tasks_testing::{Registration, register, run_with_tt}; use turbo_tasks_testing::{Registration, register, run_with_tt};
static REGISTRATION: Registration = register!(); static REGISTRATION: Registration = register!();
...@@ -20,7 +20,7 @@ async fn rectangle_stress() -> Result<()> { ...@@ -20,7 +20,7 @@ async fn rectangle_stress() -> Result<()> {
.map(|(a, b)| { .map(|(a, b)| {
let tt = tt.clone(); let tt = tt.clone();
async move { async move {
run_once(tt, async move { run_once(StaticOrArc::Shared(tt), async move {
rectangle(a, b).strongly_consistent().await?; rectangle(a, b).strongly_consistent().await?;
Ok(Vc::<()>::default()) Ok(Vc::<()>::default())
}) })
......
...@@ -63,7 +63,7 @@ impl VcStorage { ...@@ -63,7 +63,7 @@ impl VcStorage {
let task_id = TaskId::try_from(u32::try_from(i + 1).unwrap()).unwrap(); let task_id = TaskId::try_from(u32::try_from(i + 1).unwrap()).unwrap();
let execution_id = ExecutionId::try_from(u16::try_from(i + 1).unwrap()).unwrap(); let execution_id = ExecutionId::try_from(u16::try_from(i + 1).unwrap()).unwrap();
handle.spawn(with_turbo_tasks_for_testing( handle.spawn(with_turbo_tasks_for_testing(
this.clone(), StaticOrArc::Shared(this.clone()),
task_id, task_id,
execution_id, execution_id,
async move { async move {
...@@ -322,10 +322,10 @@ impl TurboTasksApi for VcStorage { ...@@ -322,10 +322,10 @@ impl TurboTasksApi for VcStorage {
impl VcStorage { impl VcStorage {
pub fn with<T>(f: impl Future<Output = T>) -> impl Future<Output = T> { pub fn with<T>(f: impl Future<Output = T>) -> impl Future<Output = T> {
with_turbo_tasks_for_testing( with_turbo_tasks_for_testing(
Arc::new_cyclic(|weak| VcStorage { StaticOrArc::Shared(Arc::new_cyclic(|weak| VcStorage {
this: weak.clone(), this: weak.clone(),
..Default::default() ..Default::default()
}), })),
TaskId::MAX, TaskId::MAX,
ExecutionId::MIN, ExecutionId::MIN,
f, f,
......
use std::{fmt::Debug, future::Future, sync::Arc}; use std::{fmt::Debug, future::Future, sync::Arc};
use anyhow::Result; use anyhow::Result;
use turbo_tasks::{TurboTasksApi, trace::TraceRawVcs}; use turbo_tasks::{TurboTasksApi, trace::TraceRawVcs, util::StaticOrArc};
pub struct Registration { pub struct Registration {
create_turbo_tasks: fn(&str, bool) -> Arc<dyn TurboTasksApi>, create_turbo_tasks: fn(&str, bool) -> Arc<dyn TurboTasksApi>,
...@@ -44,7 +44,7 @@ where ...@@ -44,7 +44,7 @@ where
{ {
let name = closure_to_name(&fut); let name = closure_to_name(&fut);
let tt = registration.create_turbo_tasks(&name, true); let tt = registration.create_turbo_tasks(&name, true);
turbo_tasks::run_once(tt, async move { Ok(fut.await) }) turbo_tasks::run_once(StaticOrArc::Shared(tt), async move { Ok(fut.await) })
.await .await
.unwrap() .unwrap()
} }
...@@ -58,7 +58,7 @@ where ...@@ -58,7 +58,7 @@ where
{ {
let name = closure_to_name(&fut); let name = closure_to_name(&fut);
let tt = registration.create_turbo_tasks(&name, true); let tt = registration.create_turbo_tasks(&name, true);
turbo_tasks::run(tt, async move { Ok(fut.await) }) turbo_tasks::run(StaticOrArc::Shared(tt), async move { Ok(fut.await) })
.await .await
.unwrap() .unwrap()
} }
...@@ -76,7 +76,10 @@ where ...@@ -76,7 +76,10 @@ where
F: Future<Output = Result<T>> + Send + 'static, F: Future<Output = Result<T>> + Send + 'static,
T: Debug + PartialEq + Eq + TraceRawVcs + Send + 'static, T: Debug + PartialEq + Eq + TraceRawVcs + Send + 'static,
{ {
run_with_tt(registration, move |tt| turbo_tasks::run_once(tt, fut())).await run_with_tt(registration, move |tt| {
turbo_tasks::run_once(StaticOrArc::Shared(tt), fut())
})
.await
} }
pub async fn run<T, F>( pub async fn run<T, F>(
...@@ -87,7 +90,10 @@ where ...@@ -87,7 +90,10 @@ where
F: Future<Output = Result<T>> + Send + 'static, F: Future<Output = Result<T>> + Send + 'static,
T: Debug + PartialEq + Eq + TraceRawVcs + Send + 'static, T: Debug + PartialEq + Eq + TraceRawVcs + Send + 'static,
{ {
run_with_tt(registration, move |tt| turbo_tasks::run(tt, fut())).await run_with_tt(registration, move |tt| {
turbo_tasks::run(StaticOrArc::Shared(tt), fut())
})
.await
} }
pub async fn run_with_tt<T, F>( pub async fn run_with_tt<T, F>(
......
use std::{ use std::{fmt::Display, hash::Hash, mem::replace, sync::Arc};
fmt::Display,
hash::Hash,
mem::replace,
sync::{Arc, Weak},
};
use anyhow::Result; use anyhow::Result;
use indexmap::map::Entry; use indexmap::map::Entry;
...@@ -17,6 +12,7 @@ use crate::{ ...@@ -17,6 +12,7 @@ use crate::{
FxIndexMap, FxIndexSet, StaticOrArc, TaskId, TurboTasksApi, FxIndexMap, FxIndexSet, StaticOrArc, TaskId, TurboTasksApi,
manager::{current_task_if_available, mark_invalidator, with_turbo_tasks}, manager::{current_task_if_available, mark_invalidator, with_turbo_tasks},
trace::TraceRawVcs, trace::TraceRawVcs,
util::StaticOrWeak,
}; };
/// Get an [`Invalidator`] that can be used to invalidate the current task /// Get an [`Invalidator`] that can be used to invalidate the current task
...@@ -29,7 +25,7 @@ pub fn get_invalidator() -> Option<Invalidator> { ...@@ -29,7 +25,7 @@ pub fn get_invalidator() -> Option<Invalidator> {
let handle = Handle::current(); let handle = Handle::current();
Some(Invalidator { Some(Invalidator {
task, task,
turbo_tasks: with_turbo_tasks(Arc::downgrade), turbo_tasks: with_turbo_tasks(|tt| tt.downgrade()),
handle, handle,
}) })
} else { } else {
...@@ -39,7 +35,7 @@ pub fn get_invalidator() -> Option<Invalidator> { ...@@ -39,7 +35,7 @@ pub fn get_invalidator() -> Option<Invalidator> {
pub struct Invalidator { pub struct Invalidator {
task: TaskId, task: TaskId,
turbo_tasks: Weak<dyn TurboTasksApi>, turbo_tasks: StaticOrWeak<dyn TurboTasksApi>,
handle: Handle, handle: Handle,
} }
...@@ -134,7 +130,7 @@ impl<'de> Deserialize<'de> for Invalidator { ...@@ -134,7 +130,7 @@ impl<'de> Deserialize<'de> for Invalidator {
{ {
Ok(Invalidator { Ok(Invalidator {
task: TaskId::deserialize(deserializer)?, task: TaskId::deserialize(deserializer)?,
turbo_tasks: with_turbo_tasks(Arc::downgrade), turbo_tasks: with_turbo_tasks(|tt| tt.downgrade()),
handle: tokio::runtime::Handle::current(), handle: tokio::runtime::Handle::current(),
}) })
} }
......
This diff is collapsed.
...@@ -18,7 +18,7 @@ use parking_lot::{Condvar, Mutex}; ...@@ -18,7 +18,7 @@ use parking_lot::{Condvar, Mutex};
use tokio::{runtime::Handle, task::block_in_place}; use tokio::{runtime::Handle, task::block_in_place};
use tracing::{Span, info_span}; use tracing::{Span, info_span};
use crate::{TurboTasksApi, manager::try_turbo_tasks, turbo_tasks_scope}; use crate::{TurboTasksApi, manager::try_turbo_tasks, turbo_tasks_scope, util::StaticOrArc};
/// Number of worker tasks to spawn that process jobs. It's 1 less than the number of cpus as we /// Number of worker tasks to spawn that process jobs. It's 1 less than the number of cpus as we
/// also use the current task as worker. /// also use the current task as worker.
...@@ -153,7 +153,7 @@ pub struct Scope<'scope, 'env: 'scope, R: Send + 'env> { ...@@ -153,7 +153,7 @@ pub struct Scope<'scope, 'env: 'scope, R: Send + 'env> {
index: AtomicUsize, index: AtomicUsize,
inner: Arc<ScopeInner>, inner: Arc<ScopeInner>,
handle: Handle, handle: Handle,
turbo_tasks: Option<Arc<dyn TurboTasksApi>>, turbo_tasks: Option<StaticOrArc<dyn TurboTasksApi>>,
span: Span, span: Span,
/// Invariance over 'env, to make sure 'env cannot shrink, /// Invariance over 'env, to make sure 'env cannot shrink,
/// which is necessary for soundness. /// which is necessary for soundness.
......
use std::{ use std::hash::Hash;
hash::Hash,
sync::{Arc, Weak},
};
use serde::{Deserialize, Serialize, de::Visitor}; use serde::{Deserialize, Serialize, de::Visitor};
use tokio::runtime::Handle; use tokio::runtime::Handle;
use crate::{TaskId, TurboTasksApi, manager::with_turbo_tasks, trace::TraceRawVcs}; use crate::{
TaskId, TurboTasksApi, manager::with_turbo_tasks, trace::TraceRawVcs, util::StaticOrWeak,
};
#[derive(Clone)] #[derive(Clone)]
pub struct SerializationInvalidator { pub struct SerializationInvalidator {
task: TaskId, task: TaskId,
turbo_tasks: Weak<dyn TurboTasksApi>, turbo_tasks: StaticOrWeak<dyn TurboTasksApi>,
handle: Handle, handle: Handle,
} }
...@@ -45,7 +44,7 @@ impl SerializationInvalidator { ...@@ -45,7 +44,7 @@ impl SerializationInvalidator {
pub(crate) fn new(task_id: TaskId) -> Self { pub(crate) fn new(task_id: TaskId) -> Self {
Self { Self {
task: task_id, task: task_id,
turbo_tasks: with_turbo_tasks(Arc::downgrade), turbo_tasks: with_turbo_tasks(|tt| tt.downgrade()),
handle: Handle::current(), handle: Handle::current(),
} }
} }
...@@ -86,7 +85,7 @@ impl<'de> Deserialize<'de> for SerializationInvalidator { ...@@ -86,7 +85,7 @@ impl<'de> Deserialize<'de> for SerializationInvalidator {
{ {
Ok(SerializationInvalidator { Ok(SerializationInvalidator {
task: TaskId::deserialize(deserializer)?, task: TaskId::deserialize(deserializer)?,
turbo_tasks: with_turbo_tasks(Arc::downgrade), turbo_tasks: with_turbo_tasks(|tt| tt.downgrade()),
handle: tokio::runtime::Handle::current(), handle: tokio::runtime::Handle::current(),
}) })
} }
......
use std::{fmt, sync::Arc}; use std::fmt;
use anyhow::{Result, anyhow}; use anyhow::{Result, anyhow};
...@@ -9,6 +9,7 @@ use crate::{ ...@@ -9,6 +9,7 @@ use crate::{
event::Event, event::Event,
macro_helpers::NativeFunction, macro_helpers::NativeFunction,
registry, registry,
util::StaticOrArc,
}; };
/// A potentially in-flight local task stored in `CurrentGlobalTaskState::local_tasks`. /// A potentially in-flight local task stored in `CurrentGlobalTaskState::local_tasks`.
...@@ -106,7 +107,7 @@ impl LocalTaskType { ...@@ -106,7 +107,7 @@ impl LocalTaskType {
mut this: Option<RawVc>, mut this: Option<RawVc>,
arg: &dyn MagicAny, arg: &dyn MagicAny,
persistence: TaskPersistence, persistence: TaskPersistence,
turbo_tasks: Arc<dyn TurboTasksBackendApi<B>>, turbo_tasks: StaticOrArc<dyn TurboTasksBackendApi<B>>,
) -> Result<RawVc> { ) -> Result<RawVc> {
if let Some(this) = this.as_mut() { if let Some(this) = this.as_mut() {
*this = this.resolve().await?; *this = this.resolve().await?;
...@@ -120,7 +121,7 @@ impl LocalTaskType { ...@@ -120,7 +121,7 @@ impl LocalTaskType {
this: RawVc, this: RawVc,
arg: &dyn MagicAny, arg: &dyn MagicAny,
persistence: TaskPersistence, persistence: TaskPersistence,
turbo_tasks: Arc<dyn TurboTasksBackendApi<B>>, turbo_tasks: StaticOrArc<dyn TurboTasksBackendApi<B>>,
) -> Result<RawVc> { ) -> Result<RawVc> {
let this = this.resolve().await?; let this = this.resolve().await?;
let TypedCellContent(this_ty, _) = this.into_read().await?; let TypedCellContent(this_ty, _) = this.into_read().await?;
......
...@@ -7,7 +7,7 @@ use std::{ ...@@ -7,7 +7,7 @@ use std::{
mem::ManuallyDrop, mem::ManuallyDrop,
ops::Deref, ops::Deref,
pin::Pin, pin::Pin,
sync::{Arc, LazyLock, Weak}, sync::{Arc, LazyLock, OnceLock, Weak},
task::{Context, Poll}, task::{Context, Poll},
thread::available_parallelism, thread::available_parallelism,
time::Duration, time::Duration,
...@@ -240,7 +240,7 @@ impl<T: ?Sized + Debug + 'static> Debug for StaticOrArc<T> { ...@@ -240,7 +240,7 @@ impl<T: ?Sized + Debug + 'static> Debug for StaticOrArc<T> {
/// Weak pointer that stores data either in a [Weak] or as a static reference. /// Weak pointer that stores data either in a [Weak] or as a static reference.
/// Can be upgraded to [StaticOrArc]. /// Can be upgraded to [StaticOrArc].
pub enum StaticOrWeak<T: ?Sized + 'static> { pub enum StaticOrWeak<T: ?Sized + 'static> {
Static(&'static T), Static(&'static OnceLock<&'static T>),
Weak(Weak<T>), Weak(Weak<T>),
} }
...@@ -248,16 +248,16 @@ impl<T: ?Sized + 'static> StaticOrWeak<T> { ...@@ -248,16 +248,16 @@ impl<T: ?Sized + 'static> StaticOrWeak<T> {
/// Attempts to upgrade the weak pointer to a [StaticOrArc]. /// Attempts to upgrade the weak pointer to a [StaticOrArc].
/// ///
/// Returns [None] if the inner value has been dropped (for the [Weak] variant). /// Returns [None] if the inner value has been dropped (for the [Weak] variant).
/// Always succeeds for the [Static] variant. /// For the [Static] variant, returns [None] if the OnceLock hasn't been initialized yet.
pub fn upgrade(&self) -> Option<StaticOrArc<T>> { pub fn upgrade(&self) -> Option<StaticOrArc<T>> {
match self { match self {
Self::Static(s) => Some(StaticOrArc::Static(s)), Self::Static(lock) => lock.get().copied().map(StaticOrArc::Static),
Self::Weak(w) => w.upgrade().map(StaticOrArc::Shared), Self::Weak(w) => w.upgrade().map(StaticOrArc::Shared),
} }
} }
/// Returns true if the two weak pointers point to the same allocation. /// Returns true if the two weak pointers point to the same allocation.
/// For static references, this compares pointer equality. /// For static references, this compares pointer equality of the OnceLock.
pub fn ptr_eq(&self, other: &Self) -> bool { pub fn ptr_eq(&self, other: &Self) -> bool {
match (self, other) { match (self, other) {
(Self::Static(a), Self::Static(b)) => std::ptr::eq(*a, *b), (Self::Static(a), Self::Static(b)) => std::ptr::eq(*a, *b),
...@@ -271,7 +271,12 @@ impl<T: ?Sized + 'static> StaticOrArc<T> { ...@@ -271,7 +271,12 @@ impl<T: ?Sized + 'static> StaticOrArc<T> {
/// Creates a weak pointer to this allocation. /// Creates a weak pointer to this allocation.
pub fn downgrade(&self) -> StaticOrWeak<T> { pub fn downgrade(&self) -> StaticOrWeak<T> {
match self { match self {
Self::Static(s) => StaticOrWeak::Static(s), Self::Static(s) => {
// Create a OnceLock that's already initialized with the static reference
let lock = Box::leak(Box::new(OnceLock::new()));
let _ = lock.set(*s);
StaticOrWeak::Static(lock)
}
Self::Shared(arc) => StaticOrWeak::Weak(Arc::downgrade(arc)), Self::Shared(arc) => StaticOrWeak::Weak(Arc::downgrade(arc)),
} }
} }
......
...@@ -33,7 +33,8 @@ use tokio::task::JoinHandle; ...@@ -33,7 +33,8 @@ use tokio::task::JoinHandle;
use tracing::{Instrument, Level, Span, event, info_span}; use tracing::{Instrument, Level, Span, event, info_span};
use turbo_tasks::{ use turbo_tasks::{
NonLocalValue, OperationVc, TurboTasksApi, Vc, apply_effects, run_once_with_reason, NonLocalValue, OperationVc, TurboTasksApi, Vc, apply_effects, run_once_with_reason,
trace::TraceRawVcs, util::FormatDuration, trace::TraceRawVcs,
util::{FormatDuration, StaticOrArc},
}; };
use turbopack_core::{ use turbopack_core::{
error::PrettyPrintError, error::PrettyPrintError,
...@@ -171,7 +172,7 @@ impl DevServerBuilder { ...@@ -171,7 +172,7 @@ impl DevServerBuilder {
method: request.method().clone(), method: request.method().clone(),
uri: request.uri().clone(), uri: request.uri().clone(),
}; };
run_once_with_reason(tt.clone(), reason, async move { run_once_with_reason(StaticOrArc::Shared(tt.clone()), reason, async move {
// TODO: `get_issue_reporter` should be an `OperationVc`, as there's a // TODO: `get_issue_reporter` should be an `OperationVc`, as there's a
// risk it could be a task-local Vc, which is not safe for us to await. // risk it could be a task-local Vc, which is not safe for us to await.
let issue_reporter = get_issue_reporter(); let issue_reporter = get_issue_reporter();
...@@ -252,7 +253,7 @@ impl DevServerBuilder { ...@@ -252,7 +253,7 @@ impl DevServerBuilder {
} }
if !side_effects.is_empty() { if !side_effects.is_empty() {
let join_handle = tokio::spawn(run_once_with_reason( let join_handle = tokio::spawn(run_once_with_reason(
tt.clone(), StaticOrArc::Shared(tt.clone()),
side_effects_reason, side_effects_reason,
async move { async move {
for side_effect in side_effects { for side_effect in side_effects {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment