pdk-flex-abi 1.7.0

PDK Flex ABI
Documentation
// Copyright (c) 2026, Salesforce, Inc.,
// All rights reserved.
// For full license text, see the LICENSE.txt file

//! Entrypoint utilities for PDK Flex policies.
//!
//! This module provides the core functionality for initializing and executing
//! PDK Flex policies within the Flex Gateway runtime.

use std::fmt::Display;

use anyhow::anyhow;
use serde::Serialize;

use crate::api::metadata::PolicyMetadata;
use crate::api::{FlexAbi, FlexAbiImpl};
use crate::hostcalls;
use crate::hostcalls::FlexLogLevel;

/// Wraps a policy's entrypoint function with proper error handling and initialization.
///
/// This function should be used as the main entry point for PDK Flex policies.
/// It handles initialization of the policy environment and provides a clean interface
/// for policy implementations to interact with the Flex Gateway runtime.
///
pub fn wrap_entrypoint<O, E>(entrypoint: fn(&dyn FlexAbi) -> Result<O, E>) -> bool
where
    O: Serialize,
    E: Display,
{
    match do_wrap_entrypoint(entrypoint) {
        Ok(_) => true,
        Err(e) => {
            let casted: anyhow::Error = e;
            hostcalls::log(
                FlexLogLevel::Error,
                format!("Error initializing policy: {casted}").as_str(),
            );
            false
        }
    }
}

fn do_wrap_entrypoint<O, E>(
    entrypoint: fn(&dyn FlexAbi) -> Result<O, E>,
) -> Result<(), anyhow::Error>
where
    O: Serialize,
    E: Display,
{
    let config = hostcalls::get_configuration()?.unwrap_or_default();
    let metadata_bytes = hostcalls::get_metadata()?.unwrap_or_default();
    let metadata: PolicyMetadata = serde_json::from_slice(&metadata_bytes).unwrap();
    let abi: &dyn FlexAbi = &FlexAbiImpl { metadata, config };

    entrypoint(abi).map_err(|e| anyhow!(format!("{e}")))?;

    Ok(())
}