Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

5.9 KB
Raw Blame
use std::collections::HashMap;

use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use tracing::{debug, info, warn};
use uuid::Uuid;

use crate::{
    api::client::ClientError,
    invocation_context::context,
    utils::{files::content_hash, git::GitInfo},
};

const RELEASE_HASH_IN_USE_ERROR_CODE: &str = "release_hash_in_use";

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Release {
    pub id: Uuid,
    pub hash_id: String,
    pub version: String,
    pub project: String,
}

#[derive(Debug, Clone, Default)]
pub struct ReleaseBuilder {
    name: Option<String>,
    version: Option<String>,
    metadata: HashMap<String, Value>,
}

// Internal, what we send to the API
#[derive(Debug, Clone, Serialize, Deserialize)]
struct CreateReleaseRequest {
    #[serde(skip_serializing_if = "HashMap::is_empty")]
    pub metadata: HashMap<String, Value>,
    pub hash_id: String,
    pub version: String,
    // TODO: update API to use name instead
    pub project: String,
}

impl Release {
    pub fn lookup(name: &str, version: &str) -> Result<Option<Self>, ClientError> {
        let hash_id = content_hash([name, version]);
        let client = &context().client;

        let path = format!("error_tracking/releases/hash/{hash_id}");
        let response = client.send_get(client.project_url(&path)?, |req| req);

        if let Err(err) = response {
            if let ClientError::ApiError(404, _, _) = err {
                // The caller creates the release after this, so a 404 is normal flow.
                debug!("release {}@{} not found", name, version);
                return Ok(None);
            }
            warn!("failed to get release from hash: {}", err);
            Err(err)
        } else {
            info!("found release {}@{}", name, version);
            Ok(Some(response.unwrap().json()?))
        }
    }
}

impl ReleaseBuilder {
    pub fn init_from_git(info: GitInfo) -> Self {
        let mut metadata = HashMap::new();
        metadata.insert(
            "git".to_string(),
            serde_json::to_value(info.clone()).expect("can serialize gitinfo"),
        );

        Self {
            metadata,
            version: Some(info.commit_id), // TODO - We should pull this commits tags and use them if we can
            name: info.repo_name,
        }
    }

    pub fn with_git(&mut self, info: GitInfo) -> &mut Self {
        if !self.has_name() {
            if let Some(name) = &info.repo_name {
                self.with_name(name);
            }
        }
        if !self.has_version() {
            self.with_version(&info.commit_id);
        }
        self.with_metadata("git", info)
            .expect("We can serialise git info")
    }

    pub fn with_metadata<T>(&mut self, key: &str, val: T) -> Result<&mut Self>
    where
        T: Serialize,
    {
        self.metadata
            .insert(key.to_string(), serde_json::to_value(val)?);
        Ok(self)
    }

    pub fn has_name(&self) -> bool {
        self.name.is_some()
    }

    pub fn with_name(&mut self, name: &str) -> &mut Self {
        self.name = Some(name.to_string());
        self
    }

    pub fn has_version(&self) -> bool {
        self.version.is_some()
    }

    pub fn with_version(&mut self, version: &str) -> &mut Self {
        self.version = Some(version.to_string());
        self
    }

    pub fn can_create(&self) -> bool {
        self.version.is_some() && self.name.is_some()
    }

    pub fn missing(&self) -> Vec<&str> {
        let mut missing = Vec::new();

        if self.version.is_none() {
            missing.push("release-version");
        }
        if self.name.is_none() {
            missing.push("release-name");
        }
        missing
    }

    pub fn fetch_or_create(self) -> Result<Release> {
        if !self.can_create() {
            anyhow::bail!(
                "Tried to create a release while missing key fields: {}",
                self.missing().join(", ")
            )
        }
        let version = self.version.as_ref().unwrap();
        let project = self.name.as_ref().unwrap();
        if let Some(release) = Release::lookup(project, version)? {
            Ok(release)
        } else {
            self.create_release()
        }
    }

    pub fn create_release(self) -> Result<Release> {
        // The way to encode this kind of thing in the type system is a thing called "Type-state". It's cool,
        // and if you're reading this and thinking "hmm this feels kind of gross and fragile", you should
        // google "rust type state pattern". The only problem is it's a lot of boilerplate, so I didn't do it.
        if !self.can_create() {
            anyhow::bail!(
                "Tried to create a release while missing key fields: {}",
                self.missing().join(", ")
            )
        }
        let version = self.version.unwrap();
        let name = self.name.unwrap();
        let metadata = self.metadata;

        let hash_id = content_hash([name.as_bytes(), version.as_bytes()]);

        let request = CreateReleaseRequest {
            metadata,
            hash_id,
            version,
            project: name,
        };

        let client = &context().client;

        let response = match client
            .send_post(client.project_url("error_tracking/releases")?, |req| {
                req.json(&request)
            }) {
            Ok(response) => response,
            Err(e) if e.has_structured_api_error_code(RELEASE_HASH_IN_USE_ERROR_CODE) => {
                if let Ok(Some(release)) = Release::lookup(&request.project, &request.version) {
                    return Ok(release);
                }
                return Err(e).context("Failed to create release");
            }
            Err(e) => return Err(e).context("Failed to create release"),
        };

        let response = response.json::<Release>()?;
        info!(
            "Release {}@{} created successfully! {}",
            request.project, request.version, response.id
        );
        Ok(response)
    }
}