use indicatrix_net::{
library::{
AngleSettingWire, AttachedFileMeta, AttributeRangesWire, DesignRecord, DesignSummary,
LibraryRequest, LibraryResponse, PerformanceAggregateWire, PerformanceBoundWire,
PerformanceFilterWire, PerformanceMetricWire, RangeFilterWire,
},
messages::ErrorMsg,
};
use indicatrix_vault::{
db::sqlite::{Database, SEARCH_RESULT_CAP},
model::{
entry::{DiagramListItem, FullDiagramMeta},
filter::{AttributeRanges, RangeFilter},
performance::{
PerformanceAggregate, PerformanceBound, PerformanceFilter, PerformanceMetric,
},
},
};
use sha2::{Digest, Sha256};
pub const LIBRARY_VALIDATION_ERROR_CODE: u32 = 5;
pub const LIBRARY_ERROR_CODE: u32 = 4;
#[must_use]
pub fn handle_request(request: &LibraryRequest, db: &Database) -> LibraryResponse {
match request {
LibraryRequest::Search {
query,
shape_filter,
gear_filter,
range,
} => {
let range = match from_range_wire(range) {
Ok(r) => r,
Err(resp) => return resp,
};
match db.search_diagrams_with_performance_exclusions(
query,
shape_filter,
gear_filter,
&range,
) {
Ok(result) => LibraryResponse::SearchResults {
items: result.items.iter().map(to_summary).collect(),
excluded_for_missing_curves: result.excluded_for_missing_curves as u32,
},
Err(e) => db_error("search_diagrams_with_performance_exclusions", &e),
}
}
LibraryRequest::FilterOptions => filter_options(db),
LibraryRequest::FetchDesign { entry_id } => match db.get_diagram_full_meta(*entry_id) {
Ok(Some(meta)) => {
let preview_material = db
.get_preview_images(*entry_id)
.ok()
.and_then(|p| p.material);
LibraryResponse::Design(Box::new(to_record(&meta, preview_material)))
}
Ok(None) => LibraryResponse::NotFound,
Err(e) => db_error("get_diagram_full_meta", &e),
},
LibraryRequest::FetchAttachment { attachment_id } => {
match db.get_attachment_content(*attachment_id) {
Ok(Some((name, content))) => LibraryResponse::Attachment { name, content },
Ok(None) => LibraryResponse::NotFound,
Err(e) => db_error("get_attachment_content", &e),
}
}
LibraryRequest::SearchPage {
query,
shape_filter,
gear_filter,
range,
cursor,
} => search_page(db, query, shape_filter, gear_filter, range, *cursor),
LibraryRequest::FetchDesignSource { entry_id } => design_source(db, *entry_id),
}
}
fn design_source(db: &Database, entry_id: i64) -> LibraryResponse {
let meta = match db.get_diagram_full_meta(entry_id) {
Ok(Some(meta)) => meta,
Ok(None) => {
tracing::debug!("FetchDesignSource: entry {entry_id} not found");
return LibraryResponse::NotFound;
}
Err(e) => return db_error("get_diagram_full_meta", &e),
};
let Some(attachment) = meta
.attached_files
.iter()
.find(|f| f.name.to_lowercase().ends_with(".asc"))
else {
tracing::debug!("FetchDesignSource: entry {entry_id} has no .asc attachment");
return LibraryResponse::DesignSourceNotAvailable;
};
match db.get_attachment_content(attachment.id) {
Ok(Some((name, content))) => {
tracing::debug!(
"FetchDesignSource: entry {entry_id} serving attachment {} ('{name}', {} bytes)",
attachment.id,
content.len()
);
LibraryResponse::DesignSource {
entry_id,
file_name: name,
asc_text: String::from_utf8_lossy(&content).into_owned(),
}
}
Ok(None) => {
tracing::debug!(
"FetchDesignSource: entry {entry_id}'s .asc attachment {} vanished concurrently",
attachment.id
);
LibraryResponse::DesignSourceNotAvailable
}
Err(e) => db_error("get_attachment_content", &e),
}
}
fn search_page(
db: &Database,
query: &str,
shape_filter: &str,
gear_filter: &str,
range: &RangeFilterWire,
cursor: Option<i64>,
) -> LibraryResponse {
let range = match from_range_wire(range) {
Ok(r) => r,
Err(resp) => return resp,
};
match db.search_diagrams_page(
query,
shape_filter,
gear_filter,
&range,
cursor,
SEARCH_RESULT_CAP,
) {
Ok(items) => {
let page_full = items.len() == usize::try_from(SEARCH_RESULT_CAP).unwrap_or(usize::MAX);
let next_cursor = if page_full {
items.last().map(|i| i.id)
} else {
None
};
LibraryResponse::SearchResultsPage {
results: items.iter().map(to_summary).collect(),
next_cursor,
excluded_for_missing_curves: 0,
}
}
Err(e) => db_error("search_diagrams_page", &e),
}
}
fn filter_options(db: &Database) -> LibraryResponse {
let shapes = match db.get_unique_shapes() {
Ok(v) => v,
Err(e) => return db_error("get_unique_shapes", &e),
};
let gears = match db.get_unique_gears() {
Ok(v) => v,
Err(e) => return db_error("get_unique_gears", &e),
};
let ranges = match db.get_attribute_ranges() {
Ok(v) => v,
Err(e) => return db_error("get_attribute_ranges", &e),
};
LibraryResponse::FilterOptions {
shapes,
gears,
ranges: to_ranges_wire(ranges),
}
}
fn db_error(op: &str, e: &anyhow::Error) -> LibraryResponse {
tracing::warn!("library request failed ({op}): {e:#}");
LibraryResponse::Error(ErrorMsg {
code: LIBRARY_ERROR_CODE,
message: "internal error serving the design library".to_string(),
})
}
fn from_range_wire(r: &RangeFilterWire) -> Result<RangeFilter, LibraryResponse> {
let mut performance = Vec::with_capacity(r.performance.len());
for wire_filter in &r.performance {
performance.push(from_performance_filter_wire(wire_filter).map_err(|e| {
tracing::warn!("library request rejected: {e:#}");
LibraryResponse::Error(ErrorMsg {
code: LIBRARY_VALIDATION_ERROR_CODE,
message: "invalid tilt-performance filter in search request".to_string(),
})
})?);
}
Ok(RangeFilter {
ri_min: r.ri_min,
ri_max: r.ri_max,
lw_min: r.lw_min,
lw_max: r.lw_max,
volume_min: r.volume_min,
volume_max: r.volume_max,
facets_min: r.facets_min,
facets_max: r.facets_max,
ri_tolerance: r.ri_tolerance,
include_ignored: r.include_ignored,
performance,
})
}
fn from_performance_filter_wire(
wire: &PerformanceFilterWire,
) -> Result<PerformanceFilter, indicatrix_vault::model::performance::InvalidTiltRadius> {
let metric = match wire.metric {
PerformanceMetricWire::Brilliance => PerformanceMetric::Brilliance,
PerformanceMetricWire::Extinction => PerformanceMetric::Extinction,
PerformanceMetricWire::Windowing => PerformanceMetric::Windowing,
};
let bound = match wire.bound {
PerformanceBoundWire::AtMost(t) => PerformanceBound::AtMost(t),
PerformanceBoundWire::AtLeast(t) => PerformanceBound::AtLeast(t),
};
let aggregate = match wire.aggregate {
PerformanceAggregateWire::Worst => PerformanceAggregate::Worst,
PerformanceAggregateWire::Mean => PerformanceAggregate::Mean,
};
PerformanceFilter::new(metric, bound, wire.tilt_radius_deg, aggregate)
}
const fn to_ranges_wire(r: AttributeRanges) -> AttributeRangesWire {
AttributeRangesWire {
ri: r.ri,
lw_ratio: r.lw_ratio,
volume: r.volume,
facets: r.facets,
}
}
fn to_summary(item: &DiagramListItem) -> DesignSummary {
let mut summary = DesignSummary {
entry_id: item.id,
title: item.title.clone(),
url: item.url.clone(),
design_id: item.design_id.clone(),
shape: item.shape.clone(),
index_gear: item.index_gear.clone(),
facets_count: item.facets_count.clone(),
designer_info: item.designer_info.clone(),
lw_ratio: item.lw_ratio.clone(),
refractive_index: item.refractive_index.clone(),
volume: item.volume.clone(),
competition_diagram: item.competition_diagram.clone(),
ignored: item.ignored,
version: [0u8; 32],
};
summary.version = hash_summary(&summary);
summary
}
fn to_record(meta: &FullDiagramMeta, preview_material: Option<String>) -> DesignRecord {
let angle_settings = meta
.angle_settings
.iter()
.map(|a| AngleSettingWire {
order_index: a.order_index,
facet: a.facet.clone(),
angle: a.angle.clone(),
index: a.index.clone(),
notes: a.notes.clone(),
})
.collect();
let attachments = meta
.attached_files
.iter()
.map(|f| AttachedFileMeta {
id: f.id,
name: f.name.clone(),
url: f.url.clone(),
size: u64::try_from(f.size).unwrap_or(0),
})
.collect();
let mut record = DesignRecord {
entry_id: meta.entry_id,
title: meta.title.clone(),
url: meta.url.clone(),
design_id: meta.design_id.clone(),
page_url: meta.page_url.clone(),
diagram_image_name: meta.diagram_image_name.clone(),
diagram_image_data: meta.diagram_image_data.clone(),
competition_diagram: meta.competition_diagram.clone(),
lw_ratio: meta.lw_ratio.clone(),
refractive_index: meta.refractive_index.clone(),
index_gear: meta.index_gear.clone(),
volume: meta.volume.clone(),
facets_count: meta.facets_count.clone(),
shape: meta.shape.clone(),
designer_info: meta.designer_info.clone(),
angle_settings,
attachments,
preview_material,
hw_ratio: meta.hw_ratio.clone(),
tw_ratio: meta.tw_ratio.clone(),
uw_ratio: meta.uw_ratio.clone(),
pw_ratio: meta.pw_ratio.clone(),
cw_ratio: meta.cw_ratio.clone(),
symmetry_order: meta.symmetry_order.clone(),
mirror_symmetry: meta.mirror_symmetry,
designer: meta.designer.clone(),
version: [0u8; 32],
};
record.version = hash_record(&record);
record
}
fn hash_str(hasher: &mut Sha256, s: &str) {
hasher.update((s.len() as u64).to_le_bytes());
hasher.update(s.as_bytes());
}
fn hash_opt_str(hasher: &mut Sha256, s: Option<&str>) {
match s {
Some(s) => {
hasher.update([1u8]);
hash_str(hasher, s);
}
None => hasher.update([0u8]),
}
}
fn hash_opt_bytes(hasher: &mut Sha256, b: Option<&[u8]>) {
match b {
Some(b) => {
hasher.update([1u8]);
hasher.update((b.len() as u64).to_le_bytes());
hasher.update(b);
}
None => hasher.update([0u8]),
}
}
fn hash_opt_bool(hasher: &mut Sha256, b: Option<bool>) {
match b {
Some(b) => hasher.update([1u8, u8::from(b)]),
None => hasher.update([0u8]),
}
}
fn hash_summary(s: &DesignSummary) -> [u8; 32] {
let mut hasher = Sha256::new();
hasher.update(s.entry_id.to_le_bytes());
hash_str(&mut hasher, &s.title);
hash_str(&mut hasher, &s.url);
hash_opt_str(&mut hasher, s.design_id.as_deref());
hash_opt_str(&mut hasher, s.shape.as_deref());
hash_opt_str(&mut hasher, s.index_gear.as_deref());
hash_opt_str(&mut hasher, s.facets_count.as_deref());
hash_opt_str(&mut hasher, s.designer_info.as_deref());
hash_opt_str(&mut hasher, s.lw_ratio.as_deref());
hash_opt_str(&mut hasher, s.refractive_index.as_deref());
hash_opt_str(&mut hasher, s.volume.as_deref());
hash_opt_str(&mut hasher, s.competition_diagram.as_deref());
hasher.update([u8::from(s.ignored)]);
hasher.finalize().into()
}
fn hash_record(r: &DesignRecord) -> [u8; 32] {
let mut hasher = Sha256::new();
hasher.update(r.entry_id.to_le_bytes());
hash_str(&mut hasher, &r.title);
hash_str(&mut hasher, &r.url);
hash_opt_str(&mut hasher, r.design_id.as_deref());
hash_str(&mut hasher, &r.page_url);
hash_opt_str(&mut hasher, r.diagram_image_name.as_deref());
hash_opt_bytes(&mut hasher, r.diagram_image_data.as_deref());
hash_opt_str(&mut hasher, r.competition_diagram.as_deref());
hash_opt_str(&mut hasher, r.lw_ratio.as_deref());
hash_opt_str(&mut hasher, r.refractive_index.as_deref());
hash_opt_str(&mut hasher, r.index_gear.as_deref());
hash_opt_str(&mut hasher, r.volume.as_deref());
hash_opt_str(&mut hasher, r.facets_count.as_deref());
hash_opt_str(&mut hasher, r.shape.as_deref());
hash_opt_str(&mut hasher, r.designer_info.as_deref());
hash_opt_str(&mut hasher, r.preview_material.as_deref());
hash_opt_str(&mut hasher, r.hw_ratio.as_deref());
hash_opt_str(&mut hasher, r.tw_ratio.as_deref());
hash_opt_str(&mut hasher, r.uw_ratio.as_deref());
hash_opt_str(&mut hasher, r.pw_ratio.as_deref());
hash_opt_str(&mut hasher, r.cw_ratio.as_deref());
hash_opt_str(&mut hasher, r.symmetry_order.as_deref());
hash_opt_bool(&mut hasher, r.mirror_symmetry);
hash_opt_str(&mut hasher, r.designer.as_deref());
hasher.update((r.angle_settings.len() as u64).to_le_bytes());
for a in &r.angle_settings {
hasher.update(a.order_index.to_le_bytes());
hash_str(&mut hasher, &a.facet);
hash_str(&mut hasher, &a.angle);
hash_str(&mut hasher, &a.index);
hash_str(&mut hasher, &a.notes);
}
hasher.update((r.attachments.len() as u64).to_le_bytes());
for f in &r.attachments {
hasher.update(f.id.to_le_bytes());
hash_str(&mut hasher, &f.name);
hash_str(&mut hasher, &f.url);
hasher.update(f.size.to_le_bytes());
}
hasher.finalize().into()
}
#[cfg(test)]
mod tests {
use super::*;
use indicatrix_vault::model::{
detail::FacetDiagramDetail, entry::FacetDiagramEntry, file::AttachedFile,
};
fn populated_temp_db() -> std::path::PathBuf {
let path = std::env::temp_dir().join(format!(
"indicatrix-worker-library-test-{}-{}.sqlite",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
let path_str = path.to_str().unwrap();
let db = Database::new(Some(path_str)).unwrap();
let entry_id = db
.save_diagram_entry(
&FacetDiagramEntry {
title: "Round Brilliant".to_string(),
url: "https://example.test/diagram/1".to_string(),
design_id: "RB-1".to_string(),
},
"facetdiagrams.org",
)
.unwrap();
let mut detail = FacetDiagramDetail {
page_url: "https://example.test/diagram/1".to_string(),
shape: Some("Round".to_string()),
refractive_index: Some("2.417".to_string()),
attached_files: vec![AttachedFile {
name: "schedule.pdf".to_string(),
url: "https://example.test/schedule.pdf".to_string(),
content: vec![1, 2, 3, 4, 5],
}],
..Default::default()
};
detail.angle_settings_table = vec![indicatrix_vault::model::angle::AngleSetting {
order_index: 0,
facet: "P1".to_string(),
angle: "41.0".to_string(),
index: "96".to_string(),
notes: String::new(),
}];
db.save_diagram_detail(&detail, entry_id).unwrap();
path
}
#[test]
fn search_returns_the_seeded_design_with_a_version_hash() {
let path = populated_temp_db();
let db = Database::open_read_only(path.to_str().unwrap()).unwrap();
let response = handle_request(
&LibraryRequest::Search {
query: "Round".to_string(),
shape_filter: "All".to_string(),
gear_filter: "All".to_string(),
range: RangeFilterWire::default(),
},
&db,
);
let LibraryResponse::SearchResults {
items,
excluded_for_missing_curves,
} = response
else {
panic!("expected SearchResults, got {response:?}");
};
assert_eq!(items.len(), 1);
assert_eq!(items[0].title, "Round Brilliant");
assert_ne!(items[0].version, [0u8; 32]);
assert!(!items[0].ignored);
assert_eq!(
excluded_for_missing_curves, 0,
"no performance filter was active, so nothing can have been excluded for lacking curves"
);
drop(db);
std::fs::remove_file(&path).ok();
}
#[test]
fn fetch_design_returns_metadata_only_never_attachment_content() {
let path = populated_temp_db();
let db = Database::open_read_only(path.to_str().unwrap()).unwrap();
let response = handle_request(&LibraryRequest::FetchDesign { entry_id: 1 }, &db);
let LibraryResponse::Design(record) = response else {
panic!("expected Design, got {response:?}");
};
assert_eq!(record.attachments.len(), 1);
assert_eq!(record.attachments[0].name, "schedule.pdf");
assert_eq!(record.attachments[0].size, 5);
assert_eq!(record.angle_settings.len(), 1);
assert_ne!(record.version, [0u8; 32]);
drop(db);
std::fs::remove_file(&path).ok();
}
#[test]
fn fetch_design_carries_the_stored_preview_material() {
let path = populated_temp_db();
let db = Database::new(Some(path.to_str().unwrap())).unwrap();
let candidates = [indicatrix_vault::model::material_match::RiPresetCandidate {
name: "Diamond".to_string(),
refractive_index: 2.417,
}];
let stored = db
.ensure_preview_material(1, 2.417, &candidates, 0.01, &mut || 0.0)
.unwrap();
assert_eq!(stored.as_deref(), Some("Diamond"));
let response = handle_request(&LibraryRequest::FetchDesign { entry_id: 1 }, &db);
let LibraryResponse::Design(record) = response else {
panic!("expected Design, got {response:?}");
};
assert_eq!(record.preview_material.as_deref(), Some("Diamond"));
drop(db);
std::fs::remove_file(&path).ok();
}
#[test]
fn fetch_design_carries_the_stored_ratio_and_symmetry_fields() {
let path = std::env::temp_dir().join(format!(
"indicatrix-worker-library-ratio-test-{}-{}.sqlite",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
let path_str = path.to_str().unwrap();
let db = Database::new(Some(path_str)).unwrap();
let entry_id = db
.save_diagram_entry(
&FacetDiagramEntry {
title: "Round Brilliant".to_string(),
url: "https://example.test/diagram/1".to_string(),
design_id: "RB-1".to_string(),
},
"facetdiagrams.org",
)
.unwrap();
let detail = FacetDiagramDetail {
page_url: "https://example.test/diagram/1".to_string(),
shape: Some("Round".to_string()),
refractive_index: Some("2.417".to_string()),
hw_ratio: Some("1.0".to_string()),
tw_ratio: Some("0.53".to_string()),
uw_ratio: Some("0.16".to_string()),
pw_ratio: Some("0.43".to_string()),
cw_ratio: Some("0.14".to_string()),
symmetry_order: Some("8".to_string()),
mirror_symmetry: Some(true),
designer: Some("Capps, Jerry".to_string()),
..Default::default()
};
db.save_diagram_detail(&detail, entry_id).unwrap();
drop(db);
let db = Database::open_read_only(path_str).unwrap();
let response = handle_request(&LibraryRequest::FetchDesign { entry_id }, &db);
let LibraryResponse::Design(record) = response else {
panic!("expected Design, got {response:?}");
};
assert_eq!(record.hw_ratio.as_deref(), Some("1.0"));
assert_eq!(record.tw_ratio.as_deref(), Some("0.53"));
assert_eq!(record.uw_ratio.as_deref(), Some("0.16"));
assert_eq!(record.pw_ratio.as_deref(), Some("0.43"));
assert_eq!(record.cw_ratio.as_deref(), Some("0.14"));
assert_eq!(record.symmetry_order.as_deref(), Some("8"));
assert_eq!(record.mirror_symmetry, Some(true));
assert_eq!(record.designer.as_deref(), Some("Capps, Jerry"));
assert_ne!(record.version, [0u8; 32]);
drop(db);
std::fs::remove_file(&path).ok();
}
#[test]
fn fetch_design_for_an_unknown_id_is_not_found() {
let path = populated_temp_db();
let db = Database::open_read_only(path.to_str().unwrap()).unwrap();
let response = handle_request(&LibraryRequest::FetchDesign { entry_id: 999 }, &db);
assert_eq!(response, LibraryResponse::NotFound);
drop(db);
std::fs::remove_file(&path).ok();
}
#[test]
fn fetch_attachment_returns_exactly_that_attachments_bytes() {
let path = populated_temp_db();
let db = Database::open_read_only(path.to_str().unwrap()).unwrap();
let response = handle_request(&LibraryRequest::FetchAttachment { attachment_id: 1 }, &db);
assert_eq!(
response,
LibraryResponse::Attachment {
name: "schedule.pdf".to_string(),
content: vec![1, 2, 3, 4, 5],
}
);
drop(db);
std::fs::remove_file(&path).ok();
}
#[test]
fn fetch_attachment_for_an_unknown_id_is_not_found() {
let path = populated_temp_db();
let db = Database::open_read_only(path.to_str().unwrap()).unwrap();
let response = handle_request(&LibraryRequest::FetchAttachment { attachment_id: 999 }, &db);
assert_eq!(response, LibraryResponse::NotFound);
drop(db);
std::fs::remove_file(&path).ok();
}
#[test]
fn filter_options_reports_the_seeded_shape_alongside_the_canonical_vocabulary() {
let path = populated_temp_db();
let db = Database::open_read_only(path.to_str().unwrap()).unwrap();
let response = handle_request(&LibraryRequest::FilterOptions, &db);
let LibraryResponse::FilterOptions { shapes, .. } = response else {
panic!("expected FilterOptions, got {response:?}");
};
assert!(
shapes.contains(&"Round".to_string()),
"the served library's own shape must still be reported, got {shapes:?}"
);
assert!(
shapes.contains(&"Marquise".to_string()),
"the seeded canonical vocabulary must reach a remote client too, got {shapes:?}"
);
assert_eq!(
shapes.iter().filter(|s| *s == "Round").count(),
1,
"a shape in both the vocabulary and the data must appear once, got {shapes:?}"
);
drop(db);
std::fs::remove_file(&path).ok();
}
#[test]
fn two_designs_with_different_fields_get_different_version_hashes() {
let path = populated_temp_db();
let db = Database::new(Some(path.to_str().unwrap())).unwrap();
db.save_diagram_entry(
&FacetDiagramEntry {
title: "Emerald Cut".to_string(),
url: "https://example.test/diagram/2".to_string(),
design_id: "EC-1".to_string(),
},
"facetdiagrams.org",
)
.unwrap();
drop(db);
let ro = Database::open_read_only(path.to_str().unwrap()).unwrap();
let response = handle_request(
&LibraryRequest::Search {
query: String::new(),
shape_filter: "All".to_string(),
gear_filter: "All".to_string(),
range: RangeFilterWire::default(),
},
&ro,
);
let LibraryResponse::SearchResults { items, .. } = response else {
panic!("expected SearchResults, got {response:?}");
};
assert_eq!(items.len(), 2);
assert_ne!(items[0].version, items[1].version);
drop(ro);
std::fs::remove_file(&path).ok();
}
#[test]
fn search_page_returns_no_next_cursor_when_the_page_is_not_full() {
let path = populated_temp_db();
let db = Database::open_read_only(path.to_str().unwrap()).unwrap();
let response = handle_request(
&LibraryRequest::SearchPage {
query: String::new(),
shape_filter: "All".to_string(),
gear_filter: "All".to_string(),
range: RangeFilterWire::default(),
cursor: None,
},
&db,
);
let LibraryResponse::SearchResultsPage {
results,
next_cursor,
excluded_for_missing_curves,
} = response
else {
panic!("expected SearchResultsPage, got {response:?}");
};
assert_eq!(results.len(), 1);
assert_eq!(
next_cursor, None,
"one row is far short of a full page -- there is nothing more to fetch"
);
assert_eq!(
excluded_for_missing_curves, 0,
"no performance filter was active on this request"
);
drop(db);
std::fs::remove_file(&path).ok();
}
#[test]
fn search_page_cursor_excludes_rows_already_returned_by_an_earlier_page() {
let path = populated_temp_db();
let db = Database::new(Some(path.to_str().unwrap())).unwrap();
let second_entry_id = db
.save_diagram_entry(
&FacetDiagramEntry {
title: "Emerald Cut".to_string(),
url: "https://example.test/diagram/2".to_string(),
design_id: "EC-1".to_string(),
},
"facetdiagrams.org",
)
.unwrap();
drop(db);
let ro = Database::open_read_only(path.to_str().unwrap()).unwrap();
let first = handle_request(
&LibraryRequest::SearchPage {
query: String::new(),
shape_filter: "All".to_string(),
gear_filter: "All".to_string(),
range: RangeFilterWire::default(),
cursor: None,
},
&ro,
);
let LibraryResponse::SearchResultsPage {
results: first_results,
..
} = first
else {
panic!("expected SearchResultsPage, got {first:?}");
};
assert_eq!(first_results.len(), 2);
let first_id = first_results[0].entry_id;
let second = handle_request(
&LibraryRequest::SearchPage {
query: String::new(),
shape_filter: "All".to_string(),
gear_filter: "All".to_string(),
range: RangeFilterWire::default(),
cursor: Some(first_id),
},
&ro,
);
let LibraryResponse::SearchResultsPage {
results: second_results,
next_cursor,
..
} = second
else {
panic!("expected SearchResultsPage, got {second:?}");
};
assert_eq!(second_results.len(), 1);
assert_eq!(second_results[0].entry_id, second_entry_id);
assert_eq!(next_cursor, None);
drop(ro);
std::fs::remove_file(&path).ok();
}
#[test]
fn search_with_an_out_of_range_tilt_radius_is_rejected_without_touching_the_database() {
let path = populated_temp_db();
let db = Database::open_read_only(path.to_str().unwrap()).unwrap();
let response = handle_request(
&LibraryRequest::Search {
query: String::new(),
shape_filter: "All".to_string(),
gear_filter: "All".to_string(),
range: RangeFilterWire {
performance: vec![PerformanceFilterWire {
metric: PerformanceMetricWire::Windowing,
bound: PerformanceBoundWire::AtMost(20.0),
tilt_radius_deg: 91.0, aggregate: PerformanceAggregateWire::Worst,
}],
..RangeFilterWire::default()
},
},
&db,
);
let LibraryResponse::Error(err) = response else {
panic!("expected Error, got {response:?}");
};
assert_eq!(err.code, LIBRARY_VALIDATION_ERROR_CODE);
drop(db);
std::fs::remove_file(&path).ok();
}
#[test]
fn search_with_a_valid_performance_filter_reaches_the_database() {
let path = populated_temp_db();
let db = Database::open_read_only(path.to_str().unwrap()).unwrap();
let response = handle_request(
&LibraryRequest::Search {
query: String::new(),
shape_filter: "All".to_string(),
gear_filter: "All".to_string(),
range: RangeFilterWire {
performance: vec![PerformanceFilterWire {
metric: PerformanceMetricWire::Brilliance,
bound: PerformanceBoundWire::AtLeast(0.0),
tilt_radius_deg: 45.0,
aggregate: PerformanceAggregateWire::Worst,
}],
..RangeFilterWire::default()
},
},
&db,
);
let LibraryResponse::SearchResults {
items,
excluded_for_missing_curves,
} = response
else {
panic!("expected SearchResults, got {response:?}");
};
assert!(
items.is_empty(),
"the seeded design has no tilt curves, so it can never satisfy an active \
performance filter"
);
assert_eq!(
excluded_for_missing_curves, 1,
"the seeded design was excluded specifically for lacking tilt curves"
);
drop(db);
std::fs::remove_file(&path).ok();
}
#[test]
fn fetch_design_source_returns_the_attached_asc_files_exact_text() {
let path = std::env::temp_dir().join(format!(
"indicatrix-worker-library-source-test-{}-{}.sqlite",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
let path_str = path.to_str().unwrap();
let db = Database::new(Some(path_str)).unwrap();
let entry_id = db
.save_diagram_entry(
&FacetDiagramEntry {
title: "Round Brilliant".to_string(),
url: "https://example.test/diagram/1".to_string(),
design_id: "RB-1".to_string(),
},
"facetdiagrams.org",
)
.unwrap();
let asc_text = "GemCad 5.0\nR1 c 41.0 96\n";
let detail = FacetDiagramDetail {
page_url: "https://example.test/diagram/1".to_string(),
shape: Some("Round".to_string()),
attached_files: vec![AttachedFile {
name: "round-brilliant.asc".to_string(),
url: "https://example.test/round-brilliant.asc".to_string(),
content: asc_text.as_bytes().to_vec(),
}],
..Default::default()
};
db.save_diagram_detail(&detail, entry_id).unwrap();
drop(db);
let ro = Database::open_read_only(path_str).unwrap();
let response = handle_request(&LibraryRequest::FetchDesignSource { entry_id }, &ro);
assert_eq!(
response,
LibraryResponse::DesignSource {
entry_id,
file_name: "round-brilliant.asc".to_string(),
asc_text: asc_text.to_string(),
}
);
drop(ro);
std::fs::remove_file(&path).ok();
}
#[test]
fn fetch_design_source_for_a_design_with_no_asc_attachment_is_not_available() {
let path = populated_temp_db();
let db = Database::open_read_only(path.to_str().unwrap()).unwrap();
let response = handle_request(&LibraryRequest::FetchDesignSource { entry_id: 1 }, &db);
assert_eq!(response, LibraryResponse::DesignSourceNotAvailable);
drop(db);
std::fs::remove_file(&path).ok();
}
#[test]
fn fetch_design_source_for_an_unknown_entry_is_not_found() {
let path = populated_temp_db();
let db = Database::open_read_only(path.to_str().unwrap()).unwrap();
let response = handle_request(&LibraryRequest::FetchDesignSource { entry_id: 999 }, &db);
assert_eq!(response, LibraryResponse::NotFound);
drop(db);
std::fs::remove_file(&path).ok();
}
#[test]
fn search_reports_an_ignored_design_as_ignored_when_include_ignored_is_set() {
let path = populated_temp_db();
let db = Database::new(Some(path.to_str().unwrap())).unwrap();
db.set_diagram_ignored(1, true).unwrap();
drop(db);
let ro = Database::open_read_only(path.to_str().unwrap()).unwrap();
let response = handle_request(
&LibraryRequest::Search {
query: String::new(),
shape_filter: "All".to_string(),
gear_filter: "All".to_string(),
range: RangeFilterWire {
include_ignored: true,
..RangeFilterWire::default()
},
},
&ro,
);
let LibraryResponse::SearchResults { items, .. } = response else {
panic!("expected SearchResults, got {response:?}");
};
assert_eq!(items.len(), 1);
assert!(items[0].ignored, "the design was just marked ignored");
drop(ro);
std::fs::remove_file(&path).ok();
}
}