Skip to main content

turbo_tasks/vc/
keyed_read_ref.rs

1use std::{
2    fmt::{self, Debug},
3    hash::{BuildHasher, Hash},
4};
5
6use parking_lot::Mutex;
7use rustc_hash::{FxBuildHasher, FxHashSet};
8
9use crate::{
10    CellId, ReadRef, TaskId,
11    keyed::{KeyedAccess, KeyedEq},
12    manager::{ProvisionalReadDependency, with_turbo_tasks},
13    vc::{VcReadTarget, VcValueType},
14};
15
16/// The result of [`Vc::keyed_reader`](crate::Vc::keyed_reader): a read of a keyed cell (a
17/// [`cell = "keyed"`](macro@crate::value) map or set) that only allows synchronous keyed access via
18/// [`KeyedReadRef::get`] and [`KeyedReadRef::contains_key`].
19///
20/// This is an efficient alternative to many [`Vc::get`](crate::Vc::get) /
21/// [`Vc::contains_key`](crate::Vc::contains_key) reads of the same cell within a single task: the
22/// cell is read (and the dependency registered) only once, and the accessed keys don't need an
23/// `await` or any locking of the backend.
24///
25/// While it is alive, the reading task depends on the whole cell, so it is invalidated by any
26/// change. The hashes of the accessed keys are recorded. When it is dropped within the task
27/// execution that read it, that dependency is replaced (in a single batch operation) with
28/// dependencies on only the accessed keys, so the task is only invalidated when one of the
29/// accessed keys changes, like with [`Vc::get`](crate::Vc::get).
30///
31/// It **must** be dropped within the task execution that called
32/// [`keyed_reader`](crate::Vc::keyed_reader) (it may be dropped in local tasks of that execution),
33/// and the same applies to the future returned by `keyed_reader`. When either is still alive at the
34/// end of that task execution (e.g. forgotten, or moved to another thread or task), that is a bug
35/// in the task function: completing the execution panics, which aborts the process.
36///
37/// Note: Like with [`Vc::contains_key`](crate::Vc::contains_key), a
38/// [`contains_key`](KeyedReadRef::contains_key) access is also invalidated when the value of the
39/// key changes, not only when its presence changes.
40#[must_use]
41pub struct KeyedReadRef<T>
42where
43    T: VcValueType,
44    VcReadTarget<T>: KeyedEq,
45{
46    read_ref: ReadRef<T>,
47    /// `None` if the read wasn't tracked (e.g. a read outside of a task execution).
48    dependency: Option<(TaskId, CellId, ProvisionalReadDependency)>,
49    accessed_key_hashes: Mutex<FxHashSet<u64>>,
50}
51
52impl<T> KeyedReadRef<T>
53where
54    T: VcValueType,
55    VcReadTarget<T>: KeyedEq,
56{
57    /// `dependency` must only be `Some` within the task execution that created it, and must
58    /// already be registered as alive ([`ProvisionalReadDependency::register_alive_ref`]). The
59    /// registration is released when this is dropped within that execution.
60    pub(crate) fn new(
61        read_ref: ReadRef<T>,
62        dependency: Option<(TaskId, CellId, ProvisionalReadDependency)>,
63    ) -> Self {
64        Self {
65            read_ref,
66            dependency,
67            accessed_key_hashes: Mutex::new(FxHashSet::default()),
68        }
69    }
70
71    fn track<Q: Hash + ?Sized>(&self, key: &Q) {
72        if self.dependency.is_some() {
73            // Same hash as `Vc::get` uses.
74            self.accessed_key_hashes
75                .lock()
76                .insert(FxBuildHasher.hash_one(key));
77        }
78    }
79
80    /// Selects a keyed value. The task will only depend on the accessed keys.
81    pub fn get<Q>(&self, key: &Q) -> Option<&<VcReadTarget<T> as KeyedAccess<Q>>::Value>
82    where
83        Q: Hash + ?Sized,
84        VcReadTarget<T>: KeyedAccess<Q>,
85    {
86        self.track(key);
87        (*self.read_ref).get(key)
88    }
89
90    /// Checks if the value contains the given key. The task will only depend on the accessed keys.
91    ///
92    /// Note: This is also invalidated when the value of the key changes, not only when the presence
93    /// of the key changes.
94    pub fn contains_key<Q>(&self, key: &Q) -> bool
95    where
96        Q: Hash + ?Sized,
97        VcReadTarget<T>: KeyedAccess<Q>,
98    {
99        self.track(key);
100        (*self.read_ref).contains_key(key)
101    }
102}
103
104impl<T> Drop for KeyedReadRef<T>
105where
106    T: VcValueType,
107    VcReadTarget<T>: KeyedEq,
108{
109    fn drop(&mut self) {
110        let Some((task, index, dependency)) = self.dependency.take() else {
111            return;
112        };
113        if !dependency.is_current_execution() {
114            // Dropped outside of the creating execution: a bug in the task function. Don't panic
115            // in `drop`. The registration stays counted, so the creating execution panics when it
116            // completes.
117            return;
118        }
119        dependency.release_alive_ref();
120        let key_hashes = std::mem::take(self.accessed_key_hashes.get_mut());
121        if let Err(error) = with_turbo_tasks(|tt| {
122            tt.refine_provisional_cell_dependency(
123                task,
124                index,
125                dependency.reader,
126                dependency.id,
127                &key_hashes,
128            )
129        }) {
130            // The cell's task was garbage collected while this execution used it.
131            dependency.fail_execution(error);
132        }
133    }
134}
135
136impl<T> Debug for KeyedReadRef<T>
137where
138    T: VcValueType,
139    VcReadTarget<T>: KeyedEq,
140{
141    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
142        f.debug_struct("KeyedReadRef")
143            .field("accessed_keys", &self.accessed_key_hashes.lock().len())
144            .finish_non_exhaustive()
145    }
146}