Skip to main content

baukit_core/
lib.rs

1//! Dependency-light shared vocabulary for Baukit crates and services.
2//!
3//! This crate is the canonical home for dependency-light process vocabulary and
4//! runtime-neutral measurements shared across crate boundaries. It deliberately
5//! contains no telemetry exporters, async runtime, HTTP framework, operational
6//! routing, or product policy. Higher-level Baukit crates re-export established
7//! compatibility types from their own APIs.
8//!
9//! The `export` module encodes CSV with spreadsheet formula neutralization.
10//! The optional `pagination` feature adds keyset pagination types that domain
11//! crates can use without an HTTP framework. The optional `media-grants`
12//! feature adds HMAC-SHA256 signed media grants that an edge verifier checks.
13//! The optional `webhook-signature` feature adds the `baukit-webhook-v1`
14//! signature that webhook senders apply and receivers verify.
15
16#![deny(missing_docs)]
17
18pub mod export;
19pub mod limits;
20#[cfg(feature = "media-grants")]
21pub mod media_grant;
22#[cfg(feature = "pagination")]
23pub mod pagination;
24#[cfg(feature = "webhook-signature")]
25pub mod webhook_signature;
26
27use std::{fmt, str::FromStr};
28
29use serde::{Deserialize, Serialize};
30use thiserror::Error;
31
32/// The deployment environment attached to configuration and telemetry signals.
33#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
34#[serde(rename_all = "lowercase")]
35pub enum DeploymentEnvironment {
36    /// A developer workstation or other local process.
37    #[default]
38    Local,
39    /// A deployed environment used for integration and acceptance testing.
40    Testing,
41    /// A deployed pre-production process.
42    Staging,
43    /// A deployed production process.
44    Production,
45}
46
47impl DeploymentEnvironment {
48    const fn as_str(self) -> &'static str {
49        match self {
50            Self::Local => "local",
51            Self::Testing => "testing",
52            Self::Staging => "staging",
53            Self::Production => "production",
54        }
55    }
56}
57
58impl fmt::Display for DeploymentEnvironment {
59    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
60        formatter.write_str(self.as_str())
61    }
62}
63
64impl FromStr for DeploymentEnvironment {
65    type Err = ParseEnvironmentError;
66
67    fn from_str(value: &str) -> Result<Self, Self::Err> {
68        match value {
69            "local" => Ok(Self::Local),
70            "testing" => Ok(Self::Testing),
71            "staging" => Ok(Self::Staging),
72            "production" => Ok(Self::Production),
73            _ => Err(ParseEnvironmentError(value.to_owned())),
74        }
75    }
76}
77
78/// An error returned when a deployment environment name is not supported.
79#[derive(Clone, Debug, Error, Eq, PartialEq)]
80#[error("unsupported environment `{0}`; expected local, testing, staging, or production")]
81pub struct ParseEnvironmentError(String);
82
83/// Selection policy for the stdout log formatter.
84#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq)]
85#[serde(rename_all = "lowercase")]
86pub enum LogFormat {
87    /// Select JSON for deployed environments, and pretty output locally.
88    #[default]
89    Auto,
90    /// Always emit newline-delimited JSON.
91    Json,
92    /// Always emit human-readable pretty output.
93    Pretty,
94}
95
96impl LogFormat {
97    /// Resolves [`LogFormat::Auto`] for a deployment environment.
98    #[must_use]
99    pub const fn resolve(self, environment: DeploymentEnvironment) -> Self {
100        match (self, environment) {
101            (Self::Auto, DeploymentEnvironment::Local) => Self::Pretty,
102            (
103                Self::Auto,
104                DeploymentEnvironment::Testing
105                | DeploymentEnvironment::Staging
106                | DeploymentEnvironment::Production,
107            ) => Self::Json,
108            (explicit, _) => explicit,
109        }
110    }
111}
112
113/// The kind of process being identified and instrumented.
114#[derive(Clone, Copy, Debug, Eq, PartialEq)]
115pub enum ProcessKind {
116    /// A public or internal HTTP API process.
117    Api,
118    /// A background worker process.
119    Worker,
120    /// A database migration process.
121    Migrate,
122    /// A data seeding process.
123    Seed,
124}
125
126impl ProcessKind {
127    const fn as_str(self) -> &'static str {
128        match self {
129            Self::Api => "api",
130            Self::Worker => "worker",
131            Self::Migrate => "migrate",
132            Self::Seed => "seed",
133        }
134    }
135}
136
137impl fmt::Display for ProcessKind {
138    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
139        formatter.write_str(self.as_str())
140    }
141}
142
143/// Stable identity and build metadata for one running process.
144#[derive(Clone, Debug, Eq, PartialEq)]
145pub struct ServiceIdentity {
146    product: String,
147    process: ProcessKind,
148    version: String,
149    commit: String,
150    environment: DeploymentEnvironment,
151}
152
153impl ServiceIdentity {
154    /// Creates a service identity.
155    pub fn new(
156        product: impl Into<String>,
157        process: ProcessKind,
158        version: impl Into<String>,
159        commit: impl Into<String>,
160        environment: DeploymentEnvironment,
161    ) -> Self {
162        Self {
163            product: product.into(),
164            process,
165            version: version.into(),
166            commit: commit.into(),
167            environment,
168        }
169    }
170
171    /// Returns the stable product identifier.
172    pub fn product(&self) -> &str {
173        &self.product
174    }
175
176    /// Returns this process's kind.
177    pub const fn process(&self) -> ProcessKind {
178        self.process
179    }
180
181    /// Returns the Cargo package version.
182    pub fn version(&self) -> &str {
183        &self.version
184    }
185
186    /// Returns the short source-control commit identifier.
187    pub fn commit(&self) -> &str {
188        &self.commit
189    }
190
191    /// Returns the deployment environment.
192    pub const fn environment(&self) -> DeploymentEnvironment {
193        self.environment
194    }
195
196    /// Composes the OpenTelemetry `service.name` value.
197    pub fn service_name(&self) -> String {
198        format!("{}-{}", self.product, self.process)
199    }
200}
201
202/// Immutable version-control and compiler metadata for a process build.
203#[derive(Clone, Debug, Eq, PartialEq)]
204pub struct BuildInfo {
205    version: String,
206    commit: String,
207    rust_version: String,
208}
209
210impl BuildInfo {
211    /// Creates build metadata from values supplied by a build pipeline.
212    pub fn new(
213        version: impl Into<String>,
214        commit: impl Into<String>,
215        rust_version: impl Into<String>,
216    ) -> Self {
217        Self {
218            version: version.into(),
219            commit: commit.into(),
220            rust_version: rust_version.into(),
221        }
222    }
223
224    /// Returns the Cargo package version.
225    pub fn version(&self) -> &str {
226        &self.version
227    }
228
229    /// Returns the source-control commit identifier.
230    pub fn commit(&self) -> &str {
231        &self.commit
232    }
233
234    /// Returns the Rust compiler version used for the build.
235    pub fn rust_version(&self) -> &str {
236        &self.rust_version
237    }
238}
239
240#[cfg(test)]
241mod tests {
242    use super::*;
243
244    #[test]
245    fn shared_vocabulary_follows_the_telemetry_contract() {
246        let identity = ServiceIdentity::new(
247            "orders",
248            ProcessKind::Api,
249            "1.2.3",
250            "abc123",
251            DeploymentEnvironment::Production,
252        );
253
254        assert_eq!(identity.service_name(), "orders-api");
255        assert_eq!(identity.environment().to_string(), "production");
256        assert_eq!(
257            LogFormat::Auto.resolve(DeploymentEnvironment::Production),
258            LogFormat::Json
259        );
260    }
261
262    #[test]
263    fn deployment_environments_parse_display_and_serialize() {
264        for (text, environment) in [
265            ("local", DeploymentEnvironment::Local),
266            ("testing", DeploymentEnvironment::Testing),
267            ("staging", DeploymentEnvironment::Staging),
268            ("production", DeploymentEnvironment::Production),
269        ] {
270            assert_eq!(text.parse::<DeploymentEnvironment>(), Ok(environment));
271            assert_eq!(environment.to_string(), text);
272            assert_eq!(
273                serde_json::to_string(&environment).expect("serialize environment"),
274                format!("\"{text}\"")
275            );
276            assert_eq!(
277                serde_json::from_str::<DeploymentEnvironment>(&format!("\"{text}\""))
278                    .expect("deserialize environment"),
279                environment
280            );
281        }
282    }
283}
284
285// Compiles the README's examples so they cannot drift from the API.
286#[doc = include_str!("../README.md")]
287#[cfg(doctest)]
288struct ReadmeDoctests;