From 5e207f42cdb770951648d23c1a7460c4e28581c7 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Fri, 4 Dec 2026 06:08:36 +1300 Subject: [PATCH] envschema: ready to publish (README, Apache-2.0, docs.rs examples, a Laravel Rust example) --- .github/workflows/release.yml | 48 ++- crates/envschema-derive/Cargo.toml | 8 + crates/envschema-derive/LICENSE | 1 + crates/envschema-derive/README.md | 12 + crates/envschema-derive/src/lib.rs | 8 +- crates/envschema/Cargo.toml | 7 +- crates/envschema/LICENSE | 1 + crates/envschema/README.md | 426 +++++++++++++++++++++++++++ crates/envschema/examples/std_env.rs | 68 +++++ crates/envschema/src/lib.rs | 118 +++++--- 10 files changed, 651 insertions(+), 46 deletions(-) create mode 120000 crates/envschema-derive/LICENSE create mode 100644 crates/envschema-derive/README.md create mode 120000 crates/envschema/LICENSE create mode 100644 crates/envschema/README.md create mode 100644 crates/envschema/examples/std_env.rs diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index e59bd59d..4ae95c17 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,5 +1,6 @@ # Release the visualci CLI: static binaries for Linux (musl) and macOS, attached to a GitHub release v; and -# publish the snapshot-diff crate (crates/snapshot-diff) to crates.io when its version isn't there yet. +# publish the snapshot-diff crate (crates/snapshot-diff) to crates.io when its version isn't there yet (and, once their +# Cargo.toml files drop `publish = false`, envschema-derive and envschema). # A release happens by itself once CI passes on main with a workspace version (Cargo.toml) that has no release yet, so # a version bump is all it takes and the docs never describe a CLI nobody can download. The cli-version job in ci.yml # fails when the CLI changed since its last release without a bump. Pushing a v* tag by hand still works too. @@ -128,3 +129,48 @@ jobs: env: CARGO_REGISTRY_TOKEN: ${{ steps.auth.outputs.token }} run: cargo publish --locked -p snapshot-diff + + # envschema-derive and envschema on crates.io, the same way: once per version in their Cargo.toml files, the derive + # first (envschema depends on it). Inert while either Cargo.toml says `publish = false`. Before that line goes, the + # first release of each is published by hand with a per-crate token, and trusted publishing is configured on + # crates.io for both crates (DocSpring/visualci, release.yml); this job then publishes every later version. + envschema: + if: github.event_name == 'push' || (github.event.workflow_run.conclusion == 'success' && github.event.workflow_run.event == 'push') + runs-on: ubuntu-latest + permissions: + contents: read + id-token: write + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ github.event.workflow_run.head_sha || github.sha }} + - id: version + run: | + publish= + for crate in envschema-derive envschema; do + manifest=crates/$crate/Cargo.toml + if grep -q '^publish = false' "$manifest"; then + echo "$crate isn't published yet ($manifest says publish = false)" + continue + fi + version=$(sed -n 's/^version = "\(.*\)"/\1/p' "$manifest" | head -1) + code=$(curl -s -o /dev/null -w '%{http_code}' -A 'envschema release (github.com/DocSpring/visualci)' \ + "https://crates.io/api/v1/crates/$crate/$version") + if [ "$code" = 200 ]; then + echo "$crate $version is already on crates.io" + else + publish="$publish $crate" + fi + done + echo "crates=${publish# }" >> "$GITHUB_OUTPUT" + - id: auth + if: steps.version.outputs.crates != '' + uses: rust-lang/crates-io-auth-action@v1 + - if: steps.version.outputs.crates != '' + env: + CARGO_REGISTRY_TOKEN: ${{ steps.auth.outputs.token }} + CRATES: ${{ steps.version.outputs.crates }} + run: | + for crate in $CRATES; do + cargo publish --locked -p "$crate" + done diff --git a/crates/envschema-derive/Cargo.toml b/crates/envschema-derive/Cargo.toml index d83baa6a..146f8ea3 100644 --- a/crates/envschema-derive/Cargo.toml +++ b/crates/envschema-derive/Cargo.toml @@ -3,8 +3,16 @@ name = "envschema-derive" description = "The derive macro for envschema: typed settings read from environment variables" version = "0.1.0" edition.workspace = true +rust-version = "1.88" license.workspace = true repository.workspace = true +homepage = "https://github.com/DocSpring/visualci/tree/main/crates/envschema" +documentation = "https://docs.rs/envschema-derive" +readme = "README.md" +keywords = ["config", "environment", "env", "settings", "derive"] +categories = ["config"] +# Not published yet: VisualCI's server runs it in production first. This flips to `true` (the line goes) when we publish +# envschema-derive and envschema to crates.io, together with the envschema jobs in .github/workflows/release.yml. publish = false [lib] diff --git a/crates/envschema-derive/LICENSE b/crates/envschema-derive/LICENSE new file mode 120000 index 00000000..30cff740 --- /dev/null +++ b/crates/envschema-derive/LICENSE @@ -0,0 +1 @@ +../../LICENSE \ No newline at end of file diff --git a/crates/envschema-derive/README.md b/crates/envschema-derive/README.md new file mode 100644 index 00000000..071f479c --- /dev/null +++ b/crates/envschema-derive/README.md @@ -0,0 +1,12 @@ +# envschema-derive + +The `#[derive(Settings)]` macro for [envschema](https://crates.io/crates/envschema): typed settings read from prefixed +environment variables, with one schema for loading, checks, secret masking, warnings about unknown variables and +generated docs. + +Don't depend on this crate directly: envschema re-exports the derive as `envschema::Settings`, and the code it +generates refers to `::envschema`. The attributes are documented there, in +[envschema's README](https://github.com/DocSpring/visualci/blob/main/crates/envschema/README.md) and +[on docs.rs](https://docs.rs/envschema). + +MSRV: Rust 1.88. Licensed under Apache-2.0. diff --git a/crates/envschema-derive/src/lib.rs b/crates/envschema-derive/src/lib.rs index 1679c447..17b0619d 100644 --- a/crates/envschema-derive/src/lib.rs +++ b/crates/envschema-derive/src/lib.rs @@ -1,5 +1,7 @@ -//! `#[derive(Settings)]` for [envschema](https://github.com/DocSpring/visualci/tree/main/crates/envschema). The -//! attributes are documented on the derive's re-export, `envschema::Settings`. +//! `#[derive(Settings)]` for [envschema](https://docs.rs/envschema). The attributes are documented on the derive's +//! re-export, `envschema::Settings`. Depend on envschema, not on this crate: the code the derive generates refers to +//! `::envschema`. +#![deny(missing_docs)] use proc_macro::TokenStream; use proc_macro2::{Span, TokenStream as TokenStream2}; @@ -9,6 +11,8 @@ use syn::{ Attribute, Data, DeriveInput, Error, Expr, Fields, GenericArgument, Ident, Lit, LitStr, PathArguments, Token, Type, }; +/// `#[derive(Settings)]`: implements `envschema::Settings` and a `Debug` that masks secrets. See `envschema::Settings` +/// for the attributes. #[proc_macro_derive(Settings, attributes(env, settings))] pub fn derive_settings(input: TokenStream) -> TokenStream { let input = syn::parse_macro_input!(input as DeriveInput); diff --git a/crates/envschema/Cargo.toml b/crates/envschema/Cargo.toml index 2a1f91ac..dad5abeb 100644 --- a/crates/envschema/Cargo.toml +++ b/crates/envschema/Cargo.toml @@ -3,11 +3,16 @@ name = "envschema" description = "Typed settings from prefixed environment variables, with one schema for loading, checks, secret masking, warnings about unknown variables, and generated docs" version = "0.1.0" edition.workspace = true +rust-version = "1.88" license.workspace = true repository.workspace = true +homepage = "https://github.com/DocSpring/visualci/tree/main/crates/envschema" +documentation = "https://docs.rs/envschema" +readme = "README.md" keywords = ["config", "environment", "env", "settings", "dotenv"] categories = ["config"] -# Used by VisualCI's server for now; published once its API has settled. +# Not published yet: VisualCI's server runs it in production first. This flips to `true` (the line goes) when we publish +# envschema-derive and envschema to crates.io, together with the envschema jobs in .github/workflows/release.yml. publish = false [dependencies] diff --git a/crates/envschema/LICENSE b/crates/envschema/LICENSE new file mode 120000 index 00000000..30cff740 --- /dev/null +++ b/crates/envschema/LICENSE @@ -0,0 +1 @@ +../../LICENSE \ No newline at end of file diff --git a/crates/envschema/README.md b/crates/envschema/README.md new file mode 100644 index 00000000..04402f86 --- /dev/null +++ b/crates/envschema/README.md @@ -0,0 +1,426 @@ +# envschema + +Typed settings from prefixed environment variables, described once. A struct with `#[derive(Settings)]` is the +schema: each field names its variable, and its doc comment, type, default, and whether it's required, required in +production or secret come with it. From that one description, envschema loads the settings, checks them, masks the +secrets, warns about variables nothing reads, and writes the reference docs. + +MSRV: Rust 1.88 (edition 2024). No dependencies besides its derive macro, [`envschema-derive`](https://crates.io/crates/envschema-derive). + +## The conventions + +envschema is built around a handful of conventions for how an app reads its environment: + +- **One prefix for everything the app owns.** Every setting the app defines starts with the same prefix, such as + `MYAPP_`. Variables a framework or library reads (`DATABASE_URL`, `RUST_LOG`, `PORT`) keep their own names, but are + described in the same schema as an external group, so the docs list everything one process needs in one place. +- **Every setting is described.** Each has a description (the field's doc comment, which the derive requires), a type, + and a default, and is marked `required`, `required_in_production` or `secret` where that applies. +- **Every problem at once, at boot.** Loading doesn't stop at the first missing or invalid variable: the error lists + all of them, so one deploy shows everything that's wrong. +- **Secrets stay out of logs.** The derived `Debug` and `Summary` (the line an app logs at boot) show `` for + secret settings, and an invalid secret's value isn't echoed in the error. +- **Unknown prefixed variables are warned about.** A variable with the app's prefix that nothing reads is usually a typo + or a renamed setting. `Schema::unknown` finds each one and names the closest known variable: + `MYAPP_DATABSE_POOL is set, but nothing reads it (did you mean MYAPP_DATABASE_POOL?)`. +- **The docs are generated, and CI keeps them in step.** `Schema::markdown` writes a reference table and + `Schema::dotenv_example` writes a `.env.example`. A test compares them with the committed files and fails when the + schema changed without them. + +## Quick start + +```toml +[dependencies] +envschema = "0.1" +``` + +```rust,no_run +use envschema::{ProcessEnv, Settings}; + +/// How the server listens. +#[derive(Settings)] +#[settings(title = "Server")] +struct Server { + /// The port to listen on. + #[env("MYAPP_PORT", default = 8080)] + port: u16, + /// Signs session cookies. At least 32 random bytes. + #[env("MYAPP_SECRET_KEY", secret, required)] + secret_key: String, + /// Postmark's server token, for email. Without it, email is only logged. + #[env("MYAPP_POSTMARK_TOKEN", secret, required_in_production)] + postmark_token: Option, +} + +#[derive(Settings)] +struct Config { + #[settings(nested)] + server: Server, +} + +fn main() { + let production = std::env::var("MYAPP_ENV").is_ok_and(|env| env == "production"); + let config = match Config::load(&ProcessEnv, production) { + Ok(config) => config, + Err(problems) => { + // the environment is invalid: + // - MYAPP_SECRET_KEY is required, but isn't set + // - MYAPP_PORT is set to `80a`, which is invalid: expected a whole number (...) + eprintln!("{problems}"); + std::process::exit(1); + } + }; + // MYAPP_PORT=8080 MYAPP_SECRET_KEY= + println!("{}", config.summary()); + + let names: Vec = std::env::vars_os().filter_map(|(name, _)| name.into_string().ok()).collect(); + for unknown in Config::schema().unknown("MYAPP_", names.iter().map(String::as_str)) { + eprintln!("warning: {unknown}"); + } +} +``` + +[`examples/std_env.rs`](https://github.com/DocSpring/visualci/blob/main/crates/envschema/examples/std_env.rs) is the +same program: `cargo run -p envschema --example std_env` in VisualCI's repository. + +## Declaring settings + +On a field: + +| Attribute | Field type | Meaning | +| --- | --- | --- | +| `#[env("NAME")]` | `Option` | Optional: `None` when unset. | +| `#[env("NAME", default = ...)]` | `T` | The default when unset: a string, number or boolean literal, parsed like the variable's value and shown as written in the docs. | +| `#[env("NAME", required)]` | `T` | Loading fails when it's unset. | +| `required_in_production` | `Option` | Loading fails when it's unset and the loader is in production mode. | +| `secret` | any | Masked in `Debug`, `Summary` and error messages. | +| `example = "..."` | any | An example value for the docs and `.env.example`. | +| `#[settings(nested)]` | another `Settings` struct | Its settings are a group of their own. | + +On the struct, `#[settings(title = "...")]` titles its group in the docs (the struct's name otherwise), and its doc +comment introduces the group. An empty value counts as unset. + +The types that work out of the box are `String`, `bool` (`true`/`false`, `1`/`0`, `yes`/`no`, `on`/`off`), the +integers, `f64` and `Vec` of any of them (comma-separated). Implement `Value` for your own types. The derive also +implements `Debug`, with secrets masked, so don't derive `Debug` as well. + +## Reading from any source + +Settings are read through the `Source` trait, not straight from `std::env`, so the same struct loads from the process +environment (`ProcessEnv`), a map, a closure over a framework's own environment, or pairs in a test. Tests don't need +to set process variables, which parallel tests can't do safely. + +An env map, here read from the process once: + +```rust +use std::collections::HashMap; +use envschema::Settings; + +#[derive(Settings)] +struct Worker { + /// Jobs run at once. + #[env("MYAPP_WORKER_CONCURRENCY", default = 4)] + concurrency: u32, + /// Queues to work, in order. + #[env("MYAPP_WORKER_QUEUES", default = "default,mail")] + queues: Vec, +} + +let mut env: HashMap = std::env::vars().collect(); +env.insert("MYAPP_WORKER_CONCURRENCY".into(), "8".into()); +let worker = Worker::load(&env, false).unwrap(); +assert_eq!(worker.concurrency, 8); +assert_eq!(worker.queues, ["default", "mail"]); +``` + +A source of your own: a `.env` file's values under the process's, which win. Any `Fn(&str) -> Option` is a +source too. + +```rust +use std::collections::HashMap; +use envschema::{Settings, Source}; + +/// The process's environment first, then the `.env` file's values. +struct WithDotenv { + file: HashMap, +} + +impl Source for WithDotenv { + fn get(&self, name: &str) -> Option { + std::env::var(name).ok().or_else(|| self.file.get(name).cloned()) + } +} + +#[derive(Settings)] +struct Cache { + /// The cache's Redis URL. + #[env("MYAPP_ENVSCHEMA_EXAMPLE_REDIS_URL", required)] + redis_url: String, +} + +let file = HashMap::from([("MYAPP_ENVSCHEMA_EXAMPLE_REDIS_URL".to_string(), "redis://127.0.0.1".to_string())]); +let cache = Cache::load(&WithDotenv { file }, false).unwrap(); +assert_eq!(cache.redis_url, "redis://127.0.0.1"); + +// A closure works as a source as well. +let source = |name: &str| (name == "MYAPP_ENVSCHEMA_EXAMPLE_REDIS_URL").then(|| "redis://cache".to_string()); +assert_eq!(Cache::load(&source, false).unwrap().redis_url, "redis://cache"); +``` + +## Every problem at once, and secrets masked + +```rust +use envschema::Settings; + +#[derive(Settings)] +struct Billing { + /// Stripe's secret API key. + #[env("MYAPP_STRIPE_KEY", secret, required)] + stripe_key: String, + /// Days a trial lasts. + #[env("MYAPP_TRIAL_DAYS", default = 14)] + trial_days: u32, + /// The PIN for the admin console. + #[env("MYAPP_ADMIN_PIN", secret, default = 0)] + admin_pin: u32, +} + +let env = [("MYAPP_TRIAL_DAYS", "two weeks"), ("MYAPP_ADMIN_PIN", "hunter2")]; +let error = Billing::load(&env, false).unwrap_err().to_string(); +assert!(error.contains("MYAPP_STRIPE_KEY is required, but isn't set")); +assert!(error.contains("MYAPP_TRIAL_DAYS is set to `two weeks`, which is invalid: expected a whole number")); +assert!(error.contains("MYAPP_ADMIN_PIN is set to a value, which is invalid")); +assert!(!error.contains("hunter2")); + +let billing = Billing::load(&[("MYAPP_STRIPE_KEY", "sk_live_123")], false).unwrap(); +assert!(!format!("{billing:?}").contains("sk_live_123")); +assert_eq!(billing.summary().to_string(), "MYAPP_STRIPE_KEY= MYAPP_TRIAL_DAYS=14 MYAPP_ADMIN_PIN="); +``` + +`load_reporting` returns the settings (with defaults standing in for anything missing or invalid) and the problems, +for an app that collects them while it sets up and reports them later at boot. + +## Production, and the framework's variables + +`required_in_production` settings are required only when the loader is in production mode, so development runs +without a mail token or a payment key, and production refuses to start without one. Variables the app doesn't read +itself go in an external group: they're documented, they're never reported as unknown, and `missing_in_production` +checks the ones production needs. + +```rust +use envschema::{Group, Settings, Variable}; + +#[derive(Settings)] +struct Mail { + /// Postmark's server token. + #[env("MYAPP_POSTMARK_TOKEN", secret, required_in_production)] + postmark_token: Option, +} + +const FRAMEWORK: &[Variable] = &[ + Variable::new("DATABASE_URL", "The database's URL.").secret().required_in_production(), + Variable::new("PORT", "The port the server listens on.").kind("integer").default("3000"), +]; + +let schema = Mail::schema().with_group(Group::external( + "Framework", + "The framework reads these itself, under its own names.", + FRAMEWORK, +)); +assert!(schema.mistakes("MYAPP_").is_empty()); + +let env = [("PORT", "8080")]; +assert!(Mail::load(&env, false).is_ok()); + +let (_, mut problems) = Mail::load_reporting(&env, true); +problems.extend(schema.missing_in_production(&env)); +let problems: Vec = problems.iter().map(ToString::to_string).collect(); +assert_eq!(problems, [ + "MYAPP_POSTMARK_TOKEN is required in production, but isn't set", + "DATABASE_URL is required in production, but isn't set", +]); +``` + +`Schema::mistakes` finds mistakes in the schema itself (a name described twice, an app setting without the prefix), and +is worth a unit test. + +## Unknown variables + +```rust +use envschema::Settings; + +#[derive(Settings)] +struct Database { + /// Connections in the pool. + #[env("MYAPP_DATABASE_POOL", default = 10)] + pool: u32, +} + +// Other programs that share the prefix (a CLI's token) are ignored, and names without the prefix aren't checked. +let schema = Database::schema().ignoring(&["MYAPP_CLI_TOKEN"]); +let names = ["MYAPP_DATABSE_POOL", "MYAPP_CLI_TOKEN", "HOME"]; +let unknown = schema.unknown("MYAPP_", names); +assert_eq!(unknown.len(), 1); +assert_eq!(unknown[0].closest, Some("MYAPP_DATABASE_POOL")); +assert_eq!( + unknown[0].to_string(), + "MYAPP_DATABSE_POOL is set, but nothing reads it (did you mean MYAPP_DATABASE_POOL?)", +); +``` + +At boot, pass the process's variable names (`std::env::vars_os()`) and log each one as a warning. + +## Generated docs, kept in step by CI + +```rust +use envschema::Settings; + +/// How the server listens. +#[derive(Settings)] +#[settings(title = "Server")] +struct Server { + /// The port to listen on. + #[env("MYAPP_PORT", default = 8080)] + port: u16, + /// Signs session cookies. + #[env("MYAPP_SECRET_KEY", secret, required, example = "change-me")] + secret_key: String, +} + +let markdown = Server::schema().markdown(); +assert!(markdown.starts_with("## Server\n\nHow the server listens.\n\n| Variable | Type | Default | Description |")); +assert!(markdown.contains("| `MYAPP_PORT` | integer | `8080` | The port to listen on. |")); +assert!(markdown.contains("**Required.** Secret. Signs session cookies. Example: `change-me`.")); + +let dotenv = Server::schema().dotenv_example(); +assert!(dotenv.contains("# The port to listen on.\n# MYAPP_PORT=8080\n")); +assert!(dotenv.contains("# Required. Secret. Signs session cookies. Example: change-me.\nMYAPP_SECRET_KEY=change-me\n")); +``` + +Required settings are written out to fill in; the rest are commented out with their defaults. To keep the committed +files in step, a test compares them with what the schema generates, and rewrites them when asked to: + +```rust +use std::path::Path; + +/// Fails when the committed docs differ from what `schema` generates. `MYAPP_UPDATE_DOCS=1` rewrites them instead. +fn assert_docs_match(schema: &envschema::Schema, root: &Path) { + let files = [ + (root.join("docs/environment-variables.md"), format!("# Environment variables\n\n{}", schema.markdown())), + (root.join(".env.example"), schema.dotenv_example()), + ]; + let update = std::env::var("MYAPP_UPDATE_DOCS").is_ok_and(|v| v == "1"); + for (path, expected) in files { + if update { + std::fs::write(&path, &expected).unwrap(); + } else { + let committed = std::fs::read_to_string(&path).unwrap_or_default(); + assert!(committed == expected, "{} is out of date: run the tests with MYAPP_UPDATE_DOCS=1", path.display()); + } + } +} +``` + +Call it from a test in the app: `assert_docs_match(&config::schema(), Path::new(env!("CARGO_MANIFEST_DIR")))`. + +## Laravel Rust + +[Laravel Rust](https://crates.io/crates/laravel-rust) reads `.env` into its own `Env`, which treats `null` and empty +values as unset and gives each test app its own variables. A closure over `Env::get` is the source, and each group goes +into the framework's config as a section of its own. This is the integration in VisualCI's server +([`app/src/config.rs`](https://github.com/DocSpring/visualci/blob/main/app/src/config.rs)), shortened to two groups. +It isn't compiled here, to keep the framework out of envschema's dependencies: + +```rust,ignore +use envschema::{Group, Settings, Variable}; + +#[derive(Settings, Clone)] +pub struct Config { + #[settings(nested)] + pub storage: Storage, + #[settings(nested)] + pub mail: Mail, +} + +/// Every variable the server reads: the app's settings, then the framework's under their own names. +pub fn schema() -> envschema::Schema { + Config::schema().with_group(Group::external( + "Laravel Rust", + "The framework reads these itself, under its own names.", + &[ + Variable::new("APP_KEY", "Encrypts cookies and sessions.").secret().required_in_production(), + Variable::new("DATABASE_URL", "The database's URL.").secret(), + ], + )) +} + +/// Problems found by `install`, kept for `check`. +struct Problems(Vec); + +/// `App::new().with_config(config::install)`: read every setting from Laravel's environment and set each group. +pub fn install(config: &mut laravel::config::Config, env: &laravel::config::Env) { + let production = config.app.env.is_production(); + let source = |name: &str| env.get::(name); + let (settings, mut problems) = Config::load_reporting(&source, production); + if production { + problems.extend(schema().missing_in_production(&source)); + } + config.set(Problems(problems)).set(settings.storage.clone()).set(settings.mail.clone()).set(settings); +} + +/// At boot, first: refuse to start with every problem listed. +pub fn check(config: &laravel::config::Config) -> laravel::Result<()> { + match config.get::() { + Some(Problems(problems)) if !problems.is_empty() => { + Err(laravel::Error::msg(envschema::Problems(problems.clone()).to_string())) + } + _ => Ok(()), + } +} + +/// At boot, after `check`: log the settings, secrets masked, and warn about unknown `MYAPP_` variables. +pub fn report(config: &laravel::config::Config) { + if let Some(settings) = config.get::() { + tracing::info!(settings = %settings.summary(), "configuration"); + } + let names: Vec = std::env::vars_os().filter_map(|(name, _)| name.into_string().ok()).collect(); + for unknown in schema().unknown("MYAPP_", names.iter().map(String::as_str)) { + tracing::warn!(variable = %unknown.name, "{unknown}"); + } +} +``` + +A handler then takes one group, as it would any section: `Section`. + +## Loco + +[Loco](https://loco.rs) needs no adapter either. Load the struct with `ProcessEnv` in your app's `Hooks` (before +`boot`, or in `after_context`), stop with the problems if there are any, and keep it in the context's shared store for +handlers to read. Loco's YAML config (`config/.yaml`, which can itself read variables with `get_env`) +stays as it is: envschema covers the app's own settings next to it, not the framework's config file. + +## When to use it, and when not + +Use envschema when an app (a web service, a worker) is configured by environment variables, as in a container or on a +twelve-factor platform, and you want the settings documented, checked at boot and safe to log, from one place. + +Look elsewhere when: + +- **Your configuration lives in files**, or layers files, environment and command-line flags. + [figment](https://crates.io/crates/figment) layers providers well, and [config](https://crates.io/crates/config) + (config-rs) merges files and the environment; envschema reads only variables, one value per variable. +- **You want serde.** [envy](https://crates.io/crates/envy) deserializes the environment into any `Deserialize` + struct, with `from_iter` for a source of your own. It's smaller and has no metadata at all: no descriptions, + secrets, docs or unknown-variable check. +- **You want a typed derive with defaults and file templates.** [confique](https://crates.io/crates/confique) is the + closest crate: a derive, env names per field, defaults, doc comments kept as metadata, and generated TOML, YAML and + JSON5 templates. It reads `std::env::var` only (no other source, so no per-test variables), and has nothing for + secrets, `required_in_production`, unknown variables, or Markdown and `.env` output. If you don't need those, use it. + +None of those warns about unknown prefixed variables. envschema is small on purpose: settings are flat values parsed +from text (no nested maps or arrays of tables), the struct can't be generic, and `Value` covers the common types, with +your own types added by implementing it. + +## Licence + +Apache-2.0. envschema was written for [VisualCI](https://visualci.com)'s server, where it runs in production. diff --git a/crates/envschema/examples/std_env.rs b/crates/envschema/examples/std_env.rs new file mode 100644 index 00000000..fc3585d5 --- /dev/null +++ b/crates/envschema/examples/std_env.rs @@ -0,0 +1,68 @@ +//! envschema with nothing but the process's environment: load the settings, stop with every problem at once, log the +//! settings with secrets masked, and warn about `MYAPP_` variables nothing reads. +//! +//! ```sh +//! cargo run -p envschema --example std_env +//! MYAPP_SECRET_KEY=s3cret MYAPP_PROT=80 cargo run -p envschema --example std_env +//! MYAPP_ENV=production MYAPP_SECRET_KEY=s3cret cargo run -p envschema --example std_env +//! ``` +//! +//! The first stops because `MYAPP_SECRET_KEY` is required, the second warns about `MYAPP_PROT` (did you mean +//! `MYAPP_PORT`?), and the third stops because production needs `MYAPP_POSTMARK_TOKEN`. + +use envschema::{ProcessEnv, Settings}; + +/// How the server listens. +#[derive(Settings)] +#[settings(title = "Server")] +struct Server { + /// The port to listen on. + #[env("MYAPP_PORT", default = 8080)] + port: u16, + /// Signs session cookies. At least 32 random bytes. + #[env("MYAPP_SECRET_KEY", secret, required)] + secret_key: String, +} + +/// Email. +#[derive(Settings)] +#[settings(title = "Email")] +struct Mail { + /// Postmark's server token. Without it, email is only logged. + #[env("MYAPP_POSTMARK_TOKEN", secret, required_in_production)] + postmark_token: Option, + /// The From address. + #[env("MYAPP_MAIL_FROM", default = "MyApp ")] + from: String, +} + +#[derive(Settings)] +struct Config { + #[settings(nested)] + server: Server, + #[settings(nested)] + mail: Mail, +} + +fn main() { + let production = std::env::var("MYAPP_ENV").is_ok_and(|env| env == "production"); + let config = match Config::load(&ProcessEnv, production) { + Ok(config) => config, + Err(problems) => { + eprintln!("{problems}"); + std::process::exit(1); + } + }; + println!("configuration: {}", config.summary()); + + let names: Vec = std::env::vars_os().filter_map(|(name, _)| name.into_string().ok()).collect(); + for unknown in Config::schema().unknown("MYAPP_", names.iter().map(String::as_str)) { + eprintln!("warning: {unknown}"); + } + + let Config { server, mail } = config; + println!("listening on port {}, sending email from {}", server.port, mail.from); + if !production && mail.postmark_token.is_none() { + println!("no MYAPP_POSTMARK_TOKEN: email is only logged"); + } +} diff --git a/crates/envschema/src/lib.rs b/crates/envschema/src/lib.rs index df3e9446..8288cc5f 100644 --- a/crates/envschema/src/lib.rs +++ b/crates/envschema/src/lib.rs @@ -1,43 +1,5 @@ -//! Typed settings from prefixed environment variables, described once. -//! -//! A struct with `#[derive(Settings)]` is the schema: each field names its variable, and its doc comment, type, -//! default, and whether it's required, required in production or secret come with it. From that one description, -//! envschema: -//! -//! - reads the struct from any [`Source`] (the process's environment, a map, a framework's own environment), listing -//! every missing or invalid variable at once instead of stopping at the first; -//! - checks the settings production can't run without ([`Loader::production`]); -//! - finds variables with the app's prefix that nothing reads, a typo or a renamed setting, and names the closest -//! known one ([`Schema::unknown`]); -//! - masks secrets in `Debug` output and in [`Summary`], for logging what the app runs with; -//! - writes the reference docs as Markdown and a `.env.example` ([`Schema::markdown`], [`Schema::dotenv_example`]). -//! -//! ``` -//! use envschema::Settings; -//! -//! /// Where uploads are kept. -//! #[derive(Settings)] -//! #[settings(title = "Storage")] -//! struct Storage { -//! /// The bucket's endpoint. -//! #[env("APP_S3_ENDPOINT", required)] -//! endpoint: String, -//! /// The bucket's region. -//! #[env("APP_S3_REGION", default = "auto")] -//! region: String, -//! /// The secret key. -//! #[env("APP_S3_SECRET", secret, required_in_production)] -//! secret: Option, -//! } -//! -//! let env = [("APP_S3_ENDPOINT", "http://127.0.0.1:9000"), ("APP_S3_SECRET", "shh"), ("APP_S3_REGOIN", "eu")]; -//! let storage = Storage::load(&env, true).unwrap(); -//! assert_eq!(storage.region, "auto"); -//! assert!(!format!("{storage:?}").contains("shh")); -//! -//! let unknown = Storage::schema().unknown("APP_", env.iter().map(|(name, _)| *name)); -//! assert_eq!(unknown[0].closest, Some("APP_S3_REGION")); -//! ``` +#![doc = include_str!("../README.md")] +#![deny(missing_docs)] use std::collections::{BTreeMap, BTreeSet, HashMap}; use std::fmt; @@ -109,6 +71,48 @@ impl Source for Vec<(&str, &str)> { } /// A setting's type: how a variable's text becomes a value, and back for the logs. +/// +/// Implemented for `String`, `bool`, the integers, `f64` and comma-separated `Vec`. A type of your own: +/// +/// ``` +/// use envschema::{Settings, Value}; +/// +/// #[derive(Debug, Default, PartialEq)] +/// enum LogFormat { +/// #[default] +/// Text, +/// Json, +/// } +/// +/// impl Value for LogFormat { +/// const KIND: &'static str = "`text` or `json`"; +/// +/// fn parse(raw: &str) -> Result { +/// match raw { +/// "text" => Ok(Self::Text), +/// "json" => Ok(Self::Json), +/// _ => Err("expected text or json".to_string()), +/// } +/// } +/// +/// fn show(&self) -> String { +/// match self { +/// Self::Text => "text".to_string(), +/// Self::Json => "json".to_string(), +/// } +/// } +/// } +/// +/// #[derive(Settings)] +/// struct Logging { +/// /// How log lines are written. +/// #[env("MYAPP_LOG_FORMAT", default = "text")] +/// format: LogFormat, +/// } +/// +/// assert_eq!(Logging::load(&[("MYAPP_LOG_FORMAT", "json")], false).unwrap().format, LogFormat::Json); +/// assert!(Logging::load(&[("MYAPP_LOG_FORMAT", "xml")], false).is_err()); +/// ``` pub trait Value: Sized { /// The type's name in the docs, such as `string` or `integer`. const KIND: &'static str; @@ -197,14 +201,21 @@ impl Value for Vec { /// One setting, as the schema describes it. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Variable { + /// The environment variable's name, such as `MYAPP_PORT`. pub name: &'static str, + /// What it's for: the field's doc comment, for the docs. pub description: &'static str, /// The type's name ([`Value::KIND`]). pub kind: &'static str, + /// The default when it's unset, as written in the attribute. pub default: Option<&'static str>, + /// An example value for the docs and `.env.example`. pub example: Option<&'static str>, + /// Loading fails when it's unset. pub required: bool, + /// Loading in production mode fails when it's unset. pub required_in_production: bool, + /// Its value is masked in `Debug` output, [`Summary`] and error messages. pub secret: bool, } @@ -225,36 +236,42 @@ impl Variable { } } + /// The type's name in the docs, such as `integer` (`string` otherwise). #[must_use] pub const fn kind(mut self, kind: &'static str) -> Self { self.kind = kind; self } + /// The value the reader uses when it's unset. #[must_use] pub const fn default(mut self, default: &'static str) -> Self { self.default = Some(default); self } + /// An example value for the docs and `.env.example`. #[must_use] pub const fn example(mut self, example: &'static str) -> Self { self.example = Some(example); self } + /// The reader fails without it. #[must_use] pub const fn required(mut self) -> Self { self.required = true; self } + /// Production needs it: [`Schema::missing_in_production`] reports it when it's unset. #[must_use] pub const fn required_in_production(mut self) -> Self { self.required_in_production = true; self } + /// Its value is a secret. #[must_use] pub const fn secret(mut self) -> Self { self.secret = true; @@ -265,8 +282,11 @@ impl Variable { /// The settings of one struct, or variables something else reads ([`Group::external`]). #[derive(Clone, Debug, PartialEq, Eq)] pub struct Group { + /// The group's heading in the docs. pub title: &'static str, + /// The paragraph under the heading: the struct's doc comment. pub description: &'static str, + /// Its variables, in the struct's order. pub variables: Vec, /// Read by something else (a framework, a library, the test suite), and described here so the docs and the /// unknown-variable check cover them too. @@ -284,6 +304,7 @@ impl Group { /// Every group of settings, in order: what the docs list, and what the unknown-variable check knows. #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct Schema { + /// The groups, in the docs' order: the struct's own and its nested structs', then the external ones. pub groups: Vec, /// Names with the prefix that belong to other programs (a CLI sharing the prefix), so they're never unknown. Not /// in the docs. @@ -293,6 +314,7 @@ pub struct Schema { /// A variable with the prefix that nothing reads. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Unknown { + /// The variable's name. pub name: String, /// The known variable whose name is closest. pub closest: Option<&'static str>, @@ -512,7 +534,9 @@ fn present(source: &dyn Source, name: &str) -> Option { /// Something wrong with one variable. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Problem { + /// The variable it's about. pub variable: &'static str, + /// What's wrong, naming the variable, such as "MYAPP_SECRET_KEY is required, but isn't set". pub message: String, } @@ -530,7 +554,10 @@ impl fmt::Display for Problem { /// Every problem found while loading, one per line. #[derive(Clone, Debug, PartialEq, Eq)] -pub struct Problems(pub Vec); +pub struct Problems( + /// The problems, in the schema's order. + pub Vec, +); impl fmt::Display for Problems { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { @@ -553,6 +580,7 @@ pub struct Loader<'a> { } impl<'a> Loader<'a> { + /// A loader for `source`, not in production mode. #[must_use] pub fn new(source: &'a dyn Source) -> Self { Self { source, production: false, problems: Vec::new() } @@ -571,6 +599,7 @@ impl<'a> Loader<'a> { &self.problems } + /// Every problem found. #[must_use] pub fn into_problems(self) -> Vec { self.problems @@ -690,12 +719,14 @@ pub trait Settings: Sized { /// A setting's name and value for logs, a secret's value masked. #[derive(Clone, PartialEq, Eq)] pub struct Shown { + /// The variable's name. pub name: &'static str, /// `None` when unset; `` for a secret that's set. pub value: Option, } impl Shown { + /// A setting's name and value, masked when it's a secret. An empty value is unset. #[must_use] pub fn new(name: &'static str, secret: bool, value: Option) -> Self { let value = value.filter(|v| !v.is_empty()).map(|v| if secret { Redacted.to_string() } else { v }); @@ -714,7 +745,10 @@ impl fmt::Debug for Shown { /// The settings that are set, as `NAME=value` pairs separated by spaces, secrets masked. #[derive(Clone, Debug, PartialEq, Eq)] -pub struct Summary(pub Vec); +pub struct Summary( + /// Every setting, set or not, in the schema's order. + pub Vec, +); impl fmt::Display for Summary { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {