Trogon.Proto.Env (Trogon.Proto v0.12.0)

Copy Markdown View Source

Compile-time macro for generating environment variable loaders from proto definitions.

Reads field-level trogon_proto.env.v1_alpha1.field extensions to generate:

  • Typed struct with proper field definitions
  • from_env/0 function that returns {:ok, t()} | {:error, LoadError.t()}

  • from_env!/0 function that returns the struct or raises LoadError
  • Inspect implementation that masks secret fields automatically

Usage

Define your configuration message in a proto file with env var options:

syntax = "proto3";

package myapp.config.v1;

import "trogon/env/v1alpha1/options.proto";

message AppConfig {
  string database_url = 1 [(trogon.env.v1alpha1.field).env_var = {
    visibility: VISIBILITY_SECRET
  }];

  string port = 2 [(trogon.env.v1alpha1.field).env_var = {
    visibility: VISIBILITY_PLAINTEXT,
    default_value: "5432"
  }];
}

Then use the macro in a module:

defmodule MyApp.Config do
  use Trogon.Proto.Env, message: Myapp.Config.V1.AppConfig
end

At runtime, load the configuration:

# Requires DATABASE_URL env var, uses PORT default of 5432
config = MyApp.Config.from_env!()

# Or handle failures without rescuing (CLI / Mix tasks / health checks):
case MyApp.Config.from_env() do
  {:ok, config} -> config
  {:error, %Trogon.Proto.Env.LoadError{errors: errors}} -> handle(errors)
end

# Secrets are automatically masked when inspecting/logging
Logger.info(inspect(config))

Type Conversions

Environment variables are always strings. This module converts them to the appropriate Elixir types based on the proto field type:

  • string - No conversion
  • int32, int64 - Parsed via String.to_integer/1
  • float, double - Parsed via Float.parse/1 (accepts both "1.5" and "1")
  • bool - Case-insensitive, truthy values: "true", "1", "yes", "on"; all other values are considered false
  • enum - Exact enum name match (for example "LOG_LEVEL_DEBUG")

Summary

Functions

Defines an environment variable loader struct from a protobuf message.

Types

field_config()

@type field_config() :: %{
  env_var_name: String.t(),
  visibility: non_neg_integer(),
  default_value: String.t() | nil,
  field_type: atom() | {:enum, module()},
  is_repeated: boolean(),
  split_delimiter: String.t(),
  trim: TrogonProto.Env.V1Alpha1.Trim.t() | nil
}

Functions

__using__(opts)

(macro)

Defines an environment variable loader struct from a protobuf message.

Options

  • :message (required) - The protobuf message module to extract env vars from

get_env(name)

See System.get_env/1.

get_env(name, default)

See System.get_env/2.