1use std::fmt;
2use std::sync::LazyLock;
3
4use serde::{Deserialize, Serialize};
5
6use crate::attr::{Attributes, Value};
7use crate::grant::TargetSelector;
8
9pub const GLOBAL: &str = "global";
11
12static GLOBAL_ANCHOR: LazyLock<Anchor> = LazyLock::new(Anchor::global);
13
14#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
16pub struct ObjectRef {
17 pub kind: String,
18 pub id: String,
19}
20
21impl ObjectRef {
22 pub fn new(kind: impl Into<String>, id: impl Into<String>) -> Self {
23 Self {
24 kind: kind.into(),
25 id: id.into(),
26 }
27 }
28}
29
30impl fmt::Display for ObjectRef {
31 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
32 write!(f, "{}:{}", self.kind, self.id)
33 }
34}
35
36#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
41pub struct Anchor {
42 pub kind: String,
43 #[serde(default, skip_serializing_if = "Option::is_none")]
44 pub id: Option<String>,
45}
46
47impl Anchor {
48 pub fn new(kind: impl Into<String>, id: impl Into<String>) -> Self {
49 Self {
50 kind: kind.into(),
51 id: Some(id.into()),
52 }
53 }
54
55 pub fn kind_only(kind: impl Into<String>) -> Self {
56 Self {
57 kind: kind.into(),
58 id: None,
59 }
60 }
61
62 pub fn global() -> Self {
63 Self::kind_only(GLOBAL)
64 }
65
66 pub fn is_global(&self) -> bool {
67 self.kind == GLOBAL
68 }
69
70 pub fn object_ref(&self) -> Option<ObjectRef> {
71 self.id.as_ref().map(|id| ObjectRef::new(self.kind.clone(), id.clone()))
72 }
73}
74
75impl fmt::Display for Anchor {
76 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77 match &self.id {
78 Some(id) => write!(f, "{}:{}", self.kind, id),
79 None => f.write_str(&self.kind),
80 }
81 }
82}
83
84#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
91pub struct Resource {
92 pub path: Vec<Anchor>,
93 #[serde(default, skip_serializing_if = "Attributes::is_empty")]
94 pub attrs: Attributes,
95}
96
97impl Resource {
98 pub fn new(kind: impl Into<String>, id: impl Into<String>) -> Self {
99 Self {
100 path: vec![Anchor::new(kind, id)],
101 attrs: Attributes::new(),
102 }
103 }
104
105 pub fn global() -> Self {
107 Self::default()
108 }
109
110 pub fn within(mut self, kind: impl Into<String>, id: impl Into<String>) -> Self {
112 self.path.push(Anchor::new(kind, id));
113 self
114 }
115
116 pub fn with_attr(mut self, key: impl Into<String>, value: impl Into<Value>) -> Self {
117 self.attrs.insert(key.into(), value.into());
118 self
119 }
120
121 pub fn primary(&self) -> Option<&Anchor> {
123 self.path.first()
124 }
125
126 pub fn contains(&self, anchor: &Anchor) -> bool {
127 anchor.is_global() || self.path.iter().any(|a| a == anchor)
128 }
129
130 pub fn locate(&self, selector: &TargetSelector) -> Option<(usize, &Anchor)> {
133 self.anchors().find(|(_, anchor)| selector.matches(anchor))
134 }
135
136 pub fn anchors(&self) -> impl Iterator<Item = (usize, &Anchor)> {
138 let explicit_global = self.path.iter().any(Anchor::is_global);
139 let tail = (!explicit_global).then_some(&*GLOBAL_ANCHOR);
140 self.path.iter().chain(tail).enumerate()
141 }
142}
143
144#[cfg(test)]
145mod tests {
146 use super::*;
147
148 fn document() -> Resource {
149 Resource::new("document", "d1")
150 .within("doc_type", "invoice")
151 .within("project", "p1")
152 .within("org", "o1")
153 }
154
155 #[test]
156 fn global_is_last_anchor() {
157 let r = document();
158 let (rank, anchor) = r.locate(&TargetSelector::global()).unwrap();
159 assert_eq!(rank, 4);
160 assert!(anchor.is_global());
161 }
162
163 #[test]
164 fn selector_without_id_matches_any_instance_of_kind() {
165 let r = document();
166 let (rank, anchor) = r.locate(&TargetSelector::kind("project")).unwrap();
167 assert_eq!(rank, 2);
168 assert_eq!(anchor.id.as_deref(), Some("p1"));
169 }
170
171 #[test]
172 fn selector_with_other_id_does_not_match() {
173 assert!(document().locate(&TargetSelector::exact("project", "p2")).is_none());
174 }
175}