Skip to main content

mj_controller/database/
profile_cache.rs

1use super::*;
2
3/// The exact result of a configuration command, once durably projected.
4pub fn load_config_result(session_id: &str, command_id: &str) -> Result<Option<Option<String>>> {
5    Ok(open_reader(&database_path())?
6        .query_row(
7            "SELECT error FROM api_config_results WHERE session_id = ?1 AND command_id = ?2",
8            params![session_id, command_id],
9            |row| row.get(0),
10        )
11        .optional()?)
12}
13
14pub fn load_profile_config_cache(
15    profile: &str,
16    model: &str,
17    fingerprint: &str,
18) -> Result<Option<String>> {
19    load_profile_config_cache_from(&database_path(), profile, model, fingerprint)
20}
21
22pub(crate) fn load_profile_config_cache_from(
23    path: &Path,
24    profile: &str,
25    model: &str,
26    fingerprint: &str,
27) -> Result<Option<String>> {
28    Ok(open_reader(path)?.query_row(
29        "SELECT body FROM profile_config_cache WHERE profile = ?1 AND model = ?2 AND fingerprint = ?3 AND observed_at > ?4",
30        params![profile, model, fingerprint, Utc::now().timestamp() - 86400], |row| row.get(0),
31    ).optional()?)
32}
33
34pub fn save_profile_config_cache(
35    profile: String,
36    model: String,
37    fingerprint: String,
38    body: String,
39) -> Result<()> {
40    submit_database_write("save profile configuration cache", move |connection| {
41        save_profile_config_cache_with(connection, &profile, &model, &fingerprint, &body)
42    })
43}
44
45/// Write one cache row into the store at `path`. The queued writer behind
46/// [`save_profile_config_cache`] serves the live store; this names a store
47/// directly so a caller can use an isolated one.
48#[cfg(test)]
49pub(crate) fn save_profile_config_cache_at(
50    path: &Path,
51    profile: &str,
52    model: &str,
53    fingerprint: &str,
54    body: &str,
55) -> Result<()> {
56    save_profile_config_cache_with(&open(path)?, profile, model, fingerprint, body)
57}
58
59pub(super) fn save_profile_config_cache_with(
60    connection: &Connection,
61    profile: &str,
62    model: &str,
63    fingerprint: &str,
64    body: &str,
65) -> Result<()> {
66    connection.execute("INSERT OR REPLACE INTO profile_config_cache(profile, model, fingerprint, observed_at, body) VALUES (?1, ?2, ?3, ?4, ?5)", params![profile, model, fingerprint, Utc::now().timestamp(), body])?;
67    Ok(())
68}