Skip to main content

helm_rs/release/
mod.rs

1//! Helm 4 release records, read natively.
2//!
3//! [`Release`] mirrors the record exactly as Helm serializes it, both in release storage and in
4//! `helm status|install|upgrade -o json` (`pkg/release/v1/release.go`, `info.go`, `hook.go`,
5//! `pkg/release/common/status.go`, and the embedded chart, [`crate::chart::Chart`]; all verified identical in
6//! Helm v4.3.0). [`Release::decode`]
7//! reads the storage encoding (`pkg/storage/driver/util.go`); the `store` module (feature
8//! `kube`) reads records from the cluster. Nothing here writes to the cluster.
9
10mod hook;
11mod kinds;
12
13#[cfg(feature = "kube")]
14pub mod store;
15
16use std::collections::BTreeMap;
17use std::fmt;
18use std::io::{Read, Write};
19
20use base64::{Engine, engine::general_purpose::STANDARD};
21use flate2::{Compression, read::GzDecoder, write::GzEncoder};
22use jiff::Timestamp;
23use serde::{Deserialize, Serialize};
24use serde_json::Value;
25
26pub use hook::{Hook, HookExecution};
27pub use kinds::{ApplyMethod, DeletePolicy, HookEvent, HookPhase, OutputLogPolicy, Status};
28
29use crate::go_json::{null_default, omit_zero};
30
31/// The gzip magic Helm checks before decompressing (`magicGzip`).
32const GZIP_MAGIC: [u8; 3] = [0x1f, 0x8b, 0x08];
33
34/// Failures reading or decoding a release record.
35#[derive(Debug, thiserror::Error)]
36pub enum Error {
37    /// The record is not valid base64.
38    #[error("release record is not valid base64: {0}")]
39    Base64(#[from] base64::DecodeError),
40    /// The record starts with the gzip magic but does not decompress.
41    #[error("release record does not decompress: {0}")]
42    Gzip(#[source] std::io::Error),
43    /// The decoded record is not a release.
44    #[error("release record is not valid release JSON: {0}")]
45    Json(#[from] serde_json::Error),
46    /// The cluster could not be queried.
47    #[cfg(feature = "kube")]
48    #[error("cannot query release storage: {0}")]
49    Kube(#[from] kube::Error),
50    /// A storage object holds no `release` entry.
51    #[cfg(feature = "kube")]
52    #[error("storage object `{0}` has no `release` entry")]
53    MissingRecord(String),
54    /// A storage object's record could not be decoded.
55    #[cfg(feature = "kube")]
56    #[error("cannot decode storage object `{name}`: {source}")]
57    Object {
58        /// The name of the Secret or `ConfigMap`.
59        name: String,
60        /// Why decoding failed.
61        #[source]
62        source: Box<Error>,
63    },
64}
65
66/// A release revision (`version` in the record; the `version` storage label).
67#[derive(
68    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize,
69)]
70#[serde(transparent)]
71pub struct Revision(pub u32);
72
73impl fmt::Display for Revision {
74    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
75        self.0.fmt(f)
76    }
77}
78
79/// A deployment of a chart with the values used (`Release`).
80///
81/// Timestamps are [`jiff::Timestamp`]s: they are written in UTC (Go writes the local offset;
82/// the instant is the same), and Go's zero time reads as `None`.
83#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
84pub struct Release {
85    /// The release name.
86    #[serde(default, skip_serializing_if = "String::is_empty")]
87    pub name: String,
88    /// Status, times and notes.
89    #[serde(default, skip_serializing_if = "Option::is_none")]
90    pub info: Option<Info>,
91    /// The chart that was released.
92    #[serde(default, skip_serializing_if = "Option::is_none")]
93    pub chart: Option<crate::chart::Chart>,
94    /// The user-supplied values only, not the coalesced result (`null` when none).
95    #[serde(default, skip_serializing_if = "Value::is_null")]
96    pub config: Value,
97    /// The rendered non-hook manifests as one YAML stream with `# Source:` comments.
98    #[serde(default, skip_serializing_if = "String::is_empty")]
99    pub manifest: String,
100    /// The hooks, kept apart from `manifest`.
101    #[serde(
102        default,
103        deserialize_with = "null_default",
104        skip_serializing_if = "Vec::is_empty"
105    )]
106    pub hooks: Vec<Hook>,
107    /// The revision.
108    #[serde(default, skip_serializing_if = "is_zero_revision")]
109    pub version: Revision,
110    /// The Kubernetes namespace of the release.
111    #[serde(default, skip_serializing_if = "String::is_empty")]
112    pub namespace: String,
113    /// Custom release labels. Not part of the JSON: they live on the storage object, so only
114    /// [`store`] fills this in (system labels removed, as Helm does).
115    #[serde(skip)]
116    pub labels: BTreeMap<String, String>,
117    /// `ssa` or `csa`; `None` when the record has no field, which means client-side apply.
118    #[serde(
119        default,
120        deserialize_with = "empty_as_none",
121        skip_serializing_if = "Option::is_none"
122    )]
123    pub apply_method: Option<ApplyMethod>,
124}
125
126/// Information about a release (`Info`). Go's zero times read as `None`.
127#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
128pub struct Info {
129    /// When the release was first deployed.
130    #[serde(default, with = "omit_zero", skip_serializing_if = "Option::is_none")]
131    pub first_deployed: Option<Timestamp>,
132    /// When the release was last deployed.
133    #[serde(default, with = "omit_zero", skip_serializing_if = "Option::is_none")]
134    pub last_deployed: Option<Timestamp>,
135    /// When the release was deleted.
136    #[serde(default, with = "omit_zero", skip_serializing_if = "Option::is_none")]
137    pub deleted: Option<Timestamp>,
138    /// A human-friendly log line about the release.
139    #[serde(default, skip_serializing_if = "String::is_empty")]
140    pub description: String,
141    /// The current state; the empty `Other("")` when the record has none.
142    #[serde(default, skip_serializing_if = "Status::is_empty")]
143    pub status: Status,
144    /// The revision rolled back to; zero when the release is not a rollback.
145    #[serde(default, skip_serializing_if = "is_zero_revision")]
146    pub rollback_revision: Revision,
147    /// The rendered `NOTES.txt`.
148    #[serde(default, skip_serializing_if = "String::is_empty")]
149    pub notes: String,
150    /// The deployed resources, by kind, as Kubernetes objects (`null` when absent).
151    #[serde(default, skip_serializing_if = "Value::is_null")]
152    pub resources: Value,
153}
154
155impl Release {
156    /// Decodes a storage record: base64, then gzip when the gzip magic (`1f 8b 08`) is present,
157    /// then JSON (`decodeRelease` in `pkg/storage/driver/util.go`).
158    ///
159    /// `record` is the base64 text. For a Secret that is `data.release` after the Kubernetes API
160    /// decoded the outer base64 (what kube-rs yields as bytes); for a `ConfigMap` it is the
161    /// `data.release` string. A raw `kubectl get secret -o json` value needs one more base64
162    /// decode first.
163    pub fn decode(record: &[u8]) -> Result<Self, Error> {
164        let mut bytes = STANDARD.decode(record)?;
165
166        if bytes.starts_with(&GZIP_MAGIC) {
167            let mut json = Vec::new();
168
169            GzDecoder::new(bytes.as_slice())
170                .read_to_end(&mut json)
171                .map_err(Error::Gzip)?;
172            bytes = json;
173        }
174
175        Ok(serde_json::from_slice(&bytes)?)
176    }
177
178    /// Encodes the release the way `encodeRelease` does: JSON, gzip at the best level, base64.
179    /// The deflate stream may differ byte for byte from Go's, but Helm decodes it identically.
180    pub fn encode(&self) -> Result<String, Error> {
181        let mut gzip = GzEncoder::new(Vec::new(), Compression::best());
182
183        gzip.write_all(&serde_json::to_vec(self)?)
184            .map_err(Error::Gzip)?;
185
186        Ok(STANDARD.encode(gzip.finish().map_err(Error::Gzip)?))
187    }
188}
189
190/// Serde predicate for Go's `omitempty` on revisions.
191#[allow(clippy::trivially_copy_pass_by_ref)]
192fn is_zero_revision(value: &Revision) -> bool {
193    value.0 == 0
194}
195
196/// Reads a string-valued field where the empty string means unset.
197fn empty_as_none<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
198where
199    D: serde::Deserializer<'de>,
200    T: From<String>,
201{
202    Ok(Option::<String>::deserialize(deserializer)?
203        .filter(|text| !text.is_empty())
204        .map(T::from))
205}
206
207#[cfg(test)]
208mod tests;