helm-rs 0.1.0

Typed Rust API for Helm 4: swappable backends, native chart, values and release reading
Documentation
//! Helm 4 release records, read natively.
//!
//! [`Release`] mirrors the record exactly as Helm serializes it, both in release storage and in
//! `helm status|install|upgrade -o json` (`pkg/release/v1/release.go`, `info.go`, `hook.go`,
//! `pkg/release/common/status.go`, and the embedded chart, [`crate::chart::Chart`]; all verified identical in
//! Helm v4.3.0). [`Release::decode`]
//! reads the storage encoding (`pkg/storage/driver/util.go`); the `store` module (feature
//! `kube`) reads records from the cluster. Nothing here writes to the cluster.

mod hook;
mod kinds;

#[cfg(feature = "kube")]
pub mod store;

use std::collections::BTreeMap;
use std::fmt;
use std::io::{Read, Write};

use base64::{Engine, engine::general_purpose::STANDARD};
use flate2::{Compression, read::GzDecoder, write::GzEncoder};
use jiff::Timestamp;
use serde::{Deserialize, Serialize};
use serde_json::Value;

pub use hook::{Hook, HookExecution};
pub use kinds::{ApplyMethod, DeletePolicy, HookEvent, HookPhase, OutputLogPolicy, Status};

use crate::go_json::{null_default, omit_zero};

/// The gzip magic Helm checks before decompressing (`magicGzip`).
const GZIP_MAGIC: [u8; 3] = [0x1f, 0x8b, 0x08];

/// Failures reading or decoding a release record.
#[derive(Debug, thiserror::Error)]
pub enum Error {
    /// The record is not valid base64.
    #[error("release record is not valid base64: {0}")]
    Base64(#[from] base64::DecodeError),
    /// The record starts with the gzip magic but does not decompress.
    #[error("release record does not decompress: {0}")]
    Gzip(#[source] std::io::Error),
    /// The decoded record is not a release.
    #[error("release record is not valid release JSON: {0}")]
    Json(#[from] serde_json::Error),
    /// The cluster could not be queried.
    #[cfg(feature = "kube")]
    #[error("cannot query release storage: {0}")]
    Kube(#[from] kube::Error),
    /// A storage object holds no `release` entry.
    #[cfg(feature = "kube")]
    #[error("storage object `{0}` has no `release` entry")]
    MissingRecord(String),
    /// A storage object's record could not be decoded.
    #[cfg(feature = "kube")]
    #[error("cannot decode storage object `{name}`: {source}")]
    Object {
        /// The name of the Secret or `ConfigMap`.
        name: String,
        /// Why decoding failed.
        #[source]
        source: Box<Error>,
    },
}

/// A release revision (`version` in the record; the `version` storage label).
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize,
)]
#[serde(transparent)]
pub struct Revision(pub u32);

impl fmt::Display for Revision {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

/// A deployment of a chart with the values used (`Release`).
///
/// Timestamps are [`jiff::Timestamp`]s: they are written in UTC (Go writes the local offset;
/// the instant is the same), and Go's zero time reads as `None`.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct Release {
    /// The release name.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub name: String,
    /// Status, times and notes.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub info: Option<Info>,
    /// The chart that was released.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub chart: Option<crate::chart::Chart>,
    /// The user-supplied values only, not the coalesced result (`null` when none).
    #[serde(default, skip_serializing_if = "Value::is_null")]
    pub config: Value,
    /// The rendered non-hook manifests as one YAML stream with `# Source:` comments.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub manifest: String,
    /// The hooks, kept apart from `manifest`.
    #[serde(
        default,
        deserialize_with = "null_default",
        skip_serializing_if = "Vec::is_empty"
    )]
    pub hooks: Vec<Hook>,
    /// The revision.
    #[serde(default, skip_serializing_if = "is_zero_revision")]
    pub version: Revision,
    /// The Kubernetes namespace of the release.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub namespace: String,
    /// Custom release labels. Not part of the JSON: they live on the storage object, so only
    /// [`store`] fills this in (system labels removed, as Helm does).
    #[serde(skip)]
    pub labels: BTreeMap<String, String>,
    /// `ssa` or `csa`; `None` when the record has no field, which means client-side apply.
    #[serde(
        default,
        deserialize_with = "empty_as_none",
        skip_serializing_if = "Option::is_none"
    )]
    pub apply_method: Option<ApplyMethod>,
}

/// Information about a release (`Info`). Go's zero times read as `None`.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct Info {
    /// When the release was first deployed.
    #[serde(default, with = "omit_zero", skip_serializing_if = "Option::is_none")]
    pub first_deployed: Option<Timestamp>,
    /// When the release was last deployed.
    #[serde(default, with = "omit_zero", skip_serializing_if = "Option::is_none")]
    pub last_deployed: Option<Timestamp>,
    /// When the release was deleted.
    #[serde(default, with = "omit_zero", skip_serializing_if = "Option::is_none")]
    pub deleted: Option<Timestamp>,
    /// A human-friendly log line about the release.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub description: String,
    /// The current state; the empty `Other("")` when the record has none.
    #[serde(default, skip_serializing_if = "Status::is_empty")]
    pub status: Status,
    /// The revision rolled back to; zero when the release is not a rollback.
    #[serde(default, skip_serializing_if = "is_zero_revision")]
    pub rollback_revision: Revision,
    /// The rendered `NOTES.txt`.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub notes: String,
    /// The deployed resources, by kind, as Kubernetes objects (`null` when absent).
    #[serde(default, skip_serializing_if = "Value::is_null")]
    pub resources: Value,
}

impl Release {
    /// Decodes a storage record: base64, then gzip when the gzip magic (`1f 8b 08`) is present,
    /// then JSON (`decodeRelease` in `pkg/storage/driver/util.go`).
    ///
    /// `record` is the base64 text. For a Secret that is `data.release` after the Kubernetes API
    /// decoded the outer base64 (what kube-rs yields as bytes); for a `ConfigMap` it is the
    /// `data.release` string. A raw `kubectl get secret -o json` value needs one more base64
    /// decode first.
    pub fn decode(record: &[u8]) -> Result<Self, Error> {
        let mut bytes = STANDARD.decode(record)?;

        if bytes.starts_with(&GZIP_MAGIC) {
            let mut json = Vec::new();

            GzDecoder::new(bytes.as_slice())
                .read_to_end(&mut json)
                .map_err(Error::Gzip)?;
            bytes = json;
        }

        Ok(serde_json::from_slice(&bytes)?)
    }

    /// Encodes the release the way `encodeRelease` does: JSON, gzip at the best level, base64.
    /// The deflate stream may differ byte for byte from Go's, but Helm decodes it identically.
    pub fn encode(&self) -> Result<String, Error> {
        let mut gzip = GzEncoder::new(Vec::new(), Compression::best());

        gzip.write_all(&serde_json::to_vec(self)?)
            .map_err(Error::Gzip)?;

        Ok(STANDARD.encode(gzip.finish().map_err(Error::Gzip)?))
    }
}

/// Serde predicate for Go's `omitempty` on revisions.
#[allow(clippy::trivially_copy_pass_by_ref)]
fn is_zero_revision(value: &Revision) -> bool {
    value.0 == 0
}

/// Reads a string-valued field where the empty string means unset.
fn empty_as_none<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
where
    D: serde::Deserializer<'de>,
    T: From<String>,
{
    Ok(Option::<String>::deserialize(deserializer)?
        .filter(|text| !text.is_empty())
        .map(T::from))
}

#[cfg(test)]
mod tests;