/
backend.rs
433 lines (382 loc) · 14 KB
/
backend.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
use std::{
any::Any,
borrow::Cow,
fmt,
fmt::{Debug, Display, Write},
future::Future,
pin::Pin,
sync::Arc,
time::{Duration, Instant},
};
use anyhow::{anyhow, bail, Result};
use auto_hash_map::AutoSet;
use nohash_hasher::BuildNoHashHasher;
use serde::{Deserialize, Serialize};
pub use crate::id::BackendJobId;
use crate::{
event::EventListener, manager::TurboTasksBackendApi, raw_vc::CellId, registry,
ConcreteTaskInput, FunctionId, RawVc, ReadRef, SharedReference, TaskId, TaskIdProvider,
TraitRef, TraitTypeId, Vc, VcValueTrait, VcValueType,
};
pub enum TaskType {
/// Tasks that only exist for a certain operation and
/// won't persist between sessions
Transient(TransientTaskType),
/// Tasks that can persist between sessions and potentially
/// shared globally
Persistent(PersistentTaskType),
}
type TransientTaskRoot =
Box<dyn Fn() -> Pin<Box<dyn Future<Output = Result<RawVc>> + Send>> + Send + Sync>;
pub enum TransientTaskType {
/// A root task that will track dependencies and re-execute when
/// dependencies change. Task will eventually settle to the correct
/// execution.
/// Always active. Automatically scheduled.
Root(TransientTaskRoot),
// TODO implement these strongly consistency
/// A single root task execution. It won't track dependencies.
/// Task will definitely include all invalidations that happened before the
/// start of the task. It may or may not include invalidations that
/// happened after that. It may see these invalidations partially
/// applied.
/// Active until done. Automatically scheduled.
Once(Pin<Box<dyn Future<Output = Result<RawVc>> + Send + 'static>>),
}
impl Debug for TransientTaskType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Root(_) => f.debug_tuple("Root").finish(),
Self::Once(_) => f.debug_tuple("Once").finish(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub enum PersistentTaskType {
/// A normal task execution a native (rust) function
Native(FunctionId, Vec<ConcreteTaskInput>),
/// A resolve task, which resolves arguments and calls the function with
/// resolve arguments. The inner function call will do a cache lookup.
ResolveNative(FunctionId, Vec<ConcreteTaskInput>),
/// A trait method resolve task. It resolves the first (`self`) argument and
/// looks up the trait method on that value. Then it calls that method.
/// The method call will do a cache lookup and might resolve arguments
/// before.
ResolveTrait(TraitTypeId, Cow<'static, str>, Vec<ConcreteTaskInput>),
}
impl Display for PersistentTaskType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Native(fid, _) | Self::ResolveNative(fid, _) => {
Display::fmt(®istry::get_function(*fid).name, f)
}
Self::ResolveTrait(tid, n, _) => {
write!(f, "{}::{n}", registry::get_trait(*tid).name)
}
}
}
}
impl PersistentTaskType {
pub fn shrink_to_fit(&mut self) {
match self {
Self::Native(_, inputs) => inputs.shrink_to_fit(),
Self::ResolveNative(_, inputs) => inputs.shrink_to_fit(),
Self::ResolveTrait(_, _, inputs) => inputs.shrink_to_fit(),
}
}
pub fn len(&self) -> usize {
match self {
PersistentTaskType::Native(_, v)
| PersistentTaskType::ResolveNative(_, v)
| PersistentTaskType::ResolveTrait(_, _, v) => v.len(),
}
}
pub fn is_empty(&self) -> bool {
match self {
PersistentTaskType::Native(_, v)
| PersistentTaskType::ResolveNative(_, v)
| PersistentTaskType::ResolveTrait(_, _, v) => v.is_empty(),
}
}
pub fn partial(&self, len: usize) -> Self {
match self {
PersistentTaskType::Native(f, v) => PersistentTaskType::Native(*f, v[..len].to_vec()),
PersistentTaskType::ResolveNative(f, v) => {
PersistentTaskType::ResolveNative(*f, v[..len].to_vec())
}
PersistentTaskType::ResolveTrait(f, n, v) => {
PersistentTaskType::ResolveTrait(*f, n.clone(), v[..len].to_vec())
}
}
}
}
pub struct TaskExecutionSpec {
pub future: Pin<Box<dyn Future<Output = Result<RawVc>> + Send>>,
}
// TODO technically CellContent is already indexed by the ValueTypeId, so we
// don't need to store it here
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct CellContent(pub Option<SharedReference>);
impl Display for CellContent {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.0 {
None => write!(f, "empty"),
Some(content) => Display::fmt(content, f),
}
}
}
impl CellContent {
pub fn cast<T: Any + VcValueType>(self) -> Result<ReadRef<T>> {
let data = self.0.ok_or_else(|| anyhow!("Cell is empty"))?;
let data = data
.downcast()
.ok_or_else(|| anyhow!("Unexpected type in cell"))?;
Ok(ReadRef::new(data))
}
/// # Safety
///
/// The caller must ensure that the CellContent contains a vc that
/// implements T.
pub fn cast_trait<T>(self) -> Result<TraitRef<T>>
where
T: VcValueTrait + ?Sized,
{
let shared_reference = self.0.ok_or_else(|| anyhow!("Cell is empty"))?;
if shared_reference.0.is_none() {
bail!("Cell content is untyped");
}
Ok(
// Safety: We just checked that the content is typed.
TraitRef::new(shared_reference),
)
}
pub fn try_cast<T: Any + VcValueType>(self) -> Option<ReadRef<T>> {
self.0
.and_then(|data| data.downcast().map(|data| ReadRef::new(data)))
}
}
pub trait Backend: Sync + Send {
#[allow(unused_variables)]
fn initialize(&mut self, task_id_provider: &dyn TaskIdProvider) {}
#[allow(unused_variables)]
fn startup(&self, turbo_tasks: &dyn TurboTasksBackendApi<Self>) {}
#[allow(unused_variables)]
fn stop(&self, turbo_tasks: &dyn TurboTasksBackendApi<Self>) {}
#[allow(unused_variables)]
fn idle_start(&self, turbo_tasks: &dyn TurboTasksBackendApi<Self>) {}
fn invalidate_task(&self, task: TaskId, turbo_tasks: &dyn TurboTasksBackendApi<Self>);
fn invalidate_tasks(&self, tasks: &[TaskId], turbo_tasks: &dyn TurboTasksBackendApi<Self>);
fn invalidate_tasks_set(
&self,
tasks: &AutoSet<TaskId, BuildNoHashHasher<TaskId>>,
turbo_tasks: &dyn TurboTasksBackendApi<Self>,
);
fn get_task_description(&self, task: TaskId) -> String;
type ExecutionScopeFuture<T: Future<Output = Result<()>> + Send + 'static>: Future<Output = Result<()>>
+ Send
+ 'static;
fn execution_scope<T: Future<Output = Result<()>> + Send + 'static>(
&self,
task: TaskId,
future: T,
) -> Self::ExecutionScopeFuture<T>;
fn try_start_task_execution(
&self,
task: TaskId,
turbo_tasks: &dyn TurboTasksBackendApi<Self>,
) -> Option<TaskExecutionSpec>;
fn task_execution_result(
&self,
task: TaskId,
result: Result<Result<RawVc>, Option<Cow<'static, str>>>,
turbo_tasks: &dyn TurboTasksBackendApi<Self>,
);
fn task_execution_completed(
&self,
task: TaskId,
duration: Duration,
instant: Instant,
stateful: bool,
turbo_tasks: &dyn TurboTasksBackendApi<Self>,
) -> bool;
fn run_backend_job<'a>(
&'a self,
id: BackendJobId,
turbo_tasks: &'a dyn TurboTasksBackendApi<Self>,
) -> Pin<Box<dyn Future<Output = ()> + Send + 'a>>;
fn try_read_task_output(
&self,
task: TaskId,
reader: TaskId,
strongly_consistent: bool,
turbo_tasks: &dyn TurboTasksBackendApi<Self>,
) -> Result<Result<RawVc, EventListener>>;
/// INVALIDATION: Be careful with this, it will not track dependencies, so
/// using it could break cache invalidation.
fn try_read_task_output_untracked(
&self,
task: TaskId,
strongly_consistent: bool,
turbo_tasks: &dyn TurboTasksBackendApi<Self>,
) -> Result<Result<RawVc, EventListener>>;
fn try_read_task_cell(
&self,
task: TaskId,
index: CellId,
reader: TaskId,
turbo_tasks: &dyn TurboTasksBackendApi<Self>,
) -> Result<Result<CellContent, EventListener>>;
/// INVALIDATION: Be careful with this, it will not track dependencies, so
/// using it could break cache invalidation.
fn try_read_task_cell_untracked(
&self,
task: TaskId,
index: CellId,
turbo_tasks: &dyn TurboTasksBackendApi<Self>,
) -> Result<Result<CellContent, EventListener>>;
/// INVALIDATION: Be careful with this, it will not track dependencies, so
/// using it could break cache invalidation.
fn try_read_own_task_cell_untracked(
&self,
current_task: TaskId,
index: CellId,
turbo_tasks: &dyn TurboTasksBackendApi<Self>,
) -> Result<CellContent> {
match self.try_read_task_cell_untracked(current_task, index, turbo_tasks)? {
Ok(content) => Ok(content),
Err(_) => Ok(CellContent(None)),
}
}
fn read_task_collectibles(
&self,
task: TaskId,
trait_id: TraitTypeId,
reader: TaskId,
turbo_tasks: &dyn TurboTasksBackendApi<Self>,
) -> Vc<AutoSet<RawVc>>;
fn emit_collectible(
&self,
trait_type: TraitTypeId,
collectible: RawVc,
task: TaskId,
turbo_tasks: &dyn TurboTasksBackendApi<Self>,
);
fn unemit_collectible(
&self,
trait_type: TraitTypeId,
collectible: RawVc,
task: TaskId,
turbo_tasks: &dyn TurboTasksBackendApi<Self>,
);
fn update_task_cell(
&self,
task: TaskId,
index: CellId,
content: CellContent,
turbo_tasks: &dyn TurboTasksBackendApi<Self>,
);
fn get_or_create_persistent_task(
&self,
task_type: PersistentTaskType,
parent_task: TaskId,
turbo_tasks: &dyn TurboTasksBackendApi<Self>,
) -> TaskId;
fn connect_task(
&self,
task: TaskId,
parent_task: TaskId,
turbo_tasks: &dyn TurboTasksBackendApi<Self>,
);
fn mark_own_task_as_finished(
&self,
_task: TaskId,
_turbo_tasks: &dyn TurboTasksBackendApi<Self>,
) {
// Do nothing by default
}
fn create_transient_task(
&self,
task_type: TransientTaskType,
turbo_tasks: &dyn TurboTasksBackendApi<Self>,
) -> TaskId;
}
impl PersistentTaskType {
pub async fn run_resolve_native<B: Backend + 'static>(
fn_id: FunctionId,
inputs: Vec<ConcreteTaskInput>,
turbo_tasks: Arc<dyn TurboTasksBackendApi<B>>,
) -> Result<RawVc> {
let mut resolved_inputs = Vec::with_capacity(inputs.len());
for input in inputs.into_iter() {
resolved_inputs.push(input.resolve().await?)
}
Ok(turbo_tasks.native_call(fn_id, resolved_inputs))
}
pub async fn run_resolve_trait<B: Backend + 'static>(
trait_type: TraitTypeId,
name: Cow<'static, str>,
inputs: Vec<ConcreteTaskInput>,
turbo_tasks: Arc<dyn TurboTasksBackendApi<B>>,
) -> Result<RawVc> {
let mut resolved_inputs = Vec::with_capacity(inputs.len());
let mut iter = inputs.into_iter();
if let Some(this) = iter.next() {
let this = this.resolve().await?;
let this_value = this.clone().resolve_to_value().await?;
match this_value.get_trait_method(trait_type, name) {
Ok(native_fn) => {
resolved_inputs.push(this);
for input in iter {
resolved_inputs.push(input)
}
Ok(turbo_tasks.dynamic_call(native_fn, resolved_inputs))
}
Err(name) => {
if !this_value.has_trait(trait_type) {
let traits =
this_value
.traits()
.iter()
.fold(String::new(), |mut out, t| {
let _ = write!(out, " {}", t);
out
});
Err(anyhow!(
"{} doesn't implement {} (only{})",
this_value,
registry::get_trait(trait_type),
traits,
))
} else {
Err(anyhow!(
"{} implements trait {}, but method {} is missing",
this_value,
registry::get_trait(trait_type),
name
))
}
}
}
} else {
panic!("No arguments for trait call");
}
}
pub fn run<B: Backend + 'static>(
self,
turbo_tasks: Arc<dyn TurboTasksBackendApi<B>>,
) -> Pin<Box<dyn Future<Output = Result<RawVc>> + Send>> {
match self {
PersistentTaskType::Native(fn_id, inputs) => {
let native_fn = registry::get_function(fn_id);
let bound = native_fn.bind(&inputs);
(bound)()
}
PersistentTaskType::ResolveNative(fn_id, inputs) => {
Box::pin(Self::run_resolve_native(fn_id, inputs, turbo_tasks))
}
PersistentTaskType::ResolveTrait(trait_type, name, inputs) => Box::pin(
Self::run_resolve_trait(trait_type, name, inputs, turbo_tasks),
),
}
}
}