Skip to main content

ServerConfig

Struct ServerConfig 

Source
pub struct ServerConfig {
Show 14 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 allow_insecure_url_sources: bool, pub cache_root: Option<PathBuf>, pub public_max_age_seconds: u32, pub public_stale_while_revalidate_seconds: u32, pub disable_accept_negotiation: bool, pub log_handler: Option<LogHandler>, pub max_concurrent_transforms: u64, pub transform_deadline_secs: u64, pub transforms_in_flight: Arc<AtomicU64>,
}

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.

§signed_url_secret: Option<String>

The shared secret used to verify public signed GET requests.

§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.

§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.

§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!.

§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.

§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.

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_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 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_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.