Skip to main content

ServerConfig

Struct ServerConfig 

Source
pub struct ServerConfig {
Show 36 fields pub storage_root: PathBuf, pub bearer_token: Option<String>, pub public_base_url: Option<String>, pub signed_url_key_id: Option<String>, pub signed_url_secret: Option<String>, pub signing_keys: HashMap<String, String>, pub allow_insecure_url_sources: bool, pub cache_root: Option<PathBuf>, pub cache_max_bytes: u64, pub public_max_age_seconds: u32, pub public_stale_while_revalidate_seconds: u32, pub disable_accept_negotiation: bool, pub format_preference: Vec<MediaType>, pub log_handler: Option<LogHandler>, pub log_level: Arc<AtomicU8>, pub max_concurrent_transforms: u64, pub transform_deadline_secs: u64, pub max_input_pixels: u64, pub max_upload_bytes: usize, pub keep_alive_max_requests: u64, pub metrics_token: Option<String>, pub disable_metrics: bool, pub health_cache_min_free_bytes: Option<u64>, pub health_max_memory_bytes: Option<u64>, pub shutdown_drain_secs: u64, pub draining: Arc<AtomicBool>, pub custom_response_headers: Vec<(String, String)>, pub max_source_bytes: u64, pub max_watermark_bytes: u64, pub max_remote_redirects: usize, pub enable_compression: bool, pub compression_level: u32, pub transforms_in_flight: Arc<AtomicU64>, pub presets: Arc<RwLock<HashMap<String, TransformOptionsPayload>>>, pub presets_file_path: Option<PathBuf>, pub rate_limiter: Option<Arc<RateLimiter>>,
}

Fields§

§storage_root: PathBuf

The storage root used for source.kind=path lookups.

§bearer_token: Option<String>

The expected Bearer token for private endpoints.

§public_base_url: Option<String>

The externally visible base URL used for public signed-URL authority.

When this value is set, public signed GET requests use its authority component when reconstructing the canonical signature payload. This is primarily useful when the server runs behind a reverse proxy and the incoming Host header is not the externally visible authority that clients sign.

§signed_url_key_id: Option<String>

The expected key identifier for public signed GET requests.

Deprecated in favor of signing_keys. Retained for backward compatibility: when set alongside signed_url_secret, the pair is automatically inserted into signing_keys.

§signed_url_secret: Option<String>

The shared secret used to verify public signed GET requests.

Deprecated in favor of signing_keys. See signed_url_key_id.

§signing_keys: HashMap<String, String>

Multiple signing keys for public signed GET requests (key rotation).

Each entry maps a key identifier to its HMAC shared secret. During verification the server looks up the keyId from the request in this map and uses the corresponding secret for HMAC validation.

Configurable via TRUSS_SIGNING_KEYS (JSON object {"keyId":"secret", ...}). The legacy TRUSS_SIGNED_URL_KEY_ID / TRUSS_SIGNED_URL_SECRET pair is merged into this map automatically.

§allow_insecure_url_sources: bool

Whether server-side URL sources may bypass private-network and port restrictions.

This flag is intended for local development and automated tests where fixture servers commonly run on loopback addresses and non-standard ports. Production-like configurations should keep this disabled.

§cache_root: Option<PathBuf>

Optional directory for the on-disk transform cache.

When set, transformed image bytes are cached on disk using a sharded directory layout (ab/cd/ef/<sha256_hex>). Repeated requests with the same source and transform options are served from the cache instead of re-transforming. When None, caching is disabled and every request performs a fresh transform.

§cache_max_bytes: u64

Maximum total size (in bytes) of the on-disk transform cache.

When set to a positive value, the cache performs LRU-style eviction after each write: entries are sorted by modification time and the oldest are removed until the total size drops below this limit.

0 (the default) means unlimited — no size-based eviction is performed. Configurable via TRUSS_CACHE_MAX_BYTES.

§public_max_age_seconds: u32

Cache-Control: max-age value (in seconds) for public GET image responses.

Defaults to 3600. Operators can tune this via the TRUSS_PUBLIC_MAX_AGE environment variable when running behind a CDN.

§public_stale_while_revalidate_seconds: u32

Cache-Control: stale-while-revalidate value (in seconds) for public GET image responses.

Defaults to 60. Configurable via TRUSS_PUBLIC_STALE_WHILE_REVALIDATE.

§disable_accept_negotiation: bool

Whether Accept-based content negotiation is disabled for public GET endpoints.

When running behind a CDN such as CloudFront, Accept negotiation combined with Vary: Accept can cause cache key mismatches or mis-served responses if the CDN cache policy does not forward the Accept header. Setting this flag to true disables Accept negotiation entirely: public GET requests that omit the format query parameter will preserve the input format instead of negotiating via Accept.

§format_preference: Vec<MediaType>

Preferred output format order for content negotiation.

When the client’s Accept header allows multiple formats with equal quality values, the server picks the first format from this list that the client accepts. An empty list uses the built-in default order (AVIF, WebP, JPEG/PNG).

Configurable via TRUSS_FORMAT_PREFERENCE (comma-separated list of format names, e.g. "avif,webp,png,jpeg").

§log_handler: Option<LogHandler>

Optional logging callback for diagnostic messages.

When set, the server routes all diagnostic messages (cache errors, connection failures, transform warnings) through this handler. When None, messages are written to stderr via eprintln!.

§log_level: Arc<AtomicU8>

Current log verbosity level.

Configurable at startup via TRUSS_LOG_LEVEL (default: info). Can be changed at runtime via SIGUSR1 (Unix only).

§max_concurrent_transforms: u64

Maximum number of concurrent image transforms.

Configurable via TRUSS_MAX_CONCURRENT_TRANSFORMS. Defaults to 64.

§transform_deadline_secs: u64

Per-transform wall-clock deadline in seconds.

Configurable via TRUSS_TRANSFORM_DEADLINE_SECS. Defaults to 30.

§max_input_pixels: u64

Maximum number of input pixels allowed before decode.

Configurable via TRUSS_MAX_INPUT_PIXELS. Defaults to 40,000,000 (~40 MP). Images exceeding this limit are rejected with 422 Unprocessable Entity.

§max_upload_bytes: usize

Maximum upload body size in bytes.

Configurable via TRUSS_MAX_UPLOAD_BYTES. Defaults to 100 MB. Requests exceeding this limit are rejected with 413 Payload Too Large.

§keep_alive_max_requests: u64

Maximum number of requests served over a single keep-alive connection.

Configurable via TRUSS_KEEP_ALIVE_MAX_REQUESTS. Defaults to 100.

§metrics_token: Option<String>

Bearer token for the /metrics endpoint.

When set, the /metrics endpoint requires Authorization: Bearer <token>. When absent, /metrics is accessible without authentication. Configurable via TRUSS_METRICS_TOKEN.

§disable_metrics: bool

Whether the /metrics endpoint is disabled.

Configurable via TRUSS_DISABLE_METRICS. When enabled, /metrics returns 404.

§health_cache_min_free_bytes: Option<u64>

Minimum free bytes on the cache disk before /health/ready reports failure.

Configurable via TRUSS_HEALTH_CACHE_MIN_FREE_BYTES. When unset, the cache disk free-space check is skipped.

§health_max_memory_bytes: Option<u64>

Maximum resident memory (RSS) in bytes before /health/ready reports failure.

Configurable via TRUSS_HEALTH_MAX_MEMORY_BYTES. When unset, the memory check is skipped. Only effective on Linux.

§shutdown_drain_secs: u64

Drain period (in seconds) during graceful shutdown.

On receiving a shutdown signal the server immediately marks itself as draining (causing /health/ready to return 503), then waits this many seconds before stopping acceptance of new connections so that load balancers have time to remove the instance from rotation.

Configurable via TRUSS_SHUTDOWN_DRAIN_SECS. Defaults to 10.

§draining: Arc<AtomicBool>

Runtime flag indicating the server is draining.

Set to true upon receiving SIGTERM/SIGINT. While draining, /health/ready returns 503 so that load balancers stop routing traffic.

§custom_response_headers: Vec<(String, String)>

Custom response headers applied to all public image responses.

Configurable via TRUSS_RESPONSE_HEADERS (JSON object {"Header-Name": "value", ...}). Validated at startup; invalid header names or values cause a startup error.

§max_source_bytes: u64

Maximum size (in bytes) of a source image fetched from the filesystem or remote URL.

Configurable via TRUSS_MAX_SOURCE_BYTES. Defaults to 100 MB.

§max_watermark_bytes: u64

Maximum size (in bytes) of a watermark image fetched from a remote URL.

Configurable via TRUSS_MAX_WATERMARK_BYTES. Defaults to 10 MB.

§max_remote_redirects: usize

Maximum number of HTTP redirects to follow when fetching a remote URL.

Configurable via TRUSS_MAX_REMOTE_REDIRECTS. Defaults to 5.

§enable_compression: bool

Whether gzip compression is enabled for non-image responses.

Configurable via TRUSS_DISABLE_COMPRESSION. Defaults to true.

§compression_level: u32

Gzip compression level (0-9). Higher values produce smaller output but use more CPU. 1 is fastest, 6 is the default (a good trade-off), and 9 is best compression.

Configurable via TRUSS_COMPRESSION_LEVEL. Defaults to 1 (fast).

§transforms_in_flight: Arc<AtomicU64>

Per-server counter tracking the number of image transforms currently in flight. This is runtime state (not configuration) but lives here so that each serve_with_config invocation gets an independent counter, avoiding cross-server interference when multiple listeners run in the same process or during tests.

§presets: Arc<RwLock<HashMap<String, TransformOptionsPayload>>>

Named transform presets that can be referenced by name on public endpoints.

Configurable via TRUSS_PRESETS (inline JSON) or TRUSS_PRESETS_FILE (path to JSON file). Each key is a preset name and the value is a set of transform options. Wrapped in Arc<RwLock<...>> to support hot-reload from TRUSS_PRESETS_FILE.

§presets_file_path: Option<PathBuf>

Path to the presets JSON file, if configured via TRUSS_PRESETS_FILE.

When set, a background thread watches this file for changes and reloads presets atomically. When None (inline TRUSS_PRESETS or no presets), hot-reload is disabled.

§rate_limiter: Option<Arc<RateLimiter>>

Optional per-IP rate limiter.

When TRUSS_RATE_LIMIT_RPS is set to a positive value, each client IP is limited to that many requests per second using a token-bucket algorithm. Burst size defaults to the RPS value but can be overridden via TRUSS_RATE_LIMIT_BURST. Disabled (no limiting) when unset or zero.

Implementations§

Source§

impl ServerConfig

Source

pub fn new(storage_root: PathBuf, bearer_token: Option<String>) -> Self

Creates a server configuration from explicit values.

This constructor does not canonicalize the storage root. It is primarily intended for tests and embedding scenarios where the caller already controls the filesystem layout.

§Examples
use truss::adapters::server::ServerConfig;

let config = ServerConfig::new(std::env::temp_dir(), Some("secret".to_string()));

assert_eq!(config.bearer_token.as_deref(), Some("secret"));
Source

pub fn with_signed_url_credentials( self, key_id: impl Into<String>, secret: impl Into<String>, ) -> Self

Returns a copy of the configuration with signed-URL verification credentials attached.

Public GET endpoints require both a key identifier and a shared secret. Tests and local development setups can use this helper to attach those values directly without going through environment variables.

§Examples
use truss::adapters::server::ServerConfig;

let config = ServerConfig::new(std::env::temp_dir(), None)
    .with_signed_url_credentials("public-dev", "top-secret");

assert_eq!(config.signed_url_key_id.as_deref(), Some("public-dev"));
assert_eq!(config.signed_url_secret.as_deref(), Some("top-secret"));
Source

pub fn with_signing_keys(self, keys: HashMap<String, String>) -> Self

Returns a copy of the configuration with multiple signing keys attached.

Each entry maps a key identifier to its HMAC shared secret. During key rotation both old and new keys can be active simultaneously, allowing a graceful cutover.

Source

pub fn with_insecure_url_sources(self, allow_insecure_url_sources: bool) -> Self

Returns a copy of the configuration with insecure URL source allowances toggled.

Enabling this flag allows URL sources that target loopback or private-network addresses and permits non-standard ports. This is useful for local integration tests but weakens the default SSRF protections of the server adapter.

§Examples
use truss::adapters::server::ServerConfig;

let config = ServerConfig::new(std::env::temp_dir(), Some("secret".to_string()))
    .with_insecure_url_sources(true);

assert!(config.allow_insecure_url_sources);
Source

pub fn with_cache_root(self, cache_root: impl Into<PathBuf>) -> Self

Returns a copy of the configuration with a transform cache directory set.

When a cache root is configured, the server stores transformed images on disk using a sharded directory layout and serves subsequent identical requests from the cache.

§Examples
use truss::adapters::server::ServerConfig;

let config = ServerConfig::new(std::env::temp_dir(), None)
    .with_cache_root(std::env::temp_dir().join("truss-cache"));

assert!(config.cache_root.is_some());
Source

pub fn with_cache_max_bytes(self, max_bytes: u64) -> Self

Returns a copy of the configuration with a maximum cache size set.

When max_bytes is positive, the cache performs LRU-style eviction after each write to keep the total on-disk size under this limit. 0 disables size-based eviction.

§Examples
use truss::adapters::server::ServerConfig;

let config = ServerConfig::new(std::env::temp_dir(), None)
    .with_cache_max_bytes(500 * 1024 * 1024); // 500 MB

assert_eq!(config.cache_max_bytes, 500 * 1024 * 1024);
Source

pub fn with_presets( self, presets: HashMap<String, TransformOptionsPayload>, ) -> Self

Returns a copy of the configuration with named transform presets attached.

Source

pub fn from_env() -> Result<Self>

Loads server configuration from environment variables.

The adapter currently reads:

  • TRUSS_STORAGE_ROOT: filesystem root for source.kind=path inputs. Defaults to the current directory and is canonicalized before use.
  • TRUSS_BEARER_TOKEN: private API Bearer token. When this value is missing, private endpoints remain unavailable and return 503 Service Unavailable.
  • TRUSS_PUBLIC_BASE_URL: externally visible base URL reserved for future public endpoint signing. When set, it must parse as an absolute http or https URL.
  • TRUSS_SIGNED_URL_KEY_ID: key identifier accepted by public signed GET endpoints.
  • TRUSS_SIGNED_URL_SECRET: shared secret used to verify public signed GET signatures.
  • TRUSS_ALLOW_INSECURE_URL_SOURCES: when set to 1, true, yes, or on, URL sources may target loopback or private-network addresses and non-standard ports.
  • TRUSS_CACHE_ROOT: directory for the on-disk transform cache. When set, transformed images are cached using a sharded ab/cd/ef/<sha256> layout. When absent, caching is disabled.
  • TRUSS_PUBLIC_MAX_AGE: Cache-Control: max-age value (in seconds) for public GET image responses. Defaults to 3600.
  • TRUSS_PUBLIC_STALE_WHILE_REVALIDATE: Cache-Control: stale-while-revalidate value (in seconds) for public GET image responses. Defaults to 60.
  • TRUSS_DISABLE_ACCEPT_NEGOTIATION: when set to 1, true, yes, or on, disables Accept-based content negotiation on public GET endpoints. This is recommended when running behind a CDN that does not forward the Accept header in its cache key.
  • TRUSS_STORAGE_BACKEND (requires the s3, gcs, or azure feature): storage backend for resolving Path-based public GET requests. Accepts filesystem (default), s3, gcs, or azure.
  • TRUSS_S3_BUCKET (requires the s3 feature): default S3 bucket name. Required when the storage backend is s3.
  • TRUSS_S3_FORCE_PATH_STYLE (requires the s3 feature): when set to 1, true, yes, or on, use path-style S3 addressing (http://endpoint/bucket/key) instead of virtual-hosted-style. Required for S3-compatible services such as MinIO and adobe/s3mock.
  • TRUSS_GCS_BUCKET (requires the gcs feature): default GCS bucket name. Required when the storage backend is gcs.
  • TRUSS_GCS_ENDPOINT (requires the gcs feature): custom GCS endpoint URL. Used for emulators such as fake-gcs-server. When absent, the default Google Cloud Storage endpoint is used.
  • GOOGLE_APPLICATION_CREDENTIALS: path to a GCS service account JSON key file.
  • GOOGLE_APPLICATION_CREDENTIALS_JSON: inline GCS service account JSON (alternative to file path).
  • TRUSS_AZURE_CONTAINER (requires the azure feature): default Azure Blob Storage container name. Required when the storage backend is azure.
  • TRUSS_AZURE_ENDPOINT (requires the azure feature): custom Azure Blob Storage endpoint URL. Used for emulators such as Azurite. When absent, the endpoint is derived from AZURE_STORAGE_ACCOUNT_NAME.
  • AZURE_STORAGE_ACCOUNT_NAME: Azure storage account name (used to derive the default endpoint when TRUSS_AZURE_ENDPOINT is not set).
  • TRUSS_MAX_CONCURRENT_TRANSFORMS: maximum number of concurrent image transforms (default: 64, range: 1–1024). Requests exceeding this limit are rejected with 503.
  • TRUSS_TRANSFORM_DEADLINE_SECS: per-transform wall-clock deadline in seconds (default: 30, range: 1–300). Transforms exceeding this deadline are cancelled.
  • TRUSS_MAX_INPUT_PIXELS: maximum number of input image pixels allowed before decode (default: 40,000,000, range: 1–100,000,000). Images exceeding this limit are rejected with 422 Unprocessable Entity.
  • TRUSS_MAX_UPLOAD_BYTES: maximum upload body size in bytes (default: 104,857,600 = 100 MB, range: 1–10,737,418,240). Requests exceeding this limit are rejected with 413.
  • TRUSS_METRICS_TOKEN: Bearer token for the /metrics endpoint. When set, the endpoint requires Authorization: Bearer <token>. When absent, no authentication is required.
  • TRUSS_DISABLE_METRICS: when set to 1, true, yes, or on, disables the /metrics endpoint entirely (returns 404).
  • TRUSS_STORAGE_TIMEOUT_SECS: download timeout for storage backends in seconds (default: 30, range: 1–300).
§Errors

Returns an io::Error when the configured storage root does not exist or cannot be canonicalized.

§Examples
// SAFETY: This example runs single-threaded; no concurrent env access.
unsafe {
    std::env::set_var("TRUSS_STORAGE_ROOT", ".");
    std::env::set_var("TRUSS_ALLOW_INSECURE_URL_SOURCES", "true");
}

let config = truss::adapters::server::ServerConfig::from_env().unwrap();

assert!(config.storage_root.is_absolute());
assert!(config.allow_insecure_url_sources);

Trait Implementations§

Source§

impl Clone for ServerConfig

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for ServerConfig

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl PartialEq for ServerConfig

Source§

fn eq(&self, other: &Self) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Eq for ServerConfig

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> To for T
where T: ?Sized,

Source§

fn to<T>(self) -> T
where Self: Into<T>,

Converts to T by calling Into<T>::into.
Source§

fn try_to<T>(self) -> Result<T, Self::Error>
where Self: TryInto<T>,

Tries to convert to T by calling TryInto<T>::try_into.
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.