ctb_storage/
storage.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! Storage subsystem managing database access, tenancy, and data persistence.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace crate prelude"
26)]
27pub(crate) use ctb_utilities::*;
28
29#[allow(
30    unused_imports,
31    clippy::wildcard_imports,
32    reason = "Standard workspace prelude"
33)]
34pub use ctb_utilities::ipc::service_prelude::*;
35
36use anyhow::{Context, Result};
37use ctb_formats_html::html2text_with_width;
38use ctb_formats_troff::convert_man_troff_to_html;
39use ctb_utilities::string::remove_suffix_unchecked;
40use encre_css::{Config, Preflight};
41use handlebars::Handlebars;
42use std::{
43    fs::{self, OpenOptions},
44    io::Write,
45    path::{Path, PathBuf},
46};
47
48pub mod db;
49pub mod models;
50pub use models::{graph, node, sync, user};
51pub mod global_graph_layout;
52pub mod migrations;
53pub mod packaged_node;
54mod resource_bundle;
55mod secret;
56pub use models::graph::get_global_graph;
57
58pub mod cli;
59
60#[cfg(test)]
61pub(crate) fn get_storage_fixture(key: &str) -> Option<Vec<u8>> {
62    ctb_utilities::load_manifest_fixture(env!("CARGO_MANIFEST_DIR"), key)
63}
64
65pub fn put(key: Vec<u8>, value: Vec<u8>) {
66    println!(
67        "Storage put with key {}, value {}",
68        String::from_utf8_lossy(&key),
69        String::from_utf8_lossy(&value)
70    );
71}
72
73pub fn get(key: Vec<u8>) -> Option<Vec<u8>> {
74    println!("Storage get with key {}", String::from_utf8_lossy(&key));
75    Some(key)
76}
77
78pub fn create_store(_name: String, _password: String) {}
79
80pub fn get_asset(key: &str) -> Option<Vec<u8>> {
81    resource_bundle::get_asset(key)
82}
83
84/// Find assets in the runtime resource bundle.
85///
86pub fn find_assets(glob: &str) -> Result<Vec<String>> {
87    resource_bundle::find_assets(glob)
88}
89
90pub fn validate_resource_bundle() -> Result<()> {
91    resource_bundle::validate_resource_bundle()
92}
93
94pub fn get_help_troff() -> Result<Vec<u8>> {
95    get_asset("docs/cli/ctoolbox.1").context("Could not load help")
96}
97
98pub fn get_help_html() -> Result<Vec<u8>> {
99    let (converted, log) = convert_man_troff_to_html(get_help_troff()?)?;
100    log.auto_log();
101    Ok(converted)
102}
103
104pub fn get_help_for_tty(width: u16) -> Result<Vec<u8>> {
105    html2text_with_width(get_help_html()?, width)
106}
107
108pub fn get_asset_utf8(key: &str) -> Result<String> {
109    resource_bundle::get_asset_utf8(key)
110}
111
112fn inline_css_imports(css: &str, base_path: &str) -> Result<String> {
113    fn normalize_path(p: &Path) -> PathBuf {
114        let mut stack = Vec::new();
115        for component in p.components() {
116            match component {
117                std::path::Component::Normal(c) => stack.push(c),
118                std::path::Component::ParentDir => {
119                    stack.pop();
120                }
121                std::path::Component::CurDir => {}
122                _ => {}
123            }
124        }
125        stack.into_iter().collect()
126    }
127
128    let mut result = String::new();
129    for line in css.lines() {
130        if line.trim_start().starts_with("@import") {
131            let trimmed = line.trim_start();
132            if trimmed == "@import \"tailwindcss\";" {
133                continue;
134            }
135            if let Some(start) = trimmed.find("url('")
136                && let Some(sub) = trimmed.get(start.saturating_add(5)..)
137                && let Some(end) = sub.find("')")
138                && let Some(path) = sub.get(..end)
139            {
140                let resolved =
141                    if path.starts_with("web/") || path.starts_with('/') {
142                        // Reason for fallback: CSS import path without leading slash retains original path string
143                        path.strip_prefix('/').unwrap_or(path).to_string()
144                    } else {
145                        Path::new(base_path)
146                            .join(path)
147                            .to_string_lossy()
148                            .to_string()
149                    };
150                let resolved_path = Path::new(&resolved);
151                let normalized = normalize_path(resolved_path);
152                let resolved = normalized.to_string_lossy().replace('\\', "/");
153                let imported_css = String::from_utf8(
154                    get_asset(&resolved).ok_or_else(|| {
155                        anyhow::anyhow!(
156                            "Failed to load imported CSS: {resolved}"
157                        )
158                    })?,
159                )
160                .with_context(|| {
161                    format!(
162                        "Failed to convert imported CSS to string: {resolved}"
163                    )
164                })?;
165                let new_base = Path::new(&resolved)
166                    .parent()
167                    // Reason for fallback: root asset path without parent directory defaults parent path to empty Path
168                    .unwrap_or(Path::new(""))
169                    .to_string_lossy()
170                    .replace('\\', "/");
171                let inlined = inline_css_imports(&imported_css, &new_base)?;
172                result.push_str(&inlined);
173                result.push('\n');
174                continue;
175            }
176            return Err(anyhow::anyhow!(
177                "Failed to parse @import line: {line}"
178            ));
179        }
180        result.push_str(line);
181        result.push('\n');
182    }
183    Ok(result)
184}
185
186#[expect(clippy::too_many_lines, reason = "large register_views function")]
187pub fn register_views<'a>() -> Result<handlebars::Handlebars<'a>> {
188    let mut handlebars = Handlebars::new();
189    handlebars.set_strict_mode(true);
190    let mut buffer = String::new();
191    let views = find_assets("**/*.hbs")?;
192    for path in views {
193        let template_name = substr_mb(path.as_str(), 6, -4)?.replace('/', ".");
194        // log!(format!("Registering template {}", template_name));
195        let template_contents = get_asset_utf8(&path)?;
196        handlebars.register_template_string(
197            template_name.as_str(),
198            template_contents.as_str(),
199        )?;
200        buffer.push_str(&template_contents);
201    }
202    let html = find_assets("views/**/*.html")?;
203    for path in html {
204        let file_contents = get_asset_utf8(&path)?;
205        // log!(format!("Adding HTML from {}, contents {}", path.display(), file_contents));
206        buffer.push_str(&file_contents);
207    }
208    let html = find_assets("web/**/*.html")?;
209    for path in html {
210        let file_contents = get_asset_utf8(&path)?;
211        // log!(format!("Adding HTML from {}, contents {}", path.display(), file_contents));
212        buffer.push_str(&file_contents);
213    }
214    let js = find_assets("web/**/*.js")?;
215    for path in js {
216        let file_contents = get_asset_utf8(&path)?;
217        // log!(format!("Adding JS from {}, contents {}", path.display(), file_contents));
218        buffer.push_str(&file_contents);
219    }
220
221    // JS
222    let _js = String::from_utf8(bail_if_none!(get_asset("web/app.js")))?;
223
224    let mut config = Config::default();
225    let mut css: String = String::new();
226
227    // Imports
228
229    let app_css = String::from_utf8(bail_if_none!(get_asset("web/app.css")))?;
230
231    // Preflight
232    config.preflight = Preflight::new_full();
233    css.push_str(encre_css::generate([""], &config).as_str());
234
235    config.preflight = Preflight::new_none();
236
237    // Inline imports
238
239    let inlined_app_css = inline_css_imports(&app_css, "web/")
240        .context("Failed to inline imports")?;
241
242    // app.css
243    for line in inlined_app_css.lines() {
244        if line.trim_start().starts_with("@apply") {
245            let html = format!(
246                "<div class='{}'></div>",
247                remove_suffix_unchecked(line, ";")
248            );
249            let html_css = encre_css::generate([html.as_str()], &config);
250            let html_css = html_css.as_str();
251            let mut starting_media_query;
252            let mut in_media_query = false;
253            let mut leaving_media_query;
254            for line in html_css.lines() {
255                starting_media_query = line.starts_with('@');
256                leaving_media_query = line.starts_with('}') && in_media_query;
257                if (!in_media_query && line.starts_with(' '))
258                    || starting_media_query
259                    || (in_media_query
260                        && !line.ends_with('{')
261                        && !line.ends_with('}'))
262                    || leaving_media_query
263                {
264                    css.push_str(format!("{line}\n").as_str());
265                }
266                if starting_media_query {
267                    in_media_query = true;
268                }
269                if leaving_media_query {
270                    in_media_query = false;
271                }
272            }
273            continue;
274        }
275        css.push_str(format!("{line}\n").as_str());
276    }
277
278    // Views
279    let css_from_views = encre_css::generate([buffer.as_str()], &config);
280    for line in css_from_views.lines() {
281        if line == "@media (prefers-color-scheme: dark) {" {
282            css.push_str(
283                format!("{}\n", "@container dark (width > 0) {").as_str(),
284            );
285        } else if line.trim_start().starts_with('@') {
286            css.push_str(format!("{line}\n").as_str());
287        } else {
288            css.push_str(
289                format!("{line}\n")
290                    .as_str()
291                    .replace(" {", ":not(#increase-specificity) {")
292                    .as_str(),
293            );
294        }
295    }
296    css.push('\n');
297    config.preflight = Preflight::new_none();
298
299    // log!(css);
300    ensure!(
301        handlebars
302            .register_template_string("encre_css", css)
303            .is_ok()
304    );
305    handlebars.set_strict_mode(true);
306    Ok(handlebars)
307}
308
309pub fn guarantee_dir(path: &Path) -> Result<()> {
310    if let Some(parent) = path.parent()
311        && !parent.exists()
312    {
313        fs::create_dir_all(parent).with_context(|| {
314            format!("Failed to create parent dir {parent:?}")
315        })?;
316    }
317    Ok(())
318}
319
320pub fn put_file(path: &Path, data: &[u8]) -> Result<()> {
321    guarantee_dir(path)?;
322    overwrite_file(path, data)
323}
324
325pub fn append_file(path: &Path, data: &[u8]) -> Result<()> {
326    guarantee_dir(path)?;
327    let mut file = OpenOptions::new()
328        .create(true)
329        .append(true)
330        .open(path)
331        .with_context(|| {
332            format!("Failed to open file for appending {path:?}")
333        })?;
334    file.write_all(data)
335        .with_context(|| format!("Failed to append data to {path:?}"))
336}
337
338pub fn overwrite_file(path: &Path, data: &[u8]) -> Result<()> {
339    guarantee_dir(path)?;
340    fs::write(path, data)
341        .with_context(|| format!("Failed to overwrite file {path:?}"))
342}
343
344#[cfg(test)]
345#[allow(
346    clippy::panic,
347    clippy::expect_used,
348    clippy::unwrap_used,
349    clippy::unwrap_in_result,
350    clippy::panic_in_result_fn,
351    clippy::indexing_slicing,
352    clippy::arithmetic_side_effects,
353    reason = "Standard repository test boilerplate"
354)]
355mod tests {
356    use super::*;
357
358    #[crate::ctb_test]
359    fn can_get_asset() {
360        assert_eq!(
361            strtovec("Hello, world!"),
362            get_asset("fixtures/hello.txt").expect("Could not load hello.txt")
363        );
364    }
365
366    #[crate::ctb_test]
367    fn can_store_and_get_value() {
368        put("key".as_bytes().to_owned(), "value".as_bytes().to_owned());
369        assert_eq!(
370            "key",
371            String::from_utf8_lossy(&get(strtovec("key")).unwrap())
372        );
373    }
374
375    #[crate::ctb_test]
376    fn can_get_help_troff() -> Result<()> {
377        assert!(
378            String::from_utf8_lossy(&get_help_troff()?)
379                .contains(".SH SYNOPSIS")
380        );
381        Ok(())
382    }
383
384    #[crate::ctb_test]
385    fn can_get_help_html() -> Result<()> {
386        assert!(
387            String::from_utf8_lossy(&get_help_html()?)
388                .contains(">Synopsis</h2>")
389        );
390        Ok(())
391    }
392
393    #[crate::ctb_test]
394    fn can_get_help_for_tty() -> Result<()> {
395        assert!(
396            String::from_utf8_lossy(&get_help_for_tty(8)?).contains("## iptio")
397        );
398        Ok(())
399    }
400}