port-sdk 0.1.0

Rust SDK for Port APIs.
Documentation
use std::collections::{HashMap, HashSet};
use std::sync::{Arc, Mutex};

/// Tracks resources created during tests or manual runs so stragglers can be cleaned up later.
#[derive(Debug, Default)]
pub struct ResourceTracker {
    inner: Mutex<HashMap<String, HashSet<String>>>,
}

impl ResourceTracker {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn record_creation(&self, resource_type: impl Into<String>, id: impl Into<String>) {
        let resource_key = resource_type.into();
        let mut guard = self.inner.lock().expect("resource tracker mutex poisoned");
        let entry = guard.entry(resource_key).or_default();
        entry.insert(id.into());
    }

    pub fn record_deletion(&self, resource_type: impl Into<String>, id: impl Into<String>) {
        let resource_key = resource_type.into();
        let resource_id = id.into();
        let mut guard = self.inner.lock().expect("resource tracker mutex poisoned");
        if let Some(entry) = guard.get_mut(&resource_key) {
            entry.remove(&resource_id);
            if entry.is_empty() {
                guard.remove(&resource_key);
            }
        }
    }

    pub fn outstanding(&self) -> HashMap<String, Vec<String>> {
        let guard = self.inner.lock().expect("resource tracker mutex poisoned");
        guard.iter().map(|(key, values)| (key.clone(), values.iter().cloned().collect())).collect()
    }
}

pub type ResourceTrackerHandle = Arc<ResourceTracker>;

pub fn new_shared_tracker() -> ResourceTrackerHandle {
    Arc::new(ResourceTracker::new())
}