Skip to main content

subspace_contracts/
decisions.rs

1//! Navigation to a decision by its project-scoped reference. The answering
2//! board opens and reads it in its own scope.
3
4use crate::{Contract, Request};
5
6const LINK_PREFIX: &str = "subspace-decision:";
7const NUMBER_DIGITS: std::ops::RangeInclusive<usize> = 5..=10;
8const PROJECT_KEY_LENGTH: std::ops::RangeInclusive<usize> = 2..=10;
9
10pub struct Decisions;
11
12impl Contract for Decisions {
13    const NAME: &'static str = "decisions";
14    const VERSION: u32 = 1;
15}
16
17/// Navigation capability used by the host's board navigation broker.
18// qual:api - Declared by app Spaces through the Framework facade.
19pub struct OpenDecision;
20
21impl Request for OpenDecision {
22    type Contract = Decisions;
23    const NAME: &'static str = "open";
24    type Response = ();
25}
26
27/// A decision reference such as `D-00042-EXA`, ignoring ASCII case.
28pub fn is_identifier(identifier: &str) -> bool {
29    let mut parts = identifier.split('-');
30    let (Some(prefix), Some(number), Some(key), None) =
31        (parts.next(), parts.next(), parts.next(), parts.next())
32    else {
33        return false;
34    };
35    prefix.eq_ignore_ascii_case("D")
36        && NUMBER_DIGITS.contains(&number.len())
37        && number.bytes().all(|byte| byte.is_ascii_digit())
38        && PROJECT_KEY_LENGTH.contains(&key.len())
39        && key.starts_with(|ch: char| ch.is_ascii_alphabetic())
40        && key.bytes().all(|byte| byte.is_ascii_alphanumeric())
41}
42
43pub fn link(identifier: &str) -> Option<String> {
44    is_identifier(identifier).then(|| format!("{LINK_PREFIX}{identifier}"))
45}
46
47// qual:api - The answering Space validates navigation received through the broker.
48pub fn from_link(link: &str) -> Option<&str> {
49    link.strip_prefix(LINK_PREFIX)
50        .filter(|identifier| is_identifier(identifier))
51}
52
53#[cfg(test)]
54mod tests {
55    use super::*;
56
57    #[test]
58    fn references_round_trip_without_accepting_extra_segments() {
59        for identifier in ["d-00001-ex", "D-100000-PNG"] {
60            assert_eq!(from_link(&link(identifier).unwrap()), Some(identifier));
61        }
62        for identifier in ["D-1-EX", "D-00001-X", "D-00001-EX-more", "D-00001-EX?q=x"] {
63            assert!(link(identifier).is_none());
64        }
65        assert!(from_link("https://example.com/D-00001-EX").is_none());
66    }
67}