indicatrix-worker 0.7.2

Coordinator and render worker for an indicatrix-backed design catalogue. `serve` (default build) is the coordinator: it serves indicatrix-net's read-only design-library protocol to viewers over mutual TLS and accepts joining render workers on a separate worker port. The optional `worker` feature adds render capacity -- `join` (dial a coordinator and render its requests), `serve --render` (render with the coordinator's own CPU/GPU) and `render` (a one-shot scene-to-PNG CLI).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
//! Tests for `FetchDesign`/`FetchAttachment`/`FetchDesignSource`/`FilterOptions`: the
//! single-record and metadata-lookup side of the library protocol, as opposed to
//! `tests::search`'s multi-row search/paging tests.

use super::fixtures::populated_temp_db;
use crate::serve::library::handle_request;
use indicatrix_net::library::{LibraryRequest, LibraryResponse};
use indicatrix_vault::{
    db::sqlite::Database,
    model::{detail::FacetingDiagramDetail, entry::FacetingDiagramEntry, file::AttachedFile},
};

#[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();
}

/// `DesignRecord::preview_material` must carry the preset name a design's cached
/// previews were generated with, so a remote client can run the same stale-material
/// check the local path does. Asserts a genuinely stored value, not `None`, since
/// `None` would pin nothing.
#[test]
fn fetch_design_carries_the_stored_preview_material() {
    let path = populated_temp_db();
    let db = Database::new(Some(path.to_str().unwrap())).unwrap();

    // One candidate within tolerance -> chosen outright, no RNG draw, so this
    // fixture is deterministic.
    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();
}

/// The ratio/symmetry/designer fields on `DesignRecord` must carry the same values
/// a local lookup sees. Builds its own fixture (rather than `populated_temp_db`,
/// which leaves them `None`) with every field set to a distinct, non-default value,
/// so this pins that each survives `to_record`/the wire, not merely that it exists.
#[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(
            &FacetingDiagramEntry {
                title: "Round Brilliant".to_string(),
                url: "https://example.test/diagram/1".to_string(),
                design_id: "RB-1".to_string(),
            },
            "facetdiagrams.org",
        )
        .unwrap();
    let detail = FacetingDiagramDetail {
        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();
}

/// `source_citation`/`pdf_file`/`gem_file`/`shape_category` (added to `DesignRecord`
/// under `PROTOCOL_VERSION` v15, see that constant's doc comment) must reach a remote
/// client the same way the ratio/symmetry fields above do -- pins that
/// `Database::get_diagram_full_meta` actually selects these four columns (a gap
/// `get_diagram_full`, the local-only counterpart, did not have) and that
/// `convert::to_record` maps them through.
#[test]
fn fetch_design_carries_the_stored_citation_and_shape_category_fields() {
    let path = std::env::temp_dir().join(format!(
        "indicatrix-worker-library-citation-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(
            &FacetingDiagramEntry {
                title: "Competition Entry".to_string(),
                url: "https://example.test/diagramus/1".to_string(),
                design_id: String::new(),
            },
            "facetdiagrams.org",
        )
        .unwrap();
    let detail = FacetingDiagramDetail {
        page_url: "https://example.test/diagramus/1".to_string(),
        source_citation: Some("Lapidary Journal, May 1994, p95".to_string()),
        pdf_file: Some("2002SSCMasters.pdf".to_string()),
        gem_file: Some("USFG-SSC-2020-Novice-1.gem".to_string()),
        shape_category: Some("5".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.source_citation.as_deref(),
        Some("Lapidary Journal, May 1994, p95")
    );
    assert_eq!(record.pdf_file.as_deref(), Some("2002SSCMasters.pdf"));
    assert_eq!(
        record.gem_file.as_deref(),
        Some("USFG-SSC-2020-Novice-1.gem")
    );
    assert_eq!(record.shape_category.as_deref(), Some("5"));

    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();
}

/// `FilterOptions` serves `Database::get_unique_shapes`, the union of the seeded
/// canonical vocabulary and the shapes actually present in the library -- a remote
/// client gets the full picker list, exactly as a local one does.
#[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:?}"
    );
    // "Round" is both seeded and present on the fixture -- must dedupe.
    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();
}

/// [`LibraryRequest::FetchDesignSource`] against the seeded fixture's real attached
/// `.asc` file (`populated_temp_db` names it `schedule.pdf`, NOT `.asc` -- see the
/// dedicated fixture built below) returns that attachment's exact text.
#[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(
            &FacetingDiagramEntry {
                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 = FacetingDiagramDetail {
        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();
}

/// A design with SOME attachment but no `.asc` among them (the `populated_temp_db`
/// fixture: only `schedule.pdf`) has no genuine source text to send --
/// `DesignSourceNotAvailable`, not `NotFound` (the entry itself is real).
#[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();
}

/// An `entry_id` with no matching row at all is `NotFound`, distinct from
/// `DesignSourceNotAvailable` (which means the entry exists but lacks a `.asc`).
#[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();
}

/// `FetchDesignNative` returns the `.indicatrix` attachment's bytes untouched (a binary
/// payload with a NUL and a non-UTF-8 byte, so any text round trip would corrupt it),
/// and a design without one is `DesignNativeNotAvailable`, an unknown id `NotFound`.
#[test]
fn fetch_design_native_returns_the_attachment_bytes_verbatim() {
    let path = std::env::temp_dir().join(format!(
        "indicatrix-worker-library-native-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 mut ids = Vec::new();
    for (n, files) in [
        (
            1,
            vec![
                ("schedule.pdf", b"%PDF".to_vec()),
                ("scooped.indicatrix", vec![b'v', 0, 0xFF, b'\n']),
            ],
        ),
        (2, vec![("schedule.pdf", b"%PDF".to_vec())]),
    ] {
        let entry_id = db
            .save_diagram_entry(
                &FacetingDiagramEntry {
                    title: format!("Design {n}"),
                    url: format!("https://example.test/diagram/{n}"),
                    design_id: format!("D-{n}"),
                },
                "facetdiagrams.org",
            )
            .unwrap();
        let detail = FacetingDiagramDetail {
            page_url: format!("https://example.test/diagram/{n}"),
            attached_files: files
                .into_iter()
                .map(|(name, content)| AttachedFile {
                    name: name.to_string(),
                    url: format!("https://example.test/{name}"),
                    content,
                })
                .collect(),
            ..Default::default()
        };
        db.save_diagram_detail(&detail, entry_id).unwrap();
        ids.push(entry_id);
    }
    drop(db);

    let ro = Database::open_read_only(path_str).unwrap();
    assert_eq!(
        handle_request(&LibraryRequest::FetchDesignNative { entry_id: ids[0] }, &ro),
        LibraryResponse::DesignNative {
            entry_id: ids[0],
            file_name: "scooped.indicatrix".to_string(),
            content: vec![b'v', 0, 0xFF, b'\n'],
        }
    );
    assert_eq!(
        handle_request(&LibraryRequest::FetchDesignNative { entry_id: ids[1] }, &ro),
        LibraryResponse::DesignNativeNotAvailable
    );
    assert_eq!(
        handle_request(&LibraryRequest::FetchDesignNative { entry_id: 9999 }, &ro),
        LibraryResponse::NotFound
    );

    drop(ro);
    std::fs::remove_file(&path).ok();
}