Skip to main content

waratah_storage/
layout.rs

1//! On-disk directory layout under a cluster `--data-dir`.
2//!
3//! `--data-dir` is the cluster root. Every repository gets its own store
4//! subtree and a sibling ingest staging tree:
5//!
6//! ```text
7//! {data_dir}/{repository}/s          hexastore S (SPOG, SOPG, named_graphs_catalog)
8//! {data_dir}/{repository}/p          hexastore P
9//! {data_dir}/{repository}/o          hexastore O
10//! {data_dir}/{repository}/registry   string registry
11//! {data_dir}/{repository}/registry.sst-staging
12//!                                    offline-import registry SST runs
13//! {data_dir}/ingest/{repository}/    HTTP / operator staging files
14//! {data_dir}/notebooks/              jupyter Contents root (--with-notebooks)
15//! {data_dir}/notebooks-runtime/      generated sidecar config + jupyter runtime files
16//! {data_dir}/notebooks-venv/         auto-provisioned pinned Python environment
17//! ```
18//!
19//! The MVP repository id is always [`MAIN_REPOSITORY_ID`] (`"main"`). HTTP
20//! ingest joins the `{repository_id}` path segment onto `--ingest-dir` (default
21//! `{data_dir}/ingest`) so a later catalog can add more repositories without
22//! moving the `s`/`p`/`o`/`registry` folders. The query library joins the
23//! same segment onto `--queries-dir` (no default;
24//! `waratah_api/src/query_library.rs`).
25//!
26//! Repository ids reach both join helpers only after the HTTP layer checked
27//! them against the repository catalog, so path traversal through
28//! `{repository_id}` is impossible today; a future multi-repo catalog must
29//! keep that gate (or add a charset check here) before these helpers see
30//! client-supplied ids.
31
32use std::path::{Path, PathBuf};
33
34use crate::registry::REGISTRY_DIR_NAME;
35use crate::types::PartitionAxis;
36
37/// MVP / default repository id used in on-disk paths and HTTP URLs.
38pub const MAIN_REPOSITORY_ID: &str = "main";
39
40/// Directory name under `--data-dir` that holds per-repository ingest trees.
41pub const INGEST_DIR_NAME: &str = "ingest";
42
43/// `{data_dir}/{repository}` — RocksDB stores for one repository.
44pub fn repository_store_dir(data_dir: impl AsRef<Path>, repository: &str) -> PathBuf {
45    data_dir.as_ref().join(repository)
46}
47
48/// Hexastore axis RocksDB: `{data_dir}/{repository}/{axis}`.
49pub fn hexastore_data_dir(
50    data_dir: impl AsRef<Path>,
51    repository: &str,
52    axis: PartitionAxis,
53) -> PathBuf {
54    repository_store_dir(data_dir, repository).join(axis.as_str())
55}
56
57/// The text plugin's Tantivy directory beside a hexastore directory:
58/// `{data_dir}/{repository}/o` → `{data_dir}/{repository}/o-text-index`.
59///
60/// `None` only for a path with no file name (never for a store dir). The
61/// naming rule lives here so the storage handle and the offline preflight
62/// cannot disagree about where an existing index is.
63pub fn text_index_dir_beside(hexastore_dir: impl AsRef<Path>) -> Option<PathBuf> {
64    let hexastore_dir = hexastore_dir.as_ref();
65    let name = hexastore_dir.file_name()?.to_string_lossy();
66    Some(hexastore_dir.with_file_name(format!("{name}-text-index")))
67}
68
69/// String-registry RocksDB: `{data_dir}/{repository}/registry`.
70pub fn registry_data_dir(data_dir: impl AsRef<Path>, repository: &str) -> PathBuf {
71    repository_store_dir(data_dir, repository).join(REGISTRY_DIR_NAME)
72}
73
74/// Offline-import registry SST runs beside the registry directory.
75///
76/// `Path::with_extension` on [`registry_data_dir`]: the directory has no
77/// extension, so this is `{data_dir}/{repository}/registry.sst-staging`.
78/// Finished runs are `run-NNNNNN.sst`. `run-NNNNNN.sst.partial` is an
79/// in-progress chunk and is never ingested.
80pub fn registry_sst_staging_dir(registry_path: impl AsRef<Path>) -> PathBuf {
81    registry_path.as_ref().with_extension("sst-staging")
82}
83
84/// Directory name of the content-addressed blob store under a repository
85/// (registry-process files, not a RocksDB CF).
86pub const BLOB_DIR_NAME: &str = "blobs";
87
88/// Directory name of the blob store's RocksDB index under `blobs/`.
89///
90/// The index maps a 16-byte content hash to either an inline payload or a
91/// segment locator. It is a separate RocksDB DB from the string dictionary:
92/// the dictionary is a bulk sorted walk, while the blob index is a point
93/// lookup, and they need different block sizes and caches.
94pub const BLOB_INDEX_DIR_NAME: &str = "index";
95
96/// Directory name of the append-only blob segment files under `blobs/`.
97pub const BLOB_SEGMENTS_DIR_NAME: &str = "segments";
98
99/// Blob store root for `repository`: `{data_dir}/{repository}/blobs`.
100pub fn blob_store_dir(data_dir: impl AsRef<Path>, repository: &str) -> PathBuf {
101    repository_store_dir(data_dir, repository).join(BLOB_DIR_NAME)
102}
103
104/// RocksDB index directory under a blob store root.
105pub fn blob_index_dir(blobs_root: impl AsRef<Path>) -> PathBuf {
106    blobs_root.as_ref().join(BLOB_INDEX_DIR_NAME)
107}
108
109/// Append-only segment directory under a blob store root.
110pub fn blob_segments_dir(blobs_root: impl AsRef<Path>) -> PathBuf {
111    blobs_root.as_ref().join(BLOB_SEGMENTS_DIR_NAME)
112}
113
114/// Parent of per-repository ingest trees.
115///
116/// `{data_dir}/ingest` when `--data-dir` is set, otherwise `./ingest`.
117/// `--ingest-dir PATH` replaces this parent; files still live in `{PATH}/{repository}`.
118pub fn ingest_root_dir(data_dir: Option<&Path>) -> PathBuf {
119    match data_dir {
120        Some(dir) => dir.join(INGEST_DIR_NAME),
121        None => PathBuf::from(INGEST_DIR_NAME),
122    }
123}
124
125/// Staging directory for one repository: `{ingest_root}/{repository}`.
126pub fn ingest_staging_dir(ingest_root: impl AsRef<Path>, repository: &str) -> PathBuf {
127    ingest_root.as_ref().join(repository)
128}
129
130/// Per-repository query-library directory: `{queries_root}/{repository}`.
131///
132/// Served by `GET /waratah/repositories/{id}/queries` when the process runs
133/// with `--queries-dir`. Each `*.rq` file in the directory is one published
134/// query (`id` = filename stem); an optional sibling `<stem>.toml` sidecar
135/// carries display metadata. There is no `{data_dir}`-derived default: an
136/// unset `--queries-dir` means the endpoint is unconfigured (`501`).
137///
138/// `repository` must come from the repository catalog, never raw user
139/// input — the HTTP handler checks the catalog before joining (same trust
140/// shape as [`ingest_staging_dir`]).
141pub fn queries_repo_dir(queries_root: impl AsRef<Path>, repository: &str) -> PathBuf {
142    queries_root.as_ref().join(repository)
143}
144
145/// Directory name of the notebook Contents root under `--data-dir`.
146pub const NOTEBOOKS_DIR_NAME: &str = "notebooks";
147
148/// Contents-API root for the notebook service (`--with-notebooks`).
149///
150/// `{data_dir}/notebooks` when `--data-dir` is set, otherwise `./notebooks`
151/// (same convention as [`ingest_root_dir`]).
152pub fn notebooks_root_dir(data_dir: Option<&Path>) -> PathBuf {
153    match data_dir {
154        Some(dir) => dir.join(NOTEBOOKS_DIR_NAME),
155        None => PathBuf::from(NOTEBOOKS_DIR_NAME),
156    }
157}
158
159/// Directory name of the notebook sidecar runtime files under `--data-dir`.
160pub const NOTEBOOKS_RUNTIME_DIR_NAME: &str = "notebooks-runtime";
161
162/// Sidecar runtime dir: the generated config (which carries the token) and
163/// jupyter runtime files (kernel connection JSONs, cookie secret).
164///
165/// `{data_dir}/notebooks-runtime` when `--data-dir` is set, otherwise
166/// `./notebooks-runtime` (same convention as [`notebooks_root_dir`]).
167/// Deliberately never the shared system temp dir: two dev clusters would
168/// clobber each other's token-bearing config there.
169pub fn notebooks_runtime_dir(data_dir: Option<&Path>) -> PathBuf {
170    match data_dir {
171        Some(dir) => dir.join(NOTEBOOKS_RUNTIME_DIR_NAME),
172        None => PathBuf::from(NOTEBOOKS_RUNTIME_DIR_NAME),
173    }
174}
175
176/// Auto-provisioned Python venv root for the notebook sidecar.
177///
178/// `{data_dir}/notebooks-venv` when `--data-dir` is set, otherwise
179/// `./notebooks-venv` — deliberately NOT the temp dir: the venv is expensive
180/// to build and must survive restarts.
181pub fn notebooks_venv_dir(data_dir: Option<&Path>) -> PathBuf {
182    match data_dir {
183        Some(dir) => dir.join("notebooks-venv"),
184        None => PathBuf::from("notebooks-venv"),
185    }
186}
187
188#[cfg(test)]
189mod tests {
190    use super::*;
191
192    #[test]
193    fn cluster_layout_nests_under_repository() {
194        let root = Path::new("/usr/share/waratah/data");
195        assert_eq!(
196            hexastore_data_dir(root, MAIN_REPOSITORY_ID, PartitionAxis::S),
197            PathBuf::from("/usr/share/waratah/data/main/s")
198        );
199        assert_eq!(
200            hexastore_data_dir(root, MAIN_REPOSITORY_ID, PartitionAxis::P),
201            PathBuf::from("/usr/share/waratah/data/main/p")
202        );
203        assert_eq!(
204            hexastore_data_dir(root, MAIN_REPOSITORY_ID, PartitionAxis::O),
205            PathBuf::from("/usr/share/waratah/data/main/o")
206        );
207        assert_eq!(
208            registry_data_dir(root, MAIN_REPOSITORY_ID),
209            PathBuf::from("/usr/share/waratah/data/main/registry")
210        );
211        assert_eq!(
212            ingest_staging_dir(ingest_root_dir(Some(root)), MAIN_REPOSITORY_ID),
213            PathBuf::from("/usr/share/waratah/data/ingest/main")
214        );
215        assert_eq!(
216            ingest_staging_dir(ingest_root_dir(None), MAIN_REPOSITORY_ID),
217            PathBuf::from("ingest/main")
218        );
219        assert_eq!(
220            queries_repo_dir(Path::new("/opt/waratah/queries"), MAIN_REPOSITORY_ID),
221            PathBuf::from("/opt/waratah/queries/main")
222        );
223        assert_eq!(
224            notebooks_root_dir(Some(root)),
225            PathBuf::from("/usr/share/waratah/data/notebooks")
226        );
227        assert_eq!(notebooks_root_dir(None), PathBuf::from("notebooks"));
228        assert_eq!(notebooks_venv_dir(None), PathBuf::from("notebooks-venv"));
229    }
230}