Skip to main content

psync_graph/
gates.rs

1//! Runtime checks of computed targets in straight-line code: file paths, HTTP URLs, Redis keys.
2//!
3//! `fs::write(&a, ..)` and `fs::read(&b)` conflict when the macro cannot tell `a` from `b`. When
4//! both paths can be evaluated at the start of the region (they are total and depend on nothing
5//! the region binds or anything `mut`), the region is scheduled as if differently written paths
6//! named different files, and each dependency that drops is kept at run time instead: the paths
7//! are compared at the start of the region, and when they overlap, the later chain waits for the
8//! earlier one to end before it starts ([`crate::__private`]'s `Gate`).
9//!
10//! The same holds for an HTTP request's URL (`request(Method::PUT, url)`), compared by path
11//! segments as files are, and for a Redis command's key (`redis::cmd("SET").arg(k)`), compared
12//! for equality. A URL or key whose type has no `Display` cannot be compared, and always counts
13//! as overlapping.
14
15use crate::access::{Set, mentions};
16use crate::classify::Node;
17use crate::effects::{Domain, Effect, Target, conflict};
18use crate::loops::{substitute, total};
19use crate::schedule::{Plan, depends, plan};
20use proc_macro2::TokenStream;
21use quote::{ToTokens, format_ident, quote};
22use std::collections::HashMap;
23use syn::{Expr, Stmt};
24
25/// A gate: chain `waits` starts only after chain `on` ends, when `cond` (a `bool` computed at the
26/// start of the region) is true.
27pub(crate) struct Gate {
28    pub on: usize,
29    pub waits: usize,
30    pub cond: proc_macro2::Ident,
31}
32
33/// How two targets of one kind are compared at run time.
34#[derive(Clone, Copy, PartialEq, Eq)]
35pub(crate) enum How {
36    /// File paths: overlap when one is the other or a directory containing it.
37    Path,
38    /// HTTP URLs: the same, on the path after the host, without query or fragment.
39    Url,
40    /// Redis keys: overlap when equal.
41    Key,
42}
43
44/// Pairs of keys, one from each of two statements, compared at run time.
45type Pairs = Vec<(Expr, Expr, How)>;
46
47/// How generated code compares targets at run time.
48pub(crate) struct Compare<'a> {
49    /// Path to the psync crate.
50    pub krate: &'a TokenStream,
51    /// `owned_files`: files are compared by identity (inode, resolved path), not path text.
52    pub owned_files: bool,
53}
54
55impl Compare<'_> {
56    /// The text of a URL or key, `None` at run time when its type has no `Display`.
57    fn text(&self, e: &Expr) -> TokenStream {
58        let krate = self.krate;
59        quote!({
60            #[allow(unused_imports)]
61            use #krate::__private::{KeyText as _, NoKeyText as _};
62            (&#krate::__private::Key(&(#e))).text()
63        })
64    }
65
66    /// The test that `a` and `b`, compared as `how`, may be one target.
67    fn test(&self, a: &Expr, b: &Expr, how: How) -> TokenStream {
68        let (krate, ta, tb) = (self.krate, self.text(a), self.text(b));
69        match how {
70            How::Path if self.owned_files => quote!(#krate::__private::files_overlap(&(#a), &(#b))),
71            How::Path => quote!(__psync_overlap(&(#a), &(#b))),
72            How::Url => quote!(#krate::__private::urls_overlap(#ta, #tb)),
73            How::Key => quote!(#krate::__private::keys_overlap(#ta, #tb)),
74        }
75    }
76
77    /// One target of a loop item, for the per-item check.
78    pub fn item(&self, e: &Expr, how: How) -> TokenStream {
79        let (krate, text) = (self.krate, self.text(e));
80        match how {
81            How::Path if self.owned_files => quote!(#krate::__private::ItemTarget::file(&(#e))),
82            How::Path => quote!(#krate::__private::ItemTarget::path(&(#e))),
83            How::Url => quote!(#krate::__private::ItemTarget::Url(#text)),
84            How::Key => quote!(#krate::__private::ItemTarget::Key(#text)),
85        }
86    }
87}
88
89/// Under `owned_files`, two path spellings may name one file (a symlink, a hard link): the
90/// nodes with every file target widened to any file. Planning these orders every pair of file
91/// effects; [`relax`] then compares the paths that differ by text at run time, by identity.
92pub(crate) fn widen_files(nodes: &[Node]) -> Vec<Node> {
93    let mut wide = nodes.to_vec();
94    let files = wide.iter_mut().flat_map(|n| n.effects.iter_mut());
95    for e in files.filter(|e| e.domain == Domain::Fs) {
96        e.target = widen(&e.target);
97    }
98    wide
99}
100
101/// A target that may alias any other (`Expr` is compared with nothing), shown as before.
102fn widen(t: &Target) -> Target {
103    match t {
104        Target::Literal(_) | Target::Prefixed(..) | Target::Template(..) => {
105            Target::Expr(t.shown(), t.names().cloned().unwrap_or_default())
106        }
107        other => other.clone(),
108    }
109}
110
111/// How an effect's target can be compared at run time, if it can.
112pub(crate) fn how(e: &Effect) -> Option<How> {
113    if e.domain == Domain::Fs {
114        Some(How::Path)
115    } else if matches!(e.target, Target::Any) {
116        // A POST or an unknown command: anything, whatever its argument.
117        None
118    } else if e.op.starts_with("HTTP ") {
119        Some(How::Url)
120    } else if e.op.starts_with("redis ") {
121        Some(How::Key)
122    } else {
123        None
124    }
125}
126
127/// The relaxed schedule, the gates that keep it sequentially consistent, and the statements that
128/// compute their conditions; `None` when there is nothing to gain or a gate cannot be placed.
129pub(crate) fn relax(
130    nodes: &[Node],
131    strict: &[Node],
132    mutable: &Set,
133    ids: &mut usize,
134    compare: &Compare,
135) -> Option<(Plan, Vec<Gate>, Vec<Stmt>)> {
136    // Every name the region binds, with repetitions.
137    let mut bound: HashMap<String, usize> = HashMap::new();
138    for n in nodes {
139        for (i, _) in &n.defs {
140            *bound.entry(i.to_string()).or_default() += 1;
141        }
142    }
143    // `let p = dir.join("a");` in the region: `p` stands for its value.
144    let mut lets: HashMap<String, TokenStream> = HashMap::new();
145    for n in nodes {
146        let Stmt::Local(l) = &n.stmt else { continue };
147        let p = match &l.pat {
148            syn::Pat::Type(t) => &*t.pat,
149            p => p,
150        };
151        if let (syn::Pat::Ident(id), Some(init)) = (p, &l.init)
152            && id.by_ref.is_none()
153            && id.mutability.is_none()
154            && id.subpat.is_none()
155            && init.diverge.is_none()
156            && bound.get(&id.ident.to_string()) == Some(&1)
157        {
158            let value = substitute(init.expr.to_token_stream(), &lets);
159            if syn::parse2::<Expr>(value.clone()).is_ok_and(|e| total(&e)) {
160                lets.insert(id.ident.to_string(), value);
161            }
162        }
163    }
164    // The key of each file effect whose path can be evaluated at the start of the region.
165    let key = |source: &Option<String>| -> Option<Expr> {
166        let tokens: TokenStream = source.as_ref()?.parse().ok()?;
167        let expr: Expr = syn::parse2(substitute(tokens, &lets)).ok()?;
168        let used = mentions(expr.to_token_stream());
169        (total(&expr)
170            && !used
171                .iter()
172                .any(|n| bound.contains_key(n) || mutable.contains(n)))
173        .then_some(expr)
174    };
175    let keys: Vec<Vec<Option<(Expr, How)>>> = nodes
176        .iter()
177        .map(|n| {
178            n.effects
179                .iter()
180                .map(|e| Some((key(&e.source)?, how(e)?)))
181                .collect()
182        })
183        .collect();
184    if keys.iter().flatten().filter(|k| k.is_some()).count() < 2 {
185        return None;
186    }
187    // Differently written keys stand for different files; the same key, for the same file. A
188    // literal path keeps its target: two literals already compare exactly, and a literal against
189    // a computed path still differs here, so that pair is compared at run time.
190    let mut relaxed: Vec<Node> = nodes.to_vec();
191    for (n, ks) in relaxed.iter_mut().zip(&keys) {
192        for (e, k) in n.effects.iter_mut().zip(ks) {
193            if matches!(e.target, Target::Literal(_)) {
194                continue;
195            }
196            if let Some((k, _)) = k {
197                e.target =
198                    Target::Literal(format!("`{}` (compared at run time)", k.to_token_stream()));
199            }
200        }
201    }
202    // Each dependency that dropped must have been only through keyed effect pairs.
203    type Dropped = (usize, usize, Pairs);
204    let mut dropped: Vec<Dropped> = Vec::new();
205    for j in 0..nodes.len() {
206        for i in 0..j {
207            if depends(&strict[i], &strict[j]).is_none()
208                || depends(&relaxed[i], &relaxed[j]).is_some()
209            {
210                continue;
211            }
212            let mut pairs = Vec::new();
213            for (a, ka) in strict[i].effects.iter().zip(&keys[i]) {
214                for (b, kb) in strict[j].effects.iter().zip(&keys[j]) {
215                    if conflict(a, b).is_none() {
216                        continue;
217                    }
218                    let ((ka, ha), (kb, hb)) = (ka.clone()?, kb.clone()?);
219                    // A path against a URL, say: nothing to compare them by.
220                    if ha != hb {
221                        return None;
222                    }
223                    pairs.push((ka, kb, ha));
224                }
225            }
226            dropped.push((i, j, pairs));
227        }
228    }
229    if dropped.is_empty() {
230        return None;
231    }
232    let relaxed_plan = plan(&relaxed);
233    let strict = plan(strict);
234    if relaxed_plan.levels.len() >= strict.levels.len()
235        && relaxed_plan.chains.len() <= strict.chains.len()
236    {
237        return None;
238    }
239    let mut chain_of = vec![0; nodes.len()];
240    for (c, members) in relaxed_plan.chains.iter().enumerate() {
241        for &v in members {
242            chain_of[v] = c;
243        }
244    }
245    let mut level_of = vec![0; relaxed_plan.chains.len()];
246    for (l, chains) in relaxed_plan.levels.iter().enumerate() {
247        for &c in chains {
248            level_of[c] = l;
249        }
250    }
251    // A chain waits for one of its own level: an earlier level has ended before it starts, and a
252    // later one would never start.
253    let mut conds: HashMap<(usize, usize), Pairs> = HashMap::new();
254    for (i, j, pairs) in dropped {
255        let (x, y) = (chain_of[i], chain_of[j]);
256        if x == y || level_of[x] < level_of[y] {
257            continue;
258        }
259        // A gate runs from the chain that starts first, so gates cannot wait in a circle. It
260        // also runs from a chain listed earlier in the level: in synchronous code, the level's
261        // jobs start in that order, and jobs the thread pool has no room for run on the calling
262        // thread in that order, so a job only ever waits for one that has started or finished.
263        let index = |c: usize| {
264            relaxed_plan.levels[level_of[c]]
265                .iter()
266                .position(|&d| d == c)
267        };
268        if level_of[x] > level_of[y]
269            || relaxed_plan.chains[x][0] > relaxed_plan.chains[y][0]
270            || index(x) > index(y)
271        {
272            return None;
273        }
274        conds.entry((x, y)).or_default().extend(pairs);
275    }
276    let mut gates = Vec::new();
277    let mut prelude: Vec<Stmt> = Vec::new();
278    let mut paths = false;
279    let mut conds: Vec<_> = conds.into_iter().collect();
280    conds.sort_by_key(|(k, _)| *k);
281    for ((on, waits), pairs) in conds {
282        *ids += 1;
283        let cond = format_ident!("__psync_overlap{}", *ids);
284        let tests = pairs.iter().map(|(a, b, h)| compare.test(a, b, *h));
285        paths |= !compare.owned_files && pairs.iter().any(|(_, _, h)| *h == How::Path);
286        prelude.push(syn::parse_quote!(let #cond: bool = false #(|| #tests)*;));
287        gates.push(Gate { on, waits, cond });
288    }
289    if !paths {
290        return Some((relaxed_plan, gates, prelude));
291    }
292    // Paths overlap when one is the other or a directory that contains it, after lexical
293    // normalization.
294    let helper: Stmt = syn::parse_quote! {
295        #[allow(unused)]
296        let __psync_overlap = |a: &dyn ::core::convert::AsRef<::std::path::Path>,
297                               b: &dyn ::core::convert::AsRef<::std::path::Path>| {
298            let norm = |p: &dyn ::core::convert::AsRef<::std::path::Path>| -> ::std::path::PathBuf {
299                p.as_ref()
300                    .components()
301                    .filter(|c| !::core::matches!(c, ::std::path::Component::CurDir))
302                    .collect()
303            };
304            let (a, b) = (norm(a), norm(b));
305            a.starts_with(&b) || b.starts_with(&a)
306        };
307    };
308    prelude.insert(0, helper);
309    Some((relaxed_plan, gates, prelude))
310}