Skip to main content

datadog_agent_runtime/remote_agent/
mod.rs

1//! Remote agent registration and the services that the Datadog Agent queries.
2//!
3//! [`RemoteAgentBootstrap`] registers the process with the Datadog Agent over the Remote Agent Registry, keeps that
4//! registration alive, and creates everything that depends on it: the configuration stream, and the workers that serve
5//! the status, flare, and telemetry services and report diagnostic events back to the Datadog Agent.
6//!
7//! # Bootstrapping prior to supervision
8//!
9//! Registration and the initial configuration are generally required before any decisions can be made about continuing
10//! to start up, and this means that a supervision tree is not likely to yet be running where we can spawn our
11//! background tasks for managing registration.
12//!
13//! The registration loop and the configuration stream loop therefore each start early, in a [`ResumableWorker`], and
14//! run in a task until their worker takes them over in the supervision tree. The worker continues with the same
15//! session, refresh schedule, and open stream, and so does each restart of the worker.
16//!
17//! The registration task finishes a registration attempt in flight before it hands over, so a handoff never registers
18//! twice. The registration worker shuts down brutally, even in the middle of an attempt, and a restarted worker retries
19//! an interrupted attempt right away. Dropping a loop's worker before it starts cancels the loop.
20
21use std::collections::HashMap;
22use std::sync::OnceLock;
23use std::{pin::Pin, sync::Arc, time::Duration};
24
25use async_trait::async_trait;
26use datadog_agent_commons::ipc::{
27    client::RemoteAgentClient,
28    config::RemoteAgentClientConfiguration,
29    session::{SessionId, SessionIdHandle},
30};
31use datadog_protos::agent::v1::{
32    event::Details as RemoteAgentEventDetails, Event as RemoteAgentEvent, InvalidApiKeyEvent,
33    RegisterRemoteAgentResponse, ReportRemoteAgentEventRequest,
34};
35use datadog_protos::agent::{
36    flare::v1::{flare_provider_server::*, *},
37    status::v1::{status_provider_server::*, *},
38    telemetry::v1::{get_telemetry_response::*, telemetry_provider_server::*, *},
39    ConfigEvent,
40};
41use futures::{Stream, StreamExt};
42use process_memory::Querier as MemoryQuerier;
43use saluki_api::{DynamicRoute, EndpointType};
44use saluki_common::sync::shutdown::ShutdownHandle;
45use saluki_common::time::{TimeZone, Timestamp, TimestampFormat};
46use saluki_config::dynamic::ConfigUpdate;
47use saluki_core::{
48    diagnostic::{subscribe_events, DiagnosticCollector, DiagnosticDetails, DiagnosticEvent},
49    observability::metrics::{
50        get_shared_metrics_state, AggregatedMetricsProcessor, AggregatedMetricsState, Reflector, RemapperRule,
51        TelemetryProcessor,
52    },
53    runtime::{
54        state::{DataspaceRegistry, DataspaceUpdate, IdentifierFilter, Subscription},
55        InitializationError, Resumable, ResumableWorker, ShutdownStrategy, Supervisable, SupervisorFuture,
56    },
57};
58use saluki_error::{generic_error, GenericError};
59use saluki_io::net::{GrpcTargetAddress, ListenAddress};
60use tokio::task::spawn_blocking;
61use tokio::time::{sleep_until, timeout, Instant};
62use tokio::{
63    pin, select,
64    sync::{mpsc, Mutex},
65    time::{interval, Interval, MissedTickBehavior},
66};
67use tonic::{server::NamedService, service::Routes, Status};
68use tracing::{debug, error, info, warn};
69
70use crate::agent_stream::config_event_to_update;
71
72mod status;
73pub use self::status::{StatusBuilder, StatusSectionProvider, StatusSectionWriter};
74
75const DEFAULT_REFRESH_INTERVAL: Duration = Duration::from_secs(30);
76const REFRESH_FAILED_RETRY_INTERVAL: Duration = Duration::from_secs(5);
77const CONFIG_STREAM_RETRY_INTERVAL: Duration = Duration::from_secs(5);
78
79// RAR sessions can change without restarting the process. Keep this identity for the entire process lifetime.
80static PROCESS_INSTANCE_ID: OnceLock<String> = OnceLock::new();
81
82const SESSION_ID_METADATA_KEY: &str = "session_id";
83
84const REMOTE_AGENT_SESSION_WORKER_NAME: &str = "remote-agent-session";
85const CONFIG_STREAM_WORKER_NAME: &str = "config-stream";
86const CONFIG_STREAM_CAPACITY: usize = 100;
87
88/// Remote agent initialization.
89///
90/// This helper type is used to coordinate the initialization of remote agent state by registering to the Core Agent and
91/// acquiring the necessary information to allow initialization of the remote agent itself to proceed.
92pub struct RemoteAgentBootstrap {
93    client: RemoteAgentClient,
94    session_id: SessionIdHandle,
95    registration: RemoteAgentRegistrationWorker,
96    internal_metrics: Reflector<AggregatedMetricsProcessor>,
97    dataspace: Arc<OnceLock<DataspaceRegistry>>,
98}
99
100impl RemoteAgentBootstrap {
101    /// Creates a new `RemoteAgentBootstrap` from the given configurations.
102    ///
103    /// A remote agent client is created and immediately attempts to register with the Core Agent, advertising
104    /// `secure_api_listen_address` as the address where the Core Agent reaches the status, flare, and telemetry
105    /// services. This function does not return until the first registration attempt finishes, whether successful or
106    /// not. `additional_service_names` advertises services the binary adds through
107    /// [`create_services_worker`](Self::create_services_worker). Once registered, a task keeps the registration alive
108    /// until the worker from [`into_registration_worker`][Self::into_registration_worker] takes over.
109    ///
110    /// # Errors
111    ///
112    /// Returns an error if `secure_api_listen_address` isn't a valid gRPC target address, if the client can't connect
113    /// to the Core Agent, or if the first registration attempt fails. Nothing is left running when this returns an
114    /// error.
115    pub async fn new(
116        client_config: &RemoteAgentClientConfiguration, secure_api_listen_address: &ListenAddress,
117        additional_service_names: &[&str],
118    ) -> Result<Self, GenericError> {
119        let api_listen_addr = GrpcTargetAddress::try_from_listen_addr(secure_api_listen_address)
120            .ok_or_else(|| generic_error!("Failed to get valid gRPC target address from secure API listen address."))?;
121
122        // Generate our remote agent state, which is mostly fixed but has a few dynamic bits.
123        let mut service_names = vec![
124            <StatusProviderServer<()> as NamedService>::NAME.to_string(),
125            <FlareProviderServer<()> as NamedService>::NAME.to_string(),
126            <TelemetryProviderServer<()> as NamedService>::NAME.to_string(),
127        ];
128        service_names.extend(additional_service_names.iter().map(|name| (*name).to_owned()));
129        let details = RegistrationDetails::new(api_listen_addr, service_names);
130        let session_id = SessionIdHandle::empty();
131
132        let client = RemoteAgentClient::connect(client_config).await?;
133        let registration = Registration::new(Box::new(client.clone()), details, session_id.clone())
134            .register_and_spawn()
135            .await?;
136
137        Ok(Self {
138            client,
139            session_id,
140            registration,
141            internal_metrics: get_shared_metrics_state(),
142            dataspace: Arc::new(OnceLock::new()),
143        })
144    }
145
146    /// Returns the worker that keeps the registration with the Core Agent alive.
147    ///
148    /// The worker is named `remote-agent-session`, and must be added to the supervision tree. This consumes the
149    /// bootstrap, so create the other workers first. Dropping the bootstrap without taking the worker cancels the
150    /// registration loop.
151    pub fn into_registration_worker(self) -> RemoteAgentRegistrationWorker {
152        self.registration
153    }
154
155    fn build_impl(
156        &self, status_sections: Vec<Arc<dyn StatusSectionProvider>>, remapper_rules: Vec<RemapperRule>,
157    ) -> RemoteAgentImpl {
158        RemoteAgentImpl {
159            started: Timestamp::now().ok(),
160            internal_metrics: self.internal_metrics.clone(),
161            processor: telemetry_processor(remapper_rules),
162            status_sections,
163            session_id: self.session_id.clone(),
164            dataspace: Arc::clone(&self.dataspace),
165        }
166    }
167
168    /// Creates a worker that captures the dataspace from the supervisor context and makes it available to the
169    /// diagnostic artifact collection service.
170    ///
171    /// This worker must be added to the supervision tree. When it initializes, it runs inside a supervisor process
172    /// where the dataspace task-local is set, and fills the shared [`OnceLock`] so that `get_flare_files` can
173    /// collect diagnostic artifacts at request time. Without this, the gRPC handler tasks spawned by tonic would not
174    /// have access to the dataspace since tonic's `tokio::spawn` does not propagate task-locals.
175    pub fn create_dataspace_anchor(&self) -> DataspaceAnchorWorker {
176        DataspaceAnchorWorker {
177            dataspace: Arc::clone(&self.dataspace),
178        }
179    }
180
181    /// Creates a worker that reports diagnostic events to the Core Agent as remote agent events.
182    pub fn create_event_reporter(&self) -> RemoteAgentEventReporter {
183        RemoteAgentEventReporter {
184            client: self.client.clone(),
185            session_id: self.session_id.clone(),
186        }
187    }
188
189    /// Creates a worker that serves the status, flare, and telemetry services on the privileged API endpoint.
190    ///
191    /// The status service always reports the built-in main section fields (version, Git commit, architecture, start
192    /// time, and the Agent version this build was compiled against), followed by the fields written by each of the
193    /// given `status_sections`, in order.
194    ///
195    /// The telemetry service reports the internal metrics that match the given `telemetry_rules`, renamed to the names
196    /// the Datadog Agent expects. Metrics that match no rule are not reported, so if `telemetry_rules` is empty, the
197    /// service reports no metrics at all.
198    ///
199    /// `extend_services` adds binary-specific services using the live registration session handle. Their names must
200    /// be included in the `additional_service_names` passed to [`new`](Self::new).
201    pub fn create_services_worker(
202        &self, status_sections: Vec<Arc<dyn StatusSectionProvider>>, telemetry_rules: Vec<RemapperRule>,
203        extend_services: impl FnOnce(Routes, SessionIdHandle) -> Routes,
204    ) -> RemoteAgentServicesWorker {
205        let routes = Routes::new(StatusProviderServer::new(self.build_impl(status_sections, Vec::new())))
206            .add_service(FlareProviderServer::new(self.build_impl(Vec::new(), Vec::new())))
207            .add_service(TelemetryProviderServer::new(
208                self.build_impl(Vec::new(), telemetry_rules),
209            ));
210
211        RemoteAgentServicesWorker {
212            routes: extend_services(routes, self.session_id.clone()),
213        }
214    }
215
216    /// Creates a config stream that receives configuration events from the Core Agent, along with the worker that
217    /// feeds it.
218    ///
219    /// A task feeds the stream until the worker takes over, so that the initial configuration can arrive before the
220    /// supervision tree runs. The worker is named `config-stream`, and must be added to the supervision tree.
221    pub fn create_config_stream(&self) -> (mpsc::Receiver<ConfigUpdate>, ConfigStreamWorker) {
222        ConfigStreamWorker::spawn(Box::new(self.client.clone()), self.session_id.clone())
223    }
224}
225
226/// What the remote agent advertises when it registers.
227struct RegistrationDetails {
228    pid: u32,
229    process_instance_id: &'static str,
230    display_name: String,
231    flavor: String,
232    api_listen_addr: String,
233    service_names: Vec<String>,
234}
235
236impl RegistrationDetails {
237    fn new(api_listen_addr: GrpcTargetAddress, service_names: Vec<String>) -> Self {
238        let app_details = saluki_metadata::get_app_details();
239
240        Self {
241            pid: std::process::id(),
242            process_instance_id: PROCESS_INSTANCE_ID
243                .get_or_init(|| uuid::Uuid::new_v4().to_string())
244                .as_str(),
245            display_name: app_details.full_name().to_string(),
246            flavor: app_details.full_name().replace(" ", "_").to_lowercase(),
247            api_listen_addr: api_listen_addr.to_string(),
248            service_names,
249        }
250    }
251}
252
253/// The Remote Agent Registry calls that registration makes, so that tests can stand in for the Core Agent.
254#[async_trait]
255trait RegistryClient: Send {
256    async fn register(&mut self, details: &RegistrationDetails) -> Result<RegisterRemoteAgentResponse, GenericError>;
257
258    async fn refresh(&mut self, session_id: &SessionId) -> Result<(), GenericError>;
259}
260
261#[async_trait]
262impl RegistryClient for RemoteAgentClient {
263    async fn register(&mut self, details: &RegistrationDetails) -> Result<RegisterRemoteAgentResponse, GenericError> {
264        let response = self
265            .register_remote_agent(
266                details.pid,
267                details.process_instance_id,
268                &details.display_name,
269                &details.flavor,
270                &details.api_listen_addr,
271                details.service_names.clone(),
272            )
273            .await?;
274        Ok(response.into_inner())
275    }
276
277    async fn refresh(&mut self, session_id: &SessionId) -> Result<(), GenericError> {
278        self.refresh_remote_agent(session_id).await.map(|_| ())
279    }
280}
281
282/// The registration loop, which refreshes the registration periodically and registers again whenever a refresh fails.
283struct Registration {
284    client: Box<dyn RegistryClient>,
285    details: RegistrationDetails,
286    session_id: SessionIdHandle,
287    timer: Interval,
288    attempt_in_flight: bool,
289}
290
291impl Registration {
292    fn new(client: Box<dyn RegistryClient>, details: RegistrationDetails, session_id: SessionIdHandle) -> Self {
293        let mut timer = interval(DEFAULT_REFRESH_INTERVAL);
294        timer.set_missed_tick_behavior(MissedTickBehavior::Delay);
295
296        Self {
297            client,
298            details,
299            session_id,
300            timer,
301            attempt_in_flight: false,
302        }
303    }
304
305    /// Registers, and then starts the registration loop in a task until the returned worker takes it over.
306    ///
307    /// # Errors
308    ///
309    /// If a registration attempt fails before one succeeds, an error is returned, and no task is started.
310    async fn register_and_spawn(mut self) -> Result<RemoteAgentRegistrationWorker, GenericError> {
311        debug!("Remote Agent registration task started.");
312
313        // An invalid session ID leaves us unregistered without failing the attempt, so we try again on the next tick.
314        while self.session_id.get().is_none() {
315            self.timer.tick().await;
316            self.register().await?;
317        }
318
319        Ok(RemoteAgentRegistrationWorker {
320            registration: ResumableWorker::start_early(REMOTE_AGENT_SESSION_WORKER_NAME, self),
321        })
322    }
323
324    async fn refresh_or_register(&mut self) {
325        match self.session_id.get() {
326            Some(session_id) => {
327                debug!(%session_id, "Refreshing registration with Datadog Agent.");
328
329                if self.client.refresh(&session_id).await.is_err() {
330                    self.timer.reset_after(REFRESH_FAILED_RETRY_INTERVAL);
331                    self.session_id.update(None);
332                    warn!("Failed to refresh registration with the Datadog Agent. Resetting session ID and attempting to re-register shortly.");
333                }
334            }
335            None => {
336                // `register` logs its own failures.
337                let _ = self.register().await;
338            }
339        }
340    }
341
342    async fn register(&mut self) -> Result<(), GenericError> {
343        let resp = match self.client.register(&self.details).await {
344            Ok(resp) => resp,
345            Err(e) => {
346                warn!(error = %e, "Failed to register with the Datadog Agent. Registration will be retried periodically in the background.");
347                self.timer.reset_after(DEFAULT_REFRESH_INTERVAL);
348                return Err(e);
349            }
350        };
351
352        match SessionId::new(&resp.session_id) {
353            Ok(new_session_id) => {
354                let new_refresh_interval = resp.recommended_refresh_interval_secs;
355                info!(
356                    session_id = %new_session_id,
357                    process_instance_id = %self.details.process_instance_id,
358                    "Successfully registered with the Datadog Agent. Refreshing every {} seconds.",
359                    new_refresh_interval
360                );
361
362                self.session_id.update(Some(new_session_id));
363                self.timer.reset_after(Duration::from_secs(new_refresh_interval as u64));
364            }
365            Err(e) => {
366                warn!(error = %e, "Received invalid session ID from Datadog Agent after registation. Registration will be retried periodically in the background.");
367                self.timer.reset_after(DEFAULT_REFRESH_INTERVAL);
368            }
369        }
370
371        Ok(())
372    }
373}
374
375impl Resumable for Registration {
376    fn shutdown_strategy(&self) -> ShutdownStrategy {
377        // There is nothing to finish on shutdown, and a restart retries an interrupted attempt.
378        ShutdownStrategy::Brutal
379    }
380
381    async fn run(&mut self, stop: ShutdownHandle) -> Result<(), GenericError> {
382        pin!(stop);
383
384        loop {
385            // An attempt that a dropped call interrupted is retried right away.
386            if !self.attempt_in_flight {
387                select! {
388                    biased;
389                    _ = &mut stop => return Ok(()),
390                    _ = self.timer.tick() => {}
391                }
392                self.attempt_in_flight = true;
393            }
394
395            // Not raced with `stop`, so that a handoff never registers twice.
396            self.refresh_or_register().await;
397            self.attempt_in_flight = false;
398        }
399    }
400}
401
402type ConfigEventStream = Pin<Box<dyn Stream<Item = Result<ConfigEvent, Status>> + Send>>;
403
404/// Opens configuration event streams, so that tests can stand in for the Core Agent.
405trait ConfigEventSource: Send {
406    fn open(&mut self, session_id: &SessionId) -> ConfigEventStream;
407}
408
409impl ConfigEventSource for RemoteAgentClient {
410    fn open(&mut self, session_id: &SessionId) -> ConfigEventStream {
411        Box::pin(self.stream_config_events(session_id))
412    }
413}
414
415/// The configuration stream loop, which forwards configuration events from the Core Agent to a channel.
416struct ConfigStream {
417    source: Box<dyn ConfigEventSource>,
418    sender: mpsc::Sender<ConfigUpdate>,
419    session_id: SessionIdHandle,
420    events: Option<ConfigEventStream>,
421    reconnect_at: Option<Instant>,
422    pending: Option<ConfigUpdate>,
423}
424
425impl ConfigStream {
426    fn new(
427        source: Box<dyn ConfigEventSource>, sender: mpsc::Sender<ConfigUpdate>, session_id: SessionIdHandle,
428    ) -> Self {
429        Self {
430            source,
431            sender,
432            session_id,
433            events: None,
434            reconnect_at: None,
435            pending: None,
436        }
437    }
438
439    /// Forwards configuration events until the receiver is dropped.
440    ///
441    /// Every await point is cancel-safe: the open stream, the reconnect deadline, and an update waiting for room in the
442    /// channel are all kept in `self`.
443    async fn forward(&mut self) {
444        if self.sender.is_closed() {
445            return;
446        }
447
448        loop {
449            if self.pending.is_some() {
450                let Ok(permit) = self.sender.reserve().await else {
451                    warn!("Dynamic configuration channel closed. Config stream shutting down.");
452                    self.events = None;
453                    self.pending = None;
454                    return;
455                };
456                permit.send(self.pending.take().expect("pending update should be present"));
457            }
458
459            let events = match &mut self.events {
460                Some(events) => events,
461                None => {
462                    if let Some(reconnect_at) = self.reconnect_at {
463                        sleep_until(reconnect_at).await;
464                        self.reconnect_at = None;
465                    }
466
467                    debug!("Establishing a new config stream connection to the Core Agent.");
468
469                    // Read the session ID on every reconnect, since it can change in the background due to
470                    // re-registration.
471                    let session_id = self.session_id.wait_for_update().await;
472                    self.events.insert(self.source.open(&session_id))
473                }
474            };
475
476            match events.next().await {
477                Some(Ok(event)) => self.pending = config_event_to_update(event),
478                Some(Err(e)) => error!("Error while reading config event stream: {}.", e),
479                None => {
480                    debug!("Config stream ended, retrying in 5 seconds...");
481                    self.events = None;
482                    self.reconnect_at = Some(Instant::now() + CONFIG_STREAM_RETRY_INTERVAL);
483                }
484            }
485        }
486    }
487}
488
489impl Resumable for ConfigStream {
490    async fn run(&mut self, stop: ShutdownHandle) -> Result<(), GenericError> {
491        pin!(stop);
492
493        select! {
494            biased;
495            _ = &mut stop => return Ok(()),
496            _ = self.forward() => {}
497        }
498
499        // The receiver is gone. Wait to be stopped rather than return, which would make a worker restart.
500        stop.await;
501        Ok(())
502    }
503}
504
505/// Formats the start time for the status page, as RFC 3339 in UTC, or `unavailable` if it isn't known.
506fn format_started(started: Option<Timestamp>) -> String {
507    match started {
508        Some(started) => started.format(TimestampFormat::Rfc3339(TimeZone::utc())).to_string(),
509        None => "unavailable".to_string(),
510    }
511}
512
513/// Formats the number of whole seconds from `started` to `now`, which is negative if the clock went backwards, or
514/// `unavailable` if either time isn't known.
515fn format_uptime(started: Option<Timestamp>, now: Option<Timestamp>) -> String {
516    match (started, now) {
517        (Some(started), Some(now)) => now.whole_seconds_since(started).to_string(),
518        _ => "unavailable".to_string(),
519    }
520}
521
522/// The implementation behind the status, flare, and telemetry services that the Datadog Agent queries.
523struct RemoteAgentImpl {
524    /// When the process started, or `None` if the system clock was out of range.
525    started: Option<Timestamp>,
526    internal_metrics: Reflector<AggregatedMetricsProcessor>,
527    processor: Option<Mutex<TelemetryProcessor>>,
528    status_sections: Vec<Arc<dyn StatusSectionProvider>>,
529    session_id: SessionIdHandle,
530    dataspace: Arc<OnceLock<DataspaceRegistry>>,
531}
532
533/// Creates the processor behind the telemetry service, or `None` if there are no remapper rules.
534///
535/// A `TelemetryProcessor` without rules renders every metric under its raw name, so we skip it entirely rather than
536/// report metrics that no rule selected.
537fn telemetry_processor(remapper_rules: Vec<RemapperRule>) -> Option<Mutex<TelemetryProcessor>> {
538    (!remapper_rules.is_empty()).then(|| Mutex::new(TelemetryProcessor::new().with_remapper_rules(remapper_rules)))
539}
540
541/// Renders the telemetry payload for the given internal metrics.
542///
543/// Without a processor, the payload is empty.
544async fn render_telemetry(processor: Option<&Mutex<TelemetryProcessor>>, state: &AggregatedMetricsState) -> String {
545    match processor {
546        Some(processor) => processor.lock().await.process(state),
547        None => String::new(),
548    }
549}
550
551impl RemoteAgentImpl {
552    async fn session_id_middleware<Resp, Next>(&self, next: Next) -> Result<tonic::Response<Resp>, Status>
553    where
554        Next: AsyncFnOnce() -> Result<tonic::Response<Resp>, Status>,
555    {
556        let metadata_session_id = self
557            .session_id
558            .get()
559            .ok_or(Status::failed_precondition(
560                "session ID not set; must be registered with Core Agent",
561            ))?
562            .to_grpc_header_value();
563
564        next().await.map(|mut resp| {
565            resp.metadata_mut().append(SESSION_ID_METADATA_KEY, metadata_session_id);
566            resp
567        })
568    }
569}
570
571#[async_trait]
572impl StatusProvider for RemoteAgentImpl {
573    async fn get_status_details(
574        &self, _request: tonic::Request<GetStatusDetailsRequest>,
575    ) -> Result<tonic::Response<GetStatusDetailsResponse>, Status> {
576        return self
577            .session_id_middleware(async || {
578                let app_details = saluki_metadata::get_app_details();
579
580                let mut builder = StatusBuilder::new();
581                builder
582                    .main_section()
583                    .set_field("Version", app_details.version().raw())
584                    .set_field("Git Commit", app_details.git_hash())
585                    .set_field("Architecture", app_details.target_arch())
586                    .set_field("Started", format_started(self.started));
587
588                // Surface the Agent version this build was compiled against, for debugging version-gated behavior.
589                if let Some(agent_version) = datadog_agent_commons::agent_version::version_string() {
590                    builder
591                        .main_section()
592                        .set_field("Built Against Agent Version", agent_version);
593                }
594
595                for section in &self.status_sections {
596                    section.write_status(&mut builder);
597                }
598
599                Ok(tonic::Response::new(builder.into_response()))
600            })
601            .await;
602    }
603}
604
605#[async_trait]
606impl TelemetryProvider for RemoteAgentImpl {
607    async fn get_telemetry(
608        &self, _request: tonic::Request<GetTelemetryRequest>,
609    ) -> Result<tonic::Response<GetTelemetryResponse>, Status> {
610        return self
611            .session_id_middleware(async || {
612                let prom_text = render_telemetry(self.processor.as_ref(), self.internal_metrics.state()).await;
613
614                Ok(tonic::Response::new(GetTelemetryResponse {
615                    payload: Some(Payload::PromText(prom_text)),
616                }))
617            })
618            .await;
619    }
620}
621
622/// Timeout for the tokio task dump step within [`FlareProvider::get_flare_files`].
623///
624/// `Handle::dump()` may never resolve if a runtime worker is blocked for more than 250 ms. We use
625/// a conservative 5-second budget so that a hung runtime still allows the other diagnostic artifacts
626/// to be collected and returned.
627#[cfg(all(
628    feature = "taskdump",
629    target_os = "linux",
630    any(
631        target_arch = "aarch64",
632        target_arch = "x86",
633        target_arch = "x86_64",
634        target_arch = "s390x"
635    )
636))]
637const TASK_DUMP_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);
638
639/// Timeout for collecting all component-owned diagnostic artifacts.
640///
641/// Each `collect()` closure is run on a blocking thread via `spawn_blocking`. If the overall
642/// budget is exhausted, collection stops and whatever artifacts were gathered are returned.
643/// This ensures that a slow or deadlocked component cannot stall the entire response.
644const DIAGNOSTIC_COLLECT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(4);
645
646/// Maximum size in bytes for a single diagnostic artifact.
647///
648/// Artifacts that exceed this limit are truncated and a truncation marker is appended so that
649/// readers know the content is incomplete. High-cardinality hosts can produce very large workload
650/// tag dumps; this cap keeps the overall archive size predictable.
651const DIAGNOSTIC_ARTIFACT_MAX_BYTES: usize = 5 * 1024 * 1024; // 5 MiB
652
653/// Truncation marker appended to diagnostic artifacts that exceed [`DIAGNOSTIC_ARTIFACT_MAX_BYTES`] in size.
654const DIAGNOSTIC_TRUNCATION_MARKER: &[u8] = b"\n\n[... truncated: artifact exceeded the 5 MiB per-file limit ...]\n";
655
656/// Caps `data` to [`DIAGNOSTIC_ARTIFACT_MAX_BYTES`], appending [`DIAGNOSTIC_TRUNCATION_MARKER`] if truncated.
657fn cap_artifact_data(mut data: Vec<u8>) -> Vec<u8> {
658    if data.len() > DIAGNOSTIC_ARTIFACT_MAX_BYTES {
659        data.truncate(DIAGNOSTIC_ARTIFACT_MAX_BYTES);
660        data.extend_from_slice(DIAGNOSTIC_TRUNCATION_MARKER);
661    }
662    data
663}
664
665/// Returns the number of open file descriptors for the current process.
666///
667/// Reads from `/proc/self/fd` on Linux. Returns `"unavailable"` on other platforms.
668#[cfg(target_os = "linux")]
669fn fd_count() -> String {
670    std::fs::read_dir("/proc/self/fd")
671        .map(|entries| entries.count().to_string())
672        .unwrap_or_else(|_| "unavailable".to_string())
673}
674
675#[cfg(not(target_os = "linux"))]
676fn fd_count() -> String {
677    "unavailable".to_string()
678}
679
680/// Returns the number of threads in the current process.
681///
682/// Reads the `Threads:` field from `/proc/self/status` on Linux. Returns `"unavailable"` on other
683/// platforms.
684#[cfg(target_os = "linux")]
685fn thread_count() -> String {
686    std::fs::read_to_string("/proc/self/status")
687        .ok()
688        .and_then(|s| {
689            s.lines()
690                .find(|l| l.starts_with("Threads:"))
691                .and_then(|l| l.split_whitespace().nth(1).map(str::to_string))
692        })
693        .unwrap_or_else(|| "unavailable".to_string())
694}
695
696#[cfg(not(target_os = "linux"))]
697fn thread_count() -> String {
698    "unavailable".to_string()
699}
700
701#[async_trait]
702impl FlareProvider for RemoteAgentImpl {
703    async fn get_flare_files(
704        &self, _request: tonic::Request<GetFlareFilesRequest>,
705    ) -> Result<tonic::Response<GetFlareFilesResponse>, Status> {
706        return self
707            .session_id_middleware(async || {
708                let mut files: HashMap<String, Vec<u8>> = HashMap::new();
709
710                // Grab and run all asserted diagnostic collectors.
711                if let Some(dataspace) = self.dataspace.get() {
712                    let collectors = dataspace.current_values::<DiagnosticCollector>(IdentifierFilter::all());
713                    let total_collectors = collectors.len();
714                    let deadline = Instant::now() + DIAGNOSTIC_COLLECT_TIMEOUT;
715
716                    for collector in collectors {
717                        if Instant::now() >= deadline {
718                            break;
719                        }
720
721                        let artifact_name = collector.artifact_name().to_string();
722                        let remaining = deadline.saturating_duration_since(Instant::now());
723
724                        let collect = timeout(
725                            remaining,
726                            spawn_blocking(move || collector.collect()),
727                        );
728                        let artifact_data = match collect.await {
729                            Ok(Ok(data)) => data,
730                            Ok(Err(e)) => format!("collection panicked for '{artifact_name}': {e}").into_bytes(),
731                            Err(_) => format!("collection timed out for '{artifact_name}'").into_bytes(),
732                        };
733
734                        files.insert(artifact_name, cap_artifact_data(artifact_data));
735                    }
736
737                    if files.len() < total_collectors {
738                        warn!("Diagnostic artifact collection timed out; collected {}/{total_collectors} artifacts.", files.len());
739                    }
740                }
741
742                // Process-level artifacts.
743                //
744                // These don't belong to any individual component — they describe the process
745                // itself. They stay hardwired here since there is no natural component owner to
746                // assert a handle for them.
747
748                // Process info: pid, uptime, RSS, args, fd count, thread count.
749                let pid = std::process::id();
750                let uptime = format_uptime(self.started, Timestamp::now().ok());
751                let args: Vec<String> = std::env::args().collect();
752                let rss_display = MemoryQuerier::default()
753                    .resident_set_size()
754                    .map(|b| b.to_string())
755                    .unwrap_or_else(|| "unavailable".to_string());
756                let process_info = format!(
757                    "pid: {pid}\nuptime_seconds: {uptime}\nrss_bytes: {rss_display}\nargs: {args:?}\nfd_count: {fd_count}\nthread_count: {thread_count}\n",
758                    uptime = uptime,
759                    fd_count = fd_count(),
760                    thread_count = thread_count(),
761                );
762                files.insert("runtime_debug_info.log".to_string(), cap_artifact_data(process_info.into_bytes()));
763
764                // Tokio task dump (only with the `taskdump` feature enabled, on targets where Tokio supports task dumps).
765                //
766                // Wrapped in an explicit timeout because `Handle::dump()`
767                // may never resolve if a runtime worker is blocked for
768                // more than 250ms
769                #[cfg(all(
770                    feature = "taskdump",
771                    target_os = "linux",
772                    any(
773                        target_arch = "aarch64",
774                        target_arch = "x86",
775                        target_arch = "x86_64",
776                        target_arch = "s390x"
777                    )
778                ))]
779                {
780                    let task_dump = match timeout(
781                        TASK_DUMP_TIMEOUT,
782                        tokio::runtime::Handle::current().dump(),
783                    )
784                    .await
785                    {
786                        Ok(dump) => {
787                            let mut output = String::new();
788                            for (i, task) in dump.tasks().iter().enumerate() {
789                                output.push_str(&format!("task {i}:\n{}\n", task.trace()));
790                            }
791                            output
792                        }
793                        Err(_) => format!(
794                            "task dump timed out after {}ms — a runtime worker may be blocked",
795                            TASK_DUMP_TIMEOUT.as_millis()
796                        ),
797                    };
798                    files.insert("runtime-dump.txt".to_string(), cap_artifact_data(task_dump.into_bytes()));
799                }
800
801                Ok(tonic::Response::new(GetFlareFilesResponse { files }))
802            })
803            .await;
804    }
805}
806
807/// A worker that keeps the registration with the Core Agent alive.
808///
809/// It refreshes the registration periodically, and registers again whenever a refresh fails.
810pub struct RemoteAgentRegistrationWorker {
811    registration: ResumableWorker<Registration>,
812}
813
814#[async_trait]
815impl Supervisable for RemoteAgentRegistrationWorker {
816    fn name(&self) -> &str {
817        self.registration.name()
818    }
819
820    fn shutdown_strategy(&self) -> ShutdownStrategy {
821        self.registration.shutdown_strategy()
822    }
823
824    fn wants_shutdown_signal(&self) -> bool {
825        self.registration.wants_shutdown_signal()
826    }
827
828    fn can_restart(&self) -> bool {
829        self.registration.can_restart()
830    }
831
832    async fn initialize(&self, process_shutdown: ShutdownHandle) -> Result<SupervisorFuture, InitializationError> {
833        self.registration.initialize(process_shutdown).await
834    }
835}
836
837/// A worker that feeds the config stream from [`RemoteAgentBootstrap::create_config_stream`].
838///
839/// It forwards configuration events from the Core Agent, and reconnects whenever the stream from the Core Agent ends.
840/// The config stream stays open across restarts of the worker.
841pub struct ConfigStreamWorker {
842    stream: ResumableWorker<ConfigStream>,
843}
844
845impl ConfigStreamWorker {
846    /// Starts forwarding events from `source` in a task until the returned worker takes it over.
847    fn spawn(source: Box<dyn ConfigEventSource>, session_id: SessionIdHandle) -> (mpsc::Receiver<ConfigUpdate>, Self) {
848        let (sender, receiver) = mpsc::channel(CONFIG_STREAM_CAPACITY);
849        let stream = ConfigStream::new(source, sender, session_id);
850        let worker = Self {
851            stream: ResumableWorker::start_early(CONFIG_STREAM_WORKER_NAME, stream),
852        };
853
854        (receiver, worker)
855    }
856}
857
858#[async_trait]
859impl Supervisable for ConfigStreamWorker {
860    fn name(&self) -> &str {
861        self.stream.name()
862    }
863
864    fn shutdown_strategy(&self) -> ShutdownStrategy {
865        self.stream.shutdown_strategy()
866    }
867
868    fn wants_shutdown_signal(&self) -> bool {
869        self.stream.wants_shutdown_signal()
870    }
871
872    fn can_restart(&self) -> bool {
873        self.stream.can_restart()
874    }
875
876    async fn initialize(&self, process_shutdown: ShutdownHandle) -> Result<SupervisorFuture, InitializationError> {
877        self.stream.initialize(process_shutdown).await
878    }
879}
880
881/// A worker that captures the dataspace from the supervisor context and stores it in a shared
882/// [`OnceLock`] for use by the diagnostic artifact collection service.
883///
884/// The gRPC handler runs in tasks spawned by tonic, which do not inherit tokio task-locals.
885/// This worker bridges that gap by capturing the dataspace during its own `initialize()` call,
886/// which runs inside the supervisor process where the dataspace is available.
887pub struct DataspaceAnchorWorker {
888    dataspace: Arc<OnceLock<DataspaceRegistry>>,
889}
890
891#[async_trait]
892impl Supervisable for DataspaceAnchorWorker {
893    fn name(&self) -> &str {
894        "flare-dataspace-anchor"
895    }
896
897    async fn initialize(&self, process_shutdown: ShutdownHandle) -> Result<SupervisorFuture, InitializationError> {
898        if let Some(ds) = DataspaceRegistry::try_current() {
899            let _ = self.dataspace.set(ds);
900        }
901
902        Ok(Box::pin(async move {
903            process_shutdown.await;
904            Ok(())
905        }))
906    }
907}
908
909/// A worker that serves the status, flare, and telemetry services on the privileged API endpoint.
910///
911/// The services are asserted as a dynamic gRPC route, so the privileged API endpoint in the same supervision tree serves
912/// them for as long as this worker runs.
913pub struct RemoteAgentServicesWorker {
914    routes: Routes,
915}
916
917#[async_trait]
918impl Supervisable for RemoteAgentServicesWorker {
919    fn name(&self) -> &str {
920        "remote-agent-services"
921    }
922
923    async fn initialize(&self, process_shutdown: ShutdownHandle) -> Result<SupervisorFuture, InitializationError> {
924        let route = DynamicRoute::grpc(EndpointType::Privileged, self.routes.clone());
925
926        Ok(Box::pin(async move {
927            let dataspace =
928                DataspaceRegistry::try_current().ok_or_else(|| generic_error!("Dataspace not available."))?;
929
930            dataspace.assert(route, "remote-agent-services");
931
932            process_shutdown.await;
933            Ok(())
934        }))
935    }
936}
937
938/// A worker that reports diagnostic events to the Core Agent as remote agent events.
939///
940/// It subscribes to [`DiagnosticEvent`]s emitted anywhere in the process converts the ones it recognizes into the
941/// Datadog Agent's remote agent event representation, and reports them to the Core Agent over the remote agent gRPC
942/// API. `InvalidApiKey` events are rate limited, so a sustained stream of them cannot flood the Core Agent.
943pub struct RemoteAgentEventReporter {
944    client: RemoteAgentClient,
945    session_id: SessionIdHandle,
946}
947
948#[async_trait]
949impl Supervisable for RemoteAgentEventReporter {
950    fn name(&self) -> &str {
951        "remote_agent_event_reporter"
952    }
953
954    async fn initialize(&self, process_shutdown: ShutdownHandle) -> Result<SupervisorFuture, InitializationError> {
955        let client = self.client.clone();
956        let session_id = self.session_id.clone();
957
958        Ok(Box::pin(async move {
959            let subscription = subscribe_events(IdentifierFilter::all())
960                .map_err(|e| generic_error!("Failed to subscribe to diagnostic events: {}", e))?;
961
962            select! {
963                _ = process_shutdown => Ok(()),
964                result = run_event_reporter(client, session_id, subscription) => result,
965            }
966        }))
967    }
968}
969
970async fn run_event_reporter(
971    mut client: RemoteAgentClient, session_id: SessionIdHandle, mut subscription: Subscription<DiagnosticEvent>,
972) -> Result<(), GenericError> {
973    debug!("Remote Agent event reporter started.");
974
975    let mut invalid_api_key_reports = InvalidApiKeyReportThrottle::default();
976
977    while let Some(update) = subscription.recv().await {
978        let DataspaceUpdate::Message(_, event) = update else {
979            continue;
980        };
981
982        let Some(remote_agent_event) = diagnostic_to_remote_agent_event(&event) else {
983            debug!("Received diagnostic event with no remote agent event mapping; skipping.");
984            continue;
985        };
986
987        let Some(session_id) = session_id.get() else {
988            debug!("No active remote agent session; dropping diagnostic event.");
989            continue;
990        };
991
992        let invalid_api_key = matches!(event.details(), &DiagnosticDetails::InvalidApiKey);
993        if invalid_api_key && !invalid_api_key_reports.is_allowed() {
994            debug!("Throttling an InvalidApiKey event report.");
995            continue;
996        }
997
998        let request = ReportRemoteAgentEventRequest {
999            session_id: session_id.as_str().to_string(),
1000            events: vec![remote_agent_event],
1001        };
1002
1003        match client.report_remote_agent_event(request).await {
1004            Ok(_) => {
1005                // The window opens only on delivery, so a failed report never holds back the next one.
1006                if invalid_api_key {
1007                    invalid_api_key_reports.record();
1008                }
1009            }
1010            Err(e) => {
1011                warn!(error = %e, "Failed to report remote agent event to the Datadog Agent.");
1012            }
1013        }
1014    }
1015
1016    debug!("Remote Agent event reporter stopped.");
1017    Ok(())
1018}
1019
1020/// Minimum time between `InvalidApiKey` reports.
1021const INVALID_API_KEY_REPORT_INTERVAL: Duration = Duration::from_secs(30);
1022
1023/// Rate limits `InvalidApiKey` reports.
1024///
1025/// Checking and recording are separate so that only a delivered report opens the window: a report that never
1026/// reaches the Core Agent leaves the next one free to send immediately.
1027#[derive(Debug, Default)]
1028struct InvalidApiKeyReportThrottle {
1029    last_reported: Option<Instant>,
1030}
1031
1032impl InvalidApiKeyReportThrottle {
1033    fn is_allowed(&self) -> bool {
1034        self.last_reported
1035            .is_none_or(|last| last.elapsed() >= INVALID_API_KEY_REPORT_INTERVAL)
1036    }
1037
1038    fn record(&mut self) {
1039        self.last_reported = Some(Instant::now());
1040    }
1041}
1042
1043/// Converts a [`DiagnosticEvent`] into the Datadog Agent's remote agent event representation.
1044///
1045/// Returns `None` for diagnostic details that have no corresponding remote agent event variant, in which case the
1046/// event is not reported.
1047fn diagnostic_to_remote_agent_event(event: &DiagnosticEvent) -> Option<RemoteAgentEvent> {
1048    let details = match event.details() {
1049        DiagnosticDetails::InvalidApiKey => RemoteAgentEventDetails::InvalidApiKey(InvalidApiKeyEvent {}),
1050        // `DiagnosticDetails` is `#[non_exhaustive]`; any future variant without a remote agent mapping is skipped.
1051        _ => return None,
1052    };
1053
1054    Some(RemoteAgentEvent {
1055        message: event.message().to_string(),
1056        details: Some(details),
1057    })
1058}
1059
1060#[cfg(test)]
1061mod tests {
1062    use std::collections::VecDeque;
1063
1064    use saluki_common::sync::shutdown::ShutdownCoordinator;
1065    use saluki_core::{
1066        data_model::event::{
1067            metric::{context::Context, Metric},
1068            Event,
1069        },
1070        observability::metrics::{MetricsSnapshot, Processor as _},
1071        runtime::Supervisor,
1072    };
1073
1074    use super::*;
1075
1076    #[test]
1077    fn remote_agent_process_instance_id_is_shared_across_registrations() {
1078        let address = || GrpcTargetAddress::Tcp("127.0.0.1:1234".parse().unwrap());
1079        let first = RegistrationDetails::new(address(), vec![]);
1080        assert!(uuid::Uuid::parse_str(first.process_instance_id).is_ok());
1081        assert_eq!(first.pid, std::process::id());
1082
1083        // Each bootstrap creates fresh registration details, but all of them share one process identity.
1084        let second = RegistrationDetails::new(address(), vec![]);
1085        assert_eq!(second.pid, first.pid);
1086        assert_eq!(second.process_instance_id, first.process_instance_id);
1087    }
1088
1089    fn at(secs: i64, nanos: u32) -> Timestamp {
1090        Timestamp::from_unix_nanos(i128::from(secs) * 1_000_000_000 + i128::from(nanos))
1091            .expect("test timestamp should be valid")
1092    }
1093
1094    #[test]
1095    fn started_is_rfc3339_with_the_fewest_exact_fraction_digits() {
1096        // 2026-11-18T11:06:40Z
1097        let secs = 1_795_000_000;
1098        let cases = [
1099            (0, "2026-11-18T11:06:40+00:00"),
1100            (1, "2026-11-18T11:06:40.000000001+00:00"),
1101            (1_000, "2026-11-18T11:06:40.000001+00:00"),
1102            (120_000_000, "2026-11-18T11:06:40.120+00:00"),
1103            (123_400_000, "2026-11-18T11:06:40.123400+00:00"),
1104            (123_456_789, "2026-11-18T11:06:40.123456789+00:00"),
1105        ];
1106
1107        for (nanos, expected) in cases {
1108            assert_eq!(format_started(Some(at(secs, nanos))), expected);
1109        }
1110    }
1111
1112    #[test]
1113    fn uptime_is_in_whole_seconds_rounded_toward_zero() {
1114        let started = Some(at(1_795_000_000, 500_000_000));
1115        assert_eq!(format_uptime(started, Some(at(1_795_000_090, 200_000_000))), "89");
1116        assert_eq!(format_uptime(started, Some(at(1_795_000_090, 500_000_000))), "90");
1117        assert_eq!(format_uptime(started, Some(at(1_794_999_970, 800_000_000))), "-29");
1118    }
1119
1120    #[test]
1121    fn unknown_times_are_unavailable() {
1122        let known = Some(at(1_795_000_000, 0));
1123        assert_eq!(format_started(None), "unavailable");
1124        assert_eq!(format_uptime(None, known), "unavailable");
1125        assert_eq!(format_uptime(known, None), "unavailable");
1126    }
1127
1128    #[test]
1129    fn cap_artifact_data_leaves_small_payloads_unchanged() {
1130        let input = b"hello world".to_vec();
1131        let output = cap_artifact_data(input.clone());
1132        assert_eq!(output, input);
1133    }
1134
1135    #[test]
1136    fn cap_artifact_data_truncates_at_limit_and_appends_marker() {
1137        let input = vec![b'x'; DIAGNOSTIC_ARTIFACT_MAX_BYTES + 1024];
1138        let output = cap_artifact_data(input);
1139
1140        // Total length is capped at the limit plus the marker.
1141        assert_eq!(
1142            output.len(),
1143            DIAGNOSTIC_ARTIFACT_MAX_BYTES + DIAGNOSTIC_TRUNCATION_MARKER.len()
1144        );
1145
1146        // The first DIAGNOSTIC_ARTIFACT_MAX_BYTES bytes are all 'x'.
1147        assert!(output[..DIAGNOSTIC_ARTIFACT_MAX_BYTES].iter().all(|&b| b == b'x'));
1148
1149        // The marker is appended at the end.
1150        assert!(output.ends_with(DIAGNOSTIC_TRUNCATION_MARKER));
1151    }
1152
1153    #[test]
1154    fn cap_artifact_data_at_exact_limit_is_not_truncated() {
1155        let input = vec![b'y'; DIAGNOSTIC_ARTIFACT_MAX_BYTES];
1156        let output = cap_artifact_data(input.clone());
1157        assert_eq!(output, input);
1158    }
1159
1160    fn metrics_state(names: &[&'static str]) -> AggregatedMetricsState {
1161        let processor = AggregatedMetricsProcessor;
1162        let state = processor.build_initial_state();
1163        let upserts = names
1164            .iter()
1165            .map(|name| Event::Metric(Metric::counter(Context::from_static_parts(name, &[]), 1.0)))
1166            .collect();
1167        processor.process(
1168            MetricsSnapshot {
1169                upserts,
1170                evictions: Vec::new(),
1171            },
1172            &state,
1173        );
1174        state
1175    }
1176
1177    #[tokio::test]
1178    async fn telemetry_without_remapper_rules_is_empty() {
1179        let state = metrics_state(&["test.events_received_total"]);
1180        let processor = telemetry_processor(Vec::new());
1181
1182        assert_eq!(render_telemetry(processor.as_ref(), &state).await, "");
1183    }
1184
1185    #[tokio::test]
1186    async fn telemetry_only_reports_metrics_matched_by_remapper_rules() {
1187        let state = metrics_state(&["test.events_received_total", "test.unmatched_total"]);
1188        let processor = telemetry_processor(vec![RemapperRule::by_name(
1189            "test.events_received_total",
1190            "events_received",
1191        )]);
1192
1193        let prom_text = render_telemetry(processor.as_ref(), &state).await;
1194        assert!(prom_text.contains("events_received 1"), "{prom_text}");
1195        assert!(!prom_text.contains("unmatched"), "{prom_text}");
1196    }
1197
1198    #[test]
1199    fn diagnostic_to_remote_agent_event_maps_invalid_api_key() {
1200        let event = DiagnosticEvent::new("credentials rejected", DiagnosticDetails::InvalidApiKey);
1201        let converted =
1202            diagnostic_to_remote_agent_event(&event).expect("InvalidApiKey should map to a remote agent event");
1203
1204        assert_eq!(converted.message, "credentials rejected");
1205        assert!(matches!(
1206            converted.details,
1207            Some(RemoteAgentEventDetails::InvalidApiKey(_))
1208        ));
1209    }
1210
1211    #[tokio::test(start_paused = true)]
1212    async fn invalid_api_key_reports_are_throttled_to_thirty_seconds() {
1213        let mut throttle = InvalidApiKeyReportThrottle::default();
1214
1215        assert!(throttle.is_allowed());
1216        throttle.record();
1217        assert!(!throttle.is_allowed());
1218
1219        tokio::time::advance(Duration::from_secs(30)).await;
1220        assert!(throttle.is_allowed());
1221        throttle.record();
1222        assert!(!throttle.is_allowed());
1223    }
1224
1225    #[tokio::test(start_paused = true)]
1226    async fn a_report_slightly_before_the_window_elapses_is_held() {
1227        let mut throttle = InvalidApiKeyReportThrottle::default();
1228
1229        throttle.record();
1230        tokio::time::advance(Duration::from_secs(29)).await;
1231        assert!(!throttle.is_allowed());
1232    }
1233
1234    #[test]
1235    fn a_report_that_was_never_delivered_does_not_open_the_throttle_window() {
1236        let mut throttle = InvalidApiKeyReportThrottle::default();
1237
1238        assert!(throttle.is_allowed());
1239        assert!(throttle.is_allowed());
1240        assert!(throttle.is_allowed());
1241
1242        throttle.record();
1243        assert!(!throttle.is_allowed());
1244    }
1245
1246    /// A Datadog Agent for registration and the config stream to talk to.
1247    ///
1248    /// Registration responses are scripted, and an unscripted registration is rejected. Every call is recorded with the
1249    /// number of seconds since the fake was created, which is exact with a paused clock.
1250    #[derive(Clone)]
1251    struct FakeAgent {
1252        state: Arc<std::sync::Mutex<FakeAgentState>>,
1253    }
1254
1255    struct FakeAgentState {
1256        created: Instant,
1257        calls: Vec<(u64, Call)>,
1258        registrations: VecDeque<RegisterRemoteAgentResponse>,
1259        rejected_registrations: usize,
1260        failed_refreshes: usize,
1261        hung_refreshes: usize,
1262        registration_delay: Option<Duration>,
1263        streams: VecDeque<mpsc::UnboundedReceiver<ConfigEvent>>,
1264    }
1265
1266    #[derive(Clone, Debug, PartialEq)]
1267    enum Call {
1268        Register,
1269        Refresh(String),
1270        Open(String),
1271    }
1272
1273    impl FakeAgent {
1274        fn new() -> Self {
1275            Self {
1276                state: Arc::new(std::sync::Mutex::new(FakeAgentState {
1277                    created: Instant::now(),
1278                    calls: Vec::new(),
1279                    registrations: VecDeque::new(),
1280                    rejected_registrations: 0,
1281                    failed_refreshes: 0,
1282                    hung_refreshes: 0,
1283                    registration_delay: None,
1284                    streams: VecDeque::new(),
1285                })),
1286            }
1287        }
1288
1289        fn lock(&self) -> std::sync::MutexGuard<'_, FakeAgentState> {
1290            self.state.lock().unwrap()
1291        }
1292
1293        fn accept_registration(&self, session_id: &str, recommended_refresh_interval_secs: u32) {
1294            self.lock().registrations.push_back(RegisterRemoteAgentResponse {
1295                session_id: session_id.to_string(),
1296                recommended_refresh_interval_secs,
1297            });
1298        }
1299
1300        /// Rejects the next registration, ahead of any scripted response.
1301        fn reject_next_registration(&self) {
1302            self.lock().rejected_registrations += 1;
1303        }
1304
1305        fn fail_next_refresh(&self) {
1306            self.lock().failed_refreshes += 1;
1307        }
1308
1309        /// Never answers the next refresh, ahead of any failed one.
1310        fn hang_next_refresh(&self) {
1311            self.lock().hung_refreshes += 1;
1312        }
1313
1314        /// Answers the next registration only after `delay`.
1315        fn delay_next_registration(&self, delay: Duration) {
1316            self.lock().registration_delay = Some(delay);
1317        }
1318
1319        /// Queues a stream for the next `open`, and returns the sender that feeds it.
1320        fn add_stream(&self) -> mpsc::UnboundedSender<ConfigEvent> {
1321            let (events_tx, events_rx) = mpsc::unbounded_channel();
1322            self.lock().streams.push_back(events_rx);
1323            events_tx
1324        }
1325
1326        fn calls(&self) -> Vec<(u64, Call)> {
1327            self.lock().calls.clone()
1328        }
1329
1330        /// Returns `true` if nothing other than this handle holds the fake.
1331        fn is_released(&self) -> bool {
1332            Arc::strong_count(&self.state) == 1
1333        }
1334    }
1335
1336    impl FakeAgentState {
1337        fn record(&mut self, call: Call) {
1338            let elapsed = self.created.elapsed().as_secs();
1339            self.calls.push((elapsed, call));
1340        }
1341    }
1342
1343    #[async_trait]
1344    impl RegistryClient for FakeAgent {
1345        async fn register(&mut self, _: &RegistrationDetails) -> Result<RegisterRemoteAgentResponse, GenericError> {
1346            let delay = {
1347                let mut state = self.lock();
1348                state.record(Call::Register);
1349                state.registration_delay.take()
1350            };
1351            if let Some(delay) = delay {
1352                tokio::time::sleep(delay).await;
1353            }
1354
1355            let mut state = self.lock();
1356            if state.rejected_registrations > 0 {
1357                state.rejected_registrations -= 1;
1358                return Err(generic_error!("registration rejected"));
1359            }
1360            state
1361                .registrations
1362                .pop_front()
1363                .ok_or_else(|| generic_error!("registration rejected"))
1364        }
1365
1366        async fn refresh(&mut self, session_id: &SessionId) -> Result<(), GenericError> {
1367            let hang = {
1368                let mut state = self.lock();
1369                state.record(Call::Refresh(session_id.to_string()));
1370                if state.hung_refreshes > 0 {
1371                    state.hung_refreshes -= 1;
1372                    true
1373                } else if state.failed_refreshes > 0 {
1374                    state.failed_refreshes -= 1;
1375                    return Err(generic_error!("unknown session"));
1376                } else {
1377                    false
1378                }
1379            };
1380            if hang {
1381                std::future::pending::<()>().await;
1382            }
1383            Ok(())
1384        }
1385    }
1386
1387    impl ConfigEventSource for FakeAgent {
1388        fn open(&mut self, session_id: &SessionId) -> ConfigEventStream {
1389            let mut state = self.lock();
1390            state.record(Call::Open(session_id.to_string()));
1391            match state.streams.pop_front() {
1392                Some(mut events) => Box::pin(futures::stream::poll_fn(move |cx| {
1393                    events.poll_recv(cx).map(|event| event.map(Ok))
1394                })),
1395                None => Box::pin(futures::stream::pending()),
1396            }
1397        }
1398    }
1399
1400    fn registration(agent: &FakeAgent, session_id: &SessionIdHandle) -> Registration {
1401        let details = RegistrationDetails {
1402            pid: 1,
1403            process_instance_id: "test-instance",
1404            display_name: "Test Agent".to_string(),
1405            flavor: "test_agent".to_string(),
1406            api_listen_addr: "localhost:5101".to_string(),
1407            service_names: Vec::new(),
1408        };
1409        Registration::new(Box::new(agent.clone()), details, session_id.clone())
1410    }
1411
1412    async fn registration_worker(agent: &FakeAgent, session_id: &SessionIdHandle) -> RemoteAgentRegistrationWorker {
1413        registration(agent, session_id)
1414            .register_and_spawn()
1415            .await
1416            .expect("registration should succeed")
1417    }
1418
1419    fn config_stream_worker(
1420        agent: &FakeAgent, session_id: &SessionIdHandle,
1421    ) -> (mpsc::Receiver<ConfigUpdate>, ConfigStreamWorker) {
1422        ConfigStreamWorker::spawn(Box::new(agent.clone()), session_id.clone())
1423    }
1424
1425    /// Starts `worker` the way a supervisor does, returning the coordinator that stops it and the task that runs it.
1426    async fn start(worker: &dyn Supervisable) -> (ShutdownCoordinator, tokio::task::JoinHandle<()>) {
1427        let (coordinator, shutdown) = ShutdownHandle::paired();
1428        let run = worker.initialize(shutdown).await.expect("worker should initialize");
1429        let task = tokio::spawn(async move { run.await.expect("worker should exit cleanly") });
1430        (coordinator, task)
1431    }
1432
1433    /// Stops `worker` the way its owner does: a brutal worker is halted, and a graceful one is signalled.
1434    async fn stop(worker: &dyn Supervisable, coordinator: ShutdownCoordinator, task: tokio::task::JoinHandle<()>) {
1435        match worker.shutdown_strategy() {
1436            ShutdownStrategy::Brutal => {
1437                task.abort();
1438                if let Err(e) = task.await {
1439                    assert!(e.is_cancelled(), "worker task should not panic");
1440                }
1441            }
1442            ShutdownStrategy::Graceful(_) => {
1443                coordinator.shutdown();
1444                tokio::time::timeout(Duration::from_secs(1), task)
1445                    .await
1446                    .expect("worker should stop promptly")
1447                    .expect("worker task should not panic");
1448            }
1449        }
1450    }
1451
1452    fn update_event(key: &str) -> ConfigEvent {
1453        ConfigEvent {
1454            event: Some(datadog_protos::agent::config_event::Event::Update(
1455                datadog_protos::agent::ConfigUpdate {
1456                    origin: "core-agent".to_string(),
1457                    sequence_id: 1,
1458                    setting: Some(datadog_protos::agent::ConfigSetting {
1459                        source: "file".to_string(),
1460                        key: key.to_string(),
1461                        value: Some(prost_types::Value {
1462                            kind: Some(prost_types::value::Kind::StringValue("value".to_string())),
1463                        }),
1464                        ..Default::default()
1465                    }),
1466                },
1467            )),
1468        }
1469    }
1470
1471    async fn next_key(updates: &mut mpsc::Receiver<ConfigUpdate>) -> String {
1472        let update = tokio::time::timeout(Duration::from_secs(60), updates.recv())
1473            .await
1474            .expect("an update should arrive");
1475        match update {
1476            Some(ConfigUpdate::Partial(setting)) => setting.key,
1477            other => panic!("expected a partial update, got {other:?}"),
1478        }
1479    }
1480
1481    fn session(id: &str) -> SessionIdHandle {
1482        let handle = SessionIdHandle::empty();
1483        handle.update(Some(SessionId::new(id).unwrap()));
1484        handle
1485    }
1486
1487    fn session_id_of(handle: &SessionIdHandle) -> Option<String> {
1488        handle.get().map(|session_id| session_id.to_string())
1489    }
1490
1491    #[tokio::test(start_paused = true)]
1492    async fn registration_worker_refreshes_after_the_recommended_interval_and_then_every_thirty_seconds() {
1493        let agent = FakeAgent::new();
1494        agent.accept_registration("session-1", 10);
1495        let session_id = SessionIdHandle::empty();
1496
1497        let worker = registration_worker(&agent, &session_id).await;
1498        let _running = start(&worker).await;
1499        tokio::time::sleep(Duration::from_secs(75)).await;
1500
1501        // Only the first refresh follows the Agent's recommendation; the timer's own period paces the rest.
1502        let refresh = || Call::Refresh("session-1".to_string());
1503        assert_eq!(
1504            agent.calls(),
1505            vec![(0, Call::Register), (10, refresh()), (40, refresh()), (70, refresh())]
1506        );
1507    }
1508
1509    #[tokio::test(start_paused = true)]
1510    async fn registration_worker_registers_again_after_a_failed_refresh() {
1511        let agent = FakeAgent::new();
1512        agent.accept_registration("session-1", 10);
1513        let session_id = SessionIdHandle::empty();
1514        let worker = registration_worker(&agent, &session_id).await;
1515
1516        // The refresh at 10s fails, the registration 5s later is rejected, and the next one 30s after that succeeds.
1517        agent.fail_next_refresh();
1518        agent.reject_next_registration();
1519        agent.accept_registration("session-2", 10);
1520        let _running = start(&worker).await;
1521
1522        tokio::time::sleep(Duration::from_secs(12)).await;
1523        assert_eq!(
1524            session_id_of(&session_id),
1525            None,
1526            "a failed refresh should clear the session"
1527        );
1528
1529        tokio::time::sleep(Duration::from_secs(44)).await;
1530        assert_eq!(
1531            agent.calls(),
1532            vec![
1533                (0, Call::Register),
1534                (10, Call::Refresh("session-1".to_string())),
1535                (15, Call::Register),
1536                (45, Call::Register),
1537                (55, Call::Refresh("session-2".to_string())),
1538            ]
1539        );
1540        assert_eq!(session_id_of(&session_id).as_deref(), Some("session-2"));
1541    }
1542
1543    #[tokio::test(start_paused = true)]
1544    async fn registration_worker_keeps_the_session_and_schedule_across_takeover_and_restart() {
1545        let agent = FakeAgent::new();
1546        agent.accept_registration("session-1", 10);
1547        let session_id = SessionIdHandle::empty();
1548        let worker = registration_worker(&agent, &session_id).await;
1549
1550        // The worker takes over from the task at 3s, stops at 5s, and is started again at 7s.
1551        tokio::time::sleep(Duration::from_secs(3)).await;
1552        let (coordinator, task) = start(&worker).await;
1553        tokio::time::sleep(Duration::from_secs(2)).await;
1554        stop(&worker, coordinator, task).await;
1555        tokio::time::sleep(Duration::from_secs(2)).await;
1556        let _running = start(&worker).await;
1557
1558        tokio::time::sleep(Duration::from_secs(4)).await;
1559        assert_eq!(
1560            agent.calls(),
1561            vec![(0, Call::Register), (10, Call::Refresh("session-1".to_string()))]
1562        );
1563    }
1564
1565    #[tokio::test(start_paused = true)]
1566    async fn a_handoff_lets_a_registration_in_flight_finish_without_registering_again() {
1567        let agent = FakeAgent::new();
1568        agent.accept_registration("session-1", 10);
1569        let session_id = SessionIdHandle::empty();
1570        let worker = registration_worker(&agent, &session_id).await;
1571
1572        // The refresh at 10s fails, and the registration 5s later is answered at 25s. The worker takes over at 20s,
1573        // while that registration is in flight.
1574        agent.fail_next_refresh();
1575        agent.accept_registration("session-2", 10);
1576        agent.delay_next_registration(Duration::from_secs(10));
1577        tokio::time::sleep(Duration::from_secs(20)).await;
1578        let _running = start(&worker).await;
1579
1580        tokio::time::sleep(Duration::from_secs(20)).await;
1581        assert_eq!(
1582            agent.calls(),
1583            vec![
1584                (0, Call::Register),
1585                (10, Call::Refresh("session-1".to_string())),
1586                (15, Call::Register),
1587                (35, Call::Refresh("session-2".to_string())),
1588            ]
1589        );
1590        assert_eq!(session_id_of(&session_id).as_deref(), Some("session-2"));
1591    }
1592
1593    #[tokio::test(start_paused = true)]
1594    async fn shutdown_interrupts_a_refresh_in_flight_which_a_restart_retries_right_away() {
1595        let agent = FakeAgent::new();
1596        agent.accept_registration("session-1", 10);
1597        agent.hang_next_refresh();
1598        let session_id = SessionIdHandle::empty();
1599        let worker = registration_worker(&agent, &session_id).await;
1600
1601        // The refresh at 10s never returns. The worker is stopped at 12s, and started again at 14s.
1602        let (coordinator, task) = start(&worker).await;
1603        tokio::time::sleep(Duration::from_secs(12)).await;
1604        stop(&worker, coordinator, task).await;
1605        tokio::time::sleep(Duration::from_secs(2)).await;
1606        let _running = start(&worker).await;
1607        tokio::time::sleep(Duration::from_secs(1)).await;
1608
1609        let refresh = || Call::Refresh("session-1".to_string());
1610        assert_eq!(
1611            agent.calls(),
1612            vec![(0, Call::Register), (10, refresh()), (14, refresh())]
1613        );
1614    }
1615
1616    #[tokio::test(start_paused = true)]
1617    async fn shutdown_stops_a_worker_and_its_task_while_the_task_is_in_an_attempt() {
1618        let agent = FakeAgent::new();
1619        agent.accept_registration("session-1", 10);
1620        agent.hang_next_refresh();
1621        let session_id = SessionIdHandle::empty();
1622        let worker = registration_worker(&agent, &session_id).await;
1623
1624        // The task's refresh at 10s never returns, so the worker that starts at 12s is still waiting for the task.
1625        tokio::time::sleep(Duration::from_secs(12)).await;
1626        let (coordinator, task) = start(&worker).await;
1627        tokio::time::sleep(Duration::from_secs(1)).await;
1628        stop(&worker, coordinator, task).await;
1629
1630        drop(worker);
1631        tokio::time::sleep(Duration::from_secs(1)).await;
1632        assert!(agent.is_released(), "the task should stop with the worker");
1633    }
1634
1635    #[tokio::test(start_paused = true)]
1636    async fn failed_first_registration_leaves_nothing_running() {
1637        let agent = FakeAgent::new();
1638        agent.reject_next_registration();
1639        let session_id = SessionIdHandle::empty();
1640
1641        let result = registration(&agent, &session_id).register_and_spawn().await;
1642        assert!(result.is_err(), "a rejected registration should fail");
1643
1644        tokio::time::sleep(Duration::from_secs(300)).await;
1645        assert_eq!(agent.calls(), vec![(0, Call::Register)]);
1646        assert!(agent.is_released(), "nothing should still hold the client");
1647    }
1648
1649    #[tokio::test(start_paused = true)]
1650    async fn shutdown_stops_the_registration_and_config_stream_workers() {
1651        let agent = FakeAgent::new();
1652        agent.accept_registration("session-1", 10);
1653        let events = agent.add_stream();
1654        let session_id = SessionIdHandle::empty();
1655        let registration = registration_worker(&agent, &session_id).await;
1656        let (mut updates, config_stream) = config_stream_worker(&agent, &session_id);
1657
1658        let mut supervisor = Supervisor::new("test-sup").unwrap();
1659        supervisor.add_worker(registration);
1660        supervisor.add_worker(config_stream);
1661        let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel::<()>();
1662        let run = tokio::spawn(async move { supervisor.run_with_shutdown(shutdown_rx).await });
1663
1664        events.send(update_event("before_shutdown")).unwrap();
1665        assert_eq!(next_key(&mut updates).await, "before_shutdown");
1666        tokio::time::sleep(Duration::from_secs(15)).await;
1667
1668        // The registration worker is halted, as it declares. A config stream worker that ignored the signal would be
1669        // halted at its shutdown timeout, which fails the shutdown.
1670        shutdown_tx.send(()).unwrap();
1671        let result = run.await.expect("supervisor task should not panic");
1672        assert!(result.is_ok(), "shutdown should be clean, got {result:?}");
1673
1674        let calls = agent.calls();
1675        tokio::time::sleep(Duration::from_secs(120)).await;
1676        assert_eq!(agent.calls(), calls, "registration should not continue after shutdown");
1677        assert!(events.is_closed(), "the config stream should be closed");
1678        assert!(
1679            updates.recv().await.is_none(),
1680            "the config stream channel should be closed"
1681        );
1682        assert!(agent.is_released(), "nothing should still hold the client");
1683    }
1684
1685    #[tokio::test(start_paused = true)]
1686    async fn config_stream_worker_continues_the_same_stream_without_losing_an_update() {
1687        let agent = FakeAgent::new();
1688        let events = agent.add_stream();
1689        let session_id = session("session-1");
1690
1691        // With the channel full, `b` is waiting for room in it when the worker takes over, and `c` hasn't been read
1692        // from the stream yet.
1693        let (mut updates, worker) = config_stream_worker(&agent, &session_id);
1694        let queued = (0..CONFIG_STREAM_CAPACITY)
1695            .map(|i| format!("queued-{i}"))
1696            .collect::<Vec<_>>();
1697        for key in queued.iter().map(String::as_str).chain(["b", "c"]) {
1698            events.send(update_event(key)).unwrap();
1699        }
1700        tokio::time::sleep(Duration::from_millis(10)).await;
1701
1702        let _running = start(&worker).await;
1703        events.send(update_event("d")).unwrap();
1704
1705        for key in queued.iter().map(String::as_str).chain(["b", "c", "d"]) {
1706            assert_eq!(next_key(&mut updates).await, key);
1707        }
1708        assert_eq!(agent.calls(), vec![(0, Call::Open("session-1".to_string()))]);
1709    }
1710
1711    #[tokio::test(start_paused = true)]
1712    async fn config_stream_worker_restarts_on_the_same_stream_and_channel() {
1713        let agent = FakeAgent::new();
1714        let events = agent.add_stream();
1715        let session_id = session("session-1");
1716        let (mut updates, worker) = config_stream_worker(&agent, &session_id);
1717
1718        let (coordinator, task) = start(&worker).await;
1719        events.send(update_event("a")).unwrap();
1720        assert_eq!(next_key(&mut updates).await, "a");
1721        stop(&worker, coordinator, task).await;
1722
1723        // `b` arrives while the worker is stopped.
1724        events.send(update_event("b")).unwrap();
1725        let _running = start(&worker).await;
1726        events.send(update_event("c")).unwrap();
1727
1728        for key in ["b", "c"] {
1729            assert_eq!(next_key(&mut updates).await, key);
1730        }
1731        assert_eq!(agent.calls(), vec![(0, Call::Open("session-1".to_string()))]);
1732    }
1733
1734    #[tokio::test(start_paused = true)]
1735    async fn config_stream_worker_waits_for_shutdown_once_the_receiver_is_dropped() {
1736        let agent = FakeAgent::new();
1737        let events = agent.add_stream();
1738        let session_id = session("session-1");
1739        let (mut updates, worker) = config_stream_worker(&agent, &session_id);
1740        let (coordinator, task) = start(&worker).await;
1741        events.send(update_event("a")).unwrap();
1742        assert_eq!(next_key(&mut updates).await, "a");
1743
1744        drop(updates);
1745        events.send(update_event("b")).unwrap();
1746        tokio::time::sleep(Duration::from_secs(60)).await;
1747
1748        assert!(events.is_closed(), "the config stream should be closed");
1749        assert!(!task.is_finished(), "the worker should keep running until shutdown");
1750        stop(&worker, coordinator, task).await;
1751        assert_eq!(agent.calls(), vec![(0, Call::Open("session-1".to_string()))]);
1752    }
1753
1754    #[tokio::test(start_paused = true)]
1755    async fn config_stream_reconnects_five_seconds_after_the_stream_ends_with_the_current_session() {
1756        let agent = FakeAgent::new();
1757        let first = agent.add_stream();
1758        let second = agent.add_stream();
1759        let session_id = session("session-1");
1760        let (mut updates, worker) = config_stream_worker(&agent, &session_id);
1761        let _running = start(&worker).await;
1762
1763        first.send(update_event("a")).unwrap();
1764        assert_eq!(next_key(&mut updates).await, "a");
1765        session_id.update(Some(SessionId::new("session-2").unwrap()));
1766        drop(first);
1767
1768        second.send(update_event("b")).unwrap();
1769        assert_eq!(next_key(&mut updates).await, "b");
1770        assert_eq!(
1771            agent.calls(),
1772            vec![
1773                (0, Call::Open("session-1".to_string())),
1774                (5, Call::Open("session-2".to_string()))
1775            ]
1776        );
1777    }
1778
1779    #[tokio::test(start_paused = true)]
1780    async fn tasks_stop_when_their_workers_are_dropped_without_starting() {
1781        let agent = FakeAgent::new();
1782        agent.accept_registration("session-1", 10);
1783        agent.hang_next_refresh();
1784        let events = agent.add_stream();
1785        let session_id = SessionIdHandle::empty();
1786        let registration = registration_worker(&agent, &session_id).await;
1787        let (mut updates, config_stream) = config_stream_worker(&agent, &session_id);
1788
1789        events.send(update_event("a")).unwrap();
1790        assert_eq!(next_key(&mut updates).await, "a");
1791
1792        // The registration task is still in the refresh at 10s, which never returns, when its worker is dropped.
1793        tokio::time::sleep(Duration::from_secs(12)).await;
1794        drop(registration);
1795        drop(config_stream);
1796        tokio::time::sleep(Duration::from_secs(120)).await;
1797
1798        assert_eq!(
1799            agent.calls(),
1800            vec![
1801                (0, Call::Register),
1802                (0, Call::Open("session-1".to_string())),
1803                (10, Call::Refresh("session-1".to_string()))
1804            ]
1805        );
1806        assert!(events.is_closed(), "the config stream should be closed");
1807        assert!(
1808            updates.recv().await.is_none(),
1809            "the config stream channel should be closed"
1810        );
1811        assert!(agent.is_released(), "nothing should still hold the client");
1812    }
1813}