1pub mod retry;
4mod run;
5
6use std::{
7 future::Future,
8 mem::replace,
9 panic::AssertUnwindSafe,
10 pin::Pin,
11 sync::{Arc, Mutex, Weak},
12};
13
14use anyhow::{Result, anyhow, bail};
15use futures::FutureExt;
16use rustc_hash::FxHashMap;
17use smallvec::SmallVec;
18use tokio::sync::mpsc::Receiver;
19use turbo_tasks::{
20 CellId, ExecutionId, InvalidationReason, LocalTaskId, MagicAny, RawVc, ReadCellOptions,
21 ReadOutputOptions, TaskId, TaskPersistence, TraitTypeId, TurboTasksApi, TurboTasksCallApi,
22 backend::{CellContent, TaskCollectiblesMap, TypedCellContent, VerificationMode},
23 event::{Event, EventListener},
24 message_queue::CompilationEvent,
25 test_helpers::with_turbo_tasks_for_testing,
26 util::{SharedError, StaticOrArc},
27};
28
29pub use crate::run::{
30 Registration, run, run_once, run_once_without_cache_check, run_with_tt, run_without_cache_check,
31};
32
33enum Task {
34 Spawned(Event),
35 Finished(Result<RawVc, SharedError>),
36}
37
38#[derive(Default)]
39pub struct VcStorage {
40 this: Weak<Self>,
41 cells: Mutex<FxHashMap<(TaskId, CellId), CellContent>>,
42 tasks: Mutex<Vec<Task>>,
43}
44
45impl VcStorage {
46 fn dynamic_call(
47 &self,
48 func: &'static turbo_tasks::macro_helpers::NativeFunction,
49 this_arg: Option<RawVc>,
50 arg: Box<dyn MagicAny>,
51 ) -> RawVc {
52 let this = self.this.upgrade().unwrap();
53 let handle = tokio::runtime::Handle::current();
54 let future = func.execute(this_arg, &*arg);
55 let i = {
56 let mut tasks = self.tasks.lock().unwrap();
57 let i = tasks.len();
58 tasks.push(Task::Spawned(Event::new(move || {
59 move || format!("Task({i})::event")
60 })));
61 i
62 };
63 let task_id = TaskId::try_from(u32::try_from(i + 1).unwrap()).unwrap();
64 let execution_id = ExecutionId::try_from(u16::try_from(i + 1).unwrap()).unwrap();
65 handle.spawn(with_turbo_tasks_for_testing(
66 this.clone(),
67 task_id,
68 execution_id,
69 async move {
70 let result = AssertUnwindSafe(future).catch_unwind().await;
71
72 let result = result
74 .map_err(|any| match any.downcast::<String>() {
75 Ok(owned) => anyhow!(owned),
76 Err(any) => match any.downcast::<&'static str>() {
77 Ok(str) => anyhow!(str),
78 Err(_) => anyhow!("unknown panic"),
79 },
80 })
81 .and_then(|r| r)
82 .map_err(SharedError::new);
83
84 let mut tasks = this.tasks.lock().unwrap();
85 if let Task::Spawned(event) = replace(&mut tasks[i], Task::Finished(result)) {
86 event.notify(usize::MAX);
87 }
88 },
89 ));
90 RawVc::TaskOutput(task_id)
91 }
92}
93
94impl TurboTasksCallApi for VcStorage {
95 fn dynamic_call(
96 &self,
97 func: &'static turbo_tasks::macro_helpers::NativeFunction,
98 this: Option<RawVc>,
99 arg: Box<dyn MagicAny>,
100 _persistence: TaskPersistence,
101 ) -> RawVc {
102 self.dynamic_call(func, this, arg)
103 }
104 fn native_call(
105 &self,
106 _func: &'static turbo_tasks::macro_helpers::NativeFunction,
107 _this: Option<RawVc>,
108 _arg: Box<dyn MagicAny>,
109 _persistence: TaskPersistence,
110 ) -> RawVc {
111 unreachable!()
112 }
113
114 fn trait_call(
115 &self,
116 _trait_type: &'static turbo_tasks::TraitMethod,
117 _this: RawVc,
118 _arg: Box<dyn MagicAny>,
119 _persistence: TaskPersistence,
120 ) -> RawVc {
121 unreachable!()
122 }
123
124 fn run(
125 &self,
126 _future: Pin<Box<dyn Future<Output = Result<()>> + Send + 'static>>,
127 ) -> Pin<
128 Box<dyn Future<Output = Result<(), turbo_tasks::backend::TurboTasksExecutionError>> + Send>,
129 > {
130 unreachable!()
131 }
132
133 fn run_once(
134 &self,
135 _future: std::pin::Pin<Box<dyn Future<Output = Result<()>> + Send + 'static>>,
136 ) -> Pin<
137 Box<dyn futures::Future<Output = Result<(), anyhow::Error>> + std::marker::Send + 'static>,
138 > {
139 unreachable!()
140 }
141
142 fn run_once_with_reason(
143 &self,
144 _reason: StaticOrArc<dyn InvalidationReason>,
145 _future: std::pin::Pin<Box<dyn Future<Output = Result<()>> + Send + 'static>>,
146 ) -> Pin<
147 Box<dyn futures::Future<Output = Result<(), anyhow::Error>> + std::marker::Send + 'static>,
148 > {
149 unreachable!()
150 }
151
152 fn start_once_process(
153 &self,
154 _future: std::pin::Pin<Box<dyn Future<Output = ()> + Send + 'static>>,
155 ) {
156 unreachable!()
157 }
158
159 fn send_compilation_event(&self, _event: Arc<dyn CompilationEvent>) {
162 unimplemented!()
163 }
164
165 fn get_task_name(&self, task: TaskId) -> String {
166 format!("Task({})", task)
167 }
168}
169
170impl TurboTasksApi for VcStorage {
171 fn invalidate(&self, _task: TaskId) {
172 unreachable!()
173 }
174
175 fn invalidate_with_reason(
176 &self,
177 _task: TaskId,
178 _reason: turbo_tasks::util::StaticOrArc<dyn turbo_tasks::InvalidationReason>,
179 ) {
180 unreachable!()
181 }
182
183 fn invalidate_serialization(&self, _task: TaskId) {
184 }
186
187 fn try_read_task_output(
188 &self,
189 id: TaskId,
190 _options: ReadOutputOptions,
191 ) -> Result<Result<RawVc, EventListener>> {
192 let tasks = self.tasks.lock().unwrap();
193 let i = *id - 1;
194 let task = tasks.get(i as usize).unwrap();
195 match task {
196 Task::Spawned(event) => Ok(Err(event.listen())),
197 Task::Finished(result) => match result {
198 Ok(vc) => Ok(Ok(*vc)),
199 Err(err) => bail!(err.clone()),
200 },
201 }
202 }
203
204 fn try_read_task_cell(
205 &self,
206 task: TaskId,
207 index: CellId,
208 _options: ReadCellOptions,
209 ) -> Result<Result<TypedCellContent, EventListener>> {
210 let map = self.cells.lock().unwrap();
211 Ok(Ok(if let Some(cell) = map.get(&(task, index)) {
212 cell.clone()
213 } else {
214 Default::default()
215 }
216 .into_typed(index.type_id)))
217 }
218 fn try_read_own_task_cell(
219 &self,
220 current_task: TaskId,
221 index: CellId,
222 options: ReadCellOptions,
223 ) -> Result<TypedCellContent> {
224 self.read_own_task_cell(current_task, index, options)
225 }
226
227 fn try_read_local_output(
228 &self,
229 _execution_id: ExecutionId,
230 _local_task_id: LocalTaskId,
231 ) -> Result<Result<RawVc, EventListener>> {
232 unimplemented!()
233 }
234
235 fn emit_collectible(&self, _trait_type: turbo_tasks::TraitTypeId, _collectible: RawVc) {
236 unimplemented!()
237 }
238
239 fn unemit_collectible(
240 &self,
241 _trait_type: turbo_tasks::TraitTypeId,
242 _collectible: RawVc,
243 _count: u32,
244 ) {
245 unimplemented!()
246 }
247
248 fn unemit_collectibles(
249 &self,
250 _trait_type: turbo_tasks::TraitTypeId,
251 _collectibles: &TaskCollectiblesMap,
252 ) {
253 unimplemented!()
254 }
255
256 fn read_task_collectibles(&self, _task: TaskId, _trait_id: TraitTypeId) -> TaskCollectiblesMap {
257 unimplemented!()
258 }
259
260 fn read_own_task_cell(
261 &self,
262 task: TaskId,
263 index: CellId,
264 _options: ReadCellOptions,
265 ) -> Result<TypedCellContent> {
266 let map = self.cells.lock().unwrap();
267 Ok(if let Some(cell) = map.get(&(task, index)) {
268 cell.to_owned()
269 } else {
270 Default::default()
271 }
272 .into_typed(index.type_id))
273 }
274
275 fn update_own_task_cell(
276 &self,
277 task: TaskId,
278 index: CellId,
279 _is_serializable_cell_content: bool,
280 content: CellContent,
281 _updated_key_hashes: Option<SmallVec<[u64; 2]>>,
282 _verification_mode: VerificationMode,
283 ) {
284 let mut map = self.cells.lock().unwrap();
285 let cell = map.entry((task, index)).or_default();
286 *cell = content;
287 }
288
289 fn connect_task(&self, _task: TaskId) {
290 }
292
293 fn mark_own_task_as_finished(&self, _task: TaskId) {
294 }
296
297 fn mark_own_task_as_session_dependent(&self, _task: TaskId) {
298 }
300
301 fn spawn_detached_for_testing(
302 &self,
303 _f: std::pin::Pin<Box<dyn Future<Output = ()> + Send + 'static>>,
304 ) {
305 unimplemented!()
306 }
307
308 fn task_statistics(&self) -> &turbo_tasks::task_statistics::TaskStatisticsApi {
309 unimplemented!()
310 }
311
312 fn stop_and_wait(&self) -> std::pin::Pin<Box<dyn Future<Output = ()> + Send + 'static>> {
313 Box::pin(async {})
314 }
315
316 fn subscribe_to_compilation_events(
319 &self,
320 _event_types: Option<Vec<String>>,
321 ) -> Receiver<Arc<dyn CompilationEvent>> {
322 unimplemented!()
323 }
324
325 fn is_tracking_dependencies(&self) -> bool {
326 false
327 }
328}
329
330impl VcStorage {
331 pub fn with<T>(f: impl Future<Output = T>) -> impl Future<Output = T> {
332 with_turbo_tasks_for_testing(
333 Arc::new_cyclic(|weak| VcStorage {
334 this: weak.clone(),
335 ..Default::default()
336 }),
337 TaskId::MAX,
338 ExecutionId::MIN,
339 f,
340 )
341 }
342}