pdk-metrics-lib 1.6.0

PDK Metrics Library
Documentation
// Copyright (c) 2025, Salesforce, Inc.,
// All rights reserved.
// For full license text, see the LICENSE.txt file

//! Readiness
//!
//! Contains the resource to indicate that a policies that require async initialization
//! have completed their initialization.
//!

use crate::{Metric, MetricsBuilder, MetricsInstance};
use classy::extract::context::ConfigureContext;
use classy::extract::{Extract, FromContext};
use pdk_core::policy_context::api::Metadata;
use std::convert::Infallible;

/// Used to indicate that a policy which extends the `async-initialization-wasm` has
/// completed its initialization.
pub trait Readiness {
    fn ready(&self);
}

/// Implementation of the Readiness trait that can be injected into a policy.
pub struct ReadinessInstance {
    gauge: MetricsInstance,
}

impl Readiness for ReadinessInstance {
    fn ready(&self) {
        self.gauge.set(1);
    }
}

/// It can injected by the framework during the configuration phase of the policy lifecycle:
///
/// ``` rust
/// #[entrypoint]
/// async fn configure(
///     launcher: Launcher,
///     Configuration(configuration): Configuration,
///     readiness: ReadinessInstance,
/// ) -> Result<()> {
///     // your code here.
/// }
impl FromContext<ConfigureContext> for ReadinessInstance {
    type Error = Infallible;

    fn from_context(context: &ConfigureContext) -> Result<Self, Self::Error> {
        let metrics: MetricsBuilder = context.extract()?;
        let metadata: Metadata = context.extract()?;

        let gauge = metrics
            .gauge(&format!(
                "{}/{}/ready",
                metadata.policy_metadata.policy_namespace, metadata.policy_metadata.policy_name
            ))
            .skip_default_tags()
            .build();

        Ok(ReadinessInstance { gauge })
    }
}