Skip to main content

lean_ctx_cloud/tasks/
cache.rs

1// SPDX-License-Identifier: Apache-2.0
2//! `ctx_tasks` without waiting for Cloud (connector rule "Cloud never blocks
3//! a tool call").
4//!
5//! Reads (`list`, `show`, the session briefing) answer at once from the
6//! task lists and tasks Cloud last sent, kept in `<data>/cloud/task-cache.json`
7//! (0600). An entry that is missing, older than [`FRESH`] or outdated by a
8//! change of this machine is refreshed off the tool call
9//! ([`crate::background`]); the answer says when its data is
10//! stale or not loaded yet. Changes (claim, update, submit, release, read,
11//! confirm, object) are queued the same way ([`queue`]): the tool call
12//! answers that they are queued, and what Cloud answered comes in front of
13//! the caller's next `ctx_tasks` answer. Nothing is shown as done before
14//! Cloud confirmed it.
15
16use std::collections::BTreeMap;
17use std::path::Path;
18use std::time::Duration;
19
20use lean_ctx_time::UtcDateTime;
21use serde::{Deserialize, Serialize};
22
23use super::{
24    Connected, ListFilter, TaskListing, connected, list_cached, render_listing, render_task,
25    show_cached, view_of,
26};
27use crate::CloudError;
28use crate::background;
29use crate::state::{load_or_quarantine, lock_state, write_private};
30use lean_ctx_protocol::cloud::lease::CloudRight;
31use lean_ctx_protocol::cloud::tasks::{TaskState, TaskV1};
32
33const CACHE_FILE: &str = "task-cache.json";
34/// An entry younger than this is shown without a refresh.
35pub const FRESH: Duration = Duration::from_secs(60);
36/// The answer while nothing is cached yet.
37const NOT_LOADED: &str = "Cloud tasks are not loaded on this machine yet; they are being fetched in the background. Ask again in a moment.";
38
39#[derive(Debug, Clone, Serialize, Deserialize)]
40struct Entry<T> {
41    at: UtcDateTime,
42    /// A change of this machine came after it (a claim, an update…).
43    #[serde(default)]
44    outdated: bool,
45    value: T,
46}
47
48impl<T> Entry<T> {
49    fn new(value: T) -> Self {
50        Self {
51            at: UtcDateTime::now(),
52            outdated: false,
53            value,
54        }
55    }
56
57    fn fresh(&self, now: UtcDateTime) -> bool {
58        !self.outdated
59            && lean_ctx_time::Duration::from_std(FRESH).is_ok_and(|fresh| self.at + fresh > now)
60    }
61}
62
63#[derive(Debug, Clone, Default, Serialize, Deserialize)]
64struct VaultCache {
65    /// Keyed by the list query (`?state=open`, `` for all).
66    #[serde(default)]
67    lists: BTreeMap<String, Entry<TaskListing>>,
68    #[serde(default)]
69    tasks: BTreeMap<u64, Entry<TaskV1>>,
70}
71
72#[derive(Debug, Clone, Default, Serialize, Deserialize)]
73struct Cache {
74    #[serde(default)]
75    vaults: BTreeMap<String, VaultCache>,
76}
77
78fn load(data_dir: &Path) -> Cache {
79    load_or_quarantine(&data_dir.join(CACHE_FILE), |_: &Cache| true)
80        .unwrap_or_else(|error| {
81            tracing::warn!("cloud task cache: {error}");
82            None
83        })
84        .unwrap_or_default()
85}
86
87/// Change the vault's cache under its lock; never around a request.
88fn mutate(data_dir: &Path, vault_id: &str, change: impl FnOnce(&mut VaultCache)) {
89    let saved = lock_state(data_dir, CACHE_FILE).and_then(|_lock| {
90        let mut cache = load(data_dir);
91        change(cache.vaults.entry(vault_id.to_string()).or_default());
92        let bytes = serde_json::to_vec(&cache).map_err(|e| CloudError::Local(e.to_string()))?;
93        write_private(data_dir, CACHE_FILE, &bytes)
94    });
95    if let Err(error) = saved {
96        tracing::debug!("cloud task cache not saved: {error}");
97    }
98}
99
100/// Mark what is cached for the vault outdated: the next read refreshes it
101/// (a change of this machine, or a `task.event` from Cloud).
102pub(crate) fn outdate(data_dir: &Path, vault_id: &str) {
103    super::reads::outdate(data_dir, vault_id);
104    mutate(data_dir, vault_id, |vault| {
105        vault.lists.values_mut().for_each(|e| e.outdated = true);
106        vault.tasks.values_mut().for_each(|e| e.outdated = true);
107    });
108}
109
110/// The line under data that is not fresh.
111fn stale_note(at: UtcDateTime) -> String {
112    format!(
113        "\n(Cloud data from {}; a refresh is running, ask again for newer data)",
114        at.format("%Y-%m-%dT%H:%M:%SZ")
115    )
116}
117
118/// The caller of a `ctx_tasks` call: its bus agent, else its session.
119pub fn caller(agent_or_session: &str) -> String {
120    format!("ctx_tasks:{agent_or_session}")
121}
122
123/// Refresh the list `query` off the tool call. A failure reaches `caller`
124/// with its next call; without a caller (the briefing) it is only logged.
125fn refresh_list(c: Connected, query: String, filter: ListFilter, caller: Option<&str>) {
126    let key = format!("tasks:{}:list{query}", c.project.vault_id);
127    let report = caller.is_some();
128    background::submit_once(
129        caller.unwrap_or("ctx_tasks:briefing"),
130        &key,
131        move || match list_cached(&c.link(), &filter) {
132            // A list Cloud did not send now (rate limit, not reachable) is
133            // not stored as fresh; the next read tries again.
134            Ok(read) if read.stale.is_some() => None,
135            Ok(read) => {
136                mutate(c.store.data_dir(), &c.project.vault_id, |vault| {
137                    vault.lists.insert(query, Entry::new(read.value));
138                });
139                None
140            }
141            Err(error) if report => Some(format!(
142                "Cloud tasks: the task list could not be refreshed: {error}"
143            )),
144            Err(error) => {
145                tracing::debug!("cloud task briefing refresh: {error}");
146                None
147            }
148        },
149    );
150}
151
152/// `ctx_tasks list`: the cached list, refreshed off the call when needed.
153pub fn list(project_root: &Path, filter: &ListFilter, caller: &str) -> Result<String, CloudError> {
154    let c = connected(project_root, CloudRight::TasksRead)?;
155    let query = filter.query()?;
156    let entry = load(c.store.data_dir())
157        .vaults
158        .remove(&c.project.vault_id)
159        .and_then(|mut vault| vault.lists.remove(&query));
160    let answer = match &entry {
161        Some(entry) if entry.fresh(UtcDateTime::now()) => {
162            return Ok(render_listing(&entry.value, 50));
163        }
164        Some(entry) => format!(
165            "{}{}",
166            render_listing(&entry.value, 50),
167            stale_note(entry.at)
168        ),
169        None => NOT_LOADED.to_string(),
170    };
171    refresh_list(c, query, filter.clone(), Some(caller));
172    Ok(answer)
173}
174
175/// `ctx_tasks show`: the cached task, refreshed off the call when needed.
176pub fn show(project_root: &Path, number: u64, caller: &str) -> Result<String, CloudError> {
177    let c = connected(project_root, CloudRight::TasksRead)?;
178    let entry = load(c.store.data_dir())
179        .vaults
180        .remove(&c.project.vault_id)
181        .and_then(|mut vault| vault.tasks.remove(&number));
182    let rendered = |entry: &Entry<TaskV1>| render_task(&view_of(&c.link(), entry.value.clone()));
183    let answer = match &entry {
184        Some(entry) if entry.fresh(UtcDateTime::now()) => return Ok(rendered(entry)),
185        Some(entry) => format!("{}{}", rendered(entry), stale_note(entry.at)),
186        None => NOT_LOADED.to_string(),
187    };
188    let key = format!("tasks:{}:#{number}", c.project.vault_id);
189    background::submit_once(caller, &key, move || match show_cached(&c.link(), number) {
190        Ok(read) if read.stale.is_some() => None,
191        Ok(read) => {
192            mutate(c.store.data_dir(), &c.project.vault_id, |vault| {
193                vault.tasks.insert(number, Entry::new(read.value.task));
194            });
195            None
196        }
197        Err(error) => Some(format!(
198            "Cloud tasks: task #{number} could not be fetched: {error}"
199        )),
200    });
201    Ok(answer)
202}
203
204/// The open tasks for the session briefing, from the cache; `None` when
205/// there are none. Never waits for Cloud.
206pub(super) fn open_tasks(c: Connected) -> Option<String> {
207    let filter = ListFilter {
208        state: Some(TaskState::Open),
209        ..ListFilter::default()
210    };
211    let query = filter.query().ok()?;
212    let entry = load(c.store.data_dir())
213        .vaults
214        .remove(&c.project.vault_id)
215        .and_then(|mut vault| vault.lists.remove(&query));
216    let answer = match &entry {
217        Some(entry) if entry.fresh(UtcDateTime::now()) => {
218            return (!entry.value.list.tasks.is_empty()).then(|| render_listing(&entry.value, 5));
219        }
220        Some(entry) if entry.value.list.tasks.is_empty() => None,
221        Some(entry) => Some(format!(
222            "{}{}",
223            render_listing(&entry.value, 5),
224            stale_note(entry.at)
225        )),
226        None => Some(
227            "Open Cloud tasks are being fetched in the background (ctx_tasks action=list)."
228                .to_string(),
229        ),
230    };
231    refresh_list(c, query, filter, None);
232    answer
233}
234
235/// Fetch the task lists a session reads first (all, and open) for the
236/// checkout at `project_root` into the cache, in the caller's thread: the
237/// daemon's background sync keeps them warm, so a fresh session answers at
238/// once from them (with their age) instead of "being fetched". A list the
239/// Instance fetched less than [`super::reads::READ_TTL`] ago is not asked
240/// again. `Ok(false)` when tasks do not apply there (no right, not
241/// shared): nothing fetched.
242pub fn warm(project_root: &Path) -> Result<bool, CloudError> {
243    let Ok(c) = connected(project_root, CloudRight::TasksRead) else {
244        return Ok(false);
245    };
246    let open = ListFilter {
247        state: Some(TaskState::Open),
248        ..ListFilter::default()
249    };
250    for filter in [ListFilter::default(), open] {
251        let query = filter.query()?;
252        let read = list_cached(&c.link(), &filter)?;
253        if read.stale.is_some() {
254            continue;
255        }
256        mutate(c.store.data_dir(), &c.project.vault_id, |vault| {
257            vault.lists.insert(query, Entry::new(read.value));
258        });
259    }
260    Ok(true)
261}
262
263/// Queue the change `job` (`what` names it, e.g. "claim of task #4") for
264/// `caller`. Answers at once that it is queued; what Cloud answered comes
265/// with the caller's next `ctx_tasks` call, and the cached lists and tasks
266/// are refreshed on the next read. `Err` at once when tasks do not apply
267/// here with `right` (no request made).
268pub fn queue(
269    project_root: &Path,
270    right: CloudRight,
271    caller: &str,
272    what: &str,
273    job: impl FnOnce() -> Result<String, CloudError> + Send + 'static,
274) -> Result<String, CloudError> {
275    let c = connected(project_root, right)?;
276    let (data_dir, vault_id) = (c.store.data_dir().to_path_buf(), c.project.vault_id);
277    let named = what.to_string();
278    background::submit(caller, move || {
279        let answer = job();
280        outdate(&data_dir, &vault_id);
281        Some(match answer {
282            Ok(text) => text,
283            Err(error) => format!("Cloud tasks ({named}): {error}"),
284        })
285    });
286    Ok(format!(
287        "Queued for the Cloud: {what}. The Cloud's answer comes with your next ctx_tasks call; nothing is confirmed before then."
288    ))
289}
290
291#[cfg(test)]
292mod tests {
293    use super::*;
294    use lean_ctx_protocol::cloud::tasks::TaskListV1;
295
296    #[test]
297    fn an_entry_is_fresh_until_it_ages_or_a_change_outdates_it() {
298        let mut entry = Entry::new(());
299        let now = UtcDateTime::now();
300        assert!(entry.fresh(now));
301        assert!(!entry.fresh(now + lean_ctx_time::Duration::seconds(61)));
302        entry.outdated = true;
303        assert!(!entry.fresh(now));
304    }
305
306    #[test]
307    fn the_cache_keeps_lists_and_tasks_per_vault_and_outdates_them() {
308        let dir = tempfile::tempdir().unwrap();
309        let list: TaskListV1 = serde_json::from_value(serde_json::json!({
310            "schema": lean_ctx_protocol::cloud::tasks::TASK_LIST_SCHEMA,
311            "vault_id": "vlt_a", "tasks": []
312        }))
313        .unwrap();
314        // A list cached before 3.12.3 (no `partial`) reads as whole.
315        let before: TaskListing = serde_json::from_value(serde_json::to_value(&list).unwrap())
316            .expect("an older cached list reads");
317        assert!(!before.partial);
318        mutate(dir.path(), "vlt_a", |vault| {
319            vault.lists.insert(
320                "?state=open".into(),
321                Entry::new(TaskListing {
322                    list: list.clone(),
323                    partial: false,
324                }),
325            );
326        });
327        let cached = load(dir.path());
328        let entry = &cached.vaults["vlt_a"].lists["?state=open"];
329        assert_eq!(entry.value.list, list);
330        assert!(!entry.value.partial);
331        assert!(entry.fresh(UtcDateTime::now()));
332        assert!(!cached.vaults.contains_key("vlt_b"));
333        outdate(dir.path(), "vlt_a");
334        assert!(!load(dir.path()).vaults["vlt_a"].lists["?state=open"].fresh(UtcDateTime::now()));
335    }
336}