Skip to content

Typestate Builder Pattern

Authkestra relies heavily on Rust’s Typestate Pattern through the Authkestra::builder() API. This design pattern ensures that your authentication stack is configured correctly at compile-time, completely eliminating an entire class of runtime panics and misconfigurations.

In Rust, the typestate pattern is used to encode a state machine into the type system. Methods return new types representing the transitioned state, meaning certain methods simply do not exist unless the builder is in the correct state.

For Authkestra, this means that the builder structurally guarantees you cannot use a feature if you haven’t provided its prerequisite configuration.

When you call Authkestra::builder(), it starts in an empty state. As you append configuration options (like providing an OAuth flow or a session store), the builder transitions through defined types.

Consider building an engine that issues sessions. If you attempt to invoke session-related handler generation without first providing a SessionStore, the compiler will reject it.

use authkestra::Authkestra;
use authkestra_engine::store::memory::MemoryStore;
use authkestra_engine::{OAuth2Flow, SessionStore};
use authkestra_providers::github::GithubProvider;
use std::sync::Arc;
// 1. Initialize a Provider
let github_provider = GithubProvider::new(
"CLIENT_ID".to_string(),
"SECRET".to_string(),
"URI".to_string()
);
let session_store: Arc<dyn SessionStore> = Arc::new(MemoryStore::default());
// 2. Build the Engine
let auth_engine = Authkestra::builder()
.provider(OAuth2Flow::new(github_provider))
// If you omit this line, methods reliant on a session store won't exist!
.session_store(session_store)
.build();

The typestate lives in the two generic parameters of Engine<S, T> — the session-store slot and the token-manager slot — each of which is either Missing or Configured<_>. The aliases AkWebAppEngine (sessions), AkApiEngine (tokens) and AkEngine (both) name the combinations you are most likely to store in your application state, and are far more readable in a compiler error than the expanded generics.

By leveraging this pattern, Authkestra provides an incredibly robust Developer Experience (DX). You can confidently rely on cargo and rust-analyzer to guide you through a correct, secure authentication setup.