datadog_agent_apm/semantics/
provider.rs1use std::fmt;
8use std::sync::Arc;
9
10use datadog_agent_remote_config::{ApplyError, ConfigId, RemoteConfigurationClient, Subscription};
11
12use super::registry::{Registry, EMBEDDED_REGISTRY};
13use super::remote_config::SemanticCoreDecoder;
14
15#[derive(Clone, Debug, PartialEq, Eq)]
17pub(crate) enum Origin {
18 Embedded,
20
21 Remote(ConfigId),
23}
24
25impl fmt::Display for Origin {
26 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
27 match self {
29 Self::Embedded => f.write_str("embedded"),
30 Self::Remote(id) => write!(f, "remote-config ({id})"),
31 }
32 }
33}
34
35pub(crate) struct SemanticCore {
41 pub(crate) registry: Arc<Registry>,
43
44 pub(crate) origin: Origin,
46
47 pub(crate) assigned: usize,
49}
50
51#[cfg(any(test, feature = "test-util"))]
52impl SemanticCore {
53 pub(crate) fn remote(registry: Registry, id: &str) -> Self {
55 Self {
56 registry: Arc::new(registry),
57 origin: Origin::Remote(ConfigId::new(id)),
58 assigned: 1,
59 }
60 }
61}
62
63impl fmt::Debug for SemanticCore {
64 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
65 f.debug_struct("SemanticCore")
66 .field("content_hash", &self.registry.content_hash())
67 .field("version", &self.registry.version())
68 .field("origin", &self.origin)
69 .field("assigned", &self.assigned)
70 .finish()
71 }
72}
73
74#[derive(Debug)]
79pub(crate) enum SemanticCoreError {
80 InvalidRegistry {
82 reason: String,
84 },
85
86 NoValidConfiguration {
88 assigned: usize,
90 },
91}
92
93impl fmt::Display for SemanticCoreError {
94 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
95 match self {
96 Self::InvalidRegistry { reason } => f.write_str(reason),
97 Self::NoValidConfiguration { assigned } => write!(
98 f,
99 "None of the {assigned} assigned APM_SEMANTIC_CORE_DD configurations is a valid registry."
100 ),
101 }
102 }
103}
104
105impl std::error::Error for SemanticCoreError {}
106
107impl ApplyError for SemanticCoreError {
108 fn apply_error(&self) -> String {
109 self.to_string()
110 }
111}
112
113#[derive(Clone, Debug)]
125pub struct SemanticRegistryProvider {
126 subscription: Subscription<SemanticCore, SemanticCoreError>,
127}
128
129impl SemanticRegistryProvider {
130 pub fn subscribe(client: &RemoteConfigurationClient) -> Result<Self, datadog_agent_remote_config::Error> {
139 Ok(Self::from_subscription(client.subscribe::<SemanticCoreDecoder>()?))
140 }
141
142 pub(crate) fn from_subscription(subscription: Subscription<SemanticCore, SemanticCoreError>) -> Self {
144 Self { subscription }
145 }
146
147 pub fn snapshot(&self) -> Arc<Registry> {
152 match self.subscription.current() {
153 Some(core) => Arc::clone(&core.registry),
154 None => Arc::clone(&EMBEDDED_REGISTRY),
155 }
156 }
157
158 pub async fn changed(&mut self) {
165 let _ = self.subscription.changed().await;
167 }
168}
169
170impl Default for SemanticRegistryProvider {
171 fn default() -> Self {
172 Self::from_subscription(Subscription::inert())
173 }
174}
175
176#[cfg(test)]
177mod tests {
178 use datadog_agent_remote_config::TestPublisher;
179
180 use super::*;
181 use crate::semantics::registry::registry_json;
182
183 fn remote(concepts: &str, id: &str) -> SemanticCore {
184 let registry = Registry::from_json(®istry_json(concepts)).expect("registry should parse");
185 SemanticCore::remote(registry, id)
186 }
187
188 const DB_STATEMENT: &str =
189 r#"{"db.statement":{"fallbacks":[{"name":"db.statement","provider":"datadog","type":"string"}]}}"#;
190
191 #[test]
192 fn default_provider_returns_the_embedded_registry() {
193 let provider = SemanticRegistryProvider::default();
194 assert!(Arc::ptr_eq(&provider.snapshot(), &EMBEDDED_REGISTRY));
195 }
196
197 #[test]
198 fn provider_returns_the_embedded_registry_before_a_snapshot_is_accepted() {
199 let (_publisher, subscription) = TestPublisher::new();
200 let provider = SemanticRegistryProvider::from_subscription(subscription);
201 assert!(Arc::ptr_eq(&provider.snapshot(), &EMBEDDED_REGISTRY));
202 }
203
204 #[test]
205 fn clones_observe_an_accepted_snapshot() {
206 let (publisher, subscription) = TestPublisher::new();
207 let provider = SemanticRegistryProvider::from_subscription(subscription);
208 let clone = provider.clone();
209
210 let core = remote(DB_STATEMENT, "a");
211 let registry = Arc::clone(&core.registry);
212 publisher.accept(core);
213
214 assert!(Arc::ptr_eq(&provider.snapshot(), ®istry));
215 assert!(Arc::ptr_eq(&clone.snapshot(), ®istry));
216 }
217
218 #[test]
219 fn a_snapshot_is_unchanged_by_a_later_publication() {
220 let (publisher, subscription) = TestPublisher::new();
221 let provider = SemanticRegistryProvider::from_subscription(subscription);
222
223 let pinned = provider.snapshot();
224 publisher.accept(remote(DB_STATEMENT, "a"));
225
226 assert!(Arc::ptr_eq(&pinned, &EMBEDDED_REGISTRY));
227 assert!(!Arc::ptr_eq(&provider.snapshot(), &EMBEDDED_REGISTRY));
228 }
229
230 #[test]
231 fn a_rejection_keeps_the_accepted_registry() {
232 let (publisher, subscription) = TestPublisher::new();
233 let provider = SemanticRegistryProvider::from_subscription(subscription);
234
235 let core = remote(DB_STATEMENT, "a");
236 let registry = Arc::clone(&core.registry);
237 publisher.accept(core);
238 publisher.reject(SemanticCoreError::NoValidConfiguration { assigned: 1 });
239
240 assert!(Arc::ptr_eq(&provider.snapshot(), ®istry));
241 }
242
243 #[tokio::test]
244 async fn changed_sees_an_accepted_update_coalesced_with_a_later_rejection() {
245 let (publisher, subscription) = TestPublisher::new();
246 let mut provider = SemanticRegistryProvider::from_subscription(subscription);
247
248 let core = remote(DB_STATEMENT, "a");
250 let registry = Arc::clone(&core.registry);
251 publisher.accept(core);
252 publisher.reject(SemanticCoreError::NoValidConfiguration { assigned: 1 });
253
254 provider.changed().await;
255 assert!(Arc::ptr_eq(&provider.snapshot(), ®istry));
256 }
257
258 #[tokio::test]
259 async fn changed_waits_for_an_update() {
260 let (publisher, subscription) = TestPublisher::new();
261 let mut provider = SemanticRegistryProvider::from_subscription(subscription);
262 let core = remote(DB_STATEMENT, "a");
263 let registry = Arc::clone(&core.registry);
264 {
265 let changed = provider.changed();
266 tokio::pin!(changed);
267 tokio::select! {
268 biased;
269 _ = &mut changed => panic!("nothing was published yet"),
270 _ = std::future::ready(()) => {}
271 }
272
273 publisher.accept(core);
274 changed.await;
275 }
276
277 assert!(Arc::ptr_eq(&provider.snapshot(), ®istry));
278 }
279
280 #[test]
281 fn independent_providers_do_not_share_publications() {
282 let (publisher, subscription) = TestPublisher::new();
283 let (_other_publisher, other_subscription) = TestPublisher::new();
284 let provider = SemanticRegistryProvider::from_subscription(subscription);
285 let other = SemanticRegistryProvider::from_subscription(other_subscription);
286
287 publisher.accept(remote(DB_STATEMENT, "a"));
288
289 assert!(!Arc::ptr_eq(&provider.snapshot(), &EMBEDDED_REGISTRY));
290 assert!(Arc::ptr_eq(&other.snapshot(), &EMBEDDED_REGISTRY));
291 }
292}