Skip to main content

engenho_controllers/
dns.rs

1//! R12 — DNS controller.
2//!
3//! For each Service in the store, register a DNS A record
4//! `{service}.{namespace}.svc.cluster.local → clusterIP` in a pluggable
5//! [`DnsBackend`] ([`InMemoryDnsZone`] is the in-memory one). Whether the
6//! daemon runs this controller, and why not, is recorded once, in
7//! engenho-runtime's dormant-controller catalog (`Dormant::Dns`).
8//!
9//! ## Reconcile rule
10//!
11//! 1. List Services from store.
12//! 2. For each Service, compute typed [`DnsRecord`] (name, ip).
13//! 3. Diff against backend's installed records.
14//! 4. upsert mismatches; remove orphans.
15//! 5. Idempotent — re-tick is no-op.
16
17use std::collections::BTreeMap;
18use std::sync::Arc;
19
20use async_trait::async_trait;
21use engenho_store::StoreMesh;
22use serde::{Deserialize, Serialize};
23use thiserror::Error;
24use tokio::sync::Mutex;
25
26use crate::controller::{Controller, ReconcileOutcome, ReconcileReport};
27use crate::effect::Effect;
28use crate::error::ControllerError;
29
30/// Default cluster DNS suffix (matches `CoreDNS` convention).
31pub const DEFAULT_CLUSTER_DOMAIN: &str = "cluster.local";
32
33/// One A-record in the cluster DNS zone.
34#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
35pub struct DnsRecord {
36    /// Fully-qualified name, e.g. "podinfo.default.svc.cluster.local".
37    pub fqdn: String,
38    /// IPv4 address it resolves to.
39    pub ip: String,
40    /// TTL in seconds (default 30 — match `CoreDNS`).
41    pub ttl: u32,
42}
43
44/// R12b — SRV record for headless services. Pods discover each
45/// other via `_port._proto.{service}.{namespace}.svc.{domain}`.
46#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
47pub struct SrvRecord {
48    /// Fully-qualified SRV name, e.g.
49    /// `_http._tcp.podinfo.default.svc.cluster.local`.
50    pub fqdn: String,
51    /// SRV priority (lower = preferred). Default 0.
52    pub priority: u16,
53    /// SRV weight (relative load distribution). Default 100.
54    pub weight: u16,
55    /// Target port.
56    pub port: u16,
57    /// Target FQDN (typically a pod hostname).
58    pub target: String,
59    /// TTL in seconds.
60    pub ttl: u32,
61}
62
63/// Build the SRV FQDN for a service port (pure helper).
64#[must_use]
65pub fn srv_fqdn(
66    port_name: &str,
67    protocol: &str,
68    service: &str,
69    namespace: &str,
70    domain: &str,
71) -> String {
72    format!(
73        "_{port_name}._{}.{service}.{namespace}.svc.{domain}",
74        protocol.to_lowercase()
75    )
76}
77
78/// Derive the SRV records a Service's ports imply.
79///
80/// ★ WHY THIS WAS THE GAP. `SrvRecord`, `srv_fqdn` and the backend's
81/// `upsert_srv` all existed; nothing ever CALLED them from a Service, so
82/// the only SRV records in the system were the ones tests wrote by hand.
83/// A type plus a backend method plus no producer is indistinguishable from
84/// a working feature until someone tries to resolve a name.
85///
86/// ★ WHY SRV MATTERS AND A-RECORDS ARE NOT ENOUGH. An A record answers
87/// "where is this service"; SRV answers "on WHICH PORT". Every client that
88/// discovers a port rather than hardcoding it — `StatefulSet` peers finding
89/// each other, Kafka and etcd clients, anything using
90/// `_port._proto.service` — reads SRV. Without it those clients fall back
91/// to a default port that is usually wrong, and the failure looks like a
92/// connection refused rather than a DNS problem.
93///
94/// ★ AN UNNAMED PORT PRODUCES NO SRV RECORD, deliberately. Upstream keys
95/// the name on the port's `name`, and a port without one has no
96/// `_name._proto` to be addressed by. Synthesising a name (`_0._tcp`)
97/// would publish a record nothing queries and that no upstream client
98/// would ever construct.
99///
100/// `target` is the service's own FQDN: for a headless service the client
101/// then resolves that to the pod set, which is exactly upstream's
102/// indirection.
103#[must_use]
104pub fn srv_records_for_service(
105    service: &serde_json::Value,
106    domain: &str,
107    ttl: u32,
108) -> Vec<SrvRecord> {
109    let Some(meta) = service.get("metadata") else {
110        return Vec::new();
111    };
112    let (Some(name), Some(namespace)) = (
113        meta.get("name").and_then(serde_json::Value::as_str),
114        meta.get("namespace").and_then(serde_json::Value::as_str),
115    ) else {
116        return Vec::new();
117    };
118    let Some(ports) = service
119        .get("spec")
120        .and_then(|s| s.get("ports"))
121        .and_then(serde_json::Value::as_array)
122    else {
123        return Vec::new();
124    };
125
126    let target = format!("{name}.{namespace}.svc.{domain}");
127    ports
128        .iter()
129        .filter_map(|p| {
130            // No name ⇒ no addressable SRV. See the note above.
131            let port_name = p.get("name").and_then(serde_json::Value::as_str)?;
132            if port_name.is_empty() {
133                return None;
134            }
135            let port = u16::try_from(p.get("port").and_then(serde_json::Value::as_i64)?).ok()?;
136            // Protocol defaults to TCP, matching the API's own default —
137            // a Service port that omits it is a TCP port, and treating it
138            // as unknown would drop the record.
139            let protocol = p
140                .get("protocol")
141                .and_then(serde_json::Value::as_str)
142                .unwrap_or("TCP");
143            Some(SrvRecord {
144                fqdn: srv_fqdn(port_name, protocol, name, namespace, domain),
145                priority: 0,
146                weight: 100,
147                port,
148                target: target.clone(),
149                ttl,
150            })
151        })
152        .collect()
153}
154
155/// Backend errors.
156#[derive(Debug, Clone, Error)]
157pub enum DnsError {
158    /// Backend (zone file / external DNS API) returned an error.
159    #[error("backend: {0}")]
160    Backend(String),
161    /// Invalid record shape (empty name or non-IPv4 address).
162    #[error("invalid record: {0}")]
163    InvalidRecord(String),
164}
165
166engenho_substrate::impl_error_kind! {
167    DnsError {
168        (Backend(_)) => "backend",
169        (InvalidRecord(_)) => "invalid_record",
170    }
171}
172
173/// Pluggable DNS backend trait.
174#[async_trait]
175pub trait DnsBackend: Send + Sync {
176    /// Backend identifier for telemetry.
177    fn name(&self) -> &'static str;
178
179    /// Install or refresh `record` in the zone. Idempotent.
180    ///
181    /// # Errors
182    /// [`DnsError::Backend`] on backend failure.
183    async fn upsert(&self, record: &DnsRecord) -> Result<(), DnsError>;
184
185    /// Remove a record by FQDN.
186    ///
187    /// # Errors
188    /// [`DnsError::Backend`] on backend failure.
189    async fn remove(&self, fqdn: &str) -> Result<(), DnsError>;
190
191    /// Currently-installed records.
192    ///
193    /// # Errors
194    /// [`DnsError::Backend`] on backend failure.
195    async fn list(&self) -> Result<BTreeMap<String, DnsRecord>, DnsError>;
196
197    /// R12b — Install/refresh an SRV record. Default impl returns
198    /// `Ok(())` so backends without SRV support don't break the
199    /// trait surface; production backends override.
200    ///
201    /// # Errors
202    /// [`DnsError::Backend`] on backend failure.
203    async fn upsert_srv(&self, _record: &SrvRecord) -> Result<(), DnsError> {
204        Ok(())
205    }
206
207    /// R12b — Remove an SRV record by FQDN.
208    ///
209    /// # Errors
210    /// [`DnsError::Backend`] on backend failure.
211    async fn remove_srv(&self, _fqdn: &str) -> Result<(), DnsError> {
212        Ok(())
213    }
214
215    /// R12b — Currently-installed SRV records.
216    ///
217    /// # Errors
218    /// [`DnsError::Backend`] on backend failure.
219    async fn list_srv(&self) -> Result<BTreeMap<String, SrvRecord>, DnsError> {
220        Ok(BTreeMap::new())
221    }
222}
223
224// =================================================================
225// InMemoryDnsZone — deterministic backend for tests + small clusters
226// =================================================================
227
228/// In-memory DNS zone. Tracks records in a `BTreeMap`; records every
229/// upsert/remove call for test assertions.
230#[derive(Default, Clone)]
231pub struct InMemoryDnsZone {
232    inner: Arc<Mutex<DnsState>>,
233}
234
235#[derive(Default)]
236struct DnsState {
237    records: BTreeMap<String, DnsRecord>,
238    srv_records: BTreeMap<String, SrvRecord>,
239    events: Vec<DnsEvent>,
240}
241
242/// Per-call event log entry.
243#[derive(Clone, Debug, PartialEq, Eq)]
244pub enum DnsEvent {
245    /// `upsert(fqdn)` was invoked (A record).
246    Upsert(String),
247    /// `remove(fqdn)` was invoked (A record).
248    Remove(String),
249    /// `upsert_srv(fqdn)` — R12b.
250    UpsertSrv(String),
251    /// `remove_srv(fqdn)` — R12b.
252    RemoveSrv(String),
253}
254
255impl InMemoryDnsZone {
256    /// Fresh empty zone.
257    #[must_use]
258    pub fn new() -> Self {
259        Self::default()
260    }
261
262    /// Snapshot of recorded events.
263    pub async fn events(&self) -> Vec<DnsEvent> {
264        self.inner.lock().await.events.clone()
265    }
266
267    /// Resolve a name to its current IP (test helper).
268    pub async fn resolve(&self, fqdn: &str) -> Option<String> {
269        self.inner
270            .lock()
271            .await
272            .records
273            .get(fqdn)
274            .map(|r| r.ip.clone())
275    }
276}
277
278#[async_trait]
279impl DnsBackend for InMemoryDnsZone {
280    fn name(&self) -> &'static str {
281        "in_memory"
282    }
283
284    async fn upsert(&self, record: &DnsRecord) -> Result<(), DnsError> {
285        if record.fqdn.is_empty() {
286            return Err(DnsError::InvalidRecord("empty fqdn".into()));
287        }
288        if record.ip.is_empty() {
289            return Err(DnsError::InvalidRecord("empty ip".into()));
290        }
291        let mut state = self.inner.lock().await;
292        state.records.insert(record.fqdn.clone(), record.clone());
293        state.events.push(DnsEvent::Upsert(record.fqdn.clone()));
294        Ok(())
295    }
296
297    async fn remove(&self, fqdn: &str) -> Result<(), DnsError> {
298        let mut state = self.inner.lock().await;
299        state.records.remove(fqdn);
300        state.events.push(DnsEvent::Remove(fqdn.to_string()));
301        Ok(())
302    }
303
304    async fn list(&self) -> Result<BTreeMap<String, DnsRecord>, DnsError> {
305        Ok(self.inner.lock().await.records.clone())
306    }
307
308    async fn upsert_srv(&self, record: &SrvRecord) -> Result<(), DnsError> {
309        if record.fqdn.is_empty() {
310            return Err(DnsError::InvalidRecord("empty srv fqdn".into()));
311        }
312        if record.target.is_empty() {
313            return Err(DnsError::InvalidRecord("empty srv target".into()));
314        }
315        let mut state = self.inner.lock().await;
316        state
317            .srv_records
318            .insert(record.fqdn.clone(), record.clone());
319        state.events.push(DnsEvent::UpsertSrv(record.fqdn.clone()));
320        Ok(())
321    }
322
323    async fn remove_srv(&self, fqdn: &str) -> Result<(), DnsError> {
324        let mut state = self.inner.lock().await;
325        state.srv_records.remove(fqdn);
326        state.events.push(DnsEvent::RemoveSrv(fqdn.to_string()));
327        Ok(())
328    }
329
330    async fn list_srv(&self) -> Result<BTreeMap<String, SrvRecord>, DnsError> {
331        Ok(self.inner.lock().await.srv_records.clone())
332    }
333}
334
335// =================================================================
336// DnsController — watches Services, drives the backend
337// =================================================================
338
339/// Controller that materializes DNS records from Services.
340pub struct DnsController {
341    store: Arc<StoreMesh>,
342    backend: Arc<dyn DnsBackend>,
343    cluster_domain: String,
344    namespace: Option<String>,
345}
346
347impl DnsController {
348    /// Construct a DNS controller. Uses [`DEFAULT_CLUSTER_DOMAIN`]
349    /// for the zone suffix.
350    #[must_use]
351    pub fn new(
352        store: Arc<StoreMesh>,
353        backend: Arc<dyn DnsBackend>,
354        namespace: Option<String>,
355    ) -> Self {
356        Self {
357            store,
358            backend,
359            cluster_domain: DEFAULT_CLUSTER_DOMAIN.to_string(),
360            namespace,
361        }
362    }
363
364    /// Override the cluster domain (e.g. "cluster.example").
365    #[must_use]
366    pub fn with_cluster_domain(mut self, domain: impl Into<String>) -> Self {
367        self.cluster_domain = domain.into();
368        self
369    }
370
371    /// Compute the DNS name for a service (pure).
372    #[must_use]
373    pub fn fqdn(name: &str, namespace: &str, domain: &str) -> String {
374        format!("{name}.{namespace}.svc.{domain}")
375    }
376}
377
378#[async_trait]
379impl Controller for DnsController {
380    fn name(&self) -> &'static str {
381        "dns"
382    }
383
384    async fn tick(&self) -> Result<ReconcileOutcome, ControllerError> {
385        let services = self
386            .store
387            .list("", "v1", "Service", self.namespace.as_deref())
388            .await;
389        let mut report = ReconcileReport::default();
390        report.objects_examined = services.len();
391
392        let desired: BTreeMap<String, DnsRecord> = services
393            .into_iter()
394            .filter_map(|(key, svc)| {
395                let ns = key.namespace.as_deref().unwrap_or("default");
396                let ip = svc.get("spec")?.get("clusterIP")?.as_str()?.to_string();
397                if ip.is_empty() || ip == "None" {
398                    // Headless service — skip A record (CoreDNS uses
399                    // SRV pointing at endpoint IPs instead; future
400                    // R12b adds that).
401                    return None;
402                }
403                let fqdn = Self::fqdn(&key.name, ns, &self.cluster_domain);
404                Some((fqdn.clone(), DnsRecord { fqdn, ip, ttl: 30 }))
405            })
406            .collect();
407
408        let installed = self
409            .backend
410            .list()
411            .await
412            .map_err(|e| ControllerError::Internal(e.to_string()))?;
413
414        for (fqdn, record) in &desired {
415            if installed.get(fqdn) != Some(record) {
416                let applied = Effect::applied(self.backend.upsert(record).await)
417                    .map_err(|e| ControllerError::Internal(e.to_string()))?;
418                report.record(applied);
419            }
420        }
421        for fqdn in installed.keys() {
422            if !desired.contains_key(fqdn) {
423                let applied = Effect::applied(self.backend.remove(fqdn).await)
424                    .map_err(|e| ControllerError::Internal(e.to_string()))?;
425                report.record(applied);
426            }
427        }
428
429        Ok(report.into())
430    }
431}
432
433#[cfg(test)]
434mod tests {
435
436    // ── SRV derivation (Phase 5.6) ────────────────────────────────────
437
438    fn svc(ports: serde_json::Value) -> serde_json::Value {
439        serde_json::json!({
440            "metadata": { "name": "podinfo", "namespace": "default" },
441            "spec": { "ports": ports }
442        })
443    }
444
445    #[test]
446    fn srv_records_are_derived_from_a_services_named_ports() {
447        // The gap this closes: the type and backend existed, nothing
448        // produced one from a Service.
449        let recs = super::srv_records_for_service(
450            &svc(serde_json::json!([
451                { "name": "http", "port": 80, "protocol": "TCP" },
452                { "name": "metrics", "port": 9090 }
453            ])),
454            "cluster.local",
455            30,
456        );
457        assert_eq!(recs.len(), 2);
458        assert_eq!(recs[0].fqdn, "_http._tcp.podinfo.default.svc.cluster.local");
459        assert_eq!(recs[0].port, 80);
460        // Protocol defaults to TCP, matching the API's own default — a
461        // port that omits it is a TCP port, and treating it as unknown
462        // would drop the record entirely.
463        assert_eq!(
464            recs[1].fqdn,
465            "_metrics._tcp.podinfo.default.svc.cluster.local"
466        );
467        assert_eq!(recs[1].port, 9090);
468    }
469
470    #[test]
471    fn the_target_is_the_services_own_fqdn() {
472        // A client resolves the target to the pod set; that indirection is
473        // upstream's, and pointing straight at a pod would break the
474        // moment the pod is replaced.
475        let recs = super::srv_records_for_service(
476            &svc(serde_json::json!([{ "name": "http", "port": 80 }])),
477            "cluster.local",
478            30,
479        );
480        assert_eq!(recs[0].target, "podinfo.default.svc.cluster.local");
481    }
482
483    #[test]
484    fn an_unnamed_port_produces_no_srv_record() {
485        // Upstream keys the name on the port's `name`. Synthesising one
486        // would publish a record nothing queries and no client constructs.
487        let recs = super::srv_records_for_service(
488            &svc(serde_json::json!([
489                { "port": 80 },
490                { "name": "", "port": 81 },
491                { "name": "ok", "port": 82 }
492            ])),
493            "cluster.local",
494            30,
495        );
496        assert_eq!(recs.len(), 1);
497        assert_eq!(recs[0].port, 82);
498    }
499
500    #[test]
501    fn udp_ports_get_the_udp_protocol_label() {
502        let recs = super::srv_records_for_service(
503            &svc(serde_json::json!([{ "name": "dns", "port": 53, "protocol": "UDP" }])),
504            "cluster.local",
505            30,
506        );
507        assert_eq!(recs[0].fqdn, "_dns._udp.podinfo.default.svc.cluster.local");
508    }
509
510    #[test]
511    fn a_service_without_ports_or_metadata_yields_nothing_rather_than_panicking() {
512        assert!(
513            super::srv_records_for_service(&serde_json::json!({}), "cluster.local", 30).is_empty()
514        );
515        assert!(
516            super::srv_records_for_service(
517                &serde_json::json!({ "metadata": { "name": "s", "namespace": "d" } }),
518                "cluster.local",
519                30
520            )
521            .is_empty()
522        );
523    }
524    use super::*;
525
526    #[test]
527    fn fqdn_format_matches_kubernetes_convention() {
528        assert_eq!(
529            DnsController::fqdn("podinfo", "default", "cluster.local"),
530            "podinfo.default.svc.cluster.local"
531        );
532        assert_eq!(
533            DnsController::fqdn("api", "engenho-system", "engenho.io"),
534            "api.engenho-system.svc.engenho.io"
535        );
536    }
537
538    #[tokio::test]
539    async fn in_memory_zone_upsert_inserts_record() {
540        let zone = InMemoryDnsZone::new();
541        zone.upsert(&DnsRecord {
542            fqdn: "x.default.svc.cluster.local".into(),
543            ip: "10.96.5.1".into(),
544            ttl: 30,
545        })
546        .await
547        .unwrap();
548        assert_eq!(
549            zone.resolve("x.default.svc.cluster.local").await,
550            Some("10.96.5.1".into())
551        );
552    }
553
554    #[tokio::test]
555    async fn in_memory_zone_rejects_empty_fqdn() {
556        let zone = InMemoryDnsZone::new();
557        let err = zone
558            .upsert(&DnsRecord {
559                fqdn: String::new(),
560                ip: "1.1.1.1".into(),
561                ttl: 30,
562            })
563            .await
564            .unwrap_err();
565        assert_eq!(err.kind(), "invalid_record");
566    }
567
568    #[tokio::test]
569    async fn in_memory_zone_rejects_empty_ip() {
570        let zone = InMemoryDnsZone::new();
571        let err = zone
572            .upsert(&DnsRecord {
573                fqdn: "x.local".into(),
574                ip: String::new(),
575                ttl: 30,
576            })
577            .await
578            .unwrap_err();
579        assert_eq!(err.kind(), "invalid_record");
580    }
581
582    #[tokio::test]
583    async fn in_memory_zone_remove_clears_record() {
584        let zone = InMemoryDnsZone::new();
585        let rec = DnsRecord {
586            fqdn: "x.local".into(),
587            ip: "1.1.1.1".into(),
588            ttl: 30,
589        };
590        zone.upsert(&rec).await.unwrap();
591        zone.remove("x.local").await.unwrap();
592        assert_eq!(zone.resolve("x.local").await, None);
593    }
594
595    #[tokio::test]
596    async fn in_memory_zone_events_recorded_in_order() {
597        let zone = InMemoryDnsZone::new();
598        let rec = DnsRecord {
599            fqdn: "a".into(),
600            ip: "1.1.1.1".into(),
601            ttl: 30,
602        };
603        zone.upsert(&rec).await.unwrap();
604        zone.remove("a").await.unwrap();
605        let events = zone.events().await;
606        assert_eq!(
607            events,
608            vec![DnsEvent::Upsert("a".into()), DnsEvent::Remove("a".into())]
609        );
610    }
611
612    #[tokio::test]
613    async fn in_memory_zone_list_returns_installed() {
614        let zone = InMemoryDnsZone::new();
615        zone.upsert(&DnsRecord {
616            fqdn: "x".into(),
617            ip: "1.1.1.1".into(),
618            ttl: 30,
619        })
620        .await
621        .unwrap();
622        let list = zone.list().await.unwrap();
623        assert_eq!(list.len(), 1);
624        assert!(list.contains_key("x"));
625    }
626
627    #[test]
628    fn error_kinds_are_stable() {
629        assert_eq!(DnsError::Backend("x".into()).kind(), "backend");
630        assert_eq!(DnsError::InvalidRecord("x".into()).kind(), "invalid_record");
631    }
632
633    #[test]
634    fn dns_controller_default_uses_cluster_local() {
635        // Sanity: the default domain matches kubernetes convention.
636        assert_eq!(DEFAULT_CLUSTER_DOMAIN, "cluster.local");
637    }
638
639    // ── R12b SRV records ───────────────────────────────────────────
640
641    #[test]
642    fn srv_fqdn_format() {
643        assert_eq!(
644            srv_fqdn("http", "TCP", "podinfo", "default", "cluster.local"),
645            "_http._tcp.podinfo.default.svc.cluster.local"
646        );
647        assert_eq!(
648            srv_fqdn("dns", "UDP", "coredns", "kube-system", "cluster.local"),
649            "_dns._udp.coredns.kube-system.svc.cluster.local"
650        );
651    }
652
653    #[tokio::test]
654    async fn in_memory_zone_upsert_srv_inserts() {
655        let zone = InMemoryDnsZone::new();
656        let srv = SrvRecord {
657            fqdn: "_http._tcp.x.default.svc.cluster.local".into(),
658            priority: 0,
659            weight: 100,
660            port: 80,
661            target: "pod-1.default.pod.cluster.local".into(),
662            ttl: 30,
663        };
664        zone.upsert_srv(&srv).await.unwrap();
665        let list = zone.list_srv().await.unwrap();
666        assert_eq!(list.len(), 1);
667        assert!(list.contains_key(&srv.fqdn));
668    }
669
670    #[tokio::test]
671    async fn in_memory_zone_rejects_empty_srv_fqdn() {
672        let zone = InMemoryDnsZone::new();
673        let err = zone
674            .upsert_srv(&SrvRecord {
675                fqdn: String::new(),
676                priority: 0,
677                weight: 100,
678                port: 80,
679                target: "x".into(),
680                ttl: 30,
681            })
682            .await
683            .unwrap_err();
684        assert_eq!(err.kind(), "invalid_record");
685    }
686
687    #[tokio::test]
688    async fn in_memory_zone_rejects_empty_srv_target() {
689        let zone = InMemoryDnsZone::new();
690        let err = zone
691            .upsert_srv(&SrvRecord {
692                fqdn: "x".into(),
693                priority: 0,
694                weight: 100,
695                port: 80,
696                target: String::new(),
697                ttl: 30,
698            })
699            .await
700            .unwrap_err();
701        assert_eq!(err.kind(), "invalid_record");
702    }
703
704    #[tokio::test]
705    async fn in_memory_zone_remove_srv_clears() {
706        let zone = InMemoryDnsZone::new();
707        let srv = SrvRecord {
708            fqdn: "x".into(),
709            priority: 0,
710            weight: 100,
711            port: 80,
712            target: "y".into(),
713            ttl: 30,
714        };
715        zone.upsert_srv(&srv).await.unwrap();
716        zone.remove_srv("x").await.unwrap();
717        assert!(zone.list_srv().await.unwrap().is_empty());
718    }
719
720    #[tokio::test]
721    async fn srv_events_record_in_order() {
722        let zone = InMemoryDnsZone::new();
723        let srv = SrvRecord {
724            fqdn: "a".into(),
725            priority: 0,
726            weight: 100,
727            port: 80,
728            target: "y".into(),
729            ttl: 30,
730        };
731        zone.upsert_srv(&srv).await.unwrap();
732        zone.remove_srv("a").await.unwrap();
733        let events = zone.events().await;
734        assert!(
735            events
736                .iter()
737                .any(|e| matches!(e, DnsEvent::UpsertSrv(n) if n == "a"))
738        );
739        assert!(
740            events
741                .iter()
742                .any(|e| matches!(e, DnsEvent::RemoveSrv(n) if n == "a"))
743        );
744    }
745}