Keyboard shortcuts

Press ← or β†’ to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

RustF Framework Documentation

πŸ€– AI-Agent Optimized | 🚧 Release Candidate | πŸ›‘οΈ Security-Focused | ⚑ High Performance

Welcome to RustF

RustF is a convention-based MVC web framework for Rust, inspired by Total.js v4. Designed to be equally intuitive for human developers and AI coding assistants, with auto-discovery, predictable patterns, comprehensive documentation, enterprise-grade security, and optimized performance.

What is RustF?

RustF provides a complete web development stack for Rust applications:

  • Convention Over Configuration - Sensible defaults reduce boilerplate
  • AI-Friendly Development - Predictable patterns and comprehensive documentation
  • Total.js Inspiration - Familiar patterns for web developers
  • Type Safety - Compile-time validation throughout the stack
  • Auto-Discovery - Automatic component registration at build time
  • Schema-Driven - YAML schemas drive model generation and database tools

Key Features

βœ… Auto-Discovery System - Automatic registration of controllers, models, middleware
βœ… Convention-Based Architecture - Predictable project structure and patterns
βœ… Comprehensive CLI Tools - Project scaffolding, schema management, database tools
βœ… Template Engine - Total.js-style template system with layouts and partials
βœ… Advanced Session Management - Memory, Redis, and database storage backends
βœ… Built-in Security Features - CORS, CSRF protection, secure headers
βœ… Database Tools - Multi-database query builder with schema management
βœ… Performance Optimized - Request pooling, caching, and memory safety

Quick Start

Get started with RustF in just 3 commands:

# Using the CLI tool (recommended)
rustf-cli new project my-app
cd my-app
cargo run

Visit Getting Started for detailed installation and setup instructions.

Most Common Paths

If you only need the common workflows, start here:

Documentation Structure

This documentation is organized to help you learn RustF at your own pace:

  • Getting Started - Perfect for beginners. Learn how to install RustF, create your first application, and understand the project structure.
  • CLI - The fastest path for most users. Create projects, generate components, inspect applications, and run schema workflows.
  • Core Guides - Essential framework concepts: controllers, views, middleware, sessions, databases, and more.
  • Advanced Topics - For experienced developers: performance optimization, workers, events, and advanced patterns.
  • API Reference - Complete API documentation for all framework components.
  • Examples & Tutorials - Step-by-step tutorials for building real-world applications.
  • Deployment - Production deployment guides, Docker setup, and performance tuning.

Who is This Documentation For?

Beginners

Experienced Developers

AI Coding Assistants

  • Structured documentation with clear patterns
  • Comprehensive API references
  • Predictable conventions
  • Code examples throughout

Framework Philosophy

RustF follows these core principles:

  1. Convention Over Configuration - Sensible defaults mean less code
  2. Type Safety First - Compile-time validation prevents runtime errors
  3. AI-Friendly - Predictable patterns make it easy for AI assistants to help
  4. Performance by Default - Optimized for speed and efficiency
  5. Security Built-In - Enterprise-grade security features included

Community & Support

Contributing

We welcome contributions! The framework was developed with AI collaboration and we actively seek feedback from the Rust community to improve code quality, safety, and performance.

License

RustF is dual-licensed under MIT and Apache 2.0 licenses.


Ready to get started? Head to Getting Started to begin your RustF journey!

Getting Started with RustF

Welcome to RustF! This guide will help you get up and running with the framework in minutes.

What You’ll Learn

In this section, you’ll learn:

  1. How to install RustF and its dependencies
  2. How to create your first β€œHello World” application
  3. How to understand the project structure
  4. Basic development workflow

Prerequisites

Before you begin, make sure you have:

  • Rust 1.70+ installed (rustup.rs)
  • Cargo (comes with Rust)
  • Basic familiarity with Rust syntax
  • A text editor or IDE (VS Code, RustRover, etc.)

Quick Start (3 Steps)

The fastest way to get started:

# 0. Install the CLI (one time)
cargo install rustf-cli

# 1. Create a new project using the CLI
rustf-cli new project my-app

# 2. Navigate to your project
cd my-app

# 3. Run the server
cargo run

That’s it! Your server will be running at http://127.0.0.1:8000.

Want a prebuilt binary instead of compiling the CLI? Use cargo binstall rustf-cli β€” see Installation for all options.

What’s Next?

  • Installation - Detailed installation instructions and setup
  • Hello World - Build your first application step-by-step
  • Project Structure - Understand how RustF projects are organized
  • CLI - Common project, generation, analysis, and schema commands

Need Help?


Ready to dive in? Let’s start with Installation!

Installation

This guide covers multiple ways to install and set up RustF for development.

The easiest way to create a new RustF project is using the CLI tool:

Install the RustF CLI

Prebuilt binary β€” fastest, no compile (recommended):

# install the binstall helper once, if you don't have it:
cargo install cargo-binstall
# then fetch the prebuilt rustf-cli binary from the GitHub Release:
cargo binstall rustf-cli

From crates.io (compiles from source β€” needs a few minutes):

cargo install rustf-cli

From source (pre-release / local development):

git clone https://github.com/numerum-tech/rustf.git
cargo install --path rustf/rustf-cli   # repo root is the clone dir 'rustf', crate is 'rustf-cli'

Until rustf-cli is published to crates.io, use the from source method. After publishing, cargo binstall rustf-cli is the quickest path.

Create a New Project

# Create a new project
rustf-cli new project my-app

# Navigate to your project
cd my-app

# Run the server
cargo run

The CLI tool will:

  • Set up the correct project structure
  • Create necessary directories (controllers, models, views, etc.)
  • Generate a basic main.rs with auto-discovery
  • Create a sample controller
  • Set up configuration files

Method 2: Manual Setup

If you prefer to set up a project manually:

1. Create a New Cargo Project

cargo new my-app
cd my-app

2. Add Dependencies

Edit Cargo.toml:

[package]
name = "my-app"
version = "0.1.0"
edition = "2021"

[dependencies]
rustf = "1.0"
tokio = { version = "1.0", features = ["full"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
log = "0.4"
env_logger = "0.10"

3. Create Project Structure

mkdir -p src/controllers src/models src/modules src/middleware
mkdir -p views/layouts public/css public/js
mkdir -p schemas uploads

4. Create Main Application

Create src/main.rs:

use rustf::prelude::*;

#[tokio::main]
async fn main() -> rustf::Result<()> {
    env_logger::init();
    
    let app = RustF::new()
        .controllers(auto_controllers!())
        .middleware_from(auto_middleware!());
    
    println!("πŸš€ Server at http://127.0.0.1:8000");
    app.start().await
}

5. Create Your First Controller

Create src/controllers/home.rs:

#![allow(unused)]
fn main() {
use rustf::prelude::*;

pub fn install() -> Vec<Route> {
    routes![
        GET "/" => index,
    ]
}

async fn index(ctx: &mut Context) -> Result<()> {
    ctx.html("<h1>Hello, RustF!</h1>")
}
}

6. Create Configuration

Create config.toml:

[server]
host = "127.0.0.1"
port = 8000

[views]
directory = "views"
cache_enabled = false

Method 3: Using Git Template

You can also use the sample application as a template:

# Clone the repository
git clone https://github.com/numerum-tech/rustf.git
cd rustf/sample-app

# Copy to your project
cp -r . /path/to/your/project
cd /path/to/your/project

# Install dependencies and run
cargo run

Cargo Features

RustF ships its SQL drivers and Redis support as optional, on-by-default features. Out of the box you get everything (PostgreSQL, MySQL, SQLite, and Redis sessions), so most users need no configuration. If you want a leaner build, opt out and enable only what you use.

FeatureDefaultWhat it enables
databaseβœ…Driverless SQL core (query builder, models, migrations) + decimal
db-postgresβœ…PostgreSQL driver
db-mysqlβœ…MySQL / MariaDB driver
db-sqliteβœ…SQLite driver
redisβœ…Redis-backed session storage (the only built-in cross-instance/cluster store)
embedded-viewsβœ…Compile templates into the binary
schemaβœ…YAML schema validation & codegen
decimalβœ…DECIMAL/NUMERIC support via rust_decimal β€” implied by database, so any db-* feature pulls it in automatically
cliβ€”clap-based CLI argument parsing

Always compiled (not features): TOML config loading, the auto-discovery macros (auto_controllers!, …), and UUID support are core to the framework and cannot be disabled β€” there are no config / auto-discovery / uuid flags.

Each db-* feature pulls in database automatically and turns on the matching sqlx driver. A PostgreSQL-only app, for example, can skip compiling the MySQL and SQLite drivers plus Redis:

[dependencies]
rustf = { version = "1.0", default-features = false, features = [
    "embedded-views", "schema",
    "db-postgres",   # pulls in `database` + `decimal` automatically
] }

Note β€” clustering: redis is the only built-in storage that lets multiple RustF instances share session state. If you disable it for a multi-instance deployment, provide your own SessionStorage implementation for shared sessions.

Verifying Installation

After installation, verify everything works:

# Build the project
cargo build

# Run tests
cargo test

# Start the server
cargo run

You should see:

πŸš€ Server at http://127.0.0.1:8000

Visit http://127.0.0.1:8000 in your browser to see your application.

Development Dependencies

For development, you may also want to add:

[dev-dependencies]
tokio-test = "0.4"
tempfile = "3.8"

Troubleshooting

Common Issues

Issue: β€œcannot find crate rustf”

  • Solution: Make sure you’ve added rustf to Cargo.toml dependencies
  • If using local development: Use path = "../rustf" in Cargo.toml
  • If using published version: Use version = "1.0.0-rc1" from crates.io

Issue: β€œproc macro not found”

  • Solution: Make sure rustf is a dependency (the auto-discovery macros are re-exported from rustf and always available β€” there is no feature to enable)
  • Bring them into scope with use rustf::prelude::*;

Issue: β€œport already in use”

  • Solution: Change the port in config.toml or stop the other process
  • Default port is 8000

Next Steps

Now that you have RustF installed:

  1. Hello World Tutorial - Build your first application
  2. Project Structure - Understand the framework layout
  3. Controllers Guide - Learn about routing and controllers

Hello World Tutorial

This tutorial will walk you through creating your first RustF application step-by-step.

What We’ll Build

We’ll create a simple application that:

  • Displays a β€œHello World” message
  • Shows a JSON API endpoint
  • Demonstrates basic routing

Step 1: Create the Project

rustf-cli new project hello-rustf
cd hello-rustf

Or manually:

cargo new hello-rustf
cd hello-rustf

Step 2: Add Dependencies

Edit Cargo.toml:

[dependencies]
rustf = "1.0"
tokio = { version = "1.0", features = ["full"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
log = "0.4"
env_logger = "0.10"

Step 3: Create the Main Application

Edit src/main.rs:

use rustf::prelude::*;

#[tokio::main]
async fn main() -> rustf::Result<()> {
    // Initialize logger
    env_logger::init();
    
    // Create the application with auto-discovery
    let app = RustF::new()
        .controllers(auto_controllers!())      // Auto-discover controllers
        .middleware_from(auto_middleware!());   // Auto-discover middleware
    
    println!("πŸš€ Server running at http://127.0.0.1:8000");
    println!("πŸ“– Visit http://127.0.0.1:8000/ for Hello World");
    println!("πŸ“‘ Visit http://127.0.0.1:8000/api/status for JSON API");
    
    // Start the server
    app.start().await
}

Step 4: Create Your First Controller

Create src/controllers/home.rs:

#![allow(unused)]
fn main() {
use rustf::prelude::*;

// Every controller must have an install() function
pub fn install() -> Vec<Route> {
    routes![
        GET "/" => hello_world,
        GET "/api/status" => api_status,
    ]
}

// Handler function - must be async and take &mut Context
async fn hello_world(ctx: &mut Context) -> Result<()> {
    // Send HTML response
    ctx.html("<h1>Hello, RustF! πŸš€</h1><p>Welcome to your first RustF application!</p>")
}

// JSON API endpoint
async fn api_status(ctx: &mut Context) -> Result<()> {
    // Create JSON data
    let data = json!({
        "status": "ok",
        "framework": "RustF",
        "version": "0.1.0",
        "message": "Hello from the API!"
    });
    
    // Send JSON response
    ctx.json(data)
}
}

Step 5: Create Configuration

Create config.toml:

[server]
host = "127.0.0.1"
port = 8000
timeout = 30

[views]
directory = "views"
cache_enabled = false
default_layout = "layouts/default"

[session]
idle_timeout = 3600
cookie_name = "hello_rustf_session"

Step 6: Run Your Application

cargo run

You should see:

πŸš€ Server running at http://127.0.0.1:8000
πŸ“– Visit http://127.0.0.1:8000/ for Hello World
πŸ“‘ Visit http://127.0.0.1:8000/api/status for JSON API

Step 7: Test Your Application

Test the HTML Endpoint

Visit http://127.0.0.1:8000/ in your browser. You should see:

Hello, RustF! πŸš€
Welcome to your first RustF application!

Test the JSON API

Visit http://127.0.0.1:8000/api/status or use curl:

curl http://127.0.0.1:8000/api/status

You should get:

{
  "status": "ok",
  "framework": "RustF",
  "version": "0.1.0",
  "message": "Hello from the API!"
}

Understanding the Code

The install() Function

Every controller must have an install() function that returns Vec<Route>. This function:

  • Defines all routes for this controller
  • Uses the routes![] macro for clean syntax
  • Is automatically discovered by auto_controllers!()

Route Handlers

Route handlers must:

  • Be async functions
  • Take &mut Context as the only parameter
  • Return Result<()>
  • Use ctx methods to send responses

Response Methods

The Context provides several response methods:

  • ctx.html(content) - Send HTML response
  • ctx.json(data) - Send JSON response
  • ctx.plain(content) - Send plain text
  • ctx.redirect(url) - Redirect to another URL
  • ctx.status(code) - Set HTTP status code

Adding More Routes

Let’s add a route with a parameter:

#![allow(unused)]
fn main() {
pub fn install() -> Vec<Route> {
    routes![
        GET "/" => hello_world,
        GET "/api/status" => api_status,
        GET "/hello/{name}" => personalized_hello,  // New route with parameter
    ]
}

async fn personalized_hello(ctx: &mut Context) -> Result<()> {
    // Get route parameter
    let name = ctx.param_str_or("name", "World");
    
    let message = format!("Hello, {}! Welcome to RustF!", name);
    ctx.html(&format!("<h1>{}</h1>", message))
}
}

Now visit http://127.0.0.1:8000/hello/Alice to see a personalized greeting!

Next Steps

Congratulations! You’ve created your first RustF application. Now you can:

  1. Learn about Project Structure - Understand how RustF projects are organized
  2. Explore Controllers - Learn more about routing and controllers
  3. Add Views - Use templates instead of inline HTML
  4. Build a REST API - Create a complete API

Common Questions

Q: Why do I need &mut Context? A: Context is mutable because it stores request/response data and session information that may change during request processing.

Q: What does auto_controllers!() do? A: It’s a macro that automatically discovers all controllers in src/controllers/ at compile time and registers their routes.

Q: Can I use &Context instead? A: No, handlers require &mut Context because they need to modify the response and potentially update session data.

Q: How do I handle errors? A: Return Err(Error::...) from your handler. The framework will handle it appropriately based on the error type.

Project Structure

Understanding the RustF project structure is essential for building maintainable applications. This guide explains the standard layout and conventions.

Standard Project Layout

your_project/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ main.rs              # Application entry point with auto-discovery
β”‚   β”œβ”€β”€ controllers/         # HTTP request handlers
β”‚   β”‚   β”œβ”€β”€ home.rs          # Home page controller
β”‚   β”‚   β”œβ”€β”€ auth.rs          # Authentication controller  
β”‚   β”‚   β”œβ”€β”€ users.rs         # User management controller
β”‚   β”‚   └── api/             # API controllers (namespaced)
β”‚   β”‚       β”œβ”€β”€ users.rs     # User API endpoints
β”‚   β”‚       └── posts.rs     # Post API endpoints
β”‚   β”œβ”€β”€ models/              # Database models (schema-generated)
β”‚   β”‚   β”œβ”€β”€ users.rs         # User model wrapper
β”‚   β”‚   β”œβ”€β”€ posts.rs         # Post model wrapper
β”‚   β”‚   └── base/            # Auto-generated base models (DO NOT EDIT)
β”‚   β”‚       β”œβ”€β”€ users.inc.rs
β”‚   β”‚       └── posts.inc.rs
β”‚   β”œβ”€β”€ modules/             # Business logic modules
β”‚   β”‚   β”œβ”€β”€ user_service.rs  # User business logic
β”‚   β”‚   └── email_service.rs # Email functionality
β”‚   β”œβ”€β”€ definitions/         # Template helpers & validators
β”‚   β”œβ”€β”€ events/              # Event handlers (optional)
β”‚   β”œβ”€β”€ middleware/          # Custom middleware
β”‚   β”‚   └── auth.rs          # Authentication middleware
β”‚   β”œβ”€β”€ workers/             # Background workers (optional)
β”‚   β”œβ”€β”€ _controllers.rs      # Auto-generated (IDE support only)
β”‚   β”œβ”€β”€ _models.rs           # Auto-generated (IDE support only)
β”‚   └── _modules.rs          # Auto-generated (IDE support only)
β”œβ”€β”€ views/                   # Template files
β”‚   β”œβ”€β”€ layouts/
β”‚   β”‚   └── default.html     # Default layout
β”‚   β”œβ”€β”€ home/
β”‚   β”‚   β”œβ”€β”€ index.html       # Home page template
β”‚   β”‚   └── about.html       # About page template
β”‚   └── auth/
β”‚       └── login.html       # Login form template
β”œβ”€β”€ schemas/                 # YAML schema definitions
β”‚   β”œβ”€β”€ users.yaml           # User table schema
β”‚   β”œβ”€β”€ posts.yaml           # Posts table schema
β”‚   └── _meta.yaml           # Database metadata
β”œβ”€β”€ public/                  # Static files
β”‚   β”œβ”€β”€ css/
β”‚   β”œβ”€β”€ js/
β”‚   └── images/
β”œβ”€β”€ uploads/                 # File uploads directory
β”œβ”€β”€ config.toml              # Base configuration
β”œβ”€β”€ config.dev.toml          # Development overrides (created by scaffold)
└── Cargo.toml               # Rust project configuration

Directory Descriptions

src/ - Source Code

All Rust source code lives in the src/ directory.

src/main.rs

The application entry point. Typically contains:

use rustf::prelude::*;

#[tokio::main]
async fn main() -> rustf::Result<()> {
    env_logger::init();
    
    let app = RustF::new()
        .controllers(auto_controllers!())
        .middleware_from(auto_middleware!());
    
    app.start().await
}

src/controllers/ - Request Handlers

Controllers handle HTTP requests and define routes. Each controller file must have an install() function.

Example: src/controllers/home.rs

#![allow(unused)]
fn main() {
use rustf::prelude::*;

pub fn install() -> Vec<Route> {
    routes![
        GET "/" => index,
        GET "/about" => about,
    ]
}

async fn index(ctx: &mut Context) -> Result<()> {
    ctx.view("home/index", json!({}))
}
}

Nested Controllers: src/controllers/api/users.rs

#![allow(unused)]
fn main() {
use rustf::prelude::*;

pub fn install() -> Vec<Route> {
    routes![
        GET "/api/users" => list_users,
        GET "/api/users/{id}" => get_user,
    ]
}
}

src/models/ - Database Models

Models represent database tables and provide type-safe database access.

Structure:

  • src/models/users.rs - User model wrapper (your code)
  • src/models/base/users.inc.rs - Auto-generated base model (don’t edit)

Example: src/models/users.rs

#![allow(unused)]
fn main() {
use rustf::prelude::*;

// The generated `Users` struct + CRUD are included directly from the base
// file (do not edit base/users.inc.rs).
include!("base/users.inc.rs");

// Add your custom business logic to the generated `Users` type:
impl Users {
    // Add custom methods here
}
}

src/modules/ - Business Logic

Modules contain business logic separate from HTTP concerns. They’re shared across controllers and can be accessed via MODULE.

Example: src/modules/user_service.rs

#![allow(unused)]
fn main() {
use rustf::prelude::*;

pub struct UserService;

impl UserService {
    pub fn create_user(&self, name: &str, email: &str) -> Result<User> {
        // Business logic here
    }
}

// Register as shared module
impl_shared_service!(UserService);
}

src/middleware/ - Request Processing

Middleware processes requests before they reach controllers.

Example: src/middleware/auth.rs

#![allow(unused)]
fn main() {
use async_trait::async_trait;
use rustf::middleware::{InboundAction, InboundMiddleware, MiddlewareRegistry};
use rustf::prelude::*;

pub struct AuthMiddleware;

#[async_trait]
impl InboundMiddleware for AuthMiddleware {
    async fn process_request(&self, ctx: &mut Context) -> rustf::Result<InboundAction> {
        // Authentication logic. Return InboundAction::Stop to short-circuit
        // the chain (after setting a response on ctx), otherwise continue.
        Ok(InboundAction::Continue)
    }
}

pub fn install(registry: &mut MiddlewareRegistry) {
    registry.register_inbound("auth", AuthMiddleware);
}
}

src/_*.rs - Auto-Generated Files

These files are generated by auto-discovery macros for IDE support:

  • _controllers.rs - Controller module declarations
  • _models.rs - Model module declarations
  • _modules.rs - Module declarations

Important: These files are NOT compiled. They’re only for IDE autocomplete.

views/ - Templates

Template files organized by feature.

Structure:

views/
β”œβ”€β”€ layouts/
β”‚   └── default.html         # Default layout
β”œβ”€β”€ home/
β”‚   β”œβ”€β”€ index.html           # Home page
β”‚   └── about.html           # About page
└── auth/
    └── login.html           # Login form

Layout Example: views/layouts/default.html

<!DOCTYPE html>
<html>
<head>
    <title>@{title}</title>
</head>
<body>
    @{body}
</body>
</html>

View Example: views/home/index.html

<h1>Welcome</h1>
<p>Hello, @{name}!</p>

schemas/ - Database Schemas

YAML schema definitions for database tables. Used by the CLI to generate models.

Example: schemas/users.yaml

table: users
fields:
  id:
    type: integer
    primary: true
    auto_increment: true
  name:
    type: string
    length: 255
    required: true
  email:
    type: string
    length: 255
    required: true
    unique: true

public/ - Static Assets

Static files served directly by the web server.

public/
β”œβ”€β”€ css/
β”‚   └── style.css
β”œβ”€β”€ js/
β”‚   └── app.js
└── images/
    └── logo.png

Access via: http://localhost:8000/css/style.css

uploads/ - User Uploads

Directory for user-uploaded files. Location is configurable in config.toml.

Configuration Files

config.toml - Base Configuration

[server]
host = "127.0.0.1"
port = 8000

[views]
directory = "views"
cache_enabled = false

config.dev.toml - Development Overrides

The scaffold creates config.dev.toml, merged over config.toml in development. Create a config.prod.toml yourself for production β€” it works the same way, merged when running in the production environment.

# config.prod.toml (you create this for production)
[server]
host = "0.0.0.0"
port = 8080

[views]
cache_enabled = true

File Naming Conventions

ComponentConventionExample
Controllerssnake_case.rsusers.rs, auth.rs
Modelssnake_case.rsusers.rs, blog_posts.rs
Modulessnake_case.rsuser_service.rs, email_service.rs
Middlewaresnake_case.rsauth.rs, rate_limit.rs
Templatessnake_case.htmlindex.html, user_profile.html
Schemassnake_case.yamlusers.yaml, blog_posts.yaml

Best Practices

1. Organize by Feature

Group related files together:

src/controllers/
β”œβ”€β”€ users.rs          # User-related routes
β”œβ”€β”€ posts.rs          # Post-related routes
└── comments.rs       # Comment-related routes

2. Use Namespaces for APIs

Separate API controllers:

src/controllers/
β”œβ”€β”€ api/
β”‚   β”œβ”€β”€ v1/
β”‚   β”‚   β”œβ”€β”€ users.rs
β”‚   β”‚   └── posts.rs
β”‚   └── v2/
β”‚       └── users.rs

3. Keep Models Simple

Models should be thin wrappers around base models:

#![allow(unused)]
fn main() {
// Good: Thin wrapper
pub struct Users {
    base: UsersBase,
}

// Avoid: Complex logic in models
// Move business logic to modules
}

4. Separate Concerns

  • Controllers - HTTP request/response handling
  • Models - Database access
  • Modules - Business logic
  • Middleware - Cross-cutting concerns

Auto-Discovery

RustF automatically discovers components based on file location:

  • src/controllers/*.rs β†’ Controllers
  • src/models/*.rs β†’ Models
  • src/modules/*.rs β†’ Modules
  • src/middleware/*.rs β†’ Middleware

No manual registration needed!

Next Steps

Now that you understand the project structure:

  1. Controllers Guide - Learn about routing
  2. Models Guide - Work with databases
  3. Views Guide - Use templates
  4. Modules Guide - Share business logic

RustF CLI

rustf-cli is the fastest way to create, inspect, and maintain a RustF project. It is not just a scaffolder: it also handles schema workflows, database inspection, validation, project analysis, and MCP serving for AI tools.

Start Here

If you are new to the CLI, this is the shortest useful path:

  1. Install it: see Installation
  2. Create an app: Create a Project
  3. Generate pieces as the app grows: Generate Components
  4. Add database workflow: Database & Schemas
  5. Audit the project before commits: Analysis & Validation

Most Common Commands

rustf-cli new project my-app
rustf-cli new controller -n users
rustf-cli new crud -n posts
rustf-cli schema generate models
rustf-cli analyze project --detailed
rustf-cli validate

Task-Focused Guides

What the CLI Covers

  • Project scaffolding
  • Component generation
  • Database introspection
  • YAML schema workflows
  • Route and project analysis
  • Validation and consistency checks
  • Local MCP serving for AI assistants

Create a Project

The most common RustF entry point is:

rustf-cli new project my-app
cd my-app
cargo run

Your server will start on http://127.0.0.1:8000 unless overridden by config.

What Gets Generated

The scaffold includes the standard RustF layout:

  • src/controllers/
  • src/models/
  • src/modules/
  • src/middleware/
  • views/
  • public/
  • private/uploads/
  • schemas/
  • .claude/skills/rustf/SKILL.md

That gives you a runnable project, a sample controller and view, default configuration, and AI guidance files aligned with RustF conventions.

Command

rustf-cli new project <PROJECT_NAME> [--path <DIR>] [--force]

Notes

  • --force overwrites an existing target after creating a backup under .rustf/backups/project/
  • Generated config includes proxy-related server settings and current framework defaults
  • The project README points to the RustF book, not legacy static docs

Next Steps

After the initial scaffold:

  1. Read Project Structure
  2. Add routes in src/controllers/
  3. Add views in views/
  4. If you use a database, continue with Database & Schemas

Generate Components

Use the CLI to create framework-shaped files instead of hand-writing boilerplate.

Common Generators

Controller

rustf-cli new controller -n users
rustf-cli new controller -n "users,posts" --routes

Creates controller files with install() route registration and RustF handler stubs.

Middleware

rustf-cli new middleware -n auth --auth --priority=-50
rustf-cli new middleware -n request-logger --logging --priority=-100

Creates middleware templates that match the current inbound/outbound API.

Module

rustf-cli new module -n billing

Use modules for business logic shared across controllers.

Worker

rustf-cli new worker -n digest-email

Creates a background worker stub and points to the worker guide.

Event

rustf-cli new event -n user-created

Creates an event handler scaffold for RustF lifecycle or custom events.

CRUD Scaffolding

rustf-cli new crud -n posts

This command assumes the model already exists and builds the HTTP layer around it.

Precondition:

  1. Define schemas/posts.yaml
  2. Run rustf-cli schema generate models
  3. Run rustf-cli new crud -n posts

The generated CRUD stack follows the RustF layering rule:

  • controller -> module -> model
  • views under views/<name>/
  • test stub under tests/

When to Use the CLI

Prefer generation when:

  • you are creating a new app area
  • you want files that already match framework conventions
  • you want current API-compatible scaffolds instead of older examples

Hand-write only when you already have a clear custom structure.

Database & Schemas

RustF’s CLI supports a database-first workflow and a schema-first workflow.

Database-First

Start from an existing database:

rustf-cli db generate-schema -o schemas
rustf-cli schema generate models -o src/models

db generate-schema writes YAML schema files and, by default, a full DDL dump:

schemas/_database_dump.sql

That SQL dump is the canonical source-controlled snapshot of the live database structure.

Schema-First

Start from YAML schema files:

rustf-cli schema validate
rustf-cli schema generate models
rustf-cli schema generate sql

Most Useful Commands

Inspect the Database

rustf-cli db test-connection
rustf-cli db list-tables --metadata
rustf-cli db describe users

Sync Schemas

rustf-cli db diff-schema schemas/users.yaml
rustf-cli schema check-consistency

Generate Code

rustf-cli schema generate models --force
rustf-cli schema generate sql --output sql

Backups and Safety

Commands with --force create backups under .rustf/backups/ before overwriting generated artifacts.

Analysis & Validation

These commands are the fastest way to inspect project health before a commit or release.

Project-Level Checks

rustf-cli analyze discover
rustf-cli analyze project --detailed
rustf-cli validate

Use them to catch route conflicts, missing assets, schema drift, middleware issues, and general project structure problems.

Common Analysis Commands

Routes and Controllers

rustf-cli analyze routes --validate
rustf-cli analyze controllers

Models and Schemas

rustf-cli analyze models --relationships
rustf-cli schema check-consistency

Middleware and Views

rustf-cli analyze middleware --conflicts
rustf-cli analyze views --security

Export Results

rustf-cli export --format json -o analysis.json

Useful Workflow

For a normal development pass:

rustf-cli analyze discover
rustf-cli validate
rustf-cli analyze routes --validate
rustf-cli analyze project --detailed --format json

Why This Matters

RustF uses conventions heavily. The CLI is the fastest way to verify that the actual project still matches those conventions after refactors or generated code changes.

Serve & MCP

rustf-cli can run a local serving endpoint for AI tooling and project inspection workflows.

Start the Server

rustf-cli serve start

Common options:

rustf-cli serve start --bind 0.0.0.0 --port 8080
rustf-cli serve start --allow-writes

Use --allow-writes only when you explicitly want remote tools to be able to mutate the project. The default posture is safer.

Manage Running Instances

rustf-cli serve list
rustf-cli serve stop 8080
rustf-cli query route "/users/{id}"
rustf-cli query model-metadata User --format json

The query family is useful when an AI tool or human reviewer needs one specific item instead of a full project analysis.

Security Notes

  • Prefer the default read-oriented mode
  • Avoid exposing a write-enabled endpoint to untrusted networks
  • Bind to loopback unless you have a deliberate remote workflow

Full Command Catalog

See Full Reference for the complete list of serve, query, and related commands.

Full CLI Reference

Use this page as an index. For task-first guidance, start from CLI Overview.

Core Command Groups

Project and Code Generation

rustf-cli new project <PROJECT_NAME> [--path <DIR>] [--force]
rustf-cli new controller -n <NAMES> [--crud] [--routes]
rustf-cli new middleware -n <NAME> [--auth] [--logging] [-p <PRIORITY>]
rustf-cli new module -n <NAME> [--shared] [--with-methods]
rustf-cli new worker -n <NAME>
rustf-cli new event -n <NAME> [--lifecycle] [--custom]
rustf-cli new crud -n <PLURAL_NAME>

Analysis and Validation

rustf-cli analyze <SUBCOMMAND>
rustf-cli validate [--fix] [-w, --watch]
rustf-cli export [-f <FORMAT>] [--include-code] [-o <FILE>]

Database and Schema

rustf-cli db <SUBCOMMAND>
rustf-cli schema <SUBCOMMAND>
rustf-cli translations <SUBCOMMAND>

Query and Serve

rustf-cli query <ITEM_TYPE> <ITEM_NAME> [-f <FORMAT>]
rustf-cli serve <SUBCOMMAND>

Performance

rustf-cli perf <SUBCOMMAND>

Global Options

-P, --project <PATH>
-v, --verbose
-h, --help
-V, --version

Deep Reference

The original monolithic command guide is still available here:

Keep that page for exhaustive command-by-command details. Use the new CLI section for normal navigation.

RustF Controllers User Guide

Complete documentation based on current framework implementation

Overview

RustF provides a clean, organized controller system inspired by Total.js. Controllers are Rust modules that group related route handlers together and expose them through an install() function. The framework supports both manual controller registration and automatic controller discovery for streamlined development.

Key Features

  • Convention-based routing - Clean routes![] macro syntax
  • Auto-discovery - Automatically finds and registers controllers at compile time
  • Total.js-inspired API - Familiar patterns for web developers
  • Type-safe handlers - All handlers are statically checked at compile time
  • Flexible organization - Group related functionality logically

Core Components

Route System

#![allow(unused)]
fn main() {
pub struct Route {
    pub method: String,    // HTTP method (GET, POST, PUT, DELETE)
    pub path: String,      // URL pattern with optional parameters ({id})
    pub handler: RouteHandler,  // Async handler function
}

// Type alias for route handlers - all handlers follow this signature
pub type RouteHandler = for<'a> fn(&'a mut Context) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'a>>;
}

Route Handler Requirements:

  • Must be async functions
  • Take a single &mut Context parameter (mutable reference)
  • Return Result<()> (response is set internally on Context)
  • Are automatically wrapped by the routes! macro

Supported HTTP Methods

The framework supports all standard HTTP methods:

#![allow(unused)]
fn main() {
// Available in routes! macro:
GET    "/path"     => handler_function
POST   "/path"     => handler_function  
PUT    "/path"     => handler_function
DELETE "/path"     => handler_function

// Manual route creation (rarely needed):
Route::get("/users", handler)           // GET request
Route::post("/users", handler)          // POST request
Route::put("/users/{id}", handler)       // PUT request
Route::delete("/users/{id}", handler)    // DELETE request
}

Controller Pattern

Basic Controller Structure

Every controller must follow this exact pattern:

#![allow(unused)]
fn main() {
use rustf::prelude::*;

// Required: Every controller must have an install() function
pub fn install() -> Vec<Route> {
    routes![
        GET "/" => index,
        POST "/submit" => submit,
        GET "/item/{id}" => show_item,
    ]
}

// Handler functions - must be async and return Result<()>
async fn index(ctx: &mut Context) -> Result<()> {
    let data = json!({"message": "Welcome!"});
    ctx.view("/home/index", data)
}

async fn submit(ctx: &mut Context) -> Result<()> {
    let form_data = ctx.body_form()?;
    // Process form data
    ctx.redirect("/success")
}

async fn show_item(ctx: &mut Context) -> Result<()> {
    let item_id = ctx.param_str_or("id", "0");
    let data = json!({"id": item_id});
    ctx.json(data)
}
}

Controller File Organization

src/controllers/
β”œβ”€β”€ home.rs          # Home page and static content
β”œβ”€β”€ auth.rs          # Login, logout, registration
β”œβ”€β”€ users.rs         # User management
β”œβ”€β”€ api/
β”‚   β”œβ”€β”€ users.rs     # API endpoints for users
β”‚   └── posts.rs     # API endpoints for posts
└── admin.rs         # Admin functionality

The routes! Macro

The routes! macro provides clean, declarative route definition:

#![allow(unused)]
fn main() {
routes![
    // Basic routes
    GET "/" => index,
    GET "/about" => about,
    
    // Routes with parameters
    GET "/users/{id}" => get_user,
    GET "/posts/{post_id}/comments/{comment_id}" => get_comment,
    
    // Different HTTP methods
    POST "/users" => create_user,
    PUT "/users/{id}" => update_user,
    DELETE "/users/{id}" => delete_user,
    
    // Complex paths
    GET "/api/v1/users/{id}/profile" => get_user_profile,
]
}

Features:

  • Clean, readable syntax
  • Automatic handler wrapping
  • Compile-time validation
  • Support for URL parameters with {parameter} syntax
  • Trailing commas allowed
  • Optional before: clause for controller-level pre-handler hooks (see below)

Controller-level before Hook

The routes! macro accepts an optional before: clause as the first item. When present, the framework runs the supplied function before every handler this install() registers. It can short-circuit the request β€” useful for setup work shared by all the controller’s handlers (e.g. setting a repository value used by all views) or for an access gate scoped to this controller.

#![allow(unused)]
fn main() {
use rustf::prelude::*;

pub fn install() -> Vec<Route> {
    async fn before(ctx: &mut Context) -> rustf::Result<BeforeAction> {
        // Setup common to every route below.
        ctx.repository_set("section", "users");

        // Access gate: kick out unauthenticated users.
        if !ctx.has_session() {
            ctx.redirect("/login")?;
            return Ok(BeforeAction::Stop);
        }
        Ok(BeforeAction::Continue)
    }

    routes![
        before: before,
        GET    "/users"      => index,
        GET    "/users/{id}" => show,
        POST   "/users"      => create,
    ]
}
}

Semantics:

  • Ok(BeforeAction::Continue) β€” the handler runs as usual.
  • Ok(BeforeAction::Stop) β€” the handler is skipped. The framework returns whatever response the hook wrote to ctx.res via ctx.redirect, ctx.throw403, ctx.json, etc.
  • Err(e) β€” propagates exactly like an error from a handler.

Pipeline order:

inbound middleware  β†’  router match  β†’  before  β†’  handler  β†’  outbound middleware

before runs after the request has been matched to one of this controller’s routes; it does NOT see traffic destined for other controllers.

Why not just middleware? Middleware applies based on URL prefix or global match and lives in a separate file. Use middleware for cross-cutting concerns (logging, CORS, compression, CSRF). Use a controller before when the rule belongs to this controller’s identity β€” e.g. β€œevery route in users requires the users.read permission”. The before lives inside the controller’s install() body, scoped lexically to it; the wiring is one opt-in line.

Defining before inside install() (Rust permits inner async fn items) keeps it scoped to the controller. No module-namespace pollution, no risk of confusing it with a route handler, no need to invent a private name. The wiring before: before, in routes![] is the one visible cue the controller has a hook.

Controller-level shared state. If you need state shared across multiple handlers in the same controller (an in-memory cache, a counter, a once-initialized resource), use module-level Rust statics. Nothing framework-specific is required.

#![allow(unused)]
fn main() {
use once_cell::sync::Lazy;
use std::sync::atomic::{AtomicU64, Ordering};

static REQUEST_COUNT: AtomicU64 = AtomicU64::new(0);
static CACHE: Lazy<dashmap::DashMap<i64, String>> = Lazy::new(DashMap::new);

async fn show(ctx: &mut Context) -> rustf::Result<()> {
    REQUEST_COUNT.fetch_add(1, Ordering::Relaxed);
    // CACHE is shared with all other handlers in this file
    Ok(())
}
}

Backward compatibility: existing controllers using the bare routes![GET ..., ...] form behave identically to before. The before: clause is purely additive.

Writing Route Handlers

Handler Function Requirements

#![allow(unused)]
fn main() {
// Required signature for all handlers
async fn handler_name(ctx: &mut Context) -> Result<()>
}

Handler Rules:

  • Must be async functions
  • Must take exactly one &mut Context parameter (mutable reference)
  • Must return Result<()> - the response is set internally on the Context
  • Can have any name (referenced in routes! macro)
  • Are automatically wrapped by the framework

Response Handling Pattern

Key Change: Handlers now receive &mut Context and return Result<()> instead of Result<Response>. This architectural change ensures that session data and all middleware modifications persist throughout the entire request/response lifecycle.

How Responses Work

  1. Response Storage: The Context struct now contains an Option<Response> field initialized with a default 200 OK response
  2. Setting Responses: All response helper methods (json(), view(), redirect(), etc.) internally call ctx.set_response()
  3. Return Type: Methods return Result<()> to indicate success/failure of setting the response
  4. Middleware Access: Both inbound and outbound middleware can access and modify the response via ctx.res
  5. Response Helpers in Middleware: Since Context initializes with a default response, middleware can use the same response helpers (ctx.json(), ctx.throw403(), etc.) as handlers

Custom Response Creation

If you need to create a custom response beyond the built-in helpers:

#![allow(unused)]
fn main() {
async fn custom_response_handler(ctx: &mut Context) -> Result<()> {
    // Create a custom response
    let response = Response::new(StatusCode::from_u16(418).unwrap())
        .with_header("X-Custom", "value")
        .with_body(b"I'm a teapot".to_vec());
    
    // Set it on the context
    ctx.set_response(response);
    Ok(())
}
}

Error Handling Pattern

Since handlers return Result<()>, error responses are handled the same way as success responses:

#![allow(unused)]
fn main() {
async fn validated_handler(ctx: &mut Context) -> Result<()> {
    let data = ctx.body_json::<MyData>()?;
    
    if !data.is_valid() {
        // Error response - still returns Result<()>
        return ctx.throw400(Some("Invalid data"));
    }
    
    // Success response - also returns Result<()>
    ctx.json(json!({"status": "success"}))
}
}

Working with Context

The Context parameter provides access to all request/response functionality.

Important Note on Middleware Context Preservation: The framework ensures that all context modifications made by middleware (such as setting layout, repository data, or session values) are properly preserved and passed to your controller handlers. The context is passed by mutable reference through the middleware chain and arrives at your handler with all modifications intact.

Request Data

#![allow(unused)]
fn main() {
// URL parameters (/users/{id} -> id)
let user_id = ctx.param_str_or("id", "0");

// Query parameters (?page=2 -> page)
let page = ctx.query_str_or("page", "1");

// Form data - Three approaches available:

// 1. Manual parsing (low-level, verbose but flexible)
let form_data = ctx.body_form()?;
let email = form_data.get("email").unwrap_or(&String::new());

// 2. Typed parsing (recommended - automatic deserialization)
#[derive(serde::Deserialize)]
struct LoginForm {
    email: String,
    password: String,
}
let form: LoginForm = ctx.body_form_typed()?;
let email = form.email;

// 3. Individual field helpers (for simple cases)
let email = ctx.body_str("email")?;              // Required field
let name = ctx.str_body_or("name", "Anonymous"); // Optional with default
let age = ctx.body_int("age")?;                  // Parse as integer
let active = ctx.bool_body_or("active", false);  // Parse as boolean

// JSON body
let json_data: MyStruct = ctx.body_json()?;

// Headers
let auth_header = ctx.header("Authorization");

// File uploads
let uploaded_file = ctx.file("avatar")?;
}

Response Modification

#![allow(unused)]
fn main() {
// Add custom headers to response
ctx.add_header("X-Custom-Header", "value");
ctx.add_header("Cache-Control", "no-cache");

// Set response status code
ctx.status(hyper::StatusCode::CREATED);  // 201 Created
ctx.status(hyper::StatusCode::ACCEPTED); // 202 Accepted

// These methods are particularly useful in middleware
// since Context now initializes with a default 200 OK response
}

Response Generation

Important: All response methods now set the response internally on the Context and return Result<()> instead of Result<Response>. This ensures that session data and middleware modifications are preserved throughout the request lifecycle.

#![allow(unused)]
fn main() {
// Template responses (data accessed via model.key or M.key in template)
ctx.view("/users/profile", json!({"user": user_data}))?  // Sets template response

// JSON responses
ctx.json(json!({"status": "success", "data": users}))?   // Sets JSON response

// Redirects
ctx.redirect("/login")?                                  // Sets redirect response

// HTTP errors - all return Result<()> after setting error response
ctx.throw404(Some("User not found"))?                   // Sets 404 error
ctx.throw400(Some("Invalid input"))?                    // Sets 400 error
ctx.throw500(None)?                                      // Sets 500 error

// Plain text
ctx.plain("Hello, world!")?                             // Sets text response

// File responses (buffered β€” whole file in memory)
ctx.file_download("/path/to/file", Some("name.pdf"))?   // Sets file download
ctx.file_inline("/path/to/image.jpg")?                  // Sets inline file

// File responses (streamed β€” 64 KiB chunks, flat memory however large the file)
ctx.file_download_stream("exports/big.zip", None).await?
ctx.file_inline_stream("media/video.mp4").await?

// Any byte stream: Vec<u8> is sent buffered, Body::from_stream(..) chunk by chunk
ctx.stream(Body::from_stream(rows), "text/csv", Some("rows.csv"))?

// Server-Sent Events: response stays open, one SseEvent per push
ctx.sse(events)?                                        // Stream<Item = SseEvent>
ctx.sse_with_keep_alive(events, Duration::from_secs(15))? // + idle comments for proxies
}

Session Management

#![allow(unused)]
fn main() {
// Set session data
ctx.session_set("user_id", 123)?;
ctx.session_set("cart", json!({"items": []}));

// Get session data
let user_id: Option<i32> = ctx.session_get("user_id");
let cart: Option<Value> = ctx.session_get("cart");

// Remove session data
ctx.session_remove("temporary_data");
}

Repository Data (Handler-Scoped Data)

The repository system allows controllers to pass data to all views called within the handler function without explicitly including it in each view’s data parameter. The repository lives for the duration of the handler function execution.

Setting Repository Data

#![allow(unused)]
fn main() {
async fn my_handler(ctx: &mut Context) -> Result<()> {
    // Set simple values
    ctx.repository_set("app_name", "RustF Application");
    ctx.repository_set("current_section", "dashboard");
    ctx.repository_set("user_level", 5);
    
    // Set arrays
    ctx.repository_set("nav_items", json!([
        {"title": "Home", "url": "/"},
        {"title": "About", "url": "/about"},
        {"title": "Contact", "url": "/contact"}
    ]));
    
    // Set complex objects
    ctx.repository_set("site_config", json!({
        "theme": "dark",
        "sidebar": "expanded",
        "notifications": true
    }));
    
    // Repository data is automatically available in the view
    // Note: View data is accessed via model.key or M.key in templates
    ctx.view("/my_view", json!({"title": "Page Title"}))
}
}

Important Note About View Data Access

#![allow(unused)]
fn main() {
// When you pass data to ctx.view(), it becomes the "model" in the template
ctx.view("/template", json!({
    "title": "My Page",
    "users": vec![...]
}))

// In the template, access this data with model. or M. prefix:
// @{model.title} or @{M.title}
// @{model.users} or @{M.users}
// NOT directly as @{title} or @{users}
}

Working with Repository

#![allow(unused)]
fn main() {
// Get data from repository
let section = ctx.repository_get("current_section");

// Clear all repository data
ctx.repository_clear();

// Chain multiple operations
ctx.repository_set("key1", "value1")
   .repository_set("key2", "value2")
   .repository_clear();  // Returns &mut Self for chaining
}

Accessing in Templates

<!-- Use repository.key or R.key (shorthand) -->
<h1>@{repository.app_name}</h1>
<div class="section-@{R.current_section}">

<!-- Access nested data -->
Theme: @{repository.site_config.theme}
Sidebar: @{R.site_config.sidebar}

<!-- Use in conditionals -->
@{if R.site_config.notifications}
    <div class="notifications">Enabled</div>
@{fi}

<!-- Iterate over arrays -->
@{foreach item in repository.nav_items}
    <a href="@{item.url}">@{item.title}</a>
@{end}

Complete Example

#![allow(unused)]
fn main() {
use rustf::prelude::*;

pub fn install() -> Vec<Route> {
    routes![
        GET "/dashboard" => dashboard,
    ]
}

async fn dashboard(ctx: &mut Context) -> Result<()> {
    // Set shared repository data
    ctx.repository_set("user", json!({
        "name": "John Doe",
        "role": "admin",
        "avatar": "/images/john.jpg"
    }));
    
    ctx.repository_set("breadcrumbs", json!([
        {"label": "Home", "url": "/"},
        {"label": "Dashboard", "url": null}
    ]));
    
    ctx.repository_set("stats", json!({
        "total_users": 1234,
        "active_sessions": 42
    }));
    
    // View-specific data
    let data = json!({
        "title": "Dashboard",
        "recent_activity": ["Login", "Posted comment", "Updated profile"]
    });
    
    ctx.view("/dashboard/index", data)
}
}

Multiple Views in One Handler

#![allow(unused)]
fn main() {
async fn dashboard_with_sidebar(ctx: &mut Context) -> Result<()> {
    // Set repository data once - available to all views in this handler
    ctx.repository_set("user", get_current_user()?);
    ctx.repository_set("notifications", get_notifications()?);
    ctx.repository_set("theme", "dark");
    
    // Conditional rendering - all views have access to repository
    if is_mobile_device(&ctx) {
        // Mobile view also has access to repository data
        return ctx.view("/dashboard/mobile", json!({
            "stats": get_stats()?
        }));
    }
    
    // Desktop view also has access to the same repository data
    ctx.view("/dashboard/desktop", json!({
        "stats": get_stats()?,
        "charts": get_charts()?
    }))
}
}

Use Cases for Repository

  • Data needed by all views rendered in the same handler
  • User information and permissions for the current handler
  • UI state (theme, layout) for views in this handler
  • Temporary data that shouldn’t be in the main view data
  • Avoiding repetition when calling multiple views

Note: The repository lives only for the handler function’s execution and is cleared when the handler returns. For application-wide data that persists across all requests and is accessible throughout the entire application, use the APP global repository system.

Flash Messages (one-time messages)

#![allow(unused)]
fn main() {
// Standard convenience methods
ctx.flash_success("User created successfully!");
ctx.flash_error("Invalid credentials");
ctx.flash_info("Please check your email");

// Generic flash setter for custom keys
ctx.flash("warning_msg", "This is a warning")?;
ctx.flash("user_level", 42)?;
ctx.flash("notification", json!({"text": "You have messages", "count": 5}))?;
ctx.flash("items", vec!["one", "two", "three"])?;

// Manual flash management
ctx.flash_clear();                    // Clear all flash messages
ctx.flash_clear_key("error_msg");     // Clear specific flash message

// Flash messages automatically appear in views via @{flash.success}, @{flash.custom_key}, etc.
}

Client Information

#![allow(unused)]
fn main() {
// Client details
let ip = ctx.ip();                    // Client IP address
let user_agent = ctx.user_agent();    // Browser/client info
let is_mobile = ctx.is_mobile();      // Mobile device detection
let is_ajax = ctx.is_xhr();           // AJAX request detection
let language = ctx.language();        // Preferred language
}

Controller Registration

Manual Registration

For simple applications or when you need precise control:

use rustf::prelude::*;

mod controllers {
    pub mod home;
    pub mod auth;
    pub mod users;
}

#[tokio::main]
async fn main() -> Result<()> {
    let app = RustF::new()
        .controllers({
            let mut routes = Vec::new();
            routes.extend(controllers::home::install());
            routes.extend(controllers::auth::install());
            routes.extend(controllers::users::install());
            routes
        });
        
    app.start().await
}

For larger applications, use automatic controller discovery:

use rustf::prelude::*;

// The #[rustf::auto_discover] attribute automatically:
// 1. Scans src/controllers/*.rs files
// 2. Generates module declarations  
// 3. Creates controller registration code
#[rustf::auto_discover]
#[tokio::main]
async fn main() -> Result<()> {
    let app = RustF::new()
        .controllers(auto_controllers!())  // Registers all discovered controllers
        .models(auto_models!())           // Also discovers models
        .middleware_from(auto_middleware!()); // And middleware
        
    app.start().await
}

Auto-discovery Process:

  1. Compile-time scanning - Framework scans src/controllers/*.rs at build time
  2. Module generation - Generates _controllers.rs with module declarations
  3. Registration - auto_controllers!() macro returns all discovered routes

Requirements for Auto-Discovery:

  • Enable auto-discovery feature in Cargo.toml
  • Each controller file must have pub fn install() -> Vec<Route>
  • Controller files must be in src/controllers/ directory
  • Use #[rustf::auto_discover] attribute on main function

Complete Controller Examples

Simple Home Controller

#![allow(unused)]
fn main() {
// src/controllers/home.rs
use rustf::prelude::*;

pub fn install() -> Vec<Route> {
    routes![
        GET "/" => index,
        GET "/about" => about,
        GET "/contact" => contact,
    ]
}

async fn index(ctx: &mut Context) -> Result<()> {
    let data = json!({
        "title": "Welcome to RustF",
        "message": "Your application is running successfully!",
        "features": [
            "Auto-discovery for controllers",
            "Template engine with layouts", 
            "Session management",
            "Built-in security features"
        ]
    });
    
    ctx.view("/home/index", data)
}

async fn about(ctx: &mut Context) -> Result<()> {
    let data = json!({
        "title": "About",
        "description": "Built with RustF framework - an AI-friendly MVC framework for Rust",
        "version": "1.0.0"
    });
    
    ctx.view("/home/about", data)
}

async fn contact(ctx: &mut Context) -> Result<()> {
    ctx.view("/home/contact", json!({
        "title": "Contact Us",
        "email": "info@example.com"
    }))
}
}

Authentication Controller with Repository

#![allow(unused)]
fn main() {
// src/controllers/auth.rs  
use rustf::prelude::*;
use serde::Deserialize;

pub fn install() -> Vec<Route> {
    routes![
        GET  "/auth/login"    => view_login,
        POST "/auth/login"    => do_login,
        GET  "/auth/logout"   => do_logout,
        GET  "/auth/register" => view_register,
        POST "/auth/register" => do_register,
    ]
}

// Struct for form validation (optional)
#[derive(Deserialize)]
struct LoginForm {
    email: String,
    password: String,
}

#[derive(Deserialize)]
struct RegisterForm {
    email: String,
    password: String,
    name: String,
}

async fn view_login(ctx: &mut Context) -> Result<()> {
    // Set repository data for this request
    ctx.repository_set("page_type", "auth")
       .repository_set("show_social_login", true)
       .repository_set("providers", json!(["google", "github"]));
    
    // Use empty layout for login page
    ctx.layout("")
       .view("/auth/login", json!({
           "title": "Login",
           "debug": cfg!(debug_assertions) // Show test credentials in debug
       }))
}

async fn do_login(ctx: &mut Context) -> Result<()> {
    // Parse form data into typed structure
    let form: LoginForm = ctx.body_form_typed()?;

    // Input validation
    if !form.email.contains('@') || form.password.is_empty() {
        ctx.flash_error("Please provide a valid email and password");
        return ctx.redirect("/auth/login");
    }

    // Authentication logic (use proper password hashing in production)
    if form.email == "admin@example.com" && form.password == "password" {
        ctx.session_set("user", json!({
            "id": 1,
            "email": form.email,
            "name": "Admin User",
            "role": "admin"
        }))?;

        ctx.flash_success("Login successful!");
        ctx.redirect("/dashboard")
    } else {
        ctx.flash_error("Invalid email or password");
        ctx.redirect("/auth/login")
    }
}

async fn do_logout(ctx: &mut Context) -> Result<()> {
    ctx.session_remove("user");
    ctx.flash_info("You have been logged out successfully");
    ctx.redirect("/auth/login")
}

async fn view_register(ctx: &mut Context) -> Result<()> {
    ctx.layout("")
       .view("/auth/register", json!({
           "title": "Create Account"
       }))
}

async fn do_register(ctx: &mut Context) -> Result<()> {
    // Parse form data into typed structure
    let form: RegisterForm = ctx.body_form_typed()?;

    // Validation
    if !form.email.contains('@') {
        ctx.flash_error("Please provide a valid email address");
        return ctx.redirect("/auth/register");
    }

    if form.password.len() < 8 {
        ctx.flash_error("Password must be at least 8 characters long");
        return ctx.redirect("/auth/register");
    }

    if form.name.trim().is_empty() {
        ctx.flash_error("Please provide your name");
        return ctx.redirect("/auth/register");
    }

    // Check if user already exists (simplified)
    // In real app: check database
    if form.email == "admin@example.com" {
        ctx.flash_error("User already exists");
        return ctx.redirect("/auth/register");
    }

    // Create user (in real app: hash password, save to database)
    ctx.flash_success(&format!("Account created successfully for {}! You can now log in.", form.name));
    ctx.redirect("/auth/login")
}
}

Form Handling with Typed Parsing

RustF provides body_form_typed<T>() for automatic form deserialization into Rust structures, significantly reducing boilerplate code.

Basic Form Parsing

#![allow(unused)]
fn main() {
use rustf::prelude::*;
use serde::Deserialize;

// Define your form structure
#[derive(Deserialize)]
struct ContactForm {
    name: String,
    email: String,
    message: String,
}

pub fn install() -> Vec<Route> {
    routes![
        GET  "/contact" => view_contact,
        POST "/contact" => submit_contact,
    ]
}

async fn view_contact(ctx: &mut Context) -> Result<()> {
    ctx.view("/contact", json!({"title": "Contact Us"}))
}

async fn submit_contact(ctx: &mut Context) -> Result<()> {
    // Parse form directly into typed structure
    let form: ContactForm = ctx.body_form_typed()?;

    // Validate
    if !form.email.contains('@') {
        ctx.flash_error("Please provide a valid email address");
        return ctx.redirect("/contact");
    }

    if form.message.trim().is_empty() {
        ctx.flash_error("Message cannot be empty");
        return ctx.redirect("/contact");
    }

    // Process form data
    log::info!("Contact form from {}: {}", form.name, form.email);

    ctx.flash_success("Thank you! We'll get back to you soon.");
    ctx.redirect("/")
}
}

Optional Fields

Use Option<T> for optional form fields:

#![allow(unused)]
fn main() {
#[derive(Deserialize)]
struct ProfileForm {
    name: String,              // Required
    bio: Option<String>,       // Optional
    website: Option<String>,   // Optional
    age: Option<i32>,          // Optional number
    newsletter: Option<bool>,  // Optional checkbox
}

async fn update_profile(ctx: &mut Context) -> Result<()> {
    let form: ProfileForm = ctx.body_form_typed()?;

    // Required field is always present
    let name = form.name;

    // Optional fields can be None
    if let Some(bio) = form.bio {
        log::info!("User bio: {}", bio);
    }

    // Provide defaults for optional fields
    let website = form.website.unwrap_or_else(|| "Not provided".to_string());
    let age = form.age.unwrap_or(0);
    let newsletter = form.newsletter.unwrap_or(false);

    ctx.flash_success("Profile updated!");
    ctx.redirect("/profile")
}
}

Working with Arrays (Multiple Select / Checkboxes)

Handle multiple values using Vec<T>:

#![allow(unused)]
fn main() {
#[derive(Deserialize)]
struct PreferencesForm {
    username: String,
    interests: Vec<String>,      // Multiple checkboxes
    languages: Vec<String>,       // Multiple select
    notifications: Option<Vec<String>>, // Optional multiple
}

async fn save_preferences(ctx: &mut Context) -> Result<()> {
    let form: PreferencesForm = ctx.body_form_typed()?;

    // Handle multiple values
    log::info!("User interests: {:?}", form.interests);
    log::info!("Languages: {:?}", form.languages);

    // Optional arrays
    if let Some(notif) = form.notifications {
        log::info!("Notification preferences: {:?}", notif);
    }

    ctx.flash_success("Preferences saved!");
    ctx.redirect("/settings")
}
}

HTML Form Example:

<form method="POST">
    <input name="username" value="john_doe" />

    <!-- Multiple checkboxes with same name -->
    <input type="checkbox" name="interests" value="sports" checked />
    <input type="checkbox" name="interests" value="music" checked />
    <input type="checkbox" name="interests" value="travel" />

    <!-- Multiple select -->
    <select name="languages" multiple>
        <option value="en" selected>English</option>
        <option value="fr" selected>French</option>
        <option value="es">Spanish</option>
    </select>
</form>

Post-Processing Transformations

Apply transformations after parsing:

#![allow(unused)]
fn main() {
#[derive(Deserialize)]
struct CountryForm {
    code: String,
    name: String,
    native_name: Option<String>,
    timezone: Option<String>,
}

async fn save_country(ctx: &mut Context) -> Result<()> {
    let mut form: CountryForm = ctx.body_form_typed()?;

    // Apply transformations
    form.code = form.code.trim().to_uppercase();
    form.name = form.name.trim().to_string();

    // Transform optional fields
    form.native_name = form.native_name
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty());

    form.timezone = form.timezone
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty());

    // Validate transformed data
    if form.code.len() != 2 {
        ctx.flash_error("Country code must be exactly 2 characters");
        return ctx.redirect("/countries/new");
    }

    // Save to database...

    ctx.flash_success(&format!("Country {} created!", form.name));
    ctx.redirect("/countries")
}
}

Nested Structures

Handle complex nested forms:

#![allow(unused)]
fn main() {
#[derive(Deserialize)]
struct Address {
    street: String,
    city: String,
    country: String,
    postal_code: String,
}

#[derive(Deserialize)]
struct UserForm {
    name: String,
    email: String,
    address: Address,  // Nested structure
}

async fn create_user(ctx: &mut Context) -> Result<()> {
    let form: UserForm = ctx.body_form_typed()?;

    // Access nested data
    log::info!("User: {}", form.name);
    log::info!("Address: {}, {}", form.address.city, form.address.country);

    ctx.json(json!({
        "success": true,
        "user": form
    }))
}
}

HTML Form Example:

<form method="POST">
    <input name="name" value="John Doe" />
    <input name="email" value="john@example.com" />

    <!-- Nested fields use dot notation -->
    <input name="address.street" value="123 Main St" />
    <input name="address.city" value="New York" />
    <input name="address.country" value="USA" />
    <input name="address.postal_code" value="10001" />
</form>

Error Handling

Handle parsing errors gracefully:

#![allow(unused)]
fn main() {
async fn safe_form_handler(ctx: &mut Context) -> Result<()> {
    // Parse form with error handling
    let form: ContactForm = match ctx.body_form_typed() {
        Ok(f) => f,
        Err(e) => {
            log::error!("Form parsing error: {}", e);
            ctx.flash_error("Invalid form data. Please check your input.");
            return ctx.redirect("/contact");
        }
    };

    // Process valid form...
    ctx.flash_success("Form submitted successfully!");
    ctx.redirect("/")
}
}

Comparison: Three Approaches

#![allow(unused)]
fn main() {
// ❌ Approach 1: Manual (verbose, error-prone)
async fn manual_approach(ctx: &mut Context) -> Result<()> {
    let form_data = ctx.body_form()?;
    let name = form_data.get("name").unwrap_or("").to_string();
    let email = form_data.get("email").unwrap_or("").to_string();
    let age = form_data.get("age").unwrap_or("0").parse::<i32>().unwrap_or(0);
    // ... lots of repetitive code
}

// ⚠️ Approach 2: Field helpers (good for simple forms)
async fn field_helpers_approach(ctx: &mut Context) -> Result<()> {
    let name = ctx.body_str("name")?;
    let email = ctx.body_str("email")?;
    let age = ctx.body_int("age")?;
    // Good for 2-3 fields, becomes verbose with many fields
}

// βœ… Approach 3: Typed parsing (recommended for complex forms)
#[derive(Deserialize)]
struct UserForm {
    name: String,
    email: String,
    age: i32,
}

async fn typed_approach(ctx: &mut Context) -> Result<()> {
    let form: UserForm = ctx.body_form_typed()?;
    // Clean, type-safe, and concise!
}
}

When to Use Each Method

Use body_form_typed<T>() when:

  • βœ… Form has 4+ fields
  • βœ… You need type safety
  • βœ… You have nested data structures
  • βœ… You want to reuse form structures
  • βœ… You need to pass form data to other functions

Use individual field helpers (str_body(), etc.) when:

  • βœ… Form has 1-3 simple fields
  • βœ… You need immediate validation
  • βœ… Quick prototyping

Use manual body_form() when:

  • βœ… You need maximum flexibility
  • βœ… Dynamic field names
  • βœ… Custom parsing logic

RESTful API Controller

#![allow(unused)]
fn main() {
// src/controllers/api.rs
use rustf::prelude::*;
use serde::{Serialize, Deserialize};

pub fn install() -> Vec<Route> {
    routes![
        // User management API
        GET    "/api/users"          => list_users,
        GET    "/api/users/{id}"      => get_user,
        POST   "/api/users"          => create_user,
        PUT    "/api/users/{id}"      => update_user,
        DELETE "/api/users/{id}"      => delete_user,
        
        // Additional endpoints
        GET    "/api/users/search"   => search_users,
        GET    "/api/health"         => health_check,
    ]
}

#[derive(Serialize, Deserialize)]
struct User {
    id: i32,
    name: String,
    email: String,
    created_at: String,
    is_active: bool,
}

#[derive(Deserialize)]
struct CreateUserRequest {
    name: String,
    email: String,
}

#[derive(Deserialize)] 
struct UpdateUserRequest {
    name: Option<String>,
    email: Option<String>,
    is_active: Option<bool>,
}

async fn list_users(ctx: &mut Context) -> Result<()> {
    // Parse query parameters for pagination
    let page = ctx.query_int_or("page", 1);
    let limit = ctx.query_int_or("limit", 10);
    
    let users = vec![
        User {
            id: 1,
            name: "Alice Johnson".to_string(),
            email: "alice@example.com".to_string(),
            created_at: "2024-01-15T10:00:00Z".to_string(),
            is_active: true,
        },
        User {
            id: 2,
            name: "Bob Smith".to_string(),
            email: "bob@example.com".to_string(),
            created_at: "2024-02-20T14:30:00Z".to_string(),
            is_active: true,
        },
    ];
    
    ctx.json(json!({
        "users": users,
        "pagination": {
            "page": page,
            "limit": limit,
            "total": users.len(),
            "total_pages": 1
        }
    }))
}

async fn get_user(ctx: &mut Context) -> Result<()> {
    let user_id = ctx.param_str_or("id", "0");
    
    match user_id.parse::<i32>() {
        Ok(id) if id > 0 => {
            let user = User {
                id,
                name: "Sample User".to_string(),
                email: "user@example.com".to_string(),
                created_at: "2024-01-01T00:00:00Z".to_string(),
                is_active: true,
            };
            
            ctx.json(json!({
                "success": true,
                "user": user
            }))
        }
        _ => {
            ctx.throw400(Some("Invalid user ID"))
        }
    }
}

async fn create_user(ctx: &mut Context) -> Result<()> {
    let request: CreateUserRequest = ctx.body_json()?;
    
    // Validation
    if request.name.trim().is_empty() {
        return ctx.throw400(Some("Name is required"));
    }
    
    if !request.email.contains('@') {
        return ctx.throw400(Some("Valid email is required"));
    }
    
    // Create user (in real app: save to database)
    let user = User {
        id: 3, // Would be generated by database
        name: request.name,
        email: request.email,
        created_at: chrono::Utc::now().to_rfc3339(),
        is_active: true,
    };
    
    ctx.json(json!({
        "success": true,
        "message": "User created successfully",
        "user": user
    }))
}

async fn update_user(ctx: &mut Context) -> Result<()> {
    let user_id = ctx.param_str_or("id", "0");
    let request: UpdateUserRequest = ctx.body_json()?;
    
    match user_id.parse::<i32>() {
        Ok(id) if id > 0 => {
            // In real app: update in database
            ctx.json(json!({
                "success": true,
                "message": "User updated successfully",
                "user_id": id,
                "updated_fields": request
            }))
        }
        _ => {
            ctx.throw400(Some("Invalid user ID"))
        }
    }
}

async fn delete_user(ctx: &mut Context) -> Result<()> {
    let user_id = ctx.param_str_or("id", "0");
    
    match user_id.parse::<i32>() {
        Ok(id) if id > 0 => {
            // In real app: delete from database
            ctx.json(json!({
                "success": true,
                "message": "User deleted successfully",
                "deleted_user_id": id
            }))
        }
        _ => {
            ctx.throw400(Some("Invalid user ID"))
        }
    }
}

async fn search_users(ctx: &mut Context) -> Result<()> {
    let query = ctx.query_str_or("q", "");
    
    if query.is_empty() {
        return ctx.throw400(Some("Search query is required"));
    }
    
    // In real app: search database
    let results = vec![
        User {
            id: 1,
            name: "Alice Johnson".to_string(),
            email: "alice@example.com".to_string(),
            created_at: "2024-01-15T10:00:00Z".to_string(),
            is_active: true,
        }
    ];
    
    ctx.json(json!({
        "success": true,
        "query": query,
        "results": results,
        "count": results.len()
    }))
}

async fn health_check(ctx: &mut Context) -> Result<()> {
    ctx.json(json!({
        "status": "healthy",
        "timestamp": chrono::Utc::now().to_rfc3339(),
        "version": "1.0.0"
    }))
}
}

Advanced Features

URL Parameters

Capture dynamic parts of URLs using the {parameter} syntax:

#![allow(unused)]
fn main() {
routes![
    GET "/users/{id}" => get_user,
    GET "/users/{user_id}/posts/{post_id}" => get_user_post,
    GET "/posts/{post_id}/comments/{comment_id}" => get_comment,
    GET "/files/{category}/{filename}" => download_file,
]

async fn get_user(ctx: &mut Context) -> Result<()> {
    let id = ctx.param_str_or("id", "0");
    
    // Validate and parse parameter
    match id.parse::<i32>() {
        Ok(user_id) if user_id > 0 => {
            // Use the validated user_id
            ctx.json(json!({"user_id": user_id, "name": "User Name"}))
        }
        _ => ctx.throw400(Some("Invalid user ID"))
    }
}

async fn get_user_post(ctx: &mut Context) -> Result<()> {
    let user_id = ctx.param_str_or("user_id", "0");
    let post_id = ctx.param_str_or("post_id", "0");
    
    ctx.json(json!({
        "user_id": user_id,
        "post_id": post_id,
        "title": "Sample Post"
    }))
}

async fn download_file(ctx: &mut Context) -> Result<()> {
    let category = ctx.param_str_or("category", "general");
    let filename = ctx.param_str_or("filename", "file.txt");
    
    // Security: validate file path (prevent directory traversal)
    if filename.contains("..") || filename.contains('/') {
        return ctx.throw403(Some("Invalid filename"));
    }
    
    let file_path = format!("uploads/{}/{}", category, filename);
    ctx.file_download(&file_path, Some(filename))
}
}

Query Parameters

#![allow(unused)]
fn main() {
// URL: /search?q=rust&category=programming&page=2
async fn search(ctx: &mut Context) -> Result<()> {
    let query = ctx.query_str_or("q", "");
    let category = ctx.query_str_or("category", "all");
    let page = ctx.query_int_or("page", 1);
    
    if query.is_empty() {
        return ctx.throw400(Some("Search query is required"));
    }
    
    // Perform search with parameters
    ctx.json(json!({
        "query": query,
        "category": category,
        "page": page,
        "results": [/* search results */]
    }))
}
}

File Handling

#![allow(unused)]
fn main() {
routes![
    GET  "/upload" => upload_form,
    POST "/upload" => handle_upload,
    GET  "/files/{filename}" => serve_file,
]

async fn upload_form(ctx: &mut Context) -> Result<()> {
    ctx.view("/upload", json!({"title": "File Upload"}))
}

async fn handle_upload(ctx: &mut Context) -> Result<()> {
    // Get uploaded files
    let files = ctx.files()?;
    
    if files.is_empty() {
        ctx.flash_error("No files were uploaded");
        return ctx.redirect("/upload");
    }
    
    // Process first uploaded file
    if let Some(file) = ctx.file("document")? {
        // Validate file type
        let allowed_types = ["pdf", "doc", "docx", "txt"];
        let file_ext = file.filename
            .as_ref()
            .and_then(|name| name.split('.').last())
            .unwrap_or("");
            
        if !allowed_types.contains(&file_ext) {
            ctx.flash_error("Only PDF, DOC, DOCX, and TXT files are allowed");
            return ctx.redirect("/upload");
        }
        
        // Save file (in real app: save to disk/cloud storage)
        let filename = format!("upload_{}.{}", U::guid(), file_ext);
        
        ctx.flash_success(&format!("File '{}' uploaded successfully as {}", 
            file.filename.as_ref().unwrap_or(&"unknown".to_string()), filename));
    }
    
    ctx.redirect("/upload")
}

async fn serve_file(ctx: &mut Context) -> Result<()> {
    let filename = ctx.param_str_or("filename", "missing");
    let file_path = format!("uploads/{}", filename);
    
    // Security check
    if filename.contains("..") {
        return ctx.throw403(Some("Access denied"));
    }
    
    ctx.file_download(&file_path, Some(filename))
}
}

Middleware Integration

Controllers work seamlessly with middleware:

#![allow(unused)]
fn main() {
// Authentication middleware can protect routes
routes![
    GET "/admin/dashboard" => admin_dashboard,  // Protected by auth middleware
    GET "/admin/users"     => admin_users,     // Protected by auth middleware
    GET "/public/info"     => public_info,     // Not protected
]

async fn admin_dashboard(ctx: &mut Context) -> Result<()> {
    // This handler only runs if auth middleware allows it
    let user: Value = ctx.session_get("user").unwrap_or_default();
    
    ctx.view("/admin/dashboard", json!({
        "title": "Admin Dashboard",
        "user": user
    }))
}
}

Error Handling Best Practices

Structured Error Handling

#![allow(unused)]
fn main() {
async fn robust_handler(ctx: &mut Context) -> Result<()> {
    // Parse form data with proper error handling
    let form_data = match ctx.body_form() {
        Ok(data) => data,
        Err(e) => {
            log::error!("Failed to parse form data: {}", e);
            return ctx.throw400(Some("Invalid form data"));
        }
    };
    
    // Validate required fields
    let email = match form_data.get("email") {
        Some(email) if !email.is_empty() => email,
        _ => {
            ctx.flash_error("Email is required");
            return ctx.redirect("/form");
        }
    };
    
    // Business logic validation
    if !email.contains('@') {
        ctx.flash_error("Please provide a valid email address");
        return ctx.redirect("/form");
    }
    
    // Success path
    ctx.flash_success("Form processed successfully!");
    ctx.redirect("/success")
}
}

API Error Responses

#![allow(unused)]
fn main() {
async fn api_handler(ctx: &mut Context) -> Result<()> {
    // Parse JSON with error handling
    let request_data: Value = match ctx.body_json() {
        Ok(data) => data,
        Err(_) => {
            return ctx.json(json!({
                "error": "Invalid JSON",
                "code": "INVALID_JSON",
                "status": 400
            }));
        }
    };
    
    // Validate required fields
    let name = match request_data["name"].as_str() {
        Some(name) if !name.trim().is_empty() => name.trim(),
        _ => {
            return ctx.json(json!({
                "error": "Name is required",
                "code": "MISSING_NAME", 
                "status": 400
            }));
        }
    };
    
    // Success response
    ctx.json(json!({
        "success": true,
        "message": "Data processed successfully",
        "data": {"name": name}
    }))
}
}

Using HTTP Error Methods

#![allow(unused)]
fn main() {
async fn comprehensive_error_handler(ctx: &mut Context) -> Result<()> {
    let action = ctx.param_str_or("action", "");
    
    match action {
        "unauthorized" => ctx.throw401(Some("Please log in")),
        "forbidden" => ctx.throw403(Some("Access denied")), 
        "notfound" => ctx.throw404(Some("Resource not found")),
        "conflict" => ctx.throw409(Some("Resource already exists")),
        "server_error" => ctx.throw500(Some("Internal server error")),
        "not_implemented" => ctx.throw501(Some("Feature not implemented")),
        _ => ctx.throw400(Some("Invalid action"))
    }
}
}

Framework Integration

How Controllers Work in RustF

  1. Route Registration - Controllers return Vec<Route> from their install() function
  2. Request Matching - Framework matches incoming requests to routes using method and path
  3. Context Creation - Framework creates a Context with request data, session, and config
  4. Middleware Chain - Request passes through middleware before reaching controller
  5. Handler Execution - Controller handler processes request and returns response
  6. Response Processing - Framework sends response back to client

Application Lifecycle

#![allow(unused)]
fn main() {
// 1. Application setup
let app = RustF::new()
    .controllers(auto_controllers!())  // Register all controllers
    // Register middleware via the registry passed into middleware_from(...)
    .middleware_from(|registry| {
        registry.register_inbound("auth", AuthMiddleware::new());
    });

// 2. Server startup
app.start().await;  // Starts HTTP server

// 3. Request processing
// HTTP Request -> Middleware Chain -> Controller Handler -> HTTP Response
}

Best Practices

1. Controller Organization

#![allow(unused)]
fn main() {
// βœ… Good: Group related functionality
// src/controllers/auth.rs - All authentication
// src/controllers/users.rs - All user management
// src/controllers/api/users.rs - API endpoints for users

// ❌ Bad: Mixed functionality in one controller
// src/controllers/everything.rs - Login, users, posts, etc.
}

2. Naming Conventions

#![allow(unused)]
fn main() {
// βœ… Good: Descriptive, consistent names
routes![
    GET  "/login"  => view_login,     // Shows form
    POST "/login"  => do_login,       // Processes form
    GET  "/users"  => list_users,     // Lists resources
    GET  "/users/{id}" => show_user,   // Shows single resource
    POST "/users"  => create_user,    // Creates resource
    PUT  "/users/{id}" => update_user, // Updates resource
    DELETE "/users/{id}" => delete_user, // Deletes resource
]

// ❌ Bad: Generic, unclear names
routes![
    GET "/login" => handler1,
    POST "/login" => handler2,
    GET "/users" => users,
]
}

3. Input Validation

#![allow(unused)]
fn main() {
// βœ… Good: Comprehensive validation
async fn create_user(ctx: &mut Context) -> Result<()> {
    let form_data = ctx.body_form()?;
    
    // Validate required fields
    let email = match form_data.get("email") {
        Some(email) if !email.trim().is_empty() => email.trim(),
        _ => {
            ctx.flash_error("Email is required");
            return ctx.redirect("/users/new");
        }
    };
    
    // Validate format
    if !email.contains('@') {
        ctx.flash_error("Please provide a valid email address");
        return ctx.redirect("/users/new");
    }
    
    // Continue with processing...
}

// ❌ Bad: No validation
async fn create_user(ctx: &mut Context) -> Result<()> {
    let form_data = ctx.body_form()?;
    let email = form_data.get("email").unwrap(); // Can panic!
    // Save without validation...
}
}

4. Error Handling

#![allow(unused)]
fn main() {
// βœ… Good: Proper error handling with user feedback
async fn process_payment(ctx: &mut Context) -> Result<()> {
    let amount_str = ctx.query_str_or("amount", "0");
    
    let amount = match amount_str.parse::<f64>() {
        Ok(amt) if amt > 0.0 => amt,
        _ => {
            ctx.flash_error("Invalid payment amount");
            return ctx.redirect("/payment");
        }
    };
    
    // Process payment with proper error handling
    match process_payment_logic(amount).await {
        Ok(receipt) => {
            ctx.flash_success("Payment processed successfully!");
            ctx.redirect(&format!("/receipt/{}", receipt.id))
        }
        Err(e) => {
            log::error!("Payment failed: {}", e);
            ctx.flash_error("Payment processing failed. Please try again.");
            ctx.redirect("/payment")
        }
    }
}
}

5. Response Patterns

#![allow(unused)]
fn main() {
// βœ… Good: Consistent response patterns
routes![
    GET  "/users"     => list_users,    // Returns view or JSON list
    POST "/users"     => create_user,   // Redirects on success, back on error
    GET  "/api/users" => api_list_users, // Always returns JSON
]

async fn list_users(ctx: &mut Context) -> Result<()> {
    let users = get_users().await?;
    ctx.view("/users/index", json!({"users": users}))
}

async fn create_user(ctx: &mut Context) -> Result<()> {
    // Validation...
    // Creation...
    
    ctx.flash_success("User created successfully!");
    ctx.redirect("/users")
}

async fn api_list_users(ctx: &mut Context) -> Result<()> {
    let users = get_users().await?;
    ctx.json(json!({
        "success": true,
        "users": users,
        "count": users.len()
    }))
}
}

6. Security Considerations

#![allow(unused)]
fn main() {
// βœ… Good: Security-aware controller
async fn download_file(ctx: &mut Context) -> Result<()> {
    let filename = ctx.param_str_or("filename", "");
    
    // Prevent directory traversal attacks
    if filename.contains("..") || filename.contains('/') || filename.contains('\\') {
        return ctx.throw403(Some("Invalid filename"));
    }
    
    // Validate file exists and user has access
    let file_path = format!("uploads/{}", filename);
    if !std::path::Path::new(&file_path).exists() {
        return ctx.throw404(Some("File not found"));
    }
    
    // Check user permissions
    if let Some(user) = ctx.session_get::<Value>("user") {
        ctx.file_download(&file_path, Some(filename))
    } else {
        ctx.throw401(Some("Login required"))
    }
}
}

7. Testing Controllers

#![allow(unused)]
fn main() {
#[cfg(test)]
mod tests {
    use super::*;
    use rustf::test_helpers::*;
    
    #[tokio::test]
    async fn test_login_success() {
        let ctx = create_test_context()
            .with_form_data([
                ("email", "test@example.com"),
                ("password", "password")
            ]);
            
        let response = do_login(ctx).await.unwrap();
        assert_eq!(response.status_code(), 302); // Redirect
    }
    
    #[tokio::test]
    async fn test_login_invalid_email() {
        let ctx = create_test_context()
            .with_form_data([
                ("email", "invalid-email"),
                ("password", "password")
            ]);
            
        let response = do_login(ctx).await.unwrap();
        assert_eq!(response.status_code(), 302); // Redirect back to form
    }
}
}

File Organization

src/
β”œβ”€β”€ controllers/
β”‚   β”œβ”€β”€ home.rs          # Home page, about, contact
β”‚   β”œβ”€β”€ auth.rs          # Authentication (login, register, logout)
β”‚   β”œβ”€β”€ users.rs         # User management (CRUD operations)
β”‚   β”œβ”€β”€ posts.rs         # Blog posts or content
β”‚   β”œβ”€β”€ api/
β”‚   β”‚   β”œβ”€β”€ mod.rs        # API module declaration
β”‚   β”‚   β”œβ”€β”€ users.rs      # User API endpoints
β”‚   β”‚   β”œβ”€β”€ posts.rs      # Posts API endpoints
β”‚   β”‚   └── auth.rs       # Authentication API
β”‚   β”œβ”€β”€ admin/
β”‚   β”‚   β”œβ”€β”€ mod.rs        # Admin module declaration
β”‚   β”‚   β”œβ”€β”€ dashboard.rs  # Admin dashboard
β”‚   β”‚   β”œβ”€β”€ users.rs      # Admin user management
β”‚   β”‚   └── settings.rs   # System settings
β”‚   └── errors.rs         # Error pages (404, 500, etc.)
β”œβ”€β”€ _controllers.rs       # Auto-generated (DO NOT EDIT)
β”œβ”€β”€ models/              # Database models
β”œβ”€β”€ modules/             # Business logic modules
β”œβ”€β”€ middleware/          # Custom middleware
└── main.rs              # Application entry point

Auto-Generated Files

  • _controllers.rs - Generated by #[rustf::auto_discover] for IDE support
  • DO NOT EDIT auto-generated files manually
  • Regenerated on each build when controllers change

Summary

RustF’s controller system provides:

βœ… Clean Architecture - Separate HTTP handling from business logic βœ… Auto-Discovery - Automatic controller registration at compile time
βœ… Type Safety - Compile-time validation of routes and handlers βœ… Total.js Familiarity - Familiar patterns for web developers βœ… Flexible Organization - Organize controllers by feature or API version βœ… Rich Context API - Comprehensive request/response handling βœ… Error Handling - Built-in HTTP error responses βœ… Security Features - Session management, input validation helpers βœ… Testing Support - Easy to unit test individual handlers

The controller system strikes a balance between simplicity and power, making it easy to build maintainable web applications while providing all the features needed for modern web development.

RustF View & Template Engine Layer

Overview

RustF provides a powerful view system with Total.js as the built-in template engine. The framework is optimized for Total.js templates, providing a familiar syntax for Total.js developers and direct integration with framework features.

Template Engine

Total.js (Built-in)

  • No feature flag required - Always available
  • Syntax: Uses @{...} for expressions
  • Compatible with Total.js v4 - Familiar syntax for Total.js developers
  • Optimized for RustF - Direct integration with framework features
  • Powerful features - Conditionals, loops, layouts, sections, helpers
  • Auto-escaping - HTML is escaped by default for security

Configuration

Configure your template engine in config.toml:

[views]
directory = "views"                # Template directory
default_layout = "layouts/default"  # Default layout template
cache_enabled = false              # Template caching (dev: false, prod: true)
extension = "html"                 # File extension for templates
# engine is always "totaljs" - no other options available
storage = "filesystem"             # Choose: "filesystem" or "embedded"
default_root = ""                  # Base URL path for deployment (e.g., "/app")

Basic Usage

In Controllers

#![allow(unused)]
fn main() {
use rustf::prelude::*;

pub fn install() -> Vec<Route> {
    routes![
        GET "/"           => index,
        GET "/about"      => about,
        GET "/standalone" => standalone,
    ]
}

async fn index(ctx: &mut Context) -> rustf::Result<()> {
    // Page-level data (title, lists, flags) goes in the repository -> @{R.key}
    ctx.repository_set("title", "Welcome");
    ctx.repository_set("message", "Hello from RustF!");
    ctx.repository_set("features", json!(["Fast", "Safe", "Productive"]));

    // The model is ONE object (the page's subject); this page has none
    ctx.view("home/index", json!({}))
}

async fn about(ctx: &mut Context) -> rustf::Result<()> {
    // Render with custom layout
    ctx.repository_set("title", "About Us");
    ctx.layout("layouts/special");
    ctx.view("about", json!({}))
}

async fn standalone(ctx: &mut Context) -> rustf::Result<()> {
    // Render without layout
    ctx.repository_set("content", "This page has no layout");
    ctx.layout("");  // Empty string = no layout
    ctx.view("standalone", json!({}))
}
}

Context Methods

#![allow(unused)]
fn main() {
// Basic template rendering
ctx.view("template_name", data)

// Set custom layout
ctx.layout("layouts/special")
    .view("template", data)

// Render without layout
ctx.layout("")  // Empty string = no layout
    .view("template", data)

// Use default layout from config (no need to call layout())
ctx.view("template", data)  // Uses config.views.default_layout

// Render HTML string directly
ctx.html("<h1>Direct HTML</h1>")

// JSON response
ctx.json(data)

// Text response
ctx.plain("Plain text response")
}

Total.js Template Syntax

Variables

<!-- Model/View data access -->
<h1>@{model.title}</h1>
<h1>@{M.title}</h1>  <!-- Alias for model -->

<!-- Nested properties -->
<p>@{model.user.name}</p>
<p>@{M.user.name}</p>  <!-- Alias -->

<!-- With default value -->
<!-- Default values using || operator -->
<p>@{model.description || 'No description'}</p>
<p>@{user.avatar || '/images/default-avatar.png'}</p>
<span>@{settings.theme || 'light'}</span>

Using || for Fallback Values:

The || (OR) operator provides default values when the left operand is falsy (null, undefined, empty string, 0, false, empty array/object):

<!-- String defaults -->
<p>Bio: @{user.bio || "No bio available"}</p>

<!-- Numeric defaults -->
<p>Items per page: @{settings.pageSize || 20}</p>

<!-- Chaining multiple fallbacks -->
<h1>@{custom_title || page.title || "Untitled Page"}</h1>

Conditionals

Basic If/Else

@{if model.logged_in}
    <p>Welcome, @{model.username}!</p>
@{else}
    <p>Please log in</p>
@{fi}

<!-- Inline conditional -->
<div class="@{if M.active}active@{else}inactive@{fi}">

Comparison Operators

<!-- Equality -->
@{if user.role == "admin"}
    <p>Admin Dashboard</p>
@{fi}

@{if status != "deleted"}
    <p>Active Item</p>
@{fi}

<!-- Strict equality (type-sensitive) -->
@{if count === 0}
    <p>Exactly zero</p>
@{fi}

<!-- Numeric comparison -->
@{if age >= 18}
    <p>Adult content</p>
@{fi}

@{if stock > 0}
    <button>Add to Cart</button>
@{else}
    <span>Out of Stock</span>
@{fi}

@{if price <= budget}
    <span class="affordable">Within Budget</span>
@{fi}

Supported Comparison Operators:

  • == - Loose equality (type coercion)
  • != - Loose inequality
  • === - Strict equality (no type coercion)
  • !== - Strict inequality
  • < - Less than
  • > - Greater than
  • <= - Less than or equal
  • >= - Greater than or equal

Logical Operators

AND (&&) - Both conditions must be true:

@{if user.is_admin && user.is_active}
    <a href="/admin">Admin Panel</a>
@{fi}

@{if age >= 18 && has_id}
    <p>Access granted</p>
@{fi}

OR (||) - At least one condition must be true:

@{if user.is_admin || user.is_moderator}
    <div class="staff-tools">Staff Area</div>
@{fi}

@{if is_weekend || is_holiday}
    <span>πŸŽ‰ Special Hours</span>
@{fi}

Complex Conditions - Combine with parentheses:

@{if (age >= 18 && verified) || is_staff}
    <p>Access granted</p>
@{fi}

@{if (is_member && points > 100) || is_vip}
    <span class="badge">Premium</span>
@{fi}

Negation with !

<!-- NOT operator -->
@{if !user.is_banned}
    <p>Welcome back!</p>
@{fi}

@{if !is_empty}
    <ul>@{foreach item in items}...@{end}</ul>
@{fi}

<!-- Negating expressions -->
@{if !(status == "deleted" || status == "archived")}
    <button>Edit</button>
@{fi}

Else-If Chains with @{elif}

@{if score > 90}
    <span class="grade-a">A - Excellent!</span>
@{elif score > 80}
    <span class="grade-b">B - Good Job</span>
@{elif score > 70}
    <span class="grade-c">C - Fair</span>
@{elif score > 60}
    <span class="grade-d">D - Needs Improvement</span>
@{else}
    <span class="grade-f">F - Failed</span>
@{fi}

Multiple elif branches:

@{if role == "owner"}
    <p>Full Access</p>
@{elif role == "admin"}
    <p>Administrative Access</p>
@{elif role == "moderator"}
    <p>Moderation Access</p>
@{elif role == "member"}
    <p>Member Access</p>
@{else}
    <p>Guest Access</p>
@{fi}

Truthy/Falsy Values

Values are evaluated as truthy or falsy in conditionals:

Falsy values:

  • false
  • null
  • 0
  • "" (empty string)
  • [] (empty array)
  • {} (empty object)

Truthy values:

  • true
  • Any non-zero number
  • Any non-empty string
  • Any non-empty array
  • Any non-empty object
<!-- Check if value exists and is truthy -->
@{if user.email}
    <p>Email: @{user.email}</p>
@{fi}

<!-- Check if array has items -->
@{if products}
    <p>@{products.length} products available</p>
@{fi}

Loops

<!-- Array iteration -->
@{foreach item in model.items}
    <li>@{item.name} - @{item.price}</li>
@{end}

<!-- With index (using M alias) -->
@{foreach item, index in M.items}
    <li>@{index}: @{item}</li>
@{end}

Escaping

<!-- Auto-escaped (safe by default) -->
<p>@{M.user_input}</p>

<!-- Raw HTML (unescaped) -->
<div>@{!M.html_content}</div>

Raw output @{!...} accepts a full expression, not just a bare variable β€” e.g. @{!M.url || '/default.jpg'} renders the value-fallback unescaped.

Expressions & Operators

The Total.js template engine supports rich expressions with multiple operator types, allowing for complex logic directly in templates.

Operator Reference

CategoryOperatorsDescriptionExample
Comparison==, !=Loose equality/inequality (with type coercion)@{if age == "18"}
===, !==Strict equality/inequality (no type coercion)@{if count === 0}
<, >Less than, greater than@{if price > 100}
<=, >=Less/greater than or equal@{if stock <= 5}
Logical&&AND - both must be true@{if a && b}
||OR - at least one must be true@{if a || b}
Unary!NOT - negates boolean@{if !is_deleted}
-Negation - negates number@{-value}
Arithmetic+Addition / String concatenation@{price + tax}
-Subtraction@{total - discount}
*Multiplication@{price * quantity}
/Division@{total / count}
%Modulo (remainder)@{index % 2}

Operator Precedence

Operators are evaluated in the following order (highest to lowest precedence):

  1. Parentheses ( ) - Grouping (evaluated first)
  2. Unary !, - - NOT, negation
  3. Multiplication/Division *, /, % - Arithmetic
  4. Addition/Subtraction +, - - Arithmetic
  5. Comparison <, >, <=, >= - Relational
  6. Equality ==, !=, ===, !== - Equality checks
  7. Logical AND && - Boolean AND
  8. Logical OR || - Boolean OR (evaluated last)

Examples:

<!-- Precedence without parentheses -->
@{if x + 5 > 10 && y < 20}
    <!-- Evaluates as: ((x + 5) > 10) && (y < 20) -->
@{fi}

<!-- Using parentheses to control precedence -->
@{if (a || b) && c}
    <!-- OR is evaluated before AND due to parentheses -->
@{fi}

Arithmetic Operations

<!-- Basic arithmetic -->
<p>Subtotal: $@{price * quantity}</p>
<p>Tax: $@{subtotal * 0.08}</p>
<p>Total: $@{subtotal + (subtotal * 0.08)}</p>

<!-- Complex calculations -->
<p>Price per unit: $@{total_price / item_count}</p>
<p>Discount: @{(original_price - sale_price) / original_price * 100}%</p>

<!-- Modulo for alternating styles -->
@{foreach item, index in items}
    <tr class="@{if index % 2 == 0}even@{else}odd@{fi}">
        <td>@{item.name}</td>
    </tr>
@{end}

String Concatenation

<!-- Concatenate strings with + -->
<p>@{first_name + " " + last_name}</p>
<p>@{"Hello, " + user.name + "!"}</p>

<!-- Build URLs -->
<a href="@{"/products/" + product.id}">View Product</a>

<!-- Combine with variables -->
<p>@{greeting + " " + M.username}</p>

Default Values with ||

The || operator provides fallback values when the left side is falsy:

<!-- Simple default -->
<p>@{user.bio || "No bio provided"}</p>

<!-- Nested properties with default -->
<p>@{user.profile.avatar || "/images/default-avatar.png"}</p>

<!-- Numeric defaults -->
<p>Items per page: @{settings.page_size || 20}</p>

<!-- Chain multiple defaults -->
<p>@{custom_title || default_title || "Untitled"}</p>

Complex Expressions

<!-- Nested conditionals in expressions -->
<p class="@{if score >= 90}excellent@{elif score >= 70}good@{else}poor@{fi}">
    Score: @{score}
</p>

<!-- Mathematical expressions in conditionals -->
@{if (price * quantity) > budget}
    <span class="warning">Over budget!</span>
@{fi}

<!-- Combining multiple operators -->
@{if ((total - discount) * tax_rate) < 100 && is_member}
    <span>Free shipping!</span>
@{fi}

<!-- Expression in attribute values -->
<div data-score="@{points * 10}" 
     class="level-@{if points > 100}high@{else}low@{fi}">
</div>

Grouping with Parentheses

Use parentheses to control evaluation order and clarify complex expressions:

<!-- Without parentheses (may be unclear) -->
@{if a && b || c && d}  <!-- Evaluates as: (a && b) || (c && d) -->

<!-- With parentheses (explicit) -->
@{if (a && b) || (c && d)}  <!-- Same result, but clearer intent -->

<!-- Change evaluation order -->
@{if a && (b || c) && d}  <!-- OR evaluated before outer ANDs -->

<!-- Arithmetic grouping -->
<p>@{(price + shipping) * (1 + tax_rate)}</p>

Practical Examples

Important: The Total.js engine does not support template-level variable assignment (@{var x = ...} and reassignment do not work) and there is no Math.* object. Inline arithmetic and boolean expressions are supported (e.g. @{price * quantity}, @{a && b}), but any value that needs to be computed once and reused β€” a subtotal, a page count, an access-control flag β€” should be calculated in the handler and passed in via the repository.

Shopping Cart Total:

Compute the per-item and subtotal values in the handler, then pass them in. Inline arithmetic is fine for purely derived display values:

#![allow(unused)]
fn main() {
// In the handler
async fn cart(ctx: &mut Context) -> rustf::Result<()> {
    // ... build `items` (each with a pre-computed `total`) and `subtotal` ...
    ctx.repository_set("items", json!(items));
    ctx.repository_set("subtotal", json!(subtotal));
    ctx.repository_set("tax_rate", json!(0.2));
    ctx.repository_set("grand_total", json!(subtotal * 1.2));
    ctx.view("cart/index", json!({}))
}
}
@{foreach item in items}
    <tr>
        <td>@{item.name}</td>
        <td>@{item.quantity} Γ— $@{item.price}</td>
        <td>$@{item.total}</td>
    </tr>
@{end}
<tr class="total">
    <td colspan="2">Subtotal:</td>
    <td>$@{subtotal}</td>
</tr>
<tr>
    <td colspan="2">Tax (@{tax_rate * 100}%):</td>
    <td>$@{subtotal * tax_rate}</td>
</tr>
<tr class="grand-total">
    <td colspan="2">Total:</td>
    <td>$@{grand_total}</td>
</tr>

Pagination Logic:

Compute total_pages, has_prev, and has_next in the handler (no Math.ceil in templates), then read them in the view:

#![allow(unused)]
fn main() {
let total_pages = (total_items + items_per_page - 1) / items_per_page; // ceil
ctx.repository_set("current_page", json!(current_page));
ctx.repository_set("total_pages", json!(total_pages));
ctx.repository_set("has_prev", json!(current_page > 1));
ctx.repository_set("has_next", json!(current_page < total_pages));
}
<div class="pagination">
    @{if has_prev}
        <a href="?page=@{current_page - 1}">Previous</a>
    @{fi}
    
    <span>Page @{current_page} of @{total_pages}</span>
    
    @{if has_next}
        <a href="?page=@{current_page + 1}">Next</a>
    @{fi}
</div>

Access Control:

Resolve permission flags in the handler and pass them through the repository:

#![allow(unused)]
fn main() {
let can_edit = user.id == post.author_id || user.is_admin;
ctx.repository_set("can_edit", json!(can_edit));
ctx.repository_set("can_delete", json!(user.is_admin || (user.is_moderator && post.flagged)));
ctx.repository_set("can_publish", json!((user.role == "editor" || user.role == "admin") && !post.published));
}
@{if can_edit}
    <button onclick="editPost()">Edit</button>
@{fi}

@{if can_delete}
    <button onclick="deletePost()" class="danger">Delete</button>
@{fi}

@{if can_publish}
    <button onclick="publishPost()" class="primary">Publish</button>
@{fi}

Data Access in Templates

Global Constants

These are directly accessible without any prefix:

@{url}          <!-- Current request URL -->
@{hostname}     <!-- Server hostname -->
@{root}         <!-- Application root path (from config.default_root) -->
@{index}        <!-- Current loop index (inside foreach) -->
@{csrf_token}   <!-- CSRF token for forms -->

Data Source Objects

These objects can be accessed entirely or via dot notation for properties:

<!-- Configuration (entire object or properties) -->
@{CONF}               <!-- Entire config object -->
@{CONF.app_name}      <!-- Specific config value -->
@{CONF.default_root}  <!-- Deployment root path -->

<!-- Session (entire object or properties) -->
@{session}            <!-- Entire session object -->
@{session.user_id}    <!-- Specific session value -->
@{session.cart}       <!-- Session cart data -->

<!-- Flash Messages (stored in session, aliased for convenience) -->
@{flash}              <!-- All flash messages -->
@{flash.error}        <!-- Error flash message -->
@{flash.success}      <!-- Success flash message -->
@{flash.info}         <!-- Info flash message -->
@{flash.custom_key}   <!-- Custom flash message -->

<!-- Query parameters (entire object or properties) -->
@{query}              <!-- All query parameters -->
@{query.page}         <!-- Specific query parameter -->
@{query.search}       <!-- Search query parameter -->

<!-- User (entire object or properties) -->
@{user}               <!-- Entire user object -->
@{user.name}          <!-- User's name -->
@{user.email}         <!-- User's email -->

<!-- Context Repository (per-handler) -->
@{repository}         <!-- Entire repository object -->
@{repository.key}     <!-- Specific repository value -->
@{R.key}              <!-- Shorthand for repository.key -->

<!-- Global Repository (application-wide) -->
@{APP.key}            <!-- Global repository value -->
@{MAIN.key}           <!-- Alias for APP.key -->

<!-- Model/View Data (from ctx.view()) -->
@{model}              <!-- Entire model object -->
@{model.key}          <!-- Specific model value -->
@{M}                  <!-- Alias for entire model -->
@{M.key}              <!-- Alias for model.key -->

Loop Variables

Within @{foreach} loops, the iterator variable is directly accessible:

@{foreach product in model.products}
    <!-- 'product' is directly accessible here -->
    <h3>@{product.name}</h3>
    <p>Price: @{product.price}</p>
    <p>Index: @{index}</p>  <!-- Loop index is available -->
@{end}

<!-- foreach binds a SINGLE loop variable. Two-variable key/value object
     iteration (e.g. `foreach key, value in obj`) is NOT supported. -->
@{foreach tag in post.tags}
    <span class="tag">@{tag}</span>
@{end}

Built-in Functions

<!-- Asset / URL helpers -->
@{url('/path')}            <!-- Resolve a URL -->
@{css('/static/app.css')}  <!-- CSS link tag -->
@{js('/static/app.js')}    <!-- Script tag. Never pass request data: any https:// URL loads and runs -->
@{image('/logo.png')}      <!-- Image tag -->

<!-- Data formatting -->
@{json(data)}           <!-- JSON, HTML-escaped: safe in text and attributes -->
@{!json(data)}          <!-- JSON for a <script> block (still escapes < > &) -->

<!-- String case (HTML is auto-escaped; use @{!expr} to bypass) -->
@{upper(text)}          <!-- Uppercase (alias: toUpperCase) -->
@{lower(text)}          <!-- Lowercase (alias: toLowerCase) -->

<!-- Iteration helpers -->
@{range(10)}            <!-- Generate array [0,1,2,3,4,5,6,7,8,9] -->
@{range(1, 11)}         <!-- Generate array [1,2,3,4,5,6,7,8,9,10] -->
@{range(0, 10, 2)}      <!-- Generate array [0,2,4,6,8] with step -->

Range Function Examples

The range() function generates numeric sequences for loops:

<!-- Simple range: 0 to N-1 -->
@{foreach num in range(5)}
    <p>Item @{num}</p>  <!-- Outputs: 0, 1, 2, 3, 4 -->
@{end}

<!-- Range with start and stop -->
@{foreach page in range(1, 6)}
    <a href="/page/@{page}">Page @{page}</a>  <!-- Pages 1-5 -->
@{end}

<!-- Range with custom step -->
@{foreach year in range(2020, 2030, 2)}
    <option value="@{year}">@{year}</option>  <!-- 2020, 2022, 2024, 2026, 2028 -->
@{end}

<!-- Practical example: pagination -->
@{foreach page in range(1, model.totalPages + 1)}
    @{if page == model.currentPage}
        <span class="active">@{page}</span>
    @{else}
        <a href="?page=@{page}">@{page}</a>
    @{fi}
@{end}

Form Helpers

Form helpers render an HTML form element and auto-bind its value from the model field named by the first argument. An optional object literal supplies HTML attributes:

@{text('email', { class: 'form', placeholder: 'you@example.com', required: true })}
<!-- with model { email: "a@b.com" }: -->
<!-- <input type="text" name="email" value="a@b.com" class="form" placeholder="you@example.com" required /> -->

Attribute object rules: key: 'str' / key: 30 β†’ key="..."; flag: true β†’ a bare boolean attribute (required); flag: false β†’ omitted. Values and attributes are HTML-escaped; a missing model field renders an empty value.

HelperRenders
@{text('field', { ...attrs })}<input type="text" name="field" value="{model.field}" ... />
@{password('field', { ...attrs })}<input type="password" ... />
@{hidden('field', { ...attrs })}<input type="hidden" ... />
@{textarea('field', { ...attrs })}<textarea name="field" ...>{model.field}</textarea>
@{checkbox('field', [label])}<input type="checkbox" name="field"[ checked] />, checked when the model field is truthy
@{radio('field', 'value', [label])}<input type="radio" name="field" value="value"[ checked] />, checked when the model field == value

checkbox and radio take an optional label that wraps the input in a <label>. For radio, the third argument is either a label string or an object whose label key is the wrap text and whose other keys are attributes:

@{checkbox('agree', 'I accept the terms')}
<!-- <label><input type="checkbox" name="agree" checked /> I accept the terms</label> -->

@{radio('gender', 'male', 'Male')}
@{radio('gender', 'female', { label: 'Female', class: 'opt' })}

Meta Helpers (title & description)

@{title('...')} and @{description('...')} are setters β€” they store the value in meta data (carried from the view into its layout) and render nothing inline. The layout reads them back with @{title} / @{description}:

<!-- view: auth/login.html -->
@{title('Sign in')}
@{description('Access your account')}

<!-- layouts/default.html -->
<head>
  <title>@{title} Β· @{MAIN.site_name}</title>
  <meta name="description" content="@{description}">
</head>

@{meta('Title', 'Description', 'Keywords')} is the all-in-one variant that emits the <title> and <meta> tags directly at its position.

Request Properties

Read-only values available in any template:

PropertyDescription
@{url}the request’s relative URL
@{hostname}the request host
@{mobile}boolean β€” true for mobile-device User-Agents (@{if mobile}…@{fi})
@{root}configured views.default_root with the trailing / stripped β€” for apps served under a sub-path

Inside a @{foreach} loop, @{break} and @{continue} work both directly and inside @{if} / @{elif} blocks:

@{foreach item in M.items}
  @{if item.sold_out}@{continue}@{fi}
  <li>@{item.name}</li>
  @{if index >= 9}@{break}@{fi}
@{end}

Template Partials and Includes

Total.js templates support including other templates (partials) using the @{view()} function:

<!-- Include a partial template -->
@{view('partials/header')}

<!-- Include with specific model data -->
@{view('partials/user-card', model.currentUser)}

<!-- Include in loops -->
@{foreach user in model.users}
    @{view('partials/user-card', user)}
@{end}

<!-- Nested partials (partials can include other partials) -->
<!-- In partials/sidebar.html: -->
@{view('partials/user-info', model.user)}
@{view('partials/menu', model.menuItems)}

Partial Template Example

Create reusable components in views/partials/:

<!-- views/partials/user-card.html -->
<div class="user-card">
    <img src="@{model.avatar}" alt="@{model.name}">
    <h3>@{model.name}</h3>
    <p>@{model.email}</p>
    @{if model.isAdmin}
        <span class="badge">Admin</span>
    @{fi}
</div>

Use it in your main templates:

<!-- views/users/list.html -->
<div class="users-grid">
    @{foreach user in model.users}
        @{view('partials/user-card', user)}
    @{end}
</div>

Important Notes

  • Partials have access to all global data (repository, session, etc.)
  • When passing model data, the partial receives only that data as its model
  • Partials are loaded relative to the views directory
  • Nested partials are supported (partials can include other partials)
  • Currently, array indexing in expressions (e.g., model.users[0]) is not supported in the view() function

Layouts

Layout System Overview

RustF follows the Total.js pattern for layouts:

  • Default layout: Configured in config.toml as views.default_layout (default: "layouts/default")
  • Custom layout: Use ctx.layout("path/to/layout") in controller
  • No layout: Use ctx.layout("") with empty string
  • Layout inheritance: Templates can specify their own layout with @{layout('path')}

Controller-Side Layout Control

#![allow(unused)]
fn main() {
use rustf::prelude::*;

pub fn install() -> Vec<Route> {
    routes![
        GET "/"        => index,
        GET "/admin"   => admin,
        GET "/api-doc" => api_doc,
    ]
}

// Uses default layout from config
async fn index(ctx: &mut Context) -> rustf::Result<()> {
    ctx.repository_set("title", "Home");
    ctx.view("home/index", json!({}))
}

// Custom layout
async fn admin(ctx: &mut Context) -> rustf::Result<()> {
    ctx.layout("layouts/admin");  // Set custom layout
    ctx.view("admin/dashboard", json!({"user": "Admin"}))
}

// No layout (standalone page)
async fn api_doc(ctx: &mut Context) -> rustf::Result<()> {
    ctx.layout("");  // Empty string = no layout
    ctx.view("docs/api", json!({"version": "1.0"}))
}
}

Total.js Layouts

Define a layout (views/layouts/default.html):

<!DOCTYPE html>
<html>
<head>
    <title>@{if R.title}@{R.title} - @{fi}My App</title>
    @{css('/static/css/main.css')}
</head>
<body>
    <nav>
        <a href="@{root}/">Home</a>
        <a href="@{root}/about">About</a>
    </nav>
    
    <main>
        @{body}  <!-- Child template content renders here -->
    </main>
    
    @{js('/static/js/app.js')}
</body>
</html>

Use in child template (views/home/index.html):

<h1>@{model.title}</h1>
<p>@{M.message}</p>

@{foreach feature in model.features}
    <div>@{feature}</div>
@{end}

Note: @{layout('...')} is not a template directive in RustF. The layout is chosen by the handler with ctx.layout("layouts/default") (or falls back to the views.default_layout value in config.toml). Set it before calling ctx.view(...).

Sections

Section System Overview

Sections allow child templates to define content blocks that parent layouts can render in specific locations. This is the standard pattern for customizing different areas of a layout (head content, sidebar, footer, etc.) from child views.

Key Concepts:

  • Child defines sections: Use @{section name}...@{end} in child templates
  • Parent renders sections: Use @{section('name')} in layout templates
  • Optional sections: Missing sections render as empty (no errors)
  • Multiple sections: Child can define multiple sections for different layout areas

Basic Section Usage

Layout with Section Placeholders (views/layouts/main.html):

<!DOCTYPE html>
<html>
<head>
    <title>@{M.title}</title>
    
    <!-- Child can inject custom styles here -->
    @{section('styles')}
    
    <!-- Child can add meta tags, scripts, etc. -->
    @{section('head')}
</head>
<body>
    <header>
        <!-- Child can customize header -->
        @{section('header')}
    </header>
    
    <main>
        @{body}  <!-- Main content -->
    </main>
    
    <aside>
        <!-- Child can provide sidebar content -->
        @{section('sidebar')}
    </aside>
    
    <footer>
        <!-- Child can customize footer -->
        @{section('footer')}
    </footer>
    
    <!-- Child can inject page-specific scripts -->
    @{section('scripts')}
</body>
</html>

Child Template Defining Sections (views/products/detail.html):

@{section styles}
<link rel="stylesheet" href="/css/products.css">
<style>
    .product-gallery { display: grid; }
</style>
@{end}

@{section head}
<meta property="og:title" content="@{M.product.name}">
<meta property="og:image" content="@{M.product.image}">
@{end}

@{section header}
<h1>@{M.product.name}</h1>
<nav class="breadcrumb">
    <a href="@{root}/">Home</a> &gt;
    <a href="@{root}/products">Products</a> &gt;
    @{M.product.category}
</nav>
@{end}

<!-- Main content (rendered in @{body}) -->
<div class="product-detail">
    <img src="@{M.product.image}" alt="@{M.product.name}">
    <div class="product-info">
        <p class="price">$@{M.product.price}</p>
        <p>@{M.product.description}</p>
    </div>
</div>

@{section sidebar}
<h3>Related Products</h3>
@{foreach item in M.related}
    <div class="related-item">
        <a href="/products/@{item.id}">@{item.name}</a>
    </div>
@{end}
@{end}

@{section scripts}
<script src="/js/product-gallery.js"></script>
<script>
    initProductGallery('@{M.product.id}');
</script>
@{end}

Section Features

1. Optional Sections - No errors if section not defined:

<!-- Layout -->
<div class="notifications">
    @{section('alerts')}  <!-- Empty if child doesn't define it -->
</div>

<!-- Child - can choose to define or skip -->
@{section alerts}
<div class="alert">Special offer!</div>
@{end}

2. Conditional Sections:

<!-- Child template -->
@{if M.show_newsletter}
    @{section footer}
    <div class="newsletter-signup">
        <form>...</form>
    </div>
    @{end}
@{fi}

3. Sections with Dynamic Content:

<!-- Child template -->
@{section sidebar}
    <h3>Categories</h3>
    @{foreach cat in M.categories}
        <a href="/category/@{cat.slug}">@{cat.name}</a>
    @{end}
    
    <h3>Tags</h3>
    @{foreach tag in M.tags}
        <span class="tag">@{tag}</span>
    @{end}
@{end}

4. Multiple Sections in One Template:

<!-- A single child view can define many sections -->
@{section meta}...@{end}
@{section styles}...@{end}
@{section header}...@{end}

<!-- Main content here -->

@{section sidebar}...@{end}
@{section footer}...@{end}
@{section scripts}...@{end}

Common Section Patterns

Meta Tags & SEO:

<!-- Layout head -->
@{section('meta')}

<!-- Child defines SEO metadata -->
@{section meta}
<meta name="description" content="@{M.description}">
<meta name="keywords" content="@{M.keywords}">
<link rel="canonical" href="@{M.canonical_url}">
@{end}

Page-Specific Styles:

<!-- Layout head -->
@{section('page_styles')}

<!-- Child adds custom CSS -->
@{section page_styles}
<link rel="stylesheet" href="/css/dashboard.css">
<style>
    .dashboard-widget { margin: 1rem; }
</style>
@{end}

JavaScript Initialization:

<!-- Layout before </body> -->
@{section('page_scripts')}

<!-- Child adds page logic -->
@{section page_scripts}
<script src="/js/chart.min.js"></script>
<script>
    initCharts(@{!json(M.chart_data)});  // raw form inside <script>
</script>
@{end}

Breadcrumbs:

<!-- Layout -->
<nav class="breadcrumbs">
    <a href="/">Home</a>
    @{section('breadcrumbs')}
</nav>

<!-- Child extends breadcrumb trail -->
@{section breadcrumbs}
&gt; <a href="/products">Products</a>
&gt; @{M.category}
@{end}

Section vs @{head} Special Placeholder

RustF provides a special @{head} placeholder that automatically renders content from a section named β€œhead”:

<!-- These are equivalent: -->
@{section('head')}
@{head}

The @{head} placeholder is a convenience feature inherited from Total.js for adding content to the HTML <head> section. For all other sections, use the explicit @{section('name')} syntax.

Best Practices

  1. Name sections clearly: Use descriptive names like page_styles, sidebar_menu, footer_links

  2. Document expected sections: Comment layout templates to show which sections are available:

    <!-- Available sections:
         - styles: Custom CSS for this page
         - header: Page-specific header content
         - sidebar: Sidebar widgets
         - scripts: Page-specific JavaScript
    -->
    
  3. Keep sections focused: Each section should have a single, clear purpose

  4. Make sections optional: Don’t require every child to define every section

  5. Use consistent naming: Establish naming conventions across your app:

    • page_styles / page_scripts for page-specific assets
    • meta for SEO metadata
    • header / footer / sidebar for layout areas

Example: Complete Blog Post Template

Layout (views/layouts/blog.html):

<!DOCTYPE html>
<html>
<head>
    <title>@{M.title} - My Blog</title>
    <meta charset="UTF-8">
    @{section('meta')}
    @{css('/css/blog.css')}
    @{section('styles')}
</head>
<body>
    <header class="site-header">
        <h1>My Blog</h1>
        @{section('breadcrumbs')}
    </header>
    
    <div class="content-wrapper">
        <article>
            @{section('article_header')}
            @{body}
        </article>
        
        <aside class="sidebar">
            @{section('sidebar')}
        </aside>
    </div>
    
    <footer>
        @{section('comments')}
        <p>&copy; 2025 My Blog</p>
    </footer>
    
    @{js('/js/blog.js')}
    @{section('scripts')}
</body>
</html>

Blog Post (views/blog/post.html):

@{section meta}
<meta name="description" content="@{M.excerpt}">
<meta name="author" content="@{M.author}">
<meta property="og:image" content="@{M.featured_image}">
@{end}

@{section breadcrumbs}
<a href="/blog">Blog</a> &gt;
<a href="/blog/@{M.category}">@{M.category_name}</a>
@{end}

@{section article_header}
<h1>@{M.title}</h1>
<div class="meta">
    By @{M.author} on @{M.published_date}
</div>
<img src="@{M.featured_image}" alt="@{M.title}">
@{end}

<!-- Main article content -->
<div class="article-body">
    @{M.content}
</div>

@{section sidebar}
<h3>About the Author</h3>
<p>@{M.author_bio}</p>

<h3>Related Posts</h3>
@{foreach post in M.related_posts}
    <a href="/blog/@{post.slug}">@{post.title}</a>
@{end}
@{end}

@{section comments}
<div class="comments">
    <h3>Comments (@{M.comment_count})</h3>
    @{foreach comment in M.comments}
        <div class="comment">
            <strong>@{comment.author}</strong>
            <p>@{comment.text}</p>
        </div>
    @{end}
</div>
@{end}

@{section scripts}
<script src="/js/syntax-highlighter.js"></script>
<script>highlightCode();</script>
@{end}

Storage Options

Filesystem (Development)

  • Templates loaded from disk at runtime
  • Supports hot-reloading
  • Easy to modify during development
  • Configure with: storage = "filesystem"

Embedded (Production)

  • Templates compiled into binary
  • Faster startup, no file I/O
  • Requires embedded-views feature
  • Configure with: storage = "embedded"

Advanced Features

Custom Template Functions

Custom functions usable in templates (@{my_helper(...)}) are registered as helpers through the Definitions system β€” there is no public engine.register_function(...) method. Register the helper inside a definitions module’s install function:

#![allow(unused)]
fn main() {
use rustf::definitions::Definitions;

pub fn install(defs: &mut Definitions) {
    // `defs.helpers` is the public HelperRegistry; `register_fn` takes a
    // name, description, and a closure `Fn(&[Value], _) -> Result<Value>`.
    defs.helpers.register_fn(
        "format_price",
        "Format a number as a price",
        |args, _| {
            let amount = args.first().and_then(|v| v.as_f64()).unwrap_or(0.0);
            Ok(serde_json::Value::String(format!("${:.2}", amount)))
        },
    );
}

// Use in template
// @{format_price(19.99)} => "$19.99"
}

See the Definitions guide for the full helper API (register_helper, register_fn) and how definitions modules are auto-discovered.

CSRF Protection

Automatic CSRF token injection:

#![allow(unused)]
fn main() {
// In controller - generate token and render view.
// generate_csrf takes an Option<&str> token id; pass None for the default.
ctx.generate_csrf(None)?;
ctx.view("form", data)
}
<!-- In template - Total.js -->
<form method="POST">
    @{csrf}  <!-- Renders hidden input with the default token -->
    <!-- or manually -->
    <input type="hidden" name="_token" value="@{csrf_token}">
</form>

Repository System

RustF provides two repository systems for sharing data between controllers and views:

Context Repository (Per-Request)

The context repository is request-scoped data that controllers can set to share with templates. It’s useful for page-specific settings, user permissions, or any data that’s specific to the current request.

Setting in Controllers:

#![allow(unused)]
fn main() {
async fn dashboard(ctx: &mut Context) -> rustf::Result<()> {
    // Set various types of repository data
    ctx.repository_set("current_section", "analytics")
       .repository_set("sidebar_expanded", true)
       .repository_set("user_role", "admin")
       .repository_set("available_actions", json!(["view", "edit", "delete"]))
       .repository_set("theme", json!({
           "primary_color": "#007bff",
           "mode": "dark"
       }));
    
    ctx.repository_set("title", "Dashboard");

    // Repository data is automatically available in templates.
    // The model is the page's single subject: here, the stats object.
    let stats = get_stats().await?;
    ctx.view("dashboard/index", json!(stats))
}
}

Accessing in Templates:

<!-- Using R. prefix (recommended, shorter) -->
@{if R.user_role == 'admin'}
    <div class="admin-panel">
        @{foreach action in R.available_actions}
            <button>@{action}</button>
        @{end}
    </div>
@{fi}

<!-- Using repository. prefix (alternative) -->
<div class="sidebar @{if repository.sidebar_expanded}expanded@{fi}">
    Current Section: @{repository.current_section}
</div>

<!-- Accessing nested data -->
<style>
    :root {
        --primary-color: @{R.theme.primary_color};
    }
    body.@{R.theme.mode} {
        /* Dark mode styles */
    }
</style>

Global Repository (APP/MAIN)

The global repository is application-wide data shared across all requests. It’s typically set during application initialization and contains site-wide settings, application metadata, or shared constants.

Setting During Application Setup:

Use the APP global repository. It accepts dotted paths, so nested values are set directly:

#![allow(unused)]
fn main() {
// In your main.rs or app initialization
use rustf::APP;

APP::set("site_name", "My Application")?;
APP::set("version", "2.1.0")?;
APP::set("copyright", "Β© 2024 MyCompany")?;
APP::set("contact_email", "support@example.com")?;

APP::set("features.comments", true)?;
APP::set("features.notifications", true)?;
APP::set("features.api_v2", false)?;

APP::set("social_links.twitter", "https://twitter.com/myapp")?;
APP::set("social_links.github", "https://github.com/myapp")?;
}

Deprecated: TotalJsEngine::set_global_repository(...) is marked #[deprecated] β€” use APP::set() as shown above instead.

Accessing in Templates:

<!-- Using APP. prefix -->
<footer>
    <p>@{APP.copyright}</p>
    <p>Contact: <a href="mailto:@{APP.contact_email}">@{APP.contact_email}</a></p>
    <p>Version @{APP.version}</p>
</footer>

<!-- Using MAIN. prefix (alias for APP) -->
<title>@{title} - @{MAIN.site_name}</title>

<!-- Checking features -->
@{if APP.features.comments}
    <div class="comments-section">
        <!-- Comments enabled -->
    </div>
@{fi}

<!-- Social links -->
<div class="social">
    @{if APP.social_links.twitter}
        <a href="@{APP.social_links.twitter}">Twitter</a>
    @{fi}
    @{if APP.social_links.github}
        <a href="@{APP.social_links.github}">GitHub</a>
    @{fi}
</div>

Repository vs Data: What’s the Difference?

Repository Data (R. or repository.)

  • Available to all views called within the same handler function
  • Set using ctx.repository_set() before calling views
  • Ideal for shared UI elements, user info, theme settings
  • Lives for the duration of the handler function execution

View Data (Model)

  • Specific to each individual view call
  • Passed via ctx.view(template, data)
  • Accessed via @{model.key} or @{M.key} prefix
  • For page-specific content
  • Only available in that specific view call
  • Preferabily used for data flowing from db to form or vis versa

Example showing both:

#![allow(unused)]
fn main() {
async fn product_page(ctx: &mut Context) -> rustf::Result<()> {
    let id = ctx.param_as::<i64>("id")?;

    // Repository: page-level data, collections and flags -> @{R.key}
    ctx.repository_set("nav_items", get_navigation())
       .repository_set("user", get_current_user())
       .repository_set("cart_count", get_cart_count())
       .repository_set("reviews", get_reviews(id))
       .repository_set("related", get_related_products(id));

    // Model: ONE object, the product this page is about -> @{M.field}
    ctx.view("products/show", get_product(id))
}
}
<!-- Repository data accessible in the template -->
<nav>
    @{foreach item in R.nav_items}
        <a href="@{item.url}">@{item.title}</a>
    @{end}
    <span class="cart">Cart (@{R.cart_count})</span>
</nav>

<!-- View data (Model): the product itself -->
<h1>@{model.name}</h1>
<p>@{M.description}</p>
@{foreach review in R.reviews}
    <div class="review">@{review.text}</div>
@{end}

Repository Best Practices

  1. Use Context Repository for:

    • Data needed by multiple views within the same handler
    • User information for the current request
    • UI state for the current handler (theme, layout settings)
    • Temporary computed values used across view calls
    • Avoiding data duplication when rendering multiple views
  2. Use Global Repository (APP/MAIN) for:

    • Application metadata (name, version, copyright)
    • Site-wide configuration (features, limits)
    • Constants needed across the entire application
    • External service URLs and API keys (non-sensitive)
    • Data accessible throughout the application, not just in views
  3. Naming Conventions:

    #![allow(unused)]
    fn main() {
    // βœ… Good: Clear, semantic names
    ctx.repository_set("user_permissions", permissions);
    ctx.repository_set("page_metadata", metadata);
    
    // ❌ Bad: Generic or unclear names
    ctx.repository_set("data", something);
    ctx.repository_set("x", value);
    }
  4. Performance Considerations:

    • Context repository exists only during handler execution (keep it reasonable)
    • Global repository is shared application-wide (can hold more persistent data)
    • Context repository is cleared when handler returns
    • Global repository persists for the application’s lifetime
  5. Common Patterns:

    #![allow(unused)]
    fn main() {
    // Pattern 1: Set common data at the start of a handler
    async fn my_handler(ctx: &mut Context) -> rustf::Result<()> {
        // Set repository data first
        ctx.repository_set("user", get_current_user(&ctx)?);
        ctx.repository_set("notifications", get_notifications(&ctx)?);
        
        // Then render view(s) that need this data
        ctx.view("my_template", specific_data)
    }
    
    // Pattern 2: Use repository for feature flags
    ctx.repository_set("features", json!({
        "new_editor": is_feature_enabled("new_editor"),
        "beta_api": is_feature_enabled("beta_api")
    }));
    
    // Pattern 3: Breadcrumb builder
    ctx.repository_set("breadcrumbs", json!([
        {"label": "Home", "url": "/"},
        {"label": "Products", "url": "/products"},
        {"label": product.name, "url": null}  // Current page
    ]));
    }

Flash Messages

Flash messages are one-time messages that survive redirects but are automatically cleared when a view is rendered. They provide a clean way to show user feedback across page redirections.

Setting Flash Messages in Controllers

#![allow(unused)]
fn main() {
// Standard convenience methods
ctx.flash_success("User created successfully!");
ctx.flash_error("Invalid credentials");
ctx.flash_info("Please check your email");

// Generic flash setter for any key and serializable value
ctx.flash("warning_msg", "This is a warning")?;
ctx.flash("user_level", 42)?;
ctx.flash("notification", json!({
    "text": "You have new messages",
    "count": 5
}))?;
ctx.flash("recent_actions", vec!["Logged in", "Updated profile"])?;

// Manual flash management
ctx.flash_clear();                    // Clear all flash messages
ctx.flash_clear_key("error_msg");     // Clear specific flash message

// Typical usage pattern
if validation_failed {
    ctx.flash_error("Please correct the errors below");
    return ctx.redirect("/form");
}

ctx.flash_success("Form submitted successfully!");
ctx.redirect("/dashboard")
}

Accessing Flash Messages in Templates

Flash messages are stored in the session but are aliased for convenience, so you can access them directly using @{flash.xxx} instead of @{session.flash.xxx}:

<!-- Standard flash messages - Total.js -->
@{if flash.success}
    <div class="alert alert-success">@{flash.success}</div>
@{fi}

@{if flash.error}
    <div class="alert alert-error">@{flash.error}</div>
@{fi}

@{if flash.info}
    <div class="alert alert-info">@{flash.info}</div>
@{fi}

<!-- Custom flash messages -->
@{if flash.warning}
    <div class="alert alert-warning">@{flash.warning}</div>
@{fi}

<!-- Complex flash data -->
@{if flash.notification}
    <div class="notification">
        @{flash.notification.text}
        @{if flash.notification.count}
            <span class="badge">@{flash.notification.count}</span>
        @{fi}
    </div>
@{fi}

<!-- Array flash data -->
@{if flash.recent_actions}
    <div class="recent-actions">
        <h4>Recent Actions:</h4>
        <ul>
        @{foreach action in flash.recent_actions}
            <li>@{action}</li>
        @{end}
        </ul>
    </div>
@{fi}

<!-- Number flash data -->
@{if flash.user_level}
    <div class="user-level">Level: @{flash.user_level}</div>
@{fi}

Flash Message Lifecycle

  • Set in controller: Flash messages are stored in the session
  • Survive redirects: Messages persist through HTTP redirects
  • Auto-cleared on view render: Messages are automatically removed when any view is rendered
  • Manual clearing: Use flash_clear() or flash_clear_key() for explicit control

Best Practices

#![allow(unused)]
fn main() {
// βœ… Good: Use specific flash keys for different message types
ctx.flash("validation_error", "Email is required")?;
ctx.flash("success", "Account created")?;
ctx.flash("warning", "Trial period expires soon")?;

// βœ… Good: Clear flash before setting new messages in error scenarios
if let Err(e) = process_data() {
    ctx.flash_clear(); // Clear any existing flash
    ctx.flash_error(&format!("Processing failed: {}", e));
    return ctx.redirect("/retry");
}

// βœ… Good: Use structured data for complex notifications
ctx.flash("notification", json!({
    "type": "info",
    "title": "System Update",
    "message": "Maintenance scheduled for tonight",
    "actions": [{"text": "Learn More", "url": "/maintenance"}]
}))?;

// βœ… Good: Selective clearing for fine-grained control
ctx.flash_clear_key("error_msg"); // Keep other flash messages
ctx.flash_success("Operation completed!");
}

Static Asset Helpers

<!-- Total.js built-in helpers -->
@{css('/static/css/app.css')}
<!-- Renders: <link rel="stylesheet" href="/static/css/app.css"> -->

@{js('/static/js/app.js')}
<!-- Renders: <script src="/static/js/app.js"></script> -->

<!-- With root path -->
@{css(root + '/static/css/app.css')}
<!-- Renders: <link rel="stylesheet" href="/myapp/static/css/app.css"> -->

Translation & Internationalization (i18n)

RustF provides a Total.js-style translation system using resource files with automatic key generation and view-scoped translations.

Template Syntax

<!-- Direct text translation (key generated from text) -->
<h1>@(Welcome to our application)</h1>
<p>@(Please enter your credentials)</p>

<!-- Translation by custom key -->
<footer>@(#app.copyright)</footer>
<nav>@(#nav.home)</nav>

Resource File Format

Translation files use the .res extension and are stored in the resources/ directory:

# resources/default.res
[global]
# Common translations used across multiple views
save : "Save"
cancel : "Cancel"
loading : "Loading..."

[views/home/index]
# View-specific translations
welcome_to_our_application : "Welcome to our application"
please_enter_your_credentials : "Please enter your credentials"

[views/layouts/main]
# Layout translations
app.copyright : "Β© 2024 My Company"
nav.home : "Home"

Setting Up Translations

Loading translations in your application:

#![allow(unused)]
fn main() {
use rustf::prelude::*;
use rustf::views::TotalJsEngine;

// During app initialization
let engine = TotalJsEngine::new("views");

// Load translations from resources directory
engine.load_translations(Path::new("resources"))?;

// Or manually with resource translation system
use rustf::views::totaljs::resource_translation::ResourceTranslationSystem;

let mut translator = ResourceTranslationSystem::new();
translator.load_resources_dir(Path::new("resources"))?;
translator.set_language("fr");  // Switch to French
engine.set_resource_translator(translator);
}

Managing Translations with CLI

# Scan views and generate default.res with all discovered translations
rustf-cli translations scan

# Output:
# πŸ” Scanning views for translations...
# βœ… Generated resources/default.res with 45 translations

# Update existing language files with new keys
rustf-cli translations update --lang fr

# Output:
# πŸ”„ Regenerating default.res...
# πŸ“ Updating fr.res...
# πŸ“Š Update Report for fr.res:
#   βœ“ Existing translations preserved: 42
#   ⚠️  New keys needing translation: 3
#      - welcome_message
#      - user_greeting
#      - logout_confirm

# Check for missing translations
rustf-cli translations check --lang es

# Show translation statistics
rustf-cli translations stats

Translation Workflow

  1. Write views with translatable text:
<!-- views/home/index.html -->
<h1>@(Welcome to RustF)</h1>
<p>@(Build fast web applications)</p>
<div>@(#custom.message)</div>
  1. Generate translation keys:
rustf-cli translations scan
  1. Translate to other languages:
# Copy default to create language file
cp resources/default.res resources/fr.res

# Edit fr.res and translate the values
vim resources/fr.res
  1. View generated fr.res:
# resources/fr.res
[global]
save : "Enregistrer"
cancel : "Annuler"
loading : "Chargement..."

[views/home/index]
welcome_to_rustf : "Bienvenue Γ  RustF"
build_fast_web_applications : "Construire des applications web rapides"
custom.message : ""  # TODO: needs translation

Key Generation

  • Text in @(text) is converted to a readable slug key (max 30 chars)
  • Spaces become underscores, special characters removed
  • Common translations (appearing in 3+ views) are automatically moved to [global]
  • Custom keys using @(#key) are preserved as-is

Best Practices

  1. Use descriptive custom keys for important text:

    @(#app.title)       <!-- Good: Clear purpose -->
    @(#msg1)           <!-- Bad: Unclear -->
    
  2. Keep translations organized by view:

    • Each view gets its own section in the .res file
    • Layouts have their own sections
    • Common text automatically extracted to global
  3. Language switching in controllers:

    #![allow(unused)]
    fn main() {
    // Set language based on user preference
    if let Some(lang) = ctx.session_get("language") {
        engine.resource_translator.set_language(&lang);
    }
    }
  4. Fallback language support:

    #![allow(unused)]
    fn main() {
    translator.set_fallback("en");  // English as fallback
    }

Global VIEW API

RustF provides a global VIEW API for rendering templates from anywhere in your application without needing a Context instance. This is particularly useful for:

  • Email generation in background workers
  • PDF/report generation
  • Dynamic content rendering in services
  • Template rendering in middleware or utilities

Basic Usage

#![allow(unused)]
fn main() {
use rustf::prelude::*;
use serde_json::json;

// Render an inline template string
let html = VIEW::render_string(
    "Hello @{M.name}!",
    json!({"name": "Alice"}),
    None
)?;
// Output: "Hello Alice!"

// Render a template file
let html = VIEW::render(
    "emails/welcome",
    json!({"user": "Alice"}),
    None,
    Some("layouts/email")
)?;
}

Method Signatures

VIEW::render_string()

Render an inline template string with model and optional repository data.

#![allow(unused)]
fn main() {
pub fn render_string(
    template_string: &str,
    model: Value,
    repository: Option<Value>
) -> Result<String>
}

Parameters:

  • template_string: Template content as string
  • model: Main template data (accessible as @{M.key})
  • repository: Optional context data (accessible as @{R.key})

Example:

#![allow(unused)]
fn main() {
let template = "Welcome @{M.user}, your role is @{R.role}";
let model = json!({"user": "Alice"});
let repository = json!({"role": "Admin"});

let html = VIEW::render_string(template, model, Some(repository))?;
// Output: "Welcome Alice, your role is Admin"
}

VIEW::render()

Render a template file with model, repository, and optional layout.

#![allow(unused)]
fn main() {
pub fn render(
    template_path: &str,
    model: Value,
    repository: Option<Value>,
    layout: Option<&str>
) -> Result<String>
}

Parameters:

  • template_path: Path to template (relative to views directory, without extension)
  • model: Main template data (accessible as @{M.key})
  • repository: Optional context data (accessible as @{R.key})
  • layout: Optional layout template name

Example:

#![allow(unused)]
fn main() {
let html = VIEW::render(
    "reports/sales",
    json!({"month": "January", "total": 50000}),
    Some(json!({"company": "ACME Corp", "year": 2025})),
    Some("layouts/pdf")
)?;
}

Model vs Repository Data

The VIEW API maintains the same model/repository separation as controller rendering:

  • Model (@{M.key}): Primary template data - the main content
  • Repository (@{R.key}): Context/metadata - site config, user info, etc.
#![allow(unused)]
fn main() {
let model = json!({
    "product": "Widget",
    "price": 29.99,
    "quantity": 5
});

let repository = json!({
    "site_name": "My Store",
    "currency": "USD",
    "tax_rate": 0.08
});

let template = r#"
    <h1>@{R.site_name}</h1>
    <p>Product: @{M.product}</p>
    <p>Price: @{R.currency} @{M.price}</p>
"#;

let html = VIEW::render_string(template, model, Some(repository))?;
}

Use Cases

Email Generation in Workers

#![allow(unused)]
fn main() {
use rustf::prelude::*;

pub async fn send_welcome_email(ctx: WorkerContext) -> rustf::Result<()> {
    let email_template = r#"
        <html>
        <body>
            <h1>Welcome to @{R.app_name}!</h1>
            <p>Hello @{M.name},</p>
            <p>Thanks for signing up. Your username is: @{M.username}</p>
            <footer>&copy; @{R.year} @{R.company}</footer>
        </body>
        </html>
    "#;
    
    let model = json!({
        "name": ctx.data["name"],
        "username": ctx.data["username"]
    });
    
    let repository = json!({
        "app_name": "My App",
        "year": 2025,
        "company": "My Company Inc."
    });
    
    let html = VIEW::render_string(email_template, model, Some(repository))?;
    
    // Send email with html content
    send_email(&ctx.data["email"].as_str().unwrap(), &html).await?;
    Ok(())
}
}

Report Generation

#![allow(unused)]
fn main() {
use rustf::prelude::*;

pub fn generate_sales_report(sales_data: Vec<SaleRecord>) -> rustf::Result<String> {
    let template = r#"
        <h1>Sales Report - @{M.period}</h1>
        <table>
            <tr><th>Product</th><th>Units</th><th>Revenue</th></tr>
            @{foreach item in M.items}
            <tr>
                <td>@{item}</td>
                <td>@{item}</td>
                <td>$@{item}</td>
            </tr>
            @{end}
        </table>
        <p>Generated: @{R.generated_date}</p>
    "#;
    
    let model = json!({
        "period": "Q1 2025",
        "items": sales_data
    });
    
    let repository = json!({
        "generated_date": chrono::Utc::now().to_rfc3339()
    });
    
    VIEW::render_string(template, model, Some(repository))
}
}

Dynamic Content in Middleware

#![allow(unused)]
fn main() {
use rustf::prelude::*;

pub async fn render_error_page(status: u16, message: &str) -> rustf::Result<String> {
    let template = r#"
        <!DOCTYPE html>
        <html>
        <head><title>Error @{M.status}</title></head>
        <body>
            <h1>@{M.status} - @{M.title}</h1>
            <p>@{M.message}</p>
            <footer>@{R.app_name}</footer>
        </body>
        </html>
    "#;
    
    let model = json!({
        "status": status,
        "title": if status == 404 { "Not Found" } else { "Error" },
        "message": message
    });
    
    let repository = json!({
        "app_name": "My Application"
    });
    
    VIEW::render_string(template, model, Some(repository))
}
}

Template File Rendering

#![allow(unused)]
fn main() {
// views/emails/order_confirmation.html
// <h1>Order Confirmation</h1>
// <p>Thank you @{M.customer_name}!</p>
// <p>Order #@{M.order_id} has been confirmed.</p>

use rustf::prelude::*;

pub async fn send_order_confirmation(order: Order) -> rustf::Result<()> {
    let html = VIEW::render(
        "emails/order_confirmation",
        json!({
            "customer_name": order.customer_name,
            "order_id": order.id,
            "total": order.total
        }),
        Some(json!({
            "site_name": "My Shop",
            "support_email": "support@myshop.com"
        })),
        Some("layouts/email")  // Use email layout
    )?;
    
    send_email(&order.customer_email, &html).await?;
    Ok(())
}
}

Limitations

  1. No Session Data: Global VIEW API doesn’t have access to session data (use ctx.view() in controllers for session access)
  2. Initialization Required: VIEW must be initialized during app startup (automatic with auto_load())
  3. Template Features: All Total.js features work (conditionals, loops, variables, etc.)

Best Practices

  1. Use Model/Repository Separation: Keep template data (M) separate from context (R)
  2. Validate Before Rendering: Ensure data is complete before calling VIEW
  3. Handle Errors: Always handle Result from VIEW methods
  4. Cache Templates: Use file-based templates for better caching in production
  5. Test Rendering: Unit test your templates with VIEW::render_string()

Performance Tips

Development

[views]
cache_enabled = false  # Hot-reload templates

Production

[views]
cache_enabled = true   # Cache compiled templates
storage = "embedded"   # Embed templates in binary

Template Caching

Templates are automatically cached when cache_enabled = true:

  • First request compiles the template
  • Subsequent requests use cached version
  • No manual cache management needed

Directory Structure

views/
β”œβ”€β”€ layouts/
β”‚   └── application.html    # Main layout
β”œβ”€β”€ home/
β”‚   β”œβ”€β”€ index.html          # Homepage
β”‚   └── about.html          # About page
β”œβ”€β”€ auth/
β”‚   β”œβ”€β”€ login.html          # Login form
β”‚   └── register.html       # Registration
└── components/
    β”œβ”€β”€ navbar.html         # Reusable navbar
    └── footer.html         # Reusable footer

Error Handling

Template Not Found

#![allow(unused)]
fn main() {
// Graceful fallback
match ctx.view("missing-template", data) {
    Ok(response) => Ok(response),
    Err(_) => ctx.view("errors/404", json!({"message": "Page not found"}))
}
}

Syntax Errors

  • Total.js: Errors shown with line numbers during development

Note: Total.js is the only supported template engine in RustF. Tera and other engines are not supported.

Migration Guide

Coming From Tera (Syntax Cheat Sheet)

If you’re used to Tera, here’s how the equivalent Total.js syntax looks. (RustF itself does not run Tera β€” this table is only to ease the transition.)

Tera (other engine)Total.js (RustF)
{{ variable }}@{variable}
{% if condition %}@{if condition}
{% endif %}@{fi}
{% for item in items %}@{foreach item in items}
{% endfor %}@{end}
{{ var | escape }}@{var} (auto-escaped)
{{ var | safe }}@{!var}

Best Practices

  1. Use layouts - Define common structure once
  2. Escape user input - Use auto-escaping by default
  3. Cache in production - Enable template caching
  4. Organize templates - Group by feature/module
  5. Keep logic minimal - Complex logic belongs in controllers
  6. Use components - Create reusable template parts
  7. Validate data - Don’t trust template input
  8. Handle errors - Provide fallback templates

Troubleshooting

Templates Not Loading

  • Check views.directory in config.toml
  • Verify file extensions match views.extension
  • Ensure template names don’t include extension in controller

Variables Not Rendering

  • Check variable names match exactly
  • Verify data is passed to ctx.view()
  • Use @{json(variable)} to debug data structure

Layout Issues

  • Verify layout path is correct
  • Check @{content} placeholder exists in layout
  • Ensure child template specifies layout

Performance Issues

  • Enable cache_enabled in production
  • Use embedded storage for deployment
  • Minimize template complexity
  • Move heavy logic to controllers

Examples

Complete Controller with Views and Repositories

#![allow(unused)]
fn main() {
use rustf::prelude::*;

pub fn install() -> Vec<Route> {
    routes![
        GET  "/products"           => index,
        GET  "/products/{id}"      => show,
        POST "/products/{id}/buy"  => purchase,
    ]
}

async fn index(ctx: &mut Context) -> rustf::Result<()> {
    let products = vec![
        json!({"id": 1, "name": "Widget", "price": 19.99}),
        json!({"id": 2, "name": "Gadget", "price": 29.99}),
    ];

    // Set context repository for this page
    ctx.repository_set("view_mode", "grid")
       .repository_set("filters_available", json!(["price", "category", "brand"]))
       .repository_set("user_preferences", json!({
           "currency": "USD",
           "show_tax": true
       }));

    ctx.repository_set("title", "Our Products")
       .repository_set("products", json!(products))
       .repository_set("featured", true);

    // A list page has no single subject: empty model
    ctx.view("products/index", json!({}))
}

async fn show(ctx: &mut Context) -> rustf::Result<()> {
    let id = ctx.param_str("id")?;

    // Fetch product from database
    let product = json!({
        "id": id,
        "name": "Premium Widget",
        "price": 49.99,
        "description": "High-quality widget"
    });

    // Set repository data for product page
    ctx.repository_set("breadcrumbs", json!([
        {"name": "Home", "url": "/"},
        {"name": "Products", "url": "/products"},
        {"name": "Premium Widget", "url": null}
    ]))
    .repository_set("show_reviews", true)
    .repository_set("related_products_count", 5);

    ctx.view("products/show", product)
}

async fn purchase(ctx: &mut Context) -> rustf::Result<()> {
    let id = ctx.param_str("id")?;

    // Process purchase...

    ctx.flash_success("Purchase completed!")?;
    ctx.redirect(&format!("/products/{}", id))
}
}

Template with All Features Including Repositories

<!-- Page specific CSS -->
@{css('/static/css/products.css')}

<!-- Breadcrumbs from repository -->
@{if R.breadcrumbs}
    <nav class="breadcrumbs">
        @{foreach crumb in R.breadcrumbs}
            @{if crumb.url}
                <a href="@{crumb.url}">@{crumb.name}</a> /
            @{else}
                <span>@{crumb.name}</span>
            @{fi}
        @{end}
    </nav>
@{fi}

<div class="products-page view-@{R.view_mode}">
    <h1>@{R.title}</h1>
    
    <!-- Filters from repository -->
    @{if R.filters_available}
        <div class="filters">
            @{foreach filter in R.filters_available}
                <button class="filter-btn">Filter by @{filter}</button>
            @{end}
        </div>
    @{fi}
    
    <!-- User preferences from repository -->
    <div class="preferences">
        Currency: @{R.user_preferences.currency}
        @{if R.user_preferences.show_tax}
            <small>(Prices include tax)</small>
        @{fi}
    </div>
    
    <!-- Conditional rendering -->
    @{if R.featured}
        <div class="featured-banner">
            <p>Check out our featured products!</p>
        </div>
    @{fi}
    
    <!-- Loop through products -->
    <div class="product-grid">
        @{foreach product in R.products}
            <div class="product-card">
                <h3>@{product.name}</h3>
                <p class="price">@{format_price(product.price)}</p>
                <a href="@{root}/products/@{product.id}" class="btn">
                    View Details
                </a>
            </div>
        @{end}
    </div>
    
    <!-- Reviews section if enabled -->
    @{if R.show_reviews}
        <div class="reviews-section">
            <h2>Customer Reviews</h2>
            <!-- Reviews content -->
        </div>
    @{fi}
    
    <!-- Related products -->
    @{if R.related_products_count > 0}
        <div class="related">
            <p>See @{R.related_products_count} related products</p>
        </div>
    @{fi}
    
    <!-- Raw HTML inclusion -->
    @{if marketing_content}
        @{!marketing_content}
    @{fi}
</div>

<!-- Footer with global repository data -->
<footer>
    <p>@{APP.site_name} v@{APP.version}</p>
    <p>@{MAIN.copyright}</p>
    <p>Contact: @{APP.contact_email}</p>
</footer>

<!-- Page specific JS -->
@{js('/static/js/products.js')}

This documentation provides a complete guide to using the RustF view system with practical examples and best practices for the Total.js template engine (the only supported engine).

RustF Middleware System Documentation

Overview

RustF provides a comprehensive dual-phase middleware system that separates request processing from response modification. This architecture provides clear separation of concerns and predictable execution order, making it highly suitable for AI-assisted development.

Core Architecture

Dual-Phase Processing

The middleware system operates in two distinct phases:

  1. Inbound Phase - Processes incoming requests before they reach controllers
  2. Outbound Phase - Modifies responses after controllers have executed

This separation allows middleware to cleanly handle both request validation/transformation and response enhancement without complex state management.

Core Components

InboundMiddleware Trait

Processes requests before they reach controllers:

#![allow(unused)]
fn main() {
use async_trait::async_trait;

#[async_trait]
pub trait InboundMiddleware: Send + Sync + 'static {
    async fn process_request(&self, ctx: &mut Context) -> Result<InboundAction>;
    
    fn name(&self) -> &'static str { "unnamed" }
    fn priority(&self) -> i32 { 0 }
    fn should_run(&self, ctx: &Context) -> bool { true }
}
}

Key Methods:

  • process_request() - Main processing logic for incoming requests
  • name() - Identifies the middleware for debugging/logging
  • priority() - Execution order (lower numbers run first, -1000 to 1000)
  • should_run() - Conditional execution based on request context

InboundAction Enum

Inbound middleware returns one of three actions:

#![allow(unused)]
fn main() {
pub enum InboundAction {
    Continue,           // Continue to next middleware
    Stop,               // Stop chain and return response set on context
    Capture,           // Continue but process response later
}
}
  • Continue - Pass request to next middleware without capturing response
  • Stop - Stop processing and return the response that was set on context using response helpers
  • Capture - Continue processing but ensure outbound phase runs

OutboundMiddleware Trait

Modifies responses after controllers execute:

#![allow(unused)]
fn main() {
use async_trait::async_trait;

#[async_trait]
pub trait OutboundMiddleware: Send + Sync + 'static {
    async fn process_response(&self, ctx: &mut Context) -> Result<()>;
}
}

Important Change: The outbound middleware now receives &mut Context instead of separate context and response parameters. The response is accessed and modified through ctx.res field.

DualPhaseMiddleware Trait

For middleware that needs both phases:

#![allow(unused)]
fn main() {
pub trait DualPhaseMiddleware: InboundMiddleware + OutboundMiddleware {}
}

Any type implementing both traits automatically implements DualPhaseMiddleware.

⚠️ Critical: Async Middleware Requirements

IMPORTANT: All middleware in RustF MUST be async to prevent application hangs:

  1. Always use #[async_trait] - Required for all middleware trait implementations
  2. Never use block_on - Using futures::executor::block_on will cause the application to hang, especially with database storage
  3. All I/O operations must be async - Session operations, database queries, and network calls must use async/await

Why This Matters

The middleware system was redesigned to be fully async to fix a critical issue where applications would hang when using database-backed session storage. The previous implementation used block_on which blocked the async runtime, causing deadlocks with connection pools and async I/O operations.

Writing Middleware

Simple Inbound Middleware

#![allow(unused)]
fn main() {
use rustf::middleware::{InboundMiddleware, InboundAction};
use rustf::context::Context;
use rustf::error::Result;
use async_trait::async_trait;

pub struct AuthMiddleware {
    required_role: String,
}

#[async_trait]
impl InboundMiddleware for AuthMiddleware {
    async fn process_request(&self, ctx: &mut Context) -> Result<InboundAction> {
        // Check authentication
        if let Some(user) = ctx.session_get::<User>("user") {
            if user.role == self.required_role {
                return Ok(InboundAction::Continue);
            }
        }
        
        // Not authorized - use context helpers to set response
        ctx.throw403(Some("Unauthorized"))?;
        Ok(InboundAction::Stop)
    }
    
    fn name(&self) -> &'static str {
        "auth"
    }
    
    fn priority(&self) -> i32 {
        -500  // Run early (lower numbers execute first)
    }
}
}

Simple Outbound Middleware

#![allow(unused)]
fn main() {
use rustf::middleware::OutboundMiddleware;
use rustf::context::Context;
use rustf::error::Result;
use async_trait::async_trait;

pub struct CompressionMiddleware;

#[async_trait]
impl OutboundMiddleware for CompressionMiddleware {
    async fn process_response(&self, ctx: &mut Context) -> Result<()> {
        // Access the response through ctx.res
        if let Some(response) = ctx.res.as_mut() {
            // Add compression headers
            response.headers.push((
                "Content-Encoding".to_string(),
                "gzip".to_string()
            ));
            
            // Compress body (simplified)
            // response.body = compress(response.body);
        }
        
        Ok(())
    }
}
}

Dual-Phase Middleware

#![allow(unused)]
fn main() {
use rustf::middleware::{InboundMiddleware, OutboundMiddleware, InboundAction};
use async_trait::async_trait;
use std::time::Instant;

pub struct TimingMiddleware;

#[async_trait]
impl InboundMiddleware for TimingMiddleware {
    async fn process_request(&self, ctx: &mut Context) -> Result<InboundAction> {
        // Store start time
        ctx.set("request_start", Instant::now());
        
        // Capture response to add timing header
        Ok(InboundAction::Capture)
    }
}

#[async_trait]
impl OutboundMiddleware for TimingMiddleware {
    async fn process_response(&self, ctx: &mut Context) -> Result<()> {
        if let Some(start) = ctx.get::<Instant>("request_start") {
            let duration = start.elapsed();
            
            // Access response through ctx.res
            if let Some(response) = ctx.res.as_mut() {
                response.headers.push((
                    "X-Response-Time".to_string(),
                    format!("{}ms", duration.as_millis())
                ));
            }
        }
        Ok(())
    }
}
}

Registration

Basic Registration

There are three ways to register middleware in RustF:

Place your middleware in src/middleware/*.rs with an install function:

#![allow(unused)]
fn main() {
// src/middleware/auth.rs
pub fn install(registry: &mut MiddlewareRegistry) {
    registry.register_inbound("auth", AuthMiddleware::new());
}

// In main.rs
let app = RustF::new()
    .middleware_from(auto_middleware!()); // Auto-discovers all middleware
}

Method 2: Manual Registration with middleware_from

#![allow(unused)]
fn main() {
let app = RustF::new()
    .middleware_from(|registry| {
        // Register inbound middleware
        registry.register_inbound("auth", AuthMiddleware::new());
        
        // Register outbound middleware  
        registry.register_outbound("compression", CompressionMiddleware);
        
        // Register dual-phase middleware
        registry.register_dual("timing", TimingMiddleware);
    });
}

Method 3: Registration via middleware_from

The middleware registry is private, so it is registered to through the .middleware_from(...) builder method, which hands you the registry:

#![allow(unused)]
fn main() {
let app = RustF::new()
    .middleware_from(|registry| {
        // Register inbound middleware
        registry.register_inbound("auth", AuthMiddleware::new());

        // Register outbound middleware
        registry.register_outbound("compression", CompressionMiddleware);

        // Register dual-phase middleware
        registry.register_dual("timing", TimingMiddleware);
    });
}

Setting Middleware Priority

Priority is set by implementing the priority() method in your middleware trait implementation. Lower numbers execute first (range: -1000 to 1000).

#![allow(unused)]
fn main() {
use async_trait::async_trait;

#[async_trait]
impl InboundMiddleware for AuthMiddleware {
    async fn process_request(&self, ctx: &mut Context) -> Result<InboundAction> {
        // Your middleware logic here
        Ok(InboundAction::Continue)
    }
    
    fn priority(&self) -> i32 {
        -500  // Runs early in the chain
    }
}

// Example: Multiple middleware with different priorities
#[async_trait]
impl InboundMiddleware for LoggingMiddleware {
    async fn process_request(&self, ctx: &mut Context) -> Result<InboundAction> {
        // Log request
        Ok(InboundAction::Continue)
    }
    
    fn priority(&self) -> i32 {
        -1000  // Highest priority, runs first
    }
}

#[async_trait]
impl InboundMiddleware for RateLimitMiddleware {
    async fn process_request(&self, ctx: &mut Context) -> Result<InboundAction> {
        // Check rate limits
        Ok(InboundAction::Continue)
    }
    
    fn priority(&self) -> i32 {
        -900  // Runs after logging but before auth
    }
}
}

Default Security Middleware

RustF provides built-in security middleware that can be enabled with one call:

#![allow(unused)]
fn main() {
let app = RustF::new()
    .with_default_security();  // Enables security headers, input validation, CSP
}

Or configure individually using middleware_from:

#![allow(unused)]
fn main() {
let app = RustF::new()
    .middleware_from(|registry| {
        registry.register_outbound("security_headers", SecurityHeadersMiddleware::new());
        registry.register_inbound("input_validation", InputValidationMiddleware::new());
        registry.register_dual("csp", CspMiddleware::permissive());
        registry.register_inbound("rate_limit", RateLimitMiddleware::new());
    });
}

Built-in Middleware

Note: All built-in middleware properly implement async traits without any blocking operations. They are safe to use with database-backed session storage and other async I/O operations.

Security Middleware

  1. SecurityHeadersMiddleware (Outbound)

    • Adds comprehensive security headers (X-Frame-Options, X-Content-Type-Options, etc.)
    • Configurable for development/production environments
  2. InputValidationMiddleware (Inbound)

    • Validates input for SQL injection, XSS, path traversal
    • Configurable patterns and exclusions
  3. CspMiddleware (Dual-Phase)

    • Content Security Policy with nonce generation
    • Inbound: generates nonces for inline scripts/styles
    • Outbound: adds CSP headers with nonces
  4. RateLimitMiddleware (Inbound)

    • IP-based rate limiting with configurable windows
    • DashMap-based for thread-safe operation
    • Automatic cleanup of old entries

Utility Middleware

  1. LoggingMiddleware (Dual-Phase)

    • Logs requests with timing information
    • Inbound: logs incoming request
    • Outbound: logs response with duration
  2. CorsMiddleware (Dual-Phase)

    • Handles CORS preflight and headers
    • Inbound: responds to OPTIONS requests
    • Outbound: adds CORS headers to responses
  3. SessionMiddleware (Dual-Phase)

    • Session management with cookie handling
    • Inbound: loads session from cookie (async, no blocking)
    • Outbound: saves session to cookie (async, no blocking)
    • Fixed: Previously used block_on causing hangs with database storage - now fully async
  4. ValidationMiddleware (Inbound)

    • Form validation with configurable rules
    • CSRF protection integration
    • Automatic error response generation
  5. CompressionMiddleware (Outbound)

    • Gzip-compresses responses when the client sends Accept-Encoding: gzip
    • Skips bodies < 256 B, non-compressible content-types, and already-encoded responses
    • Adds Content-Encoding: gzip and Vary: Accept-Encoding headers; updates Content-Length
    • Opt-in builder: RustF::new().with_compression() (registers the middleware for you)
    • Configurable compression level via CompressionMiddleware::fast() / ::best() / ::new() (default level 6)
  6. MethodOverrideMiddleware (Inbound)

    • Upgrades a POST request to PUT, PATCH, or DELETE when the body or query carries _method=<METHOD>
    • Standard convention used by Rails / Express / Phoenix to make HTML forms expressive (browsers only natively send GET and POST)
    • Reads _method from the query string OR from application/x-www-form-urlencoded body β€” JSON bodies that incidentally contain _method are NOT touched
    • Required for the HTML forms emitted by rustf-cli new crud to work as-is
    • Opt-in builder: RustF::new().with_method_override()

Builder helpers for opt-in middleware

Some built-ins are registered via dedicated builder methods on RustF rather than auto_load_with(&[...]) strings, because they are commonly toggled on/off per project:

#![allow(unused)]
fn main() {
let app = RustF::with_args()?
    .auto_load()                  // builtin mw via config + auto-discovery
    .with_compression()           // gzip, opt-in
    .with_method_override();      // _method=PUT/DELETE for HTML forms
}

Both helpers are no-ops if you don’t call them β€” fully opt-in.

Execution Order

Priority System

Middleware executes based on priority (lower numbers first):

-1000: Logging (capture everything)
 -900: Rate limiting (block early)
 -800: Security headers
 -700: CSP 
 -600: Input validation
 -500: CORS
 -400: Authentication
 -300: Session loading
    0: Default priority
 +100: Business logic
 +500: Caching
+1000: Final cleanup

Phase Execution

  1. Inbound Phase (before controller):

    • Middleware sorted by priority (ascending)
    • Each middleware’s should_run() checked
    • process_request() called sequentially
    • Chain stops if any returns Stop (using response set on context)
  2. Controller Execution:

    • Only if all inbound middleware returned Continue or Capture
  3. Outbound Phase (after controller):

    • Only for middleware that returned Capture or registered as outbound
    • Executes in reverse order of inbound
    • Each modifies response in place

Accessing Response in Outbound Phase

With the new architecture, outbound middleware accesses the response through the Context’s res field:

Response Access Pattern

#![allow(unused)]
fn main() {
#[async_trait]
impl OutboundMiddleware for MyMiddleware {
    async fn process_response(&self, ctx: &mut Context) -> Result<()> {
        // The response might be None if an error occurred
        if let Some(response) = ctx.res.as_mut() {
            // Modify response headers
            response.headers.push(("X-Custom".to_string(), "value".to_string()));
            
            // Check status
            if response.status.is_server_error() {
                // Handle error responses differently
                response.headers.push(("X-Error".to_string(), "true".to_string()));
            }
            
            // Modify body if needed
            if response.status == StatusCode::OK {
                // Can inspect or modify response.body
            }
        }
        Ok(())
    }
}
}

When Response Might Be None

The response field will be None in rare cases:

  • If a panic occurred before the response was set
  • If middleware or handler failed to set any response

In practice, the framework ensures a response is always set, even for errors.

Important Notes

  1. InboundAction::Stop - Uses the response set on context via helpers like ctx.json(), ctx.throw403(), etc.
  2. Handler Responses - Controllers set response via ctx.json(), ctx.view(), etc.
  3. Error Responses - Error methods like ctx.throw404() also set the response
  4. Middleware Order - Outbound middleware runs in reverse order of inbound
  5. Context Initialization - Context now initializes with a default 200 OK response, enabling response helpers everywhere

Advanced Patterns

Conditional Middleware

#![allow(unused)]
fn main() {
use async_trait::async_trait;

#[async_trait]
impl InboundMiddleware for ApiAuthMiddleware {
    fn should_run(&self, ctx: &Context) -> bool {
        // Only run for API routes
        ctx.req.uri.starts_with("/api/")
    }
    
    async fn process_request(&self, ctx: &mut Context) -> Result<InboundAction> {
        // API authentication logic
        Ok(InboundAction::Continue)
    }
}
}

State Sharing Between Phases

#![allow(unused)]
fn main() {
use async_trait::async_trait;

#[async_trait]
impl InboundMiddleware for MetricsMiddleware {
    async fn process_request(&self, ctx: &mut Context) -> Result<InboundAction> {
        // Store request data for metrics
        ctx.set("metrics_start", Instant::now())?;
        ctx.set("metrics_path", ctx.req.uri.clone())?;
        
        Ok(InboundAction::Capture)
    }
}

#[async_trait]
impl OutboundMiddleware for MetricsMiddleware {
    async fn process_response(&self, ctx: &mut Context) -> Result<()> {
        if let Some(start) = ctx.get::<Instant>("metrics_start") {
            let path = ctx.get::<String>("metrics_path").cloned().unwrap_or_default();
            let duration = start.elapsed();
            
            // Get status from response
            let status = ctx.res.as_ref()
                .map(|r| r.status.as_u16())
                .unwrap_or(500);
            
            // Record metrics
            record_metric(&path, status, duration);
        }
        Ok(())
    }
}
}

Early Response Pattern

#![allow(unused)]
fn main() {
use async_trait::async_trait;

#[async_trait]
impl InboundMiddleware for CacheMiddleware {
    async fn process_request(&self, ctx: &mut Context) -> Result<InboundAction> {
        let cache_key = generate_cache_key(&ctx.req);
        
        if let Some(cached) = self.cache.get(&cache_key) {
            // Return cached response immediately
            ctx.set_response(cached);
            return Ok(InboundAction::Stop);
        }
        
        // Store key for outbound phase
        ctx.set("cache_key", cache_key)?;
        Ok(InboundAction::Capture)
    }
}
}

Testing Middleware

#![allow(unused)]
fn main() {
#[cfg(test)]
mod tests {
    use super::*;
    use rustf::http::Request;
    use rustf::views::ViewEngine;
    use std::sync::Arc;
    
    #[tokio::test]
    async fn test_auth_middleware() {
        let middleware = AuthMiddleware::new("admin");
        
        // Create test context
        let request = Request::default();
        let views = Arc::new(ViewEngine::from_directory("views"));
        let mut ctx = Context::new(request, views);
        
        // Test without auth
        let action = middleware.process_request(&mut ctx).await.unwrap();
        assert!(matches!(action, InboundAction::Stop));
        // Check that response was set on context
        assert!(ctx.res.is_some());
        
        // Test with auth
        ctx.session_set("user", User { role: "admin".into() });
        let action = middleware.process_request(&mut ctx).await.unwrap();
        assert!(matches!(action, InboundAction::Continue));
    }
    
    #[tokio::test]
    async fn test_outbound_middleware() {
        let middleware = CompressionMiddleware;
        
        // Create test context with response
        let request = Request::default();
        let views = Arc::new(ViewEngine::from_directory("views"));
        let mut ctx = Context::new(request, views);
        
        // Process response
        middleware.process_response(&mut ctx).await.unwrap();
        
        // Verify headers were added
        if let Some(response) = &ctx.res {
            let has_encoding = response.headers.iter()
                .any(|(k, _)| k == "Content-Encoding");
            assert!(has_encoding);
        }
    }
}
}

Best Practices

  1. Use appropriate phase:

    • Input validation β†’ Inbound
    • Response headers β†’ Outbound
    • Timing/metrics β†’ Dual-phase
  2. Set meaningful priorities:

    • Security checks: -900 to -500
    • Business logic: -100 to +100
    • Response modification: +500 to +900
  3. Minimize state in middleware:

    • Use context for request-scoped data
    • Use Arc for shared immutable data
  4. Handle errors gracefully:

    • Return appropriate HTTP status codes
    • Log errors for debugging
  5. Keep middleware focused:

    • Single responsibility principle
    • Compose multiple middleware for complex logic

Migration from Express/Total.js

Express/Total.jsRustF Equivalent
app.use(middleware)registry.register_inbound() or registry.register_dual()
next()Ok(InboundAction::Continue)
res.send() in middlewareSet response on context, return Ok(InboundAction::Stop)
Error middlewareImplement error handling in middleware
Route-specific middlewareUse should_run() method
Middleware priority/orderImplement priority() method (lower = earlier)
Synchronous middlewareAll middleware MUST be async in RustF

Migration from Old RustF Blocking Middleware

If you have existing RustF middleware using the old blocking pattern:

Old Pattern (DEPRECATED - Will cause hangs)

#![allow(unused)]
fn main() {
// DON'T DO THIS - Will cause application hangs
impl InboundMiddleware for MyMiddleware {
    fn process_request(&self, ctx: &mut Context) -> Result<InboundAction> {
        // This would use block_on internally for async operations
        let session = futures::executor::block_on(load_session()); // WRONG!
        Ok(InboundAction::Continue)
    }
}
}

New Async Pattern (REQUIRED)

#![allow(unused)]
fn main() {
use async_trait::async_trait;

#[async_trait]
impl InboundMiddleware for MyMiddleware {
    async fn process_request(&self, ctx: &mut Context) -> Result<InboundAction> {
        // Properly await async operations
        let session = load_session().await?; // CORRECT!
        Ok(InboundAction::Continue)
    }
}
}

Key Changes

  1. Add #[async_trait] to all middleware implementations
  2. Change fn to async fn for process methods
  3. Replace any block_on calls with .await
  4. Ensure all I/O operations use async versions

AI Development Guidelines

When developing middleware with AI assistance:

  1. Always use async traits:

    • Include use async_trait::async_trait; at the top
    • Add #[async_trait] before every middleware impl block
    • Use async fn for process_request() and process_response()
  2. Never use blocking operations:

    • CRITICAL: Never use futures::executor::block_on - it will hang the application
    • All I/O operations must be async (database, file system, network)
    • Session operations are async - use .await properly
  3. Specify the phase: Clearly indicate if middleware should be inbound, outbound, or dual-phase

  4. Define the action: Specify when to Continue, Stop, or Capture

  5. Set priorities: Indicate relative execution order needs (-1000 to 1000)

  6. Handle errors: Specify error response formats

  7. Use built-in middleware: Leverage existing security middleware when applicable

  8. Test thoroughly:

    • Use #[tokio::test] for async tests
    • Test both phases if dual-phase
    • Verify .await is used for all async operations

Example AI Prompt

Create an authentication middleware that:
- Runs in the inbound phase only
- Checks for JWT token in Authorization header
- Uses async database queries to validate user
- Returns 401 if unauthorized
- Has priority -400 (after rate limiting)
- MUST use async/await pattern

Conclusion

The RustF dual-phase middleware system provides a clean, predictable architecture for request/response processing. The separation of inbound and outbound phases eliminates complex state management while maintaining the flexibility needed for sophisticated middleware implementations.

RustF Session System Documentation

Overview

RustF provides a comprehensive session management system with support for multiple storage backends, flash messages, and thread-safe concurrent access. The session system is designed to handle both persistent data and temporary flash messages with automatic expiration and cleanup.

New in 2025: Custom session storage can now be implemented via the Definitions System, providing a simpler, convention-based approach. See Custom Session Storage via Definitions for details.

Core Components

Session Data Structure

The Session struct stores its data as JSON (serde_json::Value) behind an RwLock, which is zero-copy for template rendering and storage backends:

#![allow(unused)]
fn main() {
pub struct Session {
    id: String,
    data: Arc<RwLock<serde_json::Value>>,   // Persistent session data (JSON)
    flash: Arc<RwLock<serde_json::Value>>,  // Flash messages (consumed when read)
    // ... plus fingerprint, timeouts, privilege level, and dirty/rotation flags
}
}

Note: Sessions are not backed by DashMap. The framework’s lock-free DashMap usage applies to the session store (the manager that holds many sessions), not to an individual Session’s data, which uses RwLock over a single JSON value.

Session Storage Backends

RustF supports multiple storage backends through the SessionStorage trait:

  • Memory Storage - Fast in-memory storage with automatic cleanup (implemented, default)
  • Redis Storage - Persistent, cross-instance storage with connection pooling (implemented; on by default via the redis Cargo feature). This is the only built-in backend that lets multiple RustF instances share sessions; if you disable the redis feature, supply a custom SessionStorage.
  • Database Storage - Planned but not yet implemented (configuration exists)

Basic Session Usage

Accessing Session in Controllers

Sessions are available through the Context object in controllers:

#![allow(unused)]
fn main() {
use rustf::prelude::*;

async fn login(ctx: &mut Context) -> rustf::Result<()> {
    // Set session data
    ctx.session_set("user_id", 123)?;
    ctx.session_set("username", "john_doe")?;

    // Get session data
    let user_id: Option<i32> = ctx.session_get("user_id");
    let username: Option<String> = ctx.session_get("username");

    ctx.json(json!({
        "message": "Login successful",
        "user_id": user_id,
        "username": username
    }))
}

async fn logout(ctx: &mut Context) -> rustf::Result<()> {
    // Canonical logout path: destroy the current authenticated session
    ctx.logout()?;

    ctx.flash_success("You have been logged out successfully")?;
    ctx.redirect("/login")
}
}

Session Data Types

Sessions support any serializable data type:

#![allow(unused)]
fn main() {
// Basic types
ctx.session_set("counter", 42)?;
ctx.session_set("is_admin", true)?;
ctx.session_set("email", "user@example.com")?;

// Complex types
let user_data = json!({
    "id": 123,
    "roles": ["user", "moderator"],
    "preferences": {
        "theme": "dark",
        "language": "en"
    }
});
ctx.session_set("user", user_data)?;

// Custom structs (must implement Serialize/Deserialize)
#[derive(Serialize, Deserialize)]
struct UserProfile {
    id: i32,
    name: String,
    preferences: HashMap<String, String>,
}

let profile = UserProfile { /* ... */ };
ctx.session_set("profile", profile)?;
}

Flash Messages

Flash messages are temporary messages that are consumed when read, perfect for displaying one-time notifications.

Setting Flash Messages

#![allow(unused)]
fn main() {
// Convenience methods for common message types
ctx.flash_success("Account created successfully!")?;
ctx.flash_error("Invalid credentials")?;
ctx.flash_info("Please verify your email")?;

// Custom flash messages (the method is `flash`, not `flash_set`)
ctx.flash("warning", "Your session will expire soon")?;
ctx.flash("custom_data", json!({"type": "notification", "data": 123}))?;
}

Reading Flash Messages

Flash messages are automatically consumed when read:

#![allow(unused)]
fn main() {
// Get specific flash message (consumes it)
let error_msg: Option<Value> = ctx.get_flash("error");
let success_msg: Option<Value> = ctx.get_flash("success");

// Get all flash messages at once (consumes all)
let all_flash: HashMap<String, Value> = ctx.get_all_flash();
}

Flash Messages in Views

Flash messages are automatically included in view contexts:

<!-- views/layouts/default.html -->
<!DOCTYPE html>
<html>
<head>
    <title>My App</title>
</head>
<body>
    <!-- Flash messages are available in 'flash' variable -->
    @{if flash.success}
        <div class="alert alert-success">@{flash.success}</div>
    @{fi}

    @{if flash.error}
        <div class="alert alert-error">@{flash.error}</div>
    @{fi}

    @{if flash.info}
        <div class="alert alert-info">@{flash.info}</div>
    @{fi}

</body>
</html>

Session Configuration

Default Memory Storage

The default session store uses in-memory storage with automatic cleanup:

#![allow(unused)]
fn main() {
// Default configuration (30 minutes timeout, 5 minutes cleanup interval)
let app = RustF::new(); // Uses MemorySessionStorage by default
}

Custom Memory Storage

#![allow(unused)]
fn main() {
use rustf::session::storage::MemorySessionStorage;
use std::time::Duration;

// Custom timeout settings
let storage = MemorySessionStorage::with_timeout(
    Duration::from_secs(60 * 60),    // 1 hour session timeout
    Duration::from_secs(10 * 60)     // 10 minutes cleanup interval
);

let session_store = SessionStore::with_storage(Arc::new(storage));
}

Redis Storage

For production environments, use Redis for persistent session storage:

The simplest way to enable Redis sessions is through configuration β€” set the session storage type to redis in config.toml and the framework wires the session middleware automatically (see Configuration below).

To build the storage explicitly and register your own session middleware, use SessionMiddleware::with_storage(...). Note that RedisSessionStorage::from_url takes seven arguments:

use rustf::session::redis::RedisSessionStorage;
use rustf::session::FingerprintMode;
use rustf::session::manager::SessionConfig;
use rustf::middleware::builtin::SessionMiddleware;
use std::sync::Arc;
use std::time::Duration;

#[tokio::main]
async fn main() -> rustf::Result<()> {
    // Default Redis connection (redis://localhost:6379)
    let redis_storage = RedisSessionStorage::new().await?;

    // Custom Redis configuration (7 args)
    let redis_storage = RedisSessionStorage::from_url(
        "redis://localhost:6379",       // redis_url
        "myapp:session:",               // prefix
        20,                             // pool_size
        FingerprintMode::Soft,          // fingerprint_mode
        Duration::from_secs(30 * 60),   // default_ttl
        Duration::from_secs(5),         // connection_timeout
        Duration::from_secs(5),         // command_timeout
    ).await?;

    // Register a session middleware backed by this storage:
    let session_mw =
        SessionMiddleware::with_storage(Arc::new(redis_storage), SessionConfig::default());

    RustF::new()
        .controllers(auto_controllers!())
        .middleware_from(move |registry| {
            registry.register_dual("session", session_mw.clone());
        })
        .serve(None)
        .await
}

Note: There is no app.with_session_store(...) builder method. Session storage is selected via config.toml (which auto-registers the middleware) or by registering SessionMiddleware::with_storage(...) yourself as shown above.

Session Lifecycle Management

Standard Session Methods

RustF provides industry-standard session lifecycle methods:

MethodPurposeScopeWhen to Use
clear()Remove all data, keep session activeMemory onlyPartial logout, data reset
flush()Alias for clear()Memory onlyLaravel compatibility
destroy()Mark for destruction, clear dataMemory onlyLocal cleanup
regenerate_id()New ID, keep dataMemory onlySecurity after login

SessionStore Methods (with Storage)

MethodPurposeScopeWhen to Use
destroy_session()Complete removalMemory + StorageFull logout, security breach
regenerate_session_id()New ID + storage updateMemory + StorageSession fixation protection
clear_session()Clear data, keep in storageMemory + StorageReset user data

Usage Examples

#![allow(unused)]
fn main() {
// Partial logout - clear data but keep session for analytics
ctx.session_clear();

// Complete logout - remove session entirely
// (requires access to SessionStore)
session_store.destroy_session(&session_id).await?;

// Security after login - regenerate ID to prevent fixation
session.regenerate_id();

// Or with storage backend update
if let Some(new_session) = session_store.regenerate_session_id(&old_id).await? {
    // Session ID changed, update any client-side references
    log::info!("New session ID: {}", new_session.id());
}
}

Session Security

Session ID Generation

Session IDs are cryptographically secure 32-character alphanumeric strings:

#![allow(unused)]
fn main() {
// Automatically generated for each new session
let session_id = storage.generate_id(); // e.g., "a7b8c9d0e1f2g3h4i5j6k7l8m9n0o1p2"
}

Session Expiration

Sessions automatically expire based on last access time:

#![allow(unused)]
fn main() {
// Configure session timeout
let storage = MemorySessionStorage::with_timeout(
    Duration::from_secs(30 * 60), // 30 minutes of inactivity
    Duration::from_secs(5 * 60)   // Cleanup every 5 minutes
);
}

Session Cleanup

Both storage backends handle automatic cleanup:

  • Memory Storage: Background task removes expired sessions
  • Redis Storage: Redis TTL automatically expires sessions
#![allow(unused)]
fn main() {
// Manual cleanup (returns number of sessions cleaned)
let cleaned_count = session_store.cleanup_expired().await?;
log::info!("Cleaned up {} expired sessions", cleaned_count);
}

RustF now provides a modern, convention-based approach to implementing custom session storage through the Definitions System. This is the recommended method for adding database or custom storage backends.

Quick Setup with Definitions

Step 1: Create Session Storage Definition

Create src/definitions/session_storage.rs:

#![allow(unused)]
fn main() {
use rustf::definitions::Definitions;
use rustf::session::{SessionStorage, SessionData, StorageStats};
use rustf::config::SessionConfig;
use rustf::error::Result;
use async_trait::async_trait;
use sqlx::PgPool;
use std::sync::Arc;
use std::time::Duration;

/// Install function called by auto-discovery
/// This MUST be present in every definitions file
pub fn install(defs: &mut Definitions) {
    log::info!("Installing custom session storage from definitions");
    defs.set_session_storage_factory(create_session_storage);
}

/// Factory function that creates our custom session storage
/// This is called by the framework when initializing sessions
fn create_session_storage(
    config: &SessionConfig
) -> Result<Arc<dyn SessionStorage>> {
    // Get database URL from environment or config
    let database_url = std::env::var("DATABASE_URL")
        .unwrap_or_else(|_| "postgresql://localhost/myapp".to_string());

    // Create your custom storage
    let storage = PostgresSessionStorage::new(&database_url)?;
    Ok(Arc::new(storage))
}

// Your SessionStorage implementation (see detailed example below)
pub struct PostgresSessionStorage {
    pool: PgPool,
}

// ... implement SessionStorage trait (see complete example in previous section)
}

Step 2: Use Auto-Discovery

In your main.rs:

#[rustf::auto_discover]
#[tokio::main]
async fn main() -> rustf::Result<()> {
    let app = RustF::new()
        .definitions_from(auto_definitions!())  // Automatically finds session_storage.rs
        .controllers(auto_controllers!());

    // Your custom session storage is now active!
    app.start().await
}

That’s it! Your custom session storage is automatically discovered and integrated.

Important: The install() function is mandatory - it’s how the auto-discovery system knows what to register.

Benefits of the Definitions Approach

  1. Zero Configuration - Just create the file in the right place
  2. Auto-Discovery - No manual registration needed
  3. Convention-Based - Follow the pattern, it just works
  4. Type-Safe - Compile-time checking of your implementation
  5. Testable - Easy to unit test in isolation

Complete Example: PostgreSQL Storage via Definitions

Here’s a complete, production-ready implementation using the definitions system:

#![allow(unused)]
fn main() {
// src/definitions/session_storage.rs
use rustf::definitions::Definitions;
use rustf::session::{SessionStorage, SessionData, StorageStats};
use rustf::config::SessionConfig;
use rustf::error::Result;
use async_trait::async_trait;
use sqlx::{PgPool, postgres::PgPoolOptions};
use std::sync::Arc;
use std::time::Duration;
use std::collections::HashMap;
use serde_json;

/// Install function called by auto-discovery - REQUIRED!
pub fn install(defs: &mut Definitions) {
    log::info!("Installing PostgreSQL session storage from definitions");
    defs.set_session_storage_factory(create_session_storage);
}

/// Factory function for session storage
fn create_session_storage(
    config: &SessionConfig
) -> Result<Arc<dyn SessionStorage>> {
    // Configuration can come from multiple sources
    let database_url = std::env::var("DATABASE_URL")
        .or_else(|_| std::env::var("SESSION_DATABASE_URL"))
        .unwrap_or_else(|_| "postgresql://localhost/myapp".to_string());

    // Create storage with configuration
    let storage = PostgresSessionStorage::new(
        &database_url,
        config.idle_timeout.as_secs(),
        config.cookie_name.clone()
    )?;

    Ok(Arc::new(storage))
}

pub struct PostgresSessionStorage {
    pool: PgPool,
    default_ttl_seconds: u64,
    table_name: String,
}

impl PostgresSessionStorage {
    pub fn new(
        database_url: &str,
        default_ttl_seconds: u64,
        cookie_name: String
    ) -> Result<Self> {
        // Create connection pool synchronously for the factory
        let pool = futures::executor::block_on(async {
            PgPoolOptions::new()
                .max_connections(5)
                .connect(database_url)
                .await
        }).map_err(|e| rustf::error::Error::internal(
            format!("Failed to connect to database: {}", e)
        ))?;

        // Create sessions table
        futures::executor::block_on(async {
            sqlx::query(&format!(
                "CREATE TABLE IF NOT EXISTS sessions_{} (
                    id VARCHAR(64) PRIMARY KEY,
                    data JSONB NOT NULL,
                    expires_at TIMESTAMP NOT NULL,
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    ip_address INET,
                    user_agent TEXT
                )",
                sanitize_table_name(&cookie_name)
            ))
            .execute(&pool)
            .await
        }).map_err(|e| rustf::error::Error::internal(
            format!("Failed to create sessions table: {}", e)
        ))?;

        // Create indexes for performance
        futures::executor::block_on(async {
            sqlx::query(&format!(
                "CREATE INDEX IF NOT EXISTS idx_sessions_{}_expires
                 ON sessions_{} (expires_at)",
                sanitize_table_name(&cookie_name),
                sanitize_table_name(&cookie_name)
            ))
            .execute(&pool)
            .await
        }).ok(); // Index creation failure is non-fatal

        Ok(Self {
            pool,
            default_ttl_seconds,
            table_name: format!("sessions_{}", sanitize_table_name(&cookie_name)),
        })
    }
}

#[async_trait]
impl SessionStorage for PostgresSessionStorage {
    async fn get(&self, session_id: &str) -> Result<Option<SessionData>> {
        let query = format!(
            "SELECT data FROM {}
             WHERE id = $1 AND expires_at > NOW()",
            self.table_name
        );

        let row = sqlx::query(&query)
            .bind(session_id)
            .fetch_optional(&self.pool)
            .await
            .map_err(|e| rustf::error::Error::internal(
                format!("Failed to get session: {}", e)
            ))?;

        match row {
            Some(row) => {
                let data: serde_json::Value = row.try_get("data")
                    .map_err(|e| rustf::error::Error::internal(
                        format!("Failed to deserialize session: {}", e)
                    ))?;

                let mut session_data: SessionData = serde_json::from_value(data)
                    .map_err(|e| rustf::error::Error::internal(
                        format!("Invalid session data format: {}", e)
                    ))?;

                // Update last accessed time
                session_data.touch();

                // Update in database (fire and forget for performance)
                let update_query = format!(
                    "UPDATE {} SET updated_at = NOW() WHERE id = $1",
                    self.table_name
                );

                let _ = sqlx::query(&update_query)
                    .bind(session_id)
                    .execute(&self.pool)
                    .await;

                Ok(Some(session_data))
            }
            None => Ok(None)
        }
    }

    async fn set(
        &self,
        session_id: &str,
        data: &SessionData,
        ttl: Duration
    ) -> Result<()> {
        let expires_at = chrono::Utc::now() +
            chrono::Duration::seconds(ttl.as_secs() as i64);

        let json_data = serde_json::to_value(data)
            .map_err(|e| rustf::error::Error::internal(
                format!("Failed to serialize session: {}", e)
            ))?;

        let query = format!(
            "INSERT INTO {} (id, data, expires_at, updated_at)
             VALUES ($1, $2, $3, NOW())
             ON CONFLICT (id) DO UPDATE
             SET data = $2, expires_at = $3, updated_at = NOW()",
            self.table_name
        );

        sqlx::query(&query)
            .bind(session_id)
            .bind(json_data)
            .bind(expires_at)
            .execute(&self.pool)
            .await
            .map_err(|e| rustf::error::Error::internal(
                format!("Failed to save session: {}", e)
            ))?;

        Ok(())
    }

    async fn delete(&self, session_id: &str) -> Result<()> {
        let query = format!(
            "DELETE FROM {} WHERE id = $1",
            self.table_name
        );

        sqlx::query(&query)
            .bind(session_id)
            .execute(&self.pool)
            .await
            .map_err(|e| rustf::error::Error::internal(
                format!("Failed to delete session: {}", e)
            ))?;

        Ok(())
    }

    async fn exists(&self, session_id: &str) -> Result<bool> {
        let query = format!(
            "SELECT 1 FROM {}
             WHERE id = $1 AND expires_at > NOW()
             LIMIT 1",
            self.table_name
        );

        let exists = sqlx::query(&query)
            .bind(session_id)
            .fetch_optional(&self.pool)
            .await
            .map_err(|e| rustf::error::Error::internal(
                format!("Failed to check session existence: {}", e)
            ))?
            .is_some();

        Ok(exists)
    }

    async fn cleanup_expired(&self) -> Result<usize> {
        let query = format!(
            "DELETE FROM {} WHERE expires_at <= NOW()",
            self.table_name
        );

        let result = sqlx::query(&query)
            .execute(&self.pool)
            .await
            .map_err(|e| rustf::error::Error::internal(
                format!("Failed to cleanup sessions: {}", e)
            ))?;

        Ok(result.rows_affected() as usize)
    }

    fn backend_name(&self) -> &'static str {
        "postgresql-definitions"
    }

    async fn stats(&self) -> Result<StorageStats> {
        let total_query = format!(
            "SELECT COUNT(*) as count FROM {}",
            self.table_name
        );

        let active_query = format!(
            "SELECT COUNT(*) as count FROM {} WHERE expires_at > NOW()",
            self.table_name
        );

        let total: i64 = sqlx::query(&total_query)
            .fetch_one(&self.pool)
            .await
            .and_then(|row| row.try_get("count"))
            .unwrap_or(0);

        let active: i64 = sqlx::query(&active_query)
            .fetch_one(&self.pool)
            .await
            .and_then(|row| row.try_get("count"))
            .unwrap_or(0);

        Ok(StorageStats {
            total_sessions: total as usize,
            active_sessions: active as usize,
            expired_sessions: (total - active) as usize,
            backend_metrics: HashMap::new(),
        })
    }
}

fn sanitize_table_name(name: &str) -> String {
    name.chars()
        .filter(|c| c.is_alphanumeric() || *c == '_')
        .collect::<String>()
        .to_lowercase()
}
}

Key Points:

  • The install(defs: &mut Definitions) function is mandatory for auto-discovery
  • The factory function (create_session_storage) should be private since it’s registered via install()
  • The factory receives &SessionConfig from rustf::config::SessionConfig, not the session manager’s config

How It Works

  1. Auto-Discovery: The auto_definitions!() macro finds session_storage.rs with an install() function
  2. Registration: The install() function is called and registers your factory via defs.set_session_storage_factory()
  3. Factory Pattern: When sessions are initialized, RustF calls your registered factory function
  4. Integration: Your storage replaces the default memory storage automatically
  5. Configuration: The factory receives SessionConfig for customization

When to Use Definitions vs Manual Integration

Use Definitions (Recommended) When:

  • You want the simplest setup
  • Following conventions is acceptable
  • You’re building a standard application
  • You want auto-discovery benefits

Use Manual Integration When:

  • You need complex initialization logic
  • You want full control over the storage lifecycle
  • You’re building a library or framework
  • You have special requirements that don’t fit the convention

For more details on the Definitions System, see Schemas & Definitions.

Advanced Usage

Session Management Methods

RustF provides comprehensive session management methods:

#![allow(unused)]
fn main() {
async fn session_management(ctx: &mut Context) -> rustf::Result<()> {
    // ctx.session() returns Option<&Session>; the Session methods below take &self.
    let info = if let Some(session) = ctx.session() {
        // Basic session operations
        session.set("user_id", 123)?;
        let _user_id: Option<i32> = session.get("user_id");
        let _removed_value = session.remove("temp_data");

        // Session lifecycle management
        session.clear();        // Clear all data but keep session active
        session.flush();        // Alias for clear() (Laravel compatibility)
        session.destroy();      // Mark session for destruction

        // Session information
        json!({
            "session_id": session.id(),
            "is_empty": session.is_empty(),
            "data_entries": session.data_count(),
            "flash_messages": session.flash_count()
        })
    } else {
        json!({ "error": "no session" })
    };

    ctx.json(info)
}

// Security: Session ID regeneration for fixation protection.
// `Session::regenerate_id` takes `&mut self`, but the context only exposes an
// immutable `&Session`, so regeneration is performed at the store level via
// `SessionStore::regenerate_session_id(...)` (see "Session Store Operations").
async fn context_session_methods(ctx: &mut Context) -> rustf::Result<()> {
    // Convenience methods available on Context
    ctx.session_set("key", "value")?;
    let value: Option<String> = ctx.session_get("key");
    ctx.session_clear();     // Clear all session data
    ctx.session_flush();     // Alias for clear
    ctx.session_destroy();   // Mark for destruction

    ctx.json(json!({"status": "ok"}))
}
}

Session Store Operations

Perform operations on the session store itself:

#![allow(unused)]
fn main() {
use rustf::session::{SessionStore, SessionData};

async fn session_store_management(session_store: &SessionStore) -> Result<()> {
    let session_id = "user_123_session";

    // Basic session store operations
    let exists = session_store.exists(session_id).await?;
    let session_opt = session_store.get(session_id).await?;

    // Complete session destruction (removes from storage)
    session_store.destroy_session(session_id).await?;

    // Regenerate session ID with storage backend updates
    if let Some(new_session) = session_store.regenerate_session_id(session_id).await? {
        log::info!("Session regenerated: {}", new_session.id());
    }

    // Clear session data but keep it in storage
    session_store.clear_session(session_id).await?;

    // Storage statistics and monitoring
    let stats = session_store.stats().await?;
    log::info!("Total sessions: {}, Active: {}",
               stats.total_sessions,
               stats.active_sessions);

    let backend = session_store.backend_name();
    log::info!("Using {} storage backend", backend);

    Ok(())
}
}

Custom Storage Backend (Manual Approach)

Note: The Definitions System approach (described above) is now the recommended way to implement custom session storage. The manual approach below is still supported for advanced use cases requiring full control.

Understanding SessionData Structure

Before implementing custom storage, understand the SessionData structure:

#![allow(unused)]
fn main() {
use serde::{Serialize, Deserialize};
use serde_json::Value;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionData {
    /// Session data as JSON object
    pub data: Value,
    /// Flash messages as JSON object
    pub flash: Value,
    /// Security fingerprint containing IP and user agent info
    pub fingerprint: Option<SessionFingerprint>,
    /// Session creation timestamp (Unix seconds)
    pub created_at: u64,
    /// Last accessed timestamp (Unix seconds)
    pub last_accessed: u64,
    /// Absolute timeout timestamp (Unix seconds)
    pub absolute_timeout: u64,
    /// Current privilege level (for security escalation tracking)
    pub privilege_level: u32,
}

impl SessionData {
    /// Update last accessed time to current timestamp
    pub fn touch(&mut self) {
        self.last_accessed = unix_timestamp();
    }

    /// Check if session has expired based on dual timeout
    pub fn is_expired(&self, idle_timeout_secs: u64) -> bool {
        let now = unix_timestamp();

        // Check absolute timeout
        if now > self.absolute_timeout {
            return true;
        }

        // Check idle timeout
        (now - self.last_accessed) > idle_timeout_secs
    }
}
}

Understanding SessionFingerprint Structure

The SessionFingerprint structure captures client information for session security validation:

#![allow(unused)]
fn main() {
use serde::{Serialize, Deserialize};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionFingerprint {
    /// Full IP address
    pub ip: String,
    /// Full user agent string
    pub user_agent: String,
    /// Creation timestamp (Unix seconds)
    pub created_at: u64,
}

impl SessionFingerprint {
    /// Create fingerprint from request (called automatically by session middleware)
    pub fn from_request(request: &Request) -> Self {
        let created_at = unix_timestamp();
        let ip = request.client_ip();  // Supports X-Forwarded-For and X-Real-IP
        let user_agent = request.user_agent().unwrap_or("unknown").to_string();

        Self { ip, user_agent, created_at }
    }
}
}

Important Notes:

  • IP address and user agent are automatically captured when a session is created
  • The ip field stores the full client IP; the user_agent field stores the full User-Agent string
  • The FingerprintMode (below) controls how strictly these are compared on subsequent requests

FingerprintMode Enum

Controls how strictly sessions are bound to client characteristics:

#![allow(unused)]
fn main() {
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum FingerprintMode {
    /// No fingerprint validation - sessions work from any IP/browser
    Disabled,

    /// Soft validation (default) - lenient comparison of IP and user agent
    /// Allows some client mobility
    Soft,

    /// Strict validation - exact IP and user agent must match
    /// Maximum security but may cause issues with mobile users or dynamic IPs
    Strict,
}

impl Default for FingerprintMode {
    fn default() -> Self {
        Self::Soft  // Balanced security and usability
    }
}
}

Validation Behavior:

  • Disabled: No validation, session works from anywhere
  • Soft: lenient comparison of the stored ip and user_agent (allows some client mobility)
  • Strict: exact ip and user_agent must match

Accessing Fingerprint Data in Controllers:

#![allow(unused)]
fn main() {
async fn show_session_info(ctx: &mut Context) -> rustf::Result<()> {
    // Read the fingerprint fields into an owned value before re-borrowing ctx mutably.
    let info = ctx.session().and_then(|session| {
        let id = session.id().to_string();
        session.fingerprint().map(|fp| json!({
            "session_id": id,
            "ip": fp.ip,                 // full client IP
            "user_agent": fp.user_agent, // full User-Agent string
            "created_at": fp.created_at,
        }))
    });

    match info {
        Some(value) => ctx.json(value),
        None => ctx.json(json!({"error": "No session found"})),
    }
}
}

Complete Database Storage Implementation with SQLx

Here’s a complete working example using SQLx for PostgreSQL:

#![allow(unused)]
fn main() {
use async_trait::async_trait;
use rustf::session::{SessionStorage, SessionData, StorageStats};
use sqlx::{PgPool, Row};
use std::time::Duration;
use serde_json;

pub struct DatabaseSessionStorage {
    pool: PgPool,
    table_name: String,
}

impl DatabaseSessionStorage {
    pub async fn new(database_url: &str) -> Result<Self> {
        // Create connection pool
        let pool = PgPool::connect(database_url).await?;

        // Create sessions table if not exists
        sqlx::query(&format!(r#"
            CREATE TABLE IF NOT EXISTS sessions (
                id VARCHAR(64) PRIMARY KEY,
                data JSONB NOT NULL,
                expires_at TIMESTAMP NOT NULL,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            )
        "#)).execute(&pool).await?;

        // Create index for cleanup
        sqlx::query("CREATE INDEX IF NOT EXISTS idx_sessions_expires ON sessions(expires_at)")
            .execute(&pool).await?;

        Ok(Self {
            pool,
            table_name: "sessions".to_string(),
        })
    }
}

#[async_trait]
impl SessionStorage for DatabaseSessionStorage {
    async fn get(&self, session_id: &str) -> Result<Option<SessionData>> {
        let query = format!(
            "SELECT data FROM {} WHERE id = $1 AND expires_at > NOW()",
            self.table_name
        );

        let row = sqlx::query(&query)
            .bind(session_id)
            .fetch_optional(&self.pool)
            .await?;

        match row {
            Some(row) => {
                let data: serde_json::Value = row.get("data");
                let mut session_data: SessionData = serde_json::from_value(data)?;

                // Update last accessed time
                session_data.touch();

                // Update in database
                let update_query = format!(
                    "UPDATE {} SET updated_at = NOW() WHERE id = $1",
                    self.table_name
                );
                sqlx::query(&update_query)
                    .bind(session_id)
                    .execute(&self.pool)
                    .await?;

                Ok(Some(session_data))
            }
            None => Ok(None),
        }
    }

    async fn set(&self, session_id: &str, data: &SessionData, ttl: Duration) -> Result<()> {
        let expires_at = chrono::Utc::now() + chrono::Duration::seconds(ttl.as_secs() as i64);
        let json_data = serde_json::to_value(data)?;

        let query = format!(r#"
            INSERT INTO {} (id, data, expires_at, updated_at)
            VALUES ($1, $2, $3, NOW())
            ON CONFLICT (id) DO UPDATE
            SET data = $2, expires_at = $3, updated_at = NOW()
        "#, self.table_name);

        sqlx::query(&query)
            .bind(session_id)
            .bind(json_data)
            .bind(expires_at)
            .execute(&self.pool)
            .await?;

        Ok(())
    }

    async fn delete(&self, session_id: &str) -> Result<()> {
        let query = format!("DELETE FROM {} WHERE id = $1", self.table_name);
        sqlx::query(&query)
            .bind(session_id)
            .execute(&self.pool)
            .await?;
        Ok(())
    }

    async fn exists(&self, session_id: &str) -> Result<bool> {
        let query = format!(
            "SELECT 1 FROM {} WHERE id = $1 AND expires_at > NOW()",
            self.table_name
        );

        let exists = sqlx::query(&query)
            .bind(session_id)
            .fetch_optional(&self.pool)
            .await?
            .is_some();

        Ok(exists)
    }

    async fn cleanup_expired(&self) -> Result<usize> {
        let query = format!("DELETE FROM {} WHERE expires_at <= NOW()", self.table_name);
        let result = sqlx::query(&query)
            .execute(&self.pool)
            .await?;

        Ok(result.rows_affected() as usize)
    }

    fn backend_name(&self) -> &'static str {
        "database"
    }

    async fn stats(&self) -> Result<StorageStats> {
        let total_query = format!("SELECT COUNT(*) as count FROM {}", self.table_name);
        let active_query = format!(
            "SELECT COUNT(*) as count FROM {} WHERE expires_at > NOW()",
            self.table_name
        );

        let total: i64 = sqlx::query(&total_query)
            .fetch_one(&self.pool)
            .await?
            .get("count");

        let active: i64 = sqlx::query(&active_query)
            .fetch_one(&self.pool)
            .await?
            .get("count");

        Ok(StorageStats {
            total_sessions: total as usize,
            active_sessions: active as usize,
            expired_sessions: (total - active) as usize,
            backend_metrics: HashMap::new(),
        })
    }
}

// Integration (see "How Session Storage Integration Works" section for details)
// You'll use this storage with SessionMiddleware::with_storage()
}

Complete Working Example: Putting It All Together

Here’s a complete, working example that shows exactly how to integrate custom database storage:

// main.rs
use rustf::prelude::*;
use rustf::middleware::builtin::session::SessionMiddleware;
use rustf::session::{SessionStorage, SessionData, StorageStats, manager::SessionConfig};
use rustf::config::AppConfig;
use async_trait::async_trait;
use sqlx::PgPool;
use std::sync::Arc;
use std::time::Duration;
use serde_json;

// Your custom database storage implementation
pub struct DatabaseSessionStorage {
    pool: PgPool,
}

impl DatabaseSessionStorage {
    pub async fn new(database_url: &str) -> Result<Self> {
        let pool = PgPool::connect(database_url).await?;

        // Create sessions table
        sqlx::query(
            "CREATE TABLE IF NOT EXISTS sessions (
                id VARCHAR(64) PRIMARY KEY,
                data JSONB NOT NULL,
                expires_at TIMESTAMP NOT NULL
            )"
        ).execute(&pool).await?;

        Ok(Self { pool })
    }
}

#[async_trait]
impl SessionStorage for DatabaseSessionStorage {
    async fn get(&self, session_id: &str) -> Result<Option<SessionData>> {
        let row = sqlx::query!(
            "SELECT data FROM sessions WHERE id = $1 AND expires_at > NOW()",
            session_id
        )
        .fetch_optional(&self.pool)
        .await?;

        match row {
            Some(row) => {
                let mut data: SessionData = serde_json::from_value(row.data)?;
                data.touch();
                Ok(Some(data))
            }
            None => Ok(None)
        }
    }

    async fn set(&self, session_id: &str, data: &SessionData, ttl: Duration) -> Result<()> {
        let expires_at = chrono::Utc::now() + chrono::Duration::seconds(ttl.as_secs() as i64);
        let json_data = serde_json::to_value(data)?;

        sqlx::query!(
            "INSERT INTO sessions (id, data, expires_at)
             VALUES ($1, $2, $3)
             ON CONFLICT (id) DO UPDATE
             SET data = $2, expires_at = $3",
            session_id,
            json_data,
            expires_at
        )
        .execute(&self.pool)
        .await?;

        Ok(())
    }

    async fn delete(&self, session_id: &str) -> Result<()> {
        sqlx::query!("DELETE FROM sessions WHERE id = $1", session_id)
            .execute(&self.pool)
            .await?;
        Ok(())
    }

    async fn exists(&self, session_id: &str) -> Result<bool> {
        let exists = sqlx::query!(
            "SELECT 1 as exists FROM sessions WHERE id = $1 AND expires_at > NOW()",
            session_id
        )
        .fetch_optional(&self.pool)
        .await?
        .is_some();

        Ok(exists)
    }

    async fn cleanup_expired(&self) -> Result<usize> {
        let result = sqlx::query!("DELETE FROM sessions WHERE expires_at <= NOW()")
            .execute(&self.pool)
            .await?;
        Ok(result.rows_affected() as usize)
    }

    fn backend_name(&self) -> &'static str {
        "postgresql"
    }
}

#[tokio::main]
async fn main() -> Result<()> {
    env_logger::init();

    // Step 1: Load config but disable auto session
    let mut config = AppConfig::from_file("config.toml")?;
    config.session.enabled = false;  // IMPORTANT: Disable auto-creation

    // Step 2: Create RustF app without auto session
    let app = RustF::with_config(config.clone());

    // Step 3: Create your custom database storage
    let db_storage = Arc::new(
        DatabaseSessionStorage::new(&config.database.url).await?
    );

    // Step 4: Configure session settings
    let session_config = SessionConfig {
        cookie_name: config.session.cookie_name,
        idle_timeout: Duration::from_secs(config.session.idle_timeout),
        absolute_timeout: Duration::from_secs(config.session.absolute_timeout),
        exempt_routes: config.session.exempt_routes,
        same_site: parse_same_site(&config.session.same_site),
        enabled: true,
        ..Default::default()
    };

    // Step 5: Create session middleware with your storage
    let session_middleware = SessionMiddleware::with_storage(
        db_storage,
        session_config
    );

    // Step 6: Register everything and start
    let app = app
        .middleware_from(|registry| {
            // Register your custom session middleware
            registry.register_dual("session", session_middleware);

            // Add other middleware as needed
            registry.register_dual("cors", CorsMiddleware::new());
        })
        .controllers(auto_controllers!())
        .models(auto_models!());

    println!("πŸš€ Server starting with PostgreSQL session storage");
    app.start().await
}

fn parse_same_site(value: &str) -> rustf::session::SameSite {
    match value.to_lowercase().as_str() {
        "strict" => rustf::session::SameSite::Strict,
        "lax" => rustf::session::SameSite::Lax,
        "none" => rustf::session::SameSite::None,
        _ => rustf::session::SameSite::Lax,
    }
}

# Session Data Serialization

Sessions use JSON serialization internally via `serde_json`:

```rust
// These types work automatically
ctx.session_set("string", "Hello")?;
ctx.session_set("number", 42)?;
ctx.session_set("boolean", true)?;
ctx.session_set("array", vec![1, 2, 3])?;
ctx.session_set("object", json!({"key": "value"}))?;

// Custom types need Serialize/Deserialize
#[derive(Serialize, Deserialize)]
struct CustomData {
    id: i32,
    name: String,
}

let custom = CustomData { id: 1, name: "test".to_string() };
ctx.session_set("custom", custom)?;

let retrieved: Option<CustomData> = ctx.session_get("custom");

Error Handling

Session operations return Result<T> for proper error handling:

#![allow(unused)]
fn main() {
async fn safe_session_usage(ctx: &mut Context) -> rustf::Result<()> {
    // Handle serialization errors
    match ctx.session_set("user_id", 123) {
        Ok(()) => log::info!("Session data saved"),
        Err(e) => log::error!("Failed to save session: {}", e),
    }

    // Handle deserialization
    match ctx.session_get::<i32>("user_id") {
        Some(id) => log::info!("User ID: {}", id),
        None => log::info!("No user ID in session"),
    }

    // Flash message errors are typically ignored
    let _ = ctx.flash("message", "Hello");

    ctx.json(json!({"status": "ok"}))
}
}

Storage Backend Comparison

Memory Storage (Implemented)

Pros:

  • Very fast (in-memory access)
  • No external dependencies
  • Automatic cleanup with background tasks

Cons:

  • Sessions lost on server restart
  • Not suitable for multi-server deployments
  • Memory usage grows with active sessions

Best for: Development, single-server deployments, temporary sessions

Redis Storage (Implemented)

Pros:

  • Persistent across server restarts
  • Supports multiple server instances
  • Automatic TTL expiration
  • High performance with connection pooling

Cons:

  • Requires Redis server
  • Network latency for session access
  • Additional infrastructure complexity

Best for: Production deployments, multi-server setups, persistent sessions

Database Storage (User Implementation Required)

Configuration structure exists but implementation is intentionally delegated to users:

# config.toml (configuration structure exists)
[session.storage]
type = "database"
table = "sessions"
connection_url = "postgresql://localhost/myapp"
cleanup_interval = 300

Important: When you configure database storage, the framework will return an error with instructions:

Database session storage must be implemented by the application.
Please implement the SessionStorage trait for your database backend.
See the documentation for examples using SQLx or other database libraries.

This is by design - database storage should be implemented by users to:

  • Support any database backend (PostgreSQL, MySQL, SQLite, etc.)
  • Allow custom table schemas and optimization
  • Enable integration with your existing database infrastructure
  • Provide flexibility in storage strategies (JSON, normalized, etc.)

How Session Storage Integration Works

Architecture Overview

Session storage in RustF is integrated through middleware, not directly through the application builder:

RustF β†’ SessionMiddleware β†’ SessionManager β†’ SessionStorage (Your Implementation)
         ↑
    Auto-created from config.toml if session.enabled = true

Default Behavior

When you create a RustF application, it automatically creates session middleware if session.enabled = true in your config:

#![allow(unused)]
fn main() {
// This happens automatically in RustF::with_config() (app.rs line 64)
if let Some(session_middleware) = create_session_middleware(&config) {
    middleware.register_dual("session", session_middleware);
}
}

The default session middleware uses MemorySessionStorage. To use custom storage, you must override this behavior.

Integrating Custom Storage

Method 1: Override Default Session Middleware

Step 1: Disable automatic session middleware in config:

# config.toml
[session]
enabled = false  # Disable auto-creation of session middleware

Step 2: Create and register your custom session middleware:

use rustf::prelude::*;
use rustf::middleware::builtin::session::SessionMiddleware;
use rustf::session::manager::SessionConfig;
use std::sync::Arc;
use std::time::Duration;

#[tokio::main]
async fn main() -> Result<()> {
    // Load config with sessions disabled
    let mut config = AppConfig::from_file("config.toml")?;
    config.session.enabled = false;  // Ensure auto-session is disabled

    // Create RustF without auto session middleware
    let app = RustF::with_config(config.clone());

    // Create your custom storage
    let custom_storage = Arc::new(
        DatabaseSessionStorage::new("postgresql://localhost/myapp").await?
    );

    // Create session configuration
    let session_config = SessionConfig {
        cookie_name: config.session.cookie_name.clone(),
        idle_timeout: Duration::from_secs(config.session.idle_timeout),
        absolute_timeout: Duration::from_secs(config.session.absolute_timeout),
        exempt_routes: config.session.exempt_routes.clone(),
        enabled: true,  // Re-enable for our custom middleware
        ..Default::default()
    };

    // Create session middleware with custom storage
    let session_middleware = SessionMiddleware::with_storage(
        custom_storage,
        session_config
    );

    // Register the custom session middleware
    let app = app.middleware_from(|registry| {
        registry.register_dual("session", session_middleware);
    })
    .controllers(auto_controllers!());

    app.start().await
}

Method 2: Custom Session Manager

Create a custom SessionManager and use it in middleware:

use rustf::session::manager::{SessionManager, SessionConfig};
use rustf::middleware::builtin::session::SessionMiddleware;

#[tokio::main]
async fn main() -> Result<()> {
    // Disable auto session
    let mut config = AppConfig::default();
    config.session.enabled = false;

    let app = RustF::with_config(config);

    // Create custom storage
    let storage = Arc::new(MyCustomStorage::new().await?);

    // Create custom manager
    let session_manager = SessionManager::new(storage, SessionConfig::default());

    // Create middleware with custom manager
    let session_middleware = SessionMiddleware::with_manager(session_manager);

    // Register it
    let app = app.middleware_from(|registry| {
        registry.register_dual("session", session_middleware);
    })
    .controllers(auto_controllers!());

    app.start().await
}

Method 3: Factory Pattern for Multiple Environments

Create a factory that handles different storage backends based on configuration:

use rustf::session::factory::SessionStorageFactory;
use rustf::session::FingerprintMode;
use rustf::config::SessionStorageConfig;

pub struct MyAppSessionFactory;

impl MyAppSessionFactory {
    pub async fn create_middleware(
        app_config: &AppConfig
    ) -> rustf::Result<SessionMiddleware> {
        // create_storage is async and takes (config, fingerprint_mode):
        let fp_mode = FingerprintMode::Soft;

        // Create storage based on config
        let storage = match &app_config.session.storage {
            SessionStorageConfig::Memory { .. } => {
                // Use built-in factory for memory
                SessionStorageFactory::create_storage(&app_config.session.storage, fp_mode).await?
            }
            SessionStorageConfig::Redis { .. } => {
                // Use built-in factory for Redis
                SessionStorageFactory::create_storage(&app_config.session.storage, fp_mode).await?
            }
            SessionStorageConfig::Database { connection_url, .. } => {
                // Use your custom database storage
                Arc::new(DatabaseSessionStorage::new(connection_url).await?)
            }
        };

        // Convert config; the cookie is `Secure` when the app runs in production
        let session_config = SessionConfig::from_app_config(&app_config);

        // Create middleware
        Ok(SessionMiddleware::with_storage(storage, session_config))
    }
}

// Usage in main.rs
#[tokio::main]
async fn main() -> Result<()> {
    let mut config = AppConfig::from_file("config.toml")?;
    config.session.enabled = false;  // Disable auto-creation

    let app = RustF::with_config(config.clone());

    // Create custom middleware based on config
    let session_middleware = MyAppSessionFactory::create_middleware(&config).await?;

    let app = app.middleware_from(|registry| {
        registry.register_dual("session", session_middleware);
    })
    .controllers(auto_controllers!());

    app.start().await
}

Important Notes

What DOESN’T Work

#![allow(unused)]
fn main() {
// ❌ WRONG - This method does not exist:
app.with_session_store(session_store)  // No such method on the app builder
}

Note: SessionStore::with_storage(storage) is a real, public method (SessionStore is re-exported from rustf::session). It builds a session store, but it is not how you wire sessions into the app β€” register a SessionMiddleware instead (see below), or configure sessions via config.toml.

What DOES Work

#![allow(unused)]
fn main() {
// βœ… CORRECT - Use SessionMiddleware methods:
SessionMiddleware::with_storage(storage, config)  // Custom storage
SessionMiddleware::with_manager(manager)          // Custom manager
SessionMiddleware::new(config)                    // Default memory storage
}

Key Integration Points

  1. SessionMiddleware - The main integration point for custom storage
  2. SessionManager - Manages session lifecycle and storage interaction
  3. SessionStorage trait - Your custom implementation goes here
  4. config.session.enabled - Must be false to prevent auto-creation

Monitoring and Statistics

Currently implemented storage backends provide statistics for monitoring:

#![allow(unused)]
fn main() {
// Access statistics through your storage implementation
async fn session_monitoring(storage: &Arc<dyn SessionStorage>) -> Result<()> {
    let stats = storage.stats().await?;

    println!("Session Statistics:");
    println!("  Total sessions: {}", stats.total_sessions);
    println!("  Active sessions: {}", stats.active_sessions);
    println!("  Expired sessions: {}", stats.expired_sessions);
    println!("  Backend: {}", session_store.backend_name());

    // Backend-specific metrics
    for (key, value) in &stats.backend_metrics {
        println!("  {}: {}", key, value);
    }

    Ok(())
}
}

Memory Storage Metrics

  • total_data_entries: Total data entries across all sessions
  • total_flash_entries: Total flash messages across all sessions
  • oldest_session_age_secs: Age of oldest session in seconds
  • session_timeout_secs: Session timeout configuration
  • cleanup_interval_secs: Cleanup interval configuration

Redis Storage Metrics

  • redis_pattern: Key pattern used for sessions
  • scan_method: Scanning method used (non-blocking)
  • redis_memory_used: Current Redis memory usage
  • redis_memory_peak: Peak Redis memory usage

Best Practices

1. Keep Session Data Small

Store only essential data in sessions to minimize memory/storage usage:

#![allow(unused)]
fn main() {
// Good: Store minimal user info
ctx.session_set("user_id", 123)?;
ctx.session_set("role", "admin")?;

// Less ideal: Store large objects
ctx.session_set("full_user_profile", large_user_object)?;
}

2. Use Flash Messages for UI Feedback

Flash messages are perfect for one-time user notifications:

#![allow(unused)]
fn main() {
async fn create_user(ctx: &mut Context) -> rustf::Result<()> {
    match create_user_in_db(&user_data).await {
        Ok(_) => {
            ctx.flash_success("User created successfully!")?;
            ctx.redirect("/users")
        }
        Err(e) => {
            ctx.flash_error(&format!("Failed to create user: {}", e))?;
            ctx.redirect("/users/new")
        }
    }
}
}

3. Handle Session Expiration Gracefully

Check for required session data and handle missing sessions:

#![allow(unused)]
fn main() {
async fn protected_route(ctx: &mut Context) -> rustf::Result<()> {
    match ctx.session_get::<i32>("user_id") {
        Some(user_id) => {
            // User is logged in, continue
            handle_authenticated_request(ctx, user_id).await
        }
        None => {
            ctx.flash_info("Please log in to continue")?;
            ctx.redirect("/login")
        }
    }
}
}

4. Use Appropriate Storage Backend

  • Development: Memory storage is fine
  • Single server production: Memory storage with sufficient RAM
  • Multi-server production: Redis storage for session sharing

5. Configure Appropriate Timeouts

Balance security and user experience:

#![allow(unused)]
fn main() {
// Short timeout for sensitive data
let secure_storage = MemorySessionStorage::with_timeout(
    Duration::from_secs(15 * 60), // 15 minutes
    Duration::from_secs(2 * 60)   // 2 minutes cleanup
);

// Longer timeout for general use
let general_storage = MemorySessionStorage::with_timeout(
    Duration::from_secs(2 * 60 * 60), // 2 hours
    Duration::from_secs(10 * 60)      // 10 minutes cleanup
);
}

6. Use Appropriate Session Lifecycle Methods

Choose the right method for different scenarios:

#![allow(unused)]
fn main() {
// User logout - destroy the authenticated session
async fn logout(ctx: &mut Context) -> rustf::Result<()> {
    ctx.logout()?;
    ctx.flash_success("You have been logged out")?;
    ctx.redirect("/login")
}

// Non-auth use case - clear data but keep the session active
async fn clear_wizard_state(ctx: &mut Context) -> rustf::Result<()> {
    ctx.session_clear();
    ctx.redirect("/wizard/start")
}

// Security incident - force full invalidation immediately
async fn security_logout(ctx: &mut Context) -> rustf::Result<()> {
    ctx.session_destroy();
    ctx.redirect("/login")
}

// After login - regenerate ID to prevent session fixation.
// Note: Session::regenerate_id takes &mut self, so it is applied at the store
// level (see SessionStore::regenerate_session_id) rather than through ctx.session().
async fn after_login(ctx: &mut Context) -> rustf::Result<()> {
    ctx.session_set("user_id", user.id)?;
    ctx.redirect("/dashboard")
}
}

Integration with Application

Sessions are automatically available in all controllers and middleware:

use rustf::prelude::*;

#[tokio::main]
async fn main() -> Result<()> {
    let app = RustF::new()
        .controllers(auto_controllers!())
        .middleware_from(auto_middleware!());

    // Sessions work automatically - no additional configuration needed
    app.serve(None).await
}

The session system integrates seamlessly with the RustF context system, providing a consistent API across controllers, middleware, and views for managing user state and temporary messages.

RustF Database & Model Layer Documentation

Overview

RustF provides a modern, ergonomic database layer with:

  • Transparent database access - No need to pass database connections around
  • Multi-database support - PostgreSQL, MySQL/MariaDB, SQLite (all on by default; opt out per driver via Cargo Features)
  • Type-safe query builders - Compile-time query validation
  • Laravel-style model queries - Chainable, intuitive API
  • Schema-driven development - YAML schemas generate type-safe models
  • Smart change tracking - Only update modified fields

Schema-Driven Workflow

In RustF the YAML schema is the single source of truth for your data model. One declarative schema drives both sides of the database:

                       β”Œβ”€ schema generate models ──► src/models/base/*.inc.rs
schemas/*.yaml ─────────
   (source of truth)   └─ schema generate sql ─────────► sql/schema.sql ──► DB

You version the schema in git, review changes in pull requests, and regenerate models and SQL from it. The database is never the master copy β€” it’s a target the schema produces, so new environments are reproducible and two developers can’t silently diverge.

Adopting an existing database (one-time bootstrap)

If you’re adding RustF to a project that already has a database, generate the initial schema from the live database, then switch to the schema-first loop above:

# Reverse-engineer YAML schemas from an existing database (one time).
# The connection is read from your project config (config.toml /
# config.dev.toml); DATABASE_URL overrides it. Use --connection <name> to
# pick a named connection.
rustf-cli db generate-schema --output schemas

This introspects every table (PostgreSQL, MySQL/MariaDB, or SQLite) and writes schemas/*.yaml. It also writes schemas/_database_dump.sql β€” the raw DDL of the live database (via pg_dump / mysqldump / sqlite3 .schema) β€” so the original structure stays in source control as a safety reference. Pass --no-sql to skip it.

There are two different SQL files in a RustF project; they never collide:

FileWritten byContents
schemas/_database_dump.sqldb generate-schemaRaw dump of the live database (bootstrap safety reference).
sql/schema.sqlschema generate sqlDDL generated from your YAML (experimental).

After the bootstrap, the YAML schema becomes the source of truth: edit the YAML, regenerate models and SQL β€” don’t hand-edit the database.

Direction summary: database β†’ schema is a one-time bootstrap for existing databases. schema β†’ models and schema β†’ sql are the steady-state loop you run from then on.

Quick Start

Basic Usage

#![allow(unused)]
fn main() {
use rustf::prelude::*;

// Find a user by ID
let user = Users::get_by_id(123).await?;

// Count all active users
let active_count = Users::query()?
    .where_eq("is_active", true)
    .count()
    .await?;

// Get paginated results (simple)
let users = Users::paginate(1, 20).await?;

// Get paginated results with metadata (recommended)
let result = Users::query()?
    .where_eq("is_active", true)
    .get_paginated(1, 20)
    .await?;
// result.rows - the data
// result.total_rows - total count
// result.total_pages - total pages

// Delete a record
if let Some(user) = Users::get_by_id(456).await? {
    user.delete().await?;
}
}

Database Configuration

Initial Setup

Configure your database in config.toml:

[database]
url = "postgresql://user:password@localhost/mydb"  # or mysql:// or sqlite://
max_connections = 10
timeout = 30

The database connection is automatically initialized when your app starts. No manual setup required!

Global Database Access

RustF uses a global DB singleton that’s initialized once at startup:

#![allow(unused)]
fn main() {
use rustf::database::DB;

// Check if database is initialized
if DB::is_initialized() {
    // Database is ready
}

// Get the backend type
let backend = DB::backend(); // Some(DatabaseBackend::Postgres)
}

Model System

Generated Models

Models are generated from YAML schemas using the RustF CLI. Each model consists of:

  1. Base model (base/*.inc.rs) - Auto-generated, never edit
  2. Wrapper model (*.rs) - Your business logic, safe to edit

Creating a Schema

Create a YAML schema in schemas/users.yaml. Fields are a map (keyed by column name), not a list. See the Schema Format Reference for the full specification.

Users:
  table: users
  version: 1
  description: User accounts for the application
  fields:
    id:
      type: integer
      primary_key: true
      auto: true
      required: true

    email:
      type: string(255)
      required: true
      unique: true
      description: User's email address

    username:
      type: string(100)
      required: true

    is_active:
      type: boolean
      default: true

    status:
      type: enum
      values: ["active", "inactive", "pending"]
      default: "pending"
      description: Account status

    role:
      type: enum
      values: ["admin", "user", "moderator"]
      required: true
      default: "user"
      description: User role in the system

    created_at:
      type: datetime

    updated_at:
      type: datetime

  indexes:
    - email
    - username

Generating Models

# Generate models from schemas
rustf-cli schema generate models

# Force regeneration (backs up existing files)
rustf-cli schema generate models --force

This creates:

  • src/models/base/users.inc.rs - Generated base model
  • src/models/users.rs - Wrapper for your business logic (if doesn’t exist)

Generating SQL (DDL)

Experimental. schema generate sql is verified on representative schemas across all three dialects, but has not yet been exercised at scale. Review the generated DDL before applying it to a database, and please report any mismatch.

The same schema also generates the SQL to create your tables:

# Generate the full SQL schema (DDL) from your schemas
rustf-cli schema generate sql --output sql

The target dialect is detected from the schema metadata, and the generated DDL is dialect-correct:

ConcernPostgreSQLMySQLSQLite
Auto-increment PKSERIALAUTO_INCREMENTINTEGER PRIMARY KEY AUTOINCREMENT
Enum fieldTEXT CHECK (col IN (…))native ENUM(…)TEXT CHECK (col IN (…))
JSON fieldJSONBJSONTEXT
Foreign keysALTER TABLE … ADD FOREIGN KEYsamedeclared inline (no ALTER ADD)

Foreign keys are emitted as trailing statements so table creation order never matters.

CRUD Operations

Finding Records

#![allow(unused)]
fn main() {
// Find by ID - returns Option<Model>
let user = Users::get_by_id(123).await?;

// Find first record
let first_user = Users::first().await?;

// Find all records (use with caution!)
let all_users = Users::all().await?;

// Find with conditions
let active_users = Users::query()?
    .where_eq("is_active", true)
    .get()
    .await?;
}

Creating Records

#![allow(unused)]
fn main() {
// Using the builder pattern (recommended)
let new_user = Users::builder()
    .email("user@example.com")
    .username("johndoe")
    .is_active(true)
    .save()  // Saves directly to database
    .await?;

// Manual creation (for complex cases)
let user = Users {
    id: 0,  // Will be set by database
    email: "user@example.com".to_string(),
    username: "johndoe".to_string(),
    is_active: true,
    created_at: Some(Utc::now()),
    updated_at: None,
    // ... other fields
};
// Then save using your custom method
}

Updating Records

Models track changes automatically - only modified fields are updated:

#![allow(unused)]
fn main() {
// Find and update
let mut user = Users::get_by_id(123).await?.unwrap();

// Setters automatically track changes
user.set_email("newemail@example.com");
user.set_is_active(false);

// Only updates email and is_active fields
user.update().await?;

// Check if there are changes
if user.has_changes() {
    println!("User has unsaved changes");
}
}

Deleting Records

#![allow(unused)]
fn main() {
// Delete by finding first
if let Some(user) = Users::get_by_id(123).await? {
    user.delete().await?;
}

// Delete with query
let deleted_count = Users::query()?
    .where_eq("is_active", false)
    .where_lt("last_login", "2024-01-01")
    .delete()
    .await?;
}

Query Builder

Basic Queries

#![allow(unused)]
fn main() {
// Simple equality check
let users = Users::query()?
    .where_eq("role", "admin")
    .get()
    .await?;

// Multiple conditions (AND)
let active_admins = Users::query()?
    .where_eq("role", "admin")
    .where_eq("is_active", true)
    .where_not_null("email_verified")
    .get()
    .await?;

// OR conditions
let users = Users::query()?
    .where_eq("role", "admin")
    .or_where_eq("role", "moderator")
    .get()
    .await?;
}

Available Query Methods

WHERE Conditions

  • where_eq(column, value) - Equal to
  • where_ne(column, value) - Not equal to
  • where_gt(column, value) - Greater than
  • where_lt(column, value) - Less than
  • where_gte(column, value) - Greater than or equal
  • where_lte(column, value) - Less than or equal
  • where_like(column, pattern) - LIKE pattern matching
  • where_not_like(column, pattern) - NOT LIKE
  • where_in(column, vec![values]) - IN list
  • where_not_in(column, vec![values]) - NOT IN
  • where_between(column, start, end) - BETWEEN range
  • where_null(column) - IS NULL
  • where_not_null(column) - IS NOT NULL

OR Conditions

All WHERE methods have or_where_* variants:

  • or_where_eq(column, value)
  • or_where_gt(column, value)
  • or_where_null(column)
  • etc.

Modifiers

  • order_by(column, OrderDirection::Asc/Desc)
  • limit(n)
  • offset(n)
  • paginate(page, per_page)

Field Selection

  • select(&[columns]) - Select specific fields instead of SELECT *
  • select_raw(&[expressions]) - Select with SQL expressions and aggregations
  • alias("name") - Set a table alias for complex queries

Grouping

  • group_by(&[columns]) - Group results by specified columns

Execution Methods

  • get() - Get all matching records as model instances
  • get_raw() - Get results as JSON (useful for aggregations and JOINs)
  • first() - Get first record
  • count() - Count matching records
  • exists() - Check if any records exist
  • delete() - Delete matching records

Complex Queries

#![allow(unused)]
fn main() {
// Pagination with conditions
let users = Users::query()?
    .where_eq("is_active", true)
    .where_like("email", "%@company.com")
    .order_by("created_at", OrderDirection::Desc)
    .paginate(2, 20)  // Page 2, 20 per page
    .get()
    .await?;

// Count with conditions
let admin_count = Users::query()?
    .where_eq("role", "admin")
    .where_not_null("verified_at")
    .count()
    .await?;

// Check existence
let has_admins = Users::query()?
    .where_eq("role", "admin")
    .exists()
    .await?;

// Complex date queries
let recent_users = Users::query()?
    .where_gt("created_at", "2024-01-01")
    .where_between("age", 18, 65)
    .where_in("status", vec!["active", "pending"])
    .order_by("created_at", OrderDirection::Desc)
    .limit(100)
    .get()
    .await?;
}

Reusable Query Filters (ModelFilter)

ModelFilter allows you to build reusable query conditions that can be applied to multiple queries. This is especially useful for common filtering patterns across your application.

Basic Usage

#![allow(unused)]
fn main() {
use rustf::models::ModelFilter;

// Create a reusable filter
let active_users = ModelFilter::new()
    .where_eq("is_active", true)
    .where_not_null("verified_at");

// Apply the same filter to different queries
let count = Users::query()?
    .apply_filter(&active_users)
    .count()
    .await?;

let users = Users::query()?
    .apply_filter(&active_users)
    .order_by("created_at", OrderDirection::Desc)
    .limit(10)
    .get()
    .await?;
}

Conditional Filter Building

ModelFilter supports conditional building by reassigning the filter variable:

#![allow(unused)]
fn main() {
// Start with an empty filter
let mut filter = ModelFilter::new();

// Always apply base conditions
filter = filter.where_eq("is_active", true);

// Conditionally add filters based on user input
if let Ok(search) = ctx.query_str("search") {
    filter = filter.where_like("name", &format!("%{}%", search));
}

if let Ok(role) = ctx.query_str("role") {
    filter = filter.where_eq("role", role);
}

if let Ok(min_age) = ctx.query_int("min_age") {
    filter = filter.where_gte("age", min_age);
}

// Use the conditionally built filter
let results = Users::query()?
    .apply_filter(&filter)
    .get()
    .await?;
}

Combining Filters

You can combine multiple filters using the and() method:

#![allow(unused)]
fn main() {
// Create base filters
let active_filter = ModelFilter::new()
    .where_eq("is_active", true);

let verified_filter = ModelFilter::new()
    .where_not_null("email_verified_at")
    .where_not_null("phone_verified_at");

// Combine filters
let combined = active_filter.and(verified_filter);

// Use combined filter
let users = Users::query()?
    .apply_filter(&combined)
    .get()
    .await?;
}

Common Filter Patterns

#![allow(unused)]
fn main() {
// Pagination filter with search
let mut filter = ModelFilter::new();
if let Some(search) = search_term {
    filter = filter.where_like("name", &format!("%{}%", search));
    // Note: OR conditions not yet supported, use multiple queries if needed
}
filter = filter.where_eq("is_active", true);

// Date range filter
let date_filter = ModelFilter::new()
    .where_gte("created_at", start_date)
    .where_lte("created_at", end_date);

// Complex status filter
let status_filter = ModelFilter::new()
    .where_in("status", vec!["active", "pending", "verified"])
    .where_not_null("approved_at");

// Null checks filter
let complete_profile = ModelFilter::new()
    .where_not_null("email")
    .where_not_null("phone")
    .where_not_null("address");
}

Reusable Application Filters

Create application-wide filters as functions:

#![allow(unused)]
fn main() {
// In your models or a filters module
impl Users {
    pub fn active_filter() -> ModelFilter {
        ModelFilter::new()
            .where_eq("is_active", true)
            .where_not_null("email_verified_at")
    }
    
    pub fn admin_filter() -> ModelFilter {
        ModelFilter::new()
            .where_eq("role", "admin")
            .where_eq("is_active", true)
    }
}

// Usage
let admins = Users::query()?
    .apply_filter(&Users::admin_filter())
    .get()
    .await?;
}

Advanced Query Features

Selecting Specific Fields

Instead of fetching all columns with SELECT *, you can specify exactly which fields you need:

#![allow(unused)]
fn main() {
// Select specific fields only
let users = Users::query()?
    .select(&["id", "name", "email"])
    .where_eq("is_active", true)
    .get()
    .await?;

// With table prefixes (useful for JOINs)
let results = Posts::query()?
    .alias("p")
    .select(&["p.id", "p.title", "u.name as author_name"])
    .join("users AS u", "u.id = p.user_id")
    .get_raw()
    .await?;

// Raw SQL expressions for aggregations
let stats = Users::query()?
    .select_raw(&[
        "department",
        "COUNT(*) as user_count",
        "AVG(salary) as avg_salary"
    ])
    .group_by(&["department"])
    .get_raw()
    .await?;
}

Table Aliasing

Use alias() to set a table alias, essential for self-joins and improving query readability:

#![allow(unused)]
fn main() {
// Simple aliasing
let users = Users::query()?
    .alias("u")
    .select(&["u.id", "u.name", "u.email"])
    .where_eq("u.is_active", true)
    .get()
    .await?;

// Self-join for hierarchical data (employee-manager)
let employees = Users::query()?
    .alias("emp")
    .select(&[
        "emp.id as employee_id",
        "emp.name as employee_name",
        "mgr.id as manager_id",
        "mgr.name as manager_name"
    ])
    .left_join("users AS mgr", "mgr.id = emp.manager_id")
    .get_raw()
    .await?;
}

Advanced JOIN Queries

#![allow(unused)]
fn main() {
// Simple JOIN
let posts_with_authors = Posts::query()?
    .join("users", "users.id = posts.user_id")
    .where_eq("users.is_active", true)
    .get()
    .await?;

// LEFT JOIN with aliases to avoid column conflicts
let posts = Posts::query()?
    .alias("p")
    .select(&[
        "p.id as post_id",
        "p.title",
        "p.created_at as post_date",
        "u.id as user_id",
        "u.name as author_name",
        "COUNT(c.id) as comment_count"
    ])
    .join("users AS u", "u.id = p.user_id")
    .left_join("comments AS c", "c.post_id = p.id")
    .where_eq("p.is_published", true)
    .group_by(&["p.id", "p.title", "p.created_at", "u.id", "u.name"])
    .get_raw()
    .await?;
}

Handling Column Name Conflicts in JOINs

When joining tables with identical column names (like id, created_at), always use column aliases:

#![allow(unused)]
fn main() {
// ❌ BAD: Ambiguous column names
let results = Posts::query()?
    .join("users", "users.id = posts.user_id")
    .get_raw()
    .await?;
// Which 'id' is which? posts.id or users.id?

// βœ… GOOD: Clear column aliases
let results = Posts::query()?
    .alias("p")
    .select(&[
        "p.id as post_id",
        "p.created_at as post_date",
        "u.id as user_id",
        "u.created_at as user_joined"
    ])
    .join("users AS u", "u.id = p.user_id")
    .get_raw()
    .await?;
}

GROUP BY and Aggregations

Perform aggregate queries using group_by() with select_raw():

#![allow(unused)]
fn main() {
// Department statistics
let dept_stats = Users::query()?
    .alias("u")
    .select_raw(&[
        "u.department",
        "COUNT(*) as total_users",
        "AVG(u.salary) as avg_salary",
        "MAX(u.salary) as max_salary",
        "MIN(u.salary) as min_salary"
    ])
    .where_eq("u.is_active", true)
    .group_by(&["u.department"])
    .order_by("total_users", OrderDirection::Desc)
    .get_raw()
    .await?;

// Posts per user with filtering
let user_post_counts = Users::query()?
    .alias("u")
    .select_raw(&[
        "u.id",
        "u.name",
        "COUNT(p.id) as post_count",
        "MAX(p.created_at) as latest_post"
    ])
    .left_join("posts AS p", "p.user_id = u.id AND p.is_published = true")
    .group_by(&["u.id", "u.name"])
    .order_by("post_count", OrderDirection::Desc)
    .limit(10)
    .get_raw()
    .await?;
}

Working with Raw Query Results

The get_raw() method returns Vec<serde_json::Value> for flexible result handling:

#![allow(unused)]
fn main() {
// Execute raw query
let results = Users::query()?
    .alias("u")
    .select_raw(&[
        "u.department",
        "COUNT(*) as count",
        "AVG(u.salary) as avg_salary"
    ])
    .group_by(&["u.department"])
    .get_raw()
    .await?;

// Loop over results
for row in &results {
    let dept = row["department"].as_str().unwrap_or("Unknown");
    let count = row["count"].as_i64().unwrap_or(0);
    let avg = row["avg_salary"].as_f64().unwrap_or(0.0);
    
    println!("Department: {} - {} users, avg salary: ${:.2}", dept, count, avg);
}

// Transform for view consumption
let view_data = results.iter().map(|row| {
    json!({
        "department": row["department"],
        "userCount": row["count"],
        "avgSalary": format!("${:.2}", row["avg_salary"].as_f64().unwrap_or(0.0))
    })
}).collect::<Vec<_>>();

// Pass to controller view
ctx.view("departments", json!({
    "stats": view_data,
    "total": results.len()
}))
}

Combining Filters with Complex Queries

ModelFilter works seamlessly with all the new query features:

#![allow(unused)]
fn main() {
// Create reusable filter
let active_filter = ModelFilter::new()
    .where_eq("u.is_active", true)
    .where_not_null("u.verified_at");

// Use with SELECT and JOIN
let users = Users::query()?
    .alias("u")
    .select(&["u.id", "u.name", "COUNT(p.id) as posts"])
    .apply_filter(&active_filter)
    .left_join("posts AS p", "p.user_id = u.id")
    .group_by(&["u.id", "u.name"])
    .get_raw()
    .await?;
}

Working with Models

Field Access

Generated models provide getters and setters:

#![allow(unused)]
fn main() {
let user = Users::get_by_id(123).await?.unwrap();

// Getters
let email = user.email();        // &str for String fields
let id = user.id();              // i32/i64 for ID
let active = user.is_active();   // bool
let status = user.status();      // Option<&str> for enum
let created = user.created_at(); // Option<DateTime<Utc>>

// Setters (track changes automatically)
let mut user = user;
user.set_email("new@example.com");
user.set_is_active(false);

// Enum setters - PostgreSQL type casting is automatic
user.set_status(Some(Users::STATUS_ACTIVE));  // Uses constant
user.set_role("admin");  // Direct string also works

// Check what changed
if user.is_changed("email") {
    println!("Email was modified");
}

let changed_fields = user.changed_fields(); // Vec<String>
}

Working with NULL Values

#![allow(unused)]
fn main() {
// Setting NULL values
user.set_email_verified(None);  // Sets to NULL
user.set_email_verified(Some(Utc::now()));  // Sets value

// Checking for NULL
let users = Users::query()?
    .where_null("email_verified")
    .get()
    .await?;
}

Working with Enums

RustF provides intelligent enum handling with automatic PostgreSQL type casting:

#![allow(unused)]
fn main() {
// Enum constants are generated for each enum field
user.set_status(Some(Users::STATUS_ACTIVE));      // "active"
user.set_role(Users::ROLE_ADMIN);                 // "admin"

// PostgreSQL setters automatically handle type casting
// The setter adds ::enum_type_name suffix when needed
user.set_status(Some("active"));  // Becomes "active::status_enum" for PostgreSQL

// For query builders, use field-specific converter methods
let active_users = Users::query()?
    .where_eq("status", Users::as_status_enum("active"))
    .get()
    .await?;

// Converter methods handle database-specific requirements:
// PostgreSQL: Returns "active::status_enum" 
// MySQL/SQLite: Returns "active" (pass-through)
let admins = Users::query()?
    .where_eq("role", Users::as_role_enum("admin"))
    .where_eq("status", Users::as_status_enum("active"))
    .get()
    .await?;
}

Enum Constants

Generated models include constants for all enum values:

#![allow(unused)]
fn main() {
// Generated constants in your model
pub const STATUS_ACTIVE: &'static str = "active";
pub const STATUS_INACTIVE: &'static str = "inactive";
pub const STATUS_PENDING: &'static str = "pending";

pub const ROLE_ADMIN: &'static str = "admin";
pub const ROLE_USER: &'static str = "user";
pub const ROLE_MODERATOR: &'static str = "moderator";
}

Enum Converter Methods

Each enum field gets a converter method for query builder compatibility:

#![allow(unused)]
fn main() {
// Generated converter methods
pub fn as_status_enum(value: &str) -> String {
    // PostgreSQL: Adds type suffix
    // MySQL/SQLite: Pass-through
}

pub fn as_role_enum(value: &str) -> String {
    // Database-specific handling
}
}

Custom Business Logic

Add your methods to the wrapper model:

#![allow(unused)]
fn main() {
// src/models/users.rs
impl Users {
    // Custom finder
    pub async fn find_by_email(email: &str) -> Result<Option<Self>> {
        Self::query()?
            .where_eq("email", email)
            .first()
            .await
    }
    
    // Business logic
    pub async fn verify_email(&mut self) -> Result<()> {
        self.set_email_verified(Some(Utc::now()));
        self.set_is_active(true);
        self.update().await
    }
    
    // Complex queries
    pub async fn find_inactive_users(days: i64) -> Result<Vec<Self>> {
        let cutoff = Utc::now() - Duration::days(days);
        Self::query()?
            .where_eq("is_active", false)
            .where_lt("last_login", cutoff.to_rfc3339())
            .get()
            .await
    }
}
}

Type Safety

Using Type Constants

Instead of magic strings, use generated type constants:

#![allow(unused)]
fn main() {
// ❌ Avoid
let users = Users::query()?.where_eq("email", email).get().await?;

// βœ… Prefer (compile-time checked)
let users = Users::query()?
    .where_eq(Users::columns::EMAIL, email)
    .get()
    .await?;

// For enums, use converter methods in queries
// ❌ Avoid - Won't work correctly with PostgreSQL
let users = Users::query()?
    .where_eq("status", "active")
    .get()
    .await?;

// βœ… Correct - Handles database-specific enum types
let users = Users::query()?
    .where_eq("status", Users::as_status_enum("active"))
    .get()
    .await?;
}

SqlValue Conversions

The query builder accepts many types through Into<SqlValue>:

#![allow(unused)]
fn main() {
// All of these work
query.where_eq("age", 25);           // i32
query.where_eq("age", 25i64);        // i64
query.where_eq("name", "John");      // &str
query.where_eq("name", String::from("John")); // String
query.where_eq("name", &name);       // &String (reference)
query.where_eq("active", true);      // bool
query.where_eq("created", Utc::now()); // DateTime
query.where_eq("data", json!({"key": "value"})); // JSON
}

Counting and Aggregation

Count Operations

#![allow(unused)]
fn main() {
// Count all records
let total = Users::count().await?;

// Count with conditions
let active_count = Users::query()?
    .where_eq("is_active", true)
    .count()
    .await?;

// Count by group (using raw SQL for now)
// Future: Add group_by support
}

Existence Checks

#![allow(unused)]
fn main() {
// Check if any users exist
let has_users = Users::query()?.exists().await?;

// Check with conditions
let has_admins = Users::query()?
    .where_eq("role", "admin")
    .exists()
    .await?;
}

Pagination

RustF provides two approaches to pagination:

1. Simple Pagination (Legacy)

#![allow(unused)]
fn main() {
// Simple pagination
let page = 2;
let per_page = 20;
let users = Users::paginate(page, per_page).await?;

// Pagination with conditions
let active_users = Users::query()?
    .where_eq("is_active", true)
    .order_by("created_at", OrderDirection::Desc)
    .paginate(page, per_page)
    .get_all()
    .await?;

// Manual limit/offset
let users = Users::query()?
    .limit(20)
    .offset(40)  // Skip first 40
    .get_all()
    .await?;
}

The .get_paginated() method returns a PagedResult<T> that includes both the data and pagination metadata:

#![allow(unused)]
fn main() {
use rustf::prelude::*;

// Get paginated results with metadata
let result = Users::query()?
    .where_eq("is_active", true)
    .order_by("created_at", OrderDirection::Desc)
    .get_paginated(2, 20)
    .await?;

// Access the data
for user in &result.rows {
    println!("User: {}", user.name);
}

// Access pagination metadata
println!("Page {} of {}", result.page, result.total_pages);
println!("Total rows: {}", result.total_rows);
println!("Has next page: {}", result.has_next);
println!("Has previous page: {}", result.has_prev);

// Convert to Pagination for templates
let pagination = U::pagination_from_paged_result(&result, "/users?page={0}");

// Use in view
ctx.view("users/list", json!({
    "users": result.rows,
    "pagination": pagination.to_json()
}))
}

PagedResult Structure

#![allow(unused)]
fn main() {
pub struct PagedResult<T> {
    pub rows: Vec<T>,           // The actual data rows for the current page
    pub page: u32,              // Current page number (1-based)
    pub per_page: u32,          // Number of items per page
    pub total_rows: i64,         // Total number of rows matching the query
    pub total_pages: u32,       // Total number of pages
    pub has_next: bool,         // Whether there is a next page
    pub has_prev: bool,         // Whether there is a previous page
}
}

Helper Methods

#![allow(unused)]
fn main() {
// Check if first/last page
if result.is_first() { /* ... */ }
if result.is_last() { /* ... */ }

// Get next/previous page numbers
if let Some(next_page) = result.next_page() {
    println!("Next page: {}", next_page);
}

if let Some(prev_page) = result.prev_page() {
    println!("Previous page: {}", prev_page);
}
}

Converting to Template Pagination

To use with templates, convert PagedResult to Pagination using U::pagination_from_paged_result():

#![allow(unused)]
fn main() {
// Convert for template rendering
let pagination = U::pagination_from_paged_result(&result, "/users?page={0}");

// Or use the direct function
use rustf::utils::pagination;
let pagination = pagination::pagination_from_paged_result(&result, "/users?page={0}");
}

This separation keeps database concerns (PagedResult) separate from template concerns (Pagination).

Error Handling

All database operations return Result<T>:

#![allow(unused)]
fn main() {
use rustf::Result;

async fn get_user(id: i32) -> Result<Users> {
    match Users::get_by_id(id).await? {
        Some(user) => Ok(user),
        None => Err(rustf::Error::ModelNotFound(format!("User {} not found", id))),
    }
}

// Handle different cases
match Users::get_by_id(id).await {
    Ok(Some(user)) => {
        // User found
    },
    Ok(None) => {
        // User not found
    },
    Err(e) => {
        // Database error
        log::error!("Database error: {}", e);
    }
}
}

Best Practices

1. Use Query Builder Over Raw SQL

#![allow(unused)]
fn main() {
// βœ… Good - Type-safe, database-agnostic
let users = Users::query()?
    .where_eq("is_active", true)
    .get()
    .await?;

// ⚠️ Escape hatch - only when the builder can't express the query.
// Always parameterize (never interpolate) to avoid SQL injection. The SQL is
// yours to keep portable: placeholder syntax is dialect-specific (`?` for
// MySQL/SQLite, `$1` for PostgreSQL).
let users = DB::fetch_all_with_params(
    "SELECT * FROM users WHERE is_active = ?",
    vec![true.into()],
).await?;
}

2. Always Check Option Returns

#![allow(unused)]
fn main() {
// βœ… Good - Handle None case
if let Some(user) = Users::get_by_id(id).await? {
    // Work with user
} else {
    // Handle not found
}

// ❌ Bad - Will panic on None
let user = Users::get_by_id(id).await?.unwrap();
}

3. Use Transactions for Multiple Operations

#![allow(unused)]
fn main() {
// Future: Transaction support planned
// For now, ensure operations are idempotent
}

4. Leverage Change Tracking

#![allow(unused)]
fn main() {
// βœ… Good - Only updates changed fields
let mut user = Users::get_by_id(id).await?.unwrap();
user.set_email("new@example.com");
user.update().await?;  // Only updates email

// ❌ Less efficient - Updates all fields
// (Would update everything if using a different ORM)
}

5. Use Builder Pattern for Creation

#![allow(unused)]
fn main() {
// βœ… Good - Clear, validated
let user = Users::builder()
    .email("user@example.com")
    .username("johndoe")
    .status(Some(Users::STATUS_ACTIVE))  // Use enum constants
    .role(Users::ROLE_USER)
    .save()
    .await?;

// ❌ More verbose - Manual struct creation
let user = Users { /* all fields */ };
}

6. Use Enum Converter Methods in Queries

#![allow(unused)]
fn main() {
// βœ… Good - Works across all databases
let active_admins = Users::query()?
    .where_eq("status", Users::as_status_enum("active"))
    .where_eq("role", Users::as_role_enum("admin"))
    .get()
    .await?;

// ❌ Bad - May fail with PostgreSQL enums
let active_admins = Users::query()?
    .where_eq("status", "active")  // Missing type suffix for PostgreSQL
    .where_eq("role", "admin")
    .get()
    .await?;

// βœ… Good - Using constants with converter
let pending = Users::query()?
    .where_eq("status", Users::as_status_enum(Users::STATUS_PENDING))
    .get()
    .await?;
}

Configuration Access

Use the global CONF for configuration values:

#![allow(unused)]
fn main() {
use rustf::CONF;

// Get database URL
let db_url = CONF::get_string("database.url");

// Get with default
let max_conn = CONF::get_or("database.max_connections", 10);

// Check feature flags
if CONF::get_bool("features.advanced_search").unwrap_or(false) {
    // Advanced search enabled
}
}

Performance Tips

  1. Use exists() instead of count() > 0

    #![allow(unused)]
    fn main() {
    // βœ… Faster
    let has_users = Users::query()?.exists().await?;
    
    // ❌ Slower
    let has_users = Users::query()?.count().await? > 0;
    }
  2. Select only needed columns

    #![allow(unused)]
    fn main() {
    // βœ… Good - Only fetch what you need
    let users = Users::query()?
        .select(&["id", "name", "email"])
        .where_eq("is_active", true)
        .get()
        .await?;
    
    // ❌ Avoid - Fetches all columns
    let users = Users::query()?
        .where_eq("is_active", true)
        .get()
        .await?;
    }
  3. Use pagination for large datasets

    #![allow(unused)]
    fn main() {
    // βœ… Good
    let users = Users::paginate(1, 100).await?;
    
    // ❌ Bad for large tables
    let all_users = Users::all().await?;
    }
  4. Batch operations when possible

    #![allow(unused)]
    fn main() {
    // Future: Bulk insert/update support
    }

Debugging

Enable SQL Logging

# In config.toml
[logging]
level = "debug"  # Shows SQL queries

Inspect Generated SQL

#![allow(unused)]
fn main() {
// Get the SQL without executing
let (sql, params) = Users::query()?
    .where_eq("email", "test@example.com")
    .to_sql()?;
    
println!("SQL: {}", sql);
println!("Params: {:?}", params);
}

Multi-Database Support

RustF automatically handles dialect differences:

#![allow(unused)]
fn main() {
// This works on PostgreSQL, MySQL, and SQLite
let users = Users::query()?
    .where_like("email", "%@example.com")
    .limit(10)
    .get()
    .await?;

// Behind the scenes:
// PostgreSQL: "email LIKE $1 LIMIT 10"
// MySQL: "email LIKE ? LIMIT 10"  
// SQLite: "email LIKE ? LIMIT 10"
}

Limitations & Future Features

Current Limitations

  • No transaction support yet
  • Raw parameterized SQL is available cross-dialect via DB::execute_with_params / DB::fetch_all_with_params, but the SQL itself (placeholders, functions) is dialect-specific
  • No HAVING clause support (GROUP BY is supported)
  • Limited aggregate function helpers (use select_raw() for now)

Coming Soon

  • Transaction support
  • Migrations integration
  • Bulk insert/update
  • Query caching
  • Connection retry logic

Summary

RustF’s database layer provides:

  • Zero boilerplate - No connection passing
  • Type safety - Compile-time query validation
  • Smart updates - Change tracking built-in
  • Multi-database - Write once, run anywhere
  • Developer friendly - Intuitive API inspired by Laravel

Start with schemas, generate models, and enjoy a modern database experience in Rust!# πŸ—„οΈ RustF Multi-Database Query Builder

A type-safe, AI-friendly SQL query builder for Rust that supports PostgreSQL, MySQL, MariaDB, and SQLite with a unified API. Part of the RustF web framework ecosystem.

πŸ“– Complete Guide: For comprehensive documentation including model generation, CLI workflows, and AI agent guidance, see the CLI section and Schemas Guide

🌟 Features

  • πŸš€ Type-safe query building with compile-time validation
  • πŸ”„ Multi-database support (PostgreSQL, MySQL, MariaDB, SQLite)
  • πŸ€– AI-friendly design with predictable method names and clear error messages
  • πŸ“ Automatic SQL dialect handling for cross-database compatibility
  • πŸ›‘οΈ SQL injection protection through parameterized queries
  • πŸ“Š Schema builder with database-specific type mapping
  • πŸ” Comprehensive WHERE clauses including LIKE, IN, BETWEEN, NULL checks
  • πŸ”— All JOIN types (INNER, LEFT, RIGHT, FULL, CROSS)
  • πŸ“„ Built-in pagination and aggregation helpers
  • ⚑ Zero-cost abstractions leveraging Rust’s type system
  • πŸ—οΈ Framework integration with RustF model system and CLI tools

Table of Contents

Installation

Add this to your Cargo.toml:

[dependencies]
query-builder = "0.1.0"
sqlx = { version = "0.8", features = ["postgres", "mysql", "sqlite", "runtime-tokio-rustls", "uuid", "chrono", "rust_decimal"] }
tokio = { version = "1", features = ["full"] }
thiserror = "1.0"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
async-trait = "0.1"

⚑ Quick Start

#![allow(unused)]
fn main() {
use rustf::models::Users;

// Simple model operations
let user = Users::get_by_id(123).await?;
let admins = Users::query()?.where_eq("role", "admin").get().await?;

// Model-scoped query builder
let active_users = Users::query()?
    .where_eq("is_active", true)
    .where_gt("age", 18)
    .where_like("email", "%@gmail.com")
    .order_by("created_at", OrderDirection::Desc)
    .limit(10)
    .get()
    .await?;
}

2. Direct Query Builder Usage

use rustf::models::{AnyDatabase, QueryBuilder, OrderDirection};

#[tokio::main] 
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Connect to any supported database
    let db = AnyDatabase::connect("postgresql://localhost/myapp").await?;
    
    // Build and execute a query
    let (sql, params) = db.query()
        .from("users")
        .where_gt("age", 18)
        .where_like("email", "%@gmail.com")
        .order_by("created_at", OrderDirection::Desc)
        .limit(10)
        .build()?;
    
    println!("Generated SQL: {}", sql);
    println!("Parameters: {:?}", params);
    
    Ok(())
}

3. Generate Models from Schema

# Create schema file
cat > schemas/users.yaml << EOF
name: users
table: users
fields:
  id: { type: integer, primary_key: true, auto_increment: true }
  name: { type: string, max_length: 100, required: true }
  email: { type: string, max_length: 255, unique: true, required: true }
  created_at: { type: timestamp, default: now }
EOF

# Generate models
rustf-cli schema generate models --schema-path schemas --output src/models

Database Connection

The library automatically detects the database type from the connection URL:

#![allow(unused)]
fn main() {
// PostgreSQL
let pg_db = AnyDatabase::connect("postgresql://user:pass@localhost/dbname").await?;

// MySQL
let mysql_db = AnyDatabase::connect("mysql://user:pass@localhost/dbname").await?;

// SQLite
let sqlite_db = AnyDatabase::connect("sqlite://path/to/database.db").await?;

// In-memory SQLite
let memory_db = AnyDatabase::connect("sqlite::memory:").await?;
}

Query Building

Basic Queries

#![allow(unused)]
fn main() {
// Select all columns
let query = db.query()
    .from("users")
    .build()?;
// SELECT * FROM "users" (PostgreSQL)
// SELECT * FROM `users` (MySQL)

// Select specific columns
let query = db.query()
    .select(vec!["id", "name", "email"])
    .from("users")
    .build()?;
// SELECT id, name, email FROM "users"

// Count query
let count = db.query()
    .from("users")
    .count()
    .build()?;
// SELECT COUNT(*) FROM "users"
}

WHERE Conditions

The library provides a comprehensive set of WHERE operations:

#![allow(unused)]
fn main() {
// Basic comparisons
query.where_eq("status", "active")      // WHERE status = ?
query.where_ne("status", "deleted")     // WHERE status <> ?
query.where_gt("age", 18)               // WHERE age > ?
query.where_gte("age", 18)              // WHERE age >= ?
query.where_lt("price", 100)            // WHERE price < ?
query.where_lte("price", 100)           // WHERE price <= ?

// Pattern matching
query.where_like("email", "%@gmail.com")     // WHERE email LIKE ?
query.where_not_like("email", "%spam%")      // WHERE email NOT LIKE ?

// IN clauses
query.where_in("status", vec!["active", "pending"])      // WHERE status IN (?, ?)
query.where_not_in("role", vec!["admin", "super"])       // WHERE role NOT IN (?, ?)

// NULL checks
query.where_null("deleted_at")          // WHERE deleted_at IS NULL
query.where_not_null("verified_at")     // WHERE verified_at IS NOT NULL

// Range queries
query.where_between("age", 18, 65)      // WHERE age BETWEEN ? AND ?

// OR conditions
query.where_eq("status", "active")
     .or_where_eq("role", "admin")      // WHERE status = ? OR role = ?

// Raw SQL conditions
query.where_raw("(status = 'active' OR created_at > NOW() - INTERVAL '1 day')")
}

Combining Conditions

#![allow(unused)]
fn main() {
let users = db.query()
    .from("users")
    .where_eq("active", true)
    .where_gte("age", 18)
    .where_like("email", "%@%")
    .where_not_null("verified_at")
    .build()?;
// WHERE active = ? AND age >= ? AND email LIKE ? AND verified_at IS NOT NULL
}

JOIN Operations

All standard SQL joins are supported:

#![allow(unused)]
fn main() {
// INNER JOIN
query.join("posts", "posts.user_id = users.id")

// LEFT JOIN
query.left_join("posts", "posts.user_id = users.id")

// RIGHT JOIN (not supported in SQLite)
query.right_join("posts", "posts.user_id = users.id")?

// FULL JOIN (not supported in MySQL/MariaDB)
query.full_join("posts", "posts.user_id = users.id")?

// CROSS JOIN
query.cross_join("categories")

// Complex join example
let results = db.query()
    .select(vec!["u.name", "u.email", "COUNT(p.id) as post_count"])
    .from("users u")
    .left_join("posts p", "p.user_id = u.id")
    .where_eq("u.active", true)
    .group_by(vec!["u.id", "u.name", "u.email"])
    .having("COUNT(p.id)", ">", 5)
    .order_by("post_count", OrderDirection::Desc)
    .build()?;
}

Aggregations

Built-in aggregation helpers:

#![allow(unused)]
fn main() {
// Simple count
let count = db.query()
    .from("users")
    .count()
    .where_eq("active", true)
    .build()?;

// Count specific column
let count = db.query()
    .from("orders")
    .count_column("DISTINCT user_id")
    .build()?;

// Multiple aggregations
let stats = db.query()
    .from("orders")
    .aggregate(vec![
        ("COUNT", "*"),
        ("SUM", "total"),
        ("AVG", "total"),
        ("MAX", "total"),
        ("MIN", "total")
    ])
    .where_gte("created_at", "2024-01-01")
    .group_by(vec!["product_id"])
    .build()?;
}

Ordering and Limiting

#![allow(unused)]
fn main() {
// Simple ordering
query.order_by("created_at", OrderDirection::Desc)

// Multiple order by
query.order_by_multiple(vec![
    ("status", OrderDirection::Asc),
    ("created_at", OrderDirection::Desc)
])

// Limiting results
query.limit(10)
query.offset(20)

// Pagination helper
query.paginate(2, 20)  // Page 2, 20 items per page
// Automatically calculates: LIMIT 20 OFFSET 20
}

Schema Builder

Create database tables with automatic type mapping:

#![allow(unused)]
fn main() {
use query_builder::{SchemaBuilder, DatabaseBackend};

let schema = SchemaBuilder::new(DatabaseBackend::Postgres);

let sql = schema.create_table("users")
    .id()                                    // SERIAL PRIMARY KEY
    .string("email", Some(255))
        .not_null()
        .unique()                           // VARCHAR(255) NOT NULL UNIQUE
    .string("name", Some(100))              // VARCHAR(100)
    .boolean("active")
        .default("TRUE")                    // BOOLEAN DEFAULT TRUE
    .timestamp("created_at")
        .default("CURRENT_TIMESTAMP")       // TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    .build();

// Different databases get appropriate types:
// PostgreSQL: SERIAL, VARCHAR, BOOLEAN, TIMESTAMP WITH TIME ZONE
// MySQL: INT AUTO_INCREMENT, VARCHAR, TINYINT(1), DATETIME
// SQLite: INTEGER PRIMARY KEY AUTOINCREMENT, TEXT, INTEGER, TEXT
}

Available Column Types

#![allow(unused)]
fn main() {
.id()                           // Auto-incrementing primary key
.uuid("column_name")            // UUID (or equivalent)
.string("column_name", Some(255))  // Variable-length string
.boolean("column_name")         // Boolean type
.timestamp("column_name")       // Timestamp/datetime
.integer("column_name")         // Integer
.float("column_name")           // Floating point
.text("column_name")            // Long text
}

Column Modifiers

#![allow(unused)]
fn main() {
.not_null()                     // NOT NULL constraint
.unique()                       // UNIQUE constraint
.default("value")               // DEFAULT value
.primary_key()                  // PRIMARY KEY constraint
}

Error Handling

The library provides AI-friendly error messages:

#![allow(unused)]
fn main() {
match result {
    Err(QueryError::MissingClause { clause }) => {
        // "Missing required clause: from. Add .from() to your query."
    },
    Err(QueryError::UnsupportedFeature { backend, feature }) => {
        // "Feature not supported in PostgreSQL: RIGHT JOIN"
    },
    Err(QueryError::InvalidColumn { column, available }) => {
        // "Invalid column name: 'usr_name'. Available columns: ['id', 'name', 'email']"
    },
    _ => {}
}
}

Database-Specific Features

The library automatically handles database differences:

Placeholders

  • PostgreSQL: $1, $2, $3
  • MySQL/SQLite: ?, ?, ?

Identifier Quoting

  • PostgreSQL/SQLite: "column_name"
  • MySQL/MariaDB: `column_name`

RETURNING Clause

  • Supported: PostgreSQL, SQLite
  • Not supported: MySQL/MariaDB

Boolean Types

  • PostgreSQL: BOOLEAN
  • MySQL/MariaDB: TINYINT(1)
  • SQLite: INTEGER

Examples

Example 1: User Authentication Query

#![allow(unused)]
fn main() {
let user = db.query()
    .select(vec!["id", "email", "password_hash", "role"])
    .from("users")
    .where_eq("email", email)
    .where_eq("active", true)
    .where_null("deleted_at")
    .build()?;
}

Example 2: Search with Pagination

#![allow(unused)]
fn main() {
let search_term = "%rust%";
let page = 2;

let posts = db.query()
    .select(vec!["id", "title", "content", "author_id", "created_at"])
    .from("posts")
    .where_like("title", &search_term)
    .or_where_like("content", &search_term)
    .where_eq("published", true)
    .order_by("created_at", OrderDirection::Desc)
    .paginate(page, 20)
    .build()?;
}

Example 3: Dashboard Statistics

#![allow(unused)]
fn main() {
let stats = db.query()
    .from("orders")
    .aggregate(vec![
        ("COUNT", "*"),
        ("SUM", "total_amount"),
        ("AVG", "total_amount")
    ])
    .where_between("created_at", start_date, end_date)
    .where_eq("status", "completed")
    .group_by(vec!["DATE(created_at)"])
    .order_by("DATE(created_at)", OrderDirection::Asc)
    .build()?;
}

Example 4: Complex Report Query

#![allow(unused)]
fn main() {
let report = db.query()
    .select(vec![
        "c.name as category",
        "p.name as product",
        "SUM(oi.quantity) as total_sold",
        "SUM(oi.quantity * oi.price) as revenue"
    ])
    .from("order_items oi")
    .join("orders o", "o.id = oi.order_id")
    .join("products p", "p.id = oi.product_id")
    .join("categories c", "c.id = p.category_id")
    .where_eq("o.status", "completed")
    .where_between("o.created_at", "2024-01-01", "2024-12-31")
    .group_by(vec!["c.id", "c.name", "p.id", "p.name"])
    .having("SUM(oi.quantity)", ">", 100)
    .order_by("revenue", OrderDirection::Desc)
    .limit(50)
    .build()?;
}

API Reference

QueryBuilder Methods

MethodDescriptionExample
select(columns)Select specific columns.select(vec!["id", "name"])
from(table)Specify table.from("users")
where_*WHERE conditions.where_eq("status", "active")
or_where_*OR WHERE conditions.or_where_eq("role", "admin")
join(table, on)INNER JOIN.join("posts", "posts.user_id = users.id")
left_join(table, on)LEFT JOIN.left_join("posts", "posts.user_id = users.id")
group_by(columns)GROUP BY.group_by(vec!["user_id"])
having(col, op, val)HAVING clause.having("COUNT(*)", ">", 5)
order_by(col, dir)ORDER BY.order_by("created_at", OrderDirection::Desc)
limit(n)LIMIT results.limit(10)
offset(n)OFFSET results.offset(20)
distinct()SELECT DISTINCT.distinct()
count()COUNT(*).count()
paginate(page, per_page)Pagination helper.paginate(2, 20)

WHERE Condition Methods

MethodSQL Equivalent
where_eq(col, val)WHERE col = val
where_ne(col, val)WHERE col <> val
where_gt(col, val)WHERE col > val
where_gte(col, val)WHERE col >= val
where_lt(col, val)WHERE col < val
where_lte(col, val)WHERE col <= val
where_like(col, pattern)WHERE col LIKE pattern
where_not_like(col, pattern)WHERE col NOT LIKE pattern
where_in(col, values)WHERE col IN (values)
where_not_in(col, values)WHERE col NOT IN (values)
where_between(col, start, end)WHERE col BETWEEN start AND end
where_null(col)WHERE col IS NULL
where_not_null(col)WHERE col IS NOT NULL

Best Practices

  1. Use parameterized queries: The library automatically parameterizes all values to prevent SQL injection.

  2. Check feature support: Some features like RIGHT JOIN (SQLite) or FULL JOIN (MySQL) aren’t universally supported. The library returns clear errors for unsupported features.

  3. Use type-safe values: Pass proper Rust types that implement Into<SqlValue>.

  4. Handle errors appropriately: Use the detailed error types to provide meaningful feedback to users.

  5. Leverage the schema builder: Use it to ensure consistent table structures across different databases.

πŸ€– AI Agent Guidelines

When working with the RustF query builder:

βœ… Recommended:

  • Use model-scoped queries (Users::query()) for type safety
  • Use type constants (UsersBase::Types::email) instead of hardcoding types
  • Handle database-specific features gracefully with error checking
  • Use the unified AnyDatabase API for cross-database compatibility

❌ Avoid:

  • Hardcoding SQL strings when the query builder can generate them
  • Ignoring database feature limitations (RIGHT JOIN in SQLite, etc.)
  • Using raw parameters instead of type-safe SqlValue conversion

Example AI-Friendly Error Handling:

#![allow(unused)]
fn main() {
match query.right_join("posts", "posts.user_id = users.id") {
    Ok(q) => q,
    Err(QueryError::UnsupportedFeature { backend, feature }) => {
        // Fallback to LEFT JOIN for compatibility
        query.left_join("posts", "posts.user_id = users.id")?
    }
}
}

🀝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

Development Setup

# Clone the repository
git clone https://github.com/rustf/rustf.git
cd rustf

# Run tests
cargo test

# Test with different databases
docker-compose up -d postgres mysql
cargo test --features="postgres,mysql,sqlite"

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

Pagination Helper Guide

RustF provides a built-in pagination helper through the U::paginate() function that makes it easy to implement pagination in your web applications.

Overview

The pagination helper creates a complete pagination object with:

  • Page navigation (first, last, previous, next)
  • Page number ranges
  • URL generation with customizable patterns
  • Template-friendly JSON output

Basic Usage

In Controllers (Legacy Approach)

#![allow(unused)]
fn main() {
use rustf::prelude::*;

async fn list_users(ctx: &mut Context) -> Result<()> {
    // Parse page from query parameters
    let page = ctx.query_as_or::<u32>("page", 1);
    
    let per_page = 20;
    
    // Get total count from database
    let total_users = Users::count().await?;
    
    // Fetch paginated data
    let users = Users::paginate(page, per_page).await?;
    
    // Create pagination object
    let pagination = U::paginate(
        total_users,           // Total items
        page,                  // Current page (1-based)
        per_page,              // Items per page
        "/users?page={0}"      // URL pattern with {0} placeholder
    );
    
    // Pass to view
    ctx.view("users/list", json!({
        "users": users,
        "pagination": pagination.to_json()
    }))
}
}
#![allow(unused)]
fn main() {
use rustf::prelude::*;

async fn list_users(ctx: &mut Context) -> Result<()> {
    // Parse page from query parameters
    let page = ctx.query_as_or::<u32>("page", 1);
    
    let per_page = 20;
    
    // Get paginated results with metadata (single method call)
    let result = Users::query()?
        .where_eq("is_active", true)
        .order_by("created_at", OrderDirection::Desc)
        .get_paginated(page, per_page)
        .await?;
    
    // Convert to Pagination for templates
    let pagination = U::pagination_from_paged_result(&result, "/users?page={0}");
    
    // Pass to view
    ctx.view("users/list", json!({
        "users": result.rows,
        "pagination": pagination.to_json()
    }))
}
}

Advantages of the recommended approach:

  • Single method call (.get_paginated()) instead of separate count + query
  • Automatic metadata calculation (total_rows, total_pages, has_next, has_prev)
  • Better separation of concerns (database vs template)
  • More efficient (parallel execution of COUNT and SELECT queries)

In Templates (Total.js Syntax)

<!-- Basic pagination controls -->
<div class="pagination">
    @{if pagination.isPrev}
        <a href="@{pagination.prev.url}">Previous</a>
    @{fi}
    
    @{foreach page in pagination.range}
        @{if page.selected}
            <span class="current">@{page.page}</span>
        @{else}
            <a href="@{page.url}">@{page.page}</a>
        @{fi}
    @{end}
    
    @{if pagination.isNext}
        <a href="@{pagination.next.url}">Next</a>
    @{fi}
</div>

Complete Navigation Example

<!-- Full pagination with first/last links -->
<div class="pagination">
    <!-- First & Previous -->
    @{if !pagination.isFirst}
        <a href="@{pagination.first.url}">Β« First</a>
    @{fi}
    
    @{if pagination.isPrev}
        <a href="@{pagination.prev.url}">β€Ή Previous</a>
    @{else}
        <span class="disabled">β€Ή Previous</span>
    @{fi}
    
    <!-- Page Numbers -->
    @{foreach page in pagination.range}
        @{if page.selected}
            <span class="current">@{page.page}</span>
        @{else}
            <a href="@{page.url}">@{page.page}</a>
        @{fi}
    @{end}
    
    <!-- Next & Last -->
    @{if pagination.isNext}
        <a href="@{pagination.next.url}">Next β€Ί</a>
    @{else}
        <span class="disabled">Next β€Ί</span>
    @{fi}
    
    @{if !pagination.isLast}
        <a href="@{pagination.last.url}">Last Β»</a>
    @{fi}
</div>

<!-- Page info -->
<p>Page @{pagination.page} of @{pagination.count} 
   (@{pagination.items} total items)</p>

Pagination Object Structure

The pagination.to_json() method returns:

{
  "items": 157,        // Total number of items
  "page": 5,           // Current page
  "count": 16,         // Total pages
  "per_page": 10,      // Items per page
  "isFirst": false,    // Is first page?
  "isLast": false,     // Is last page?
  "isPrev": true,      // Has previous page?
  "isNext": true,      // Has next page?
  "first": {
    "url": "/users?page=1"
  },
  "last": {
    "url": "/users?page=16"
  },
  "prev": {
    "url": "/users?page=4"
  },
  "next": {
    "url": "/users?page=6"
  },
  "range": [           // Page numbers for display
    {
      "page": 3,
      "url": "/users?page=3",
      "selected": false
    },
    {
      "page": 4,
      "url": "/users?page=4",
      "selected": false
    },
    {
      "page": 5,
      "url": "/users?page=5",
      "selected": true
    },
    // ... up to 7 pages by default
  ]
}

Advanced Usage

Custom URL Patterns

#![allow(unused)]
fn main() {
// Simple query parameter
let pagination = U::paginate(total, page, 20, "/posts?page={0}");

// With multiple parameters
let pagination = U::paginate(total, page, 20, "/posts?category=tech&page={0}");

// Path-based pagination
let pagination = U::paginate(total, page, 20, "/posts/page/{0}");

// With hash fragments
let pagination = U::paginate(total, page, 20, "/posts?page={0}#results");
}

Pagination with Filters

#![allow(unused)]
fn main() {
async fn search_posts(ctx: &mut Context) -> Result<()> {
    let page = ctx.query_as_or::<u32>("page", 1);
    let search = ctx.query_str_or("q", "");
    let category = ctx.query_str_or("category", "all");
    
    // Build query with filters
    let total = Posts::query()?
        .where_like("title", &format!("%{}%", search))
        .where_eq("category", category)
        .count()
        .await?;
    
    let posts = Posts::query()?
        .where_like("title", &format!("%{}%", search))
        .where_eq("category", category)
        .paginate(page, 20)
        .get()
        .await?;
    
    // Include filters in URL pattern
    let url_pattern = format!(
        "/search?q={}&category={}&page={{0}}", 
        U::encode(search),
        U::encode(category)
    );
    
    let pagination = U::paginate(total, page, 20, &url_pattern);
    
    ctx.view("search-results", json!({
        "posts": posts,
        "pagination": pagination.to_json(),
        "search": search,
        "category": category
    }))
}
}

Styling Example

.pagination {
    display: flex;
    justify-content: center;
    gap: 10px;
    margin: 20px 0;
}

.pagination a,
.pagination span {
    padding: 8px 12px;
    border: 1px solid #ddd;
    border-radius: 4px;
    text-decoration: none;
}

.pagination a:hover {
    background: #007bff;
    color: white;
}

.pagination .current {
    background: #007bff;
    color: white;
    font-weight: bold;
}

.pagination .disabled {
    color: #999;
    cursor: not-allowed;
}

API Reference

U::paginate()

#![allow(unused)]
fn main() {
pub fn paginate(
    total: i64,           // Total number of items
    page: u32,            // Current page (1-based)
    per_page: u32,        // Items per page
    url_pattern: &str     // URL pattern with {0} placeholder
) -> Pagination
}

U::pagination_from_paged_result()

Convert a PagedResult from database queries to a Pagination for template rendering:

#![allow(unused)]
fn main() {
pub fn pagination_from_paged_result<T>(
    paged_result: &PagedResult<T>,  // Paginated result from database query
    url_pattern: &str               // URL pattern with {0} placeholder
) -> Pagination
}

Example:

#![allow(unused)]
fn main() {
// Get paginated results from database
let result = Users::query()?
    .where_eq("is_active", true)
    .get_paginated(2, 20)
    .await?;

// Convert to Pagination for templates
let pagination = U::pagination_from_paged_result(&result, "/users?page={0}");

// Use in view
ctx.view("users/list", json!({
    "users": result.rows,
    "pagination": pagination.to_json()
}))
}

This function separates database concerns (PagedResult) from template rendering concerns (Pagination).

Pagination Methods

  • to_json() - Convert to JSON for template use
  • is_first() - Check if on first page
  • is_last() - Check if on last page
  • has_prev() - Check if previous page exists
  • has_next() - Check if next page exists
  • first_url() - Get URL for first page
  • last_url() - Get URL for last page
  • prev_url() - Get URL for previous page
  • next_url() - Get URL for next page
  • range(max_items) - Get page number range for display

PagedResult Methods

  • is_first() - Check if this is the first page
  • is_last() - Check if this is the last page
  • next_page() - Get the next page number (if available)
  • prev_page() - Get the previous page number (if available)

Best Practices

  1. Always validate page numbers - Ensure page is within valid range
  2. Use reasonable per_page limits - Typically 10-100 items
  3. Cache total counts - For large datasets, consider caching counts
  4. Include page info - Show β€œPage X of Y” for better UX
  5. Provide direct navigation - Include first/last links for long lists
  6. Make it accessible - Use proper ARIA labels and semantic HTML
  7. Handle edge cases - Empty results, single page, invalid page numbers

Schema Format Reference

RustF schemas are YAML files that describe your data model. They are the single source of truth: the CLI generates both Rust models (schema generate models) and full SQL DDL (schema generate sql) from them. SQL is a standard, but this YAML format is RustF-specific β€” this page is its complete specification.

This reference is derived from the actual parser (rustf-schema). Keys not listed here are ignored by the parser; a few keys are accepted for forward-compatibility but have no effect yet β€” those are marked (accepted, ignored).

schema generate sql is experimental. The DDL generator is verified on representative schemas across all three dialects, but has not yet been exercised at scale. Review the generated SQL before applying it. Model generation (schema generate models) is stable.

File layout

schemas/
β”œβ”€β”€ _meta.yaml        # optional global metadata (see below)
β”œβ”€β”€ users.yaml        # one file per table (or group several tables per file)
└── orders.yaml

Each table file maps a logical table name to a table definition. You may put several tables in one file.

# schemas/users.yaml
Users:                  # logical name (used for the generated model)
  table: users          # physical table name
  version: 1
  fields:
    id:
      type: mediumint
      primary_key: true
      auto: true

fields is a map, not a list. Each field is a key (id:), not a - name: id list item. List form does not parse.

Table definition

KeyTypeRequiredPurpose
tablestringyesPhysical table name used in generated SQL/queries.
versionintegeryesSchema version for change tracking and consistency checks.
namestringnoOverride for the generated model name (defaults to the YAML key).
descriptionstringnoHuman-readable description (emitted as a SQL comment).
database_typestringnomysql | postgres | sqlite (per-table override of _meta).
database_namestringnoSource database instance name (informational).
element_typestringnotable | view | materialized_view. Defaults to table.
viewmapnoView body β€” required when element_type is a view (see Views).
tagsstring[]noFree-form categorization.
ai_contextstringnoExtra guidance for AI code assistants.
fieldsmapyesΒΉField definitions (see below). Optional for views.
relationsmapnoRelationships to other tables (see below).
indexeslistnoIndex definitions (see below).
constraintslistnoTable-level constraints. (reserved β€” parsed but not yet enforced)

ΒΉ Required for tables. For views fields is optional and only drives typed, read-only model generation; omit it for an untyped view.

Views

A view is a Table entry with element_type: view (or materialized_view) and a view: block holding the SQL body. The body is raw, dialect-native SQL β€” the SELECT … statement without the leading CREATE VIEW <name> AS.

ActiveUserOrders:
  table: active_user_orders
  database_type: postgres
  element_type: view          # or: materialized_view
  version: 1
  description: "Open orders joined to their user."
  view:
    or_replace: true          # emit CREATE OR REPLACE VIEW (plain views only)
    sql: |
      SELECT o.id,
             o.user_id,
             u.email,
             o.total_cents
      FROM orders o
      JOIN users u ON u.id = o.user_id
      WHERE o.status = 'open'
  # Optional: typed output columns β†’ read-only model with no insert/update/delete.
  fields:
    id:          { type: int }
    user_id:     { type: int }
    email:       { type: string(255) }
    total_cents: { type: int }

view keys

KeyTypeRequiredPurpose
sqlstringyesRaw SELECT body. Emitted verbatim into CREATE VIEW … AS <sql>.
or_replaceboolnoEmit CREATE OR REPLACE VIEW. Ignored for materialized views (they are dropped and recreated).

Behavior

  • SQL generation emits CREATE [OR REPLACE] VIEW / CREATE MATERIALIZED VIEW, never CREATE TABLE. Views are always emitted after all tables, and a view that references another view is emitted after its dependency, so generation never hits a β€œrelation does not exist” error.
  • Models generated for views are read-only: insert / create / update / delete are omitted.
  • Validation requires a non-empty view.sql; a view does not need a primary key or any fields.
  • Introspection (db introspect / db generate-schemas) detects views and fills view.sql from pg_get_viewdef (PostgreSQL) or information_schema.VIEWS (MySQL), so an introspected view round-trips back to valid CREATE VIEW DDL.

A structured view form (select / from / where) for simple views is planned. Raw sql remains the escape hatch for anything non-trivial (CTEs, window functions, dialect specifics).

Field definition

A field maps a column name to its type and constraints.

email:
  type: string(150)
  required: true
  unique: true
  description: User's primary email

Field keys

The Effect column says where a key actually changes output:

  • DDL β€” emitted in the generated SQL schema.
  • model β€” changes the generated Rust struct/types.
  • metadata β€” parsed and exposed to tooling and AI assistants (via the CLI), but not enforced at runtime or in SQL. Validation keys live here today: they document intent but the generated model does not check them.
KeyTypeEffectPurpose
typestringDDL + modelColumn type. See Type system. Required.
valuesstring[]DDL + modelAllowed values β€” required when type: enum.
primary_keyboolDDL + modelMarks the primary key.
autoboolDDL + modelAuto-increment (SERIAL / AUTO_INCREMENT / AUTOINCREMENT).
requiredboolDDL + modelEmits NOT NULL; checked by the model builder.
nullableboolDDL + modelnullable: false also emits NOT NULL; otherwise Option<T>.
uniqueboolDDLEmits a UNIQUE constraint.
defaultscalarDDL + modelColumn default (string/number/bool).
foreign_keystringDDL"table.column" (or "table", defaulting to id).
on_deleteenumDDLFK action: cascade, restrict, set_null, set_default, no_action.
on_updateenumDDLSame actions as on_delete.
lang_typestringmodelOverride the generated Rust type (e.g. Option<u8>).
min / maxnumbermetadataIntended numeric range β€” not enforced.
min_length / max_lengthintegermetadataIntended string length β€” not enforced.
patternstringmetadataIntended regex β€” not enforced.
validationstring | mapmetadataNamed validator (email) or rule map β€” not enforced.
computedstringmetadataMarks a derived field β€” not generated.
hiddenboolmetadataIntended to hide from serialization β€” not enforced.
postgres_type_namestringmetadataNamed Postgres enum type hint.
transitionsmapmetadataIntended enum state transitions β€” not enforced.
aistringmetadataAI hint, emitted as a doc comment.
exampleanymetadataExample value (documentation).
enum, index, indexed, search_weight, column_commentβ€”ignored(accepted, parsed, no effect)

NOT NULL is emitted when required: true, nullable: false, or the field is the primary key.

Validation is not yet enforced. min, max, min_length, max_length, pattern, and validation are recorded as schema metadata and surfaced to tooling, but the generated models do not validate against them at runtime. Enforce these in your own code (e.g. a controller before hook) until runtime validation lands.

Type system

type is a string. Three forms are supported.

Simple types

These map to dialect-correct SQL (see the per-dialect table in the Database guide):

Schema typeNotes
tinyint, smallint, mediumint, int / integer, bigintInteger family; width preserved on MySQL, widened sensibly elsewhere.
serialAuto-increment integer.
boolean / boolTINYINT(1) on MySQL, BOOLEAN elsewhere.
decimal / numericFixed-point (prefer the parameterized form below).
float, doubleFloating point.
string / text, mediumtext, longtext, tinytextText.
date, time, datetime, timestampTemporal.
json, jsonbJSONB on Postgres, JSON on MySQL, TEXT on SQLite.
uuidUUID on Postgres, CHAR(36) on MySQL, TEXT on SQLite.
blob / binaryBinary data.

Native database type names produced by db generate-schema (e.g. mediumint) are accepted directly, so round-tripping an existing database works.

Parameterized types

username: { type: string(150) }     # VARCHAR(150)
code:     { type: char(8) }         # CHAR(8)
price:    { type: decimal(10,2) }   # DECIMAL(10,2)

Enum types

Enums require a sibling values list:

status:
  type: enum
  values: [active, inactive, pending]
  default: pending

This generates a native ENUM(...) on MySQL and a TEXT CHECK (status IN (...)) constraint on Postgres and SQLite.

Relations

relations:
  has_many:
    posts:
      model: Posts
      local_field: id
      foreign_field: author_id
  belongs_to:
    company:
      model: Companies
      local_field: company_id
      foreign_field: id
      on_delete: set_null
RelationRequired fieldsOptional
has_manymodel, local_field, foreign_fieldcascade, ai
has_onemodel, local_field, foreign_fieldcascade, ai
belongs_tomodel, local_field, foreign_fieldon_delete, on_update, ai
many_to_manymodel, through, local_through_field, foreign_through_field, local_field, foreign_fieldai

Relations drive model generation. Foreign-key DDL comes from a field’s foreign_key key, not from relations.

Indexes

Three forms:

indexes:
  - email                              # single-column
  - [last_name, first_name]            # composite
  - fields: [email]                    # detailed
    unique: true
    type: btree

Table-level constraints

A constraints: key is accepted by the parser but does nothing today β€” it is ignored by both SQL and model generation. In particular there is no raw-SQL CHECK support: a sql: "price >= 0" entry produces no SQL and no validation. The key exists only as a reserved slot for a future release.

For checks today, use field-level keys (which still record metadata) and enforce rules in your own code (e.g. a controller before hook) β€” see the validation note above.

Global metadata (_meta.yaml)

Optional. Provides defaults and informational metadata for the schema set. Only these keys are honored:

version: "1.0"
database_type: mysql          # default dialect for SQL generation
database_name: myapp
description: "Application schema"
ai_context: "Guidance for AI assistants working with this schema"

The SQL generator detects the target dialect from description / database_type. Set database_type (or mention the dialect in description) so the right SQL flavour is produced. Any other keys in _meta.yaml are ignored.

Complete example

# schemas/users.yaml
Users:
  table: users
  version: 1
  description: Application user accounts
  fields:
    id:
      type: mediumint
      primary_key: true
      auto: true
      required: true

    email:
      type: string(150)
      required: true
      unique: true
      validation: email

    password_hash:
      type: string(255)
      required: true
      hidden: true

    role:
      type: enum
      values: [admin, user, moderator]
      default: user
      required: true

    manager_id:
      type: mediumint
      foreign_key: users.id
      on_delete: set_null

    is_active:
      type: boolean
      default: true

    created_at:
      type: timestamp

  relations:
    belongs_to:
      manager:
        model: Users
        local_field: manager_id
        foreign_field: id

  indexes:
    - email

Generate from it:

rustf-cli schema generate models       # -> src/models/base/users.inc.rs
rustf-cli schema generate sql          # -> sql/schema.sql

RustF Configuration Guide

Complete documentation for configuration management in RustF

Overview

RustF provides a comprehensive configuration system inspired by Total.js, with a global CONF accessor that allows uniform configuration access throughout your application. Configuration can be loaded from TOML files, environment variables, or programmatically, with support for environment-specific settings and hot-reloading during development.

Key Features

  • Global CONF Access - Single, uniform way to access configuration anywhere
  • Dot Notation Paths - Access nested values with "server.port" syntax
  • Environment Support - Development and production environments
  • Multiple Sources - TOML files, environment variables, and defaults
  • Type-Safe Access - Typed getters for strings, integers, booleans, and floats
  • Custom Settings - Extensible with application-specific configuration

Global Configuration Access (CONF)

RustF provides a global CONF singleton that gives uniform access to configuration values using dot notation paths. This is the ONLY way to access configuration in RustF - there is no configuration access through Context or other means.

Basic Usage

#![allow(unused)]
fn main() {
use rustf::prelude::*;  // CONF is included in the prelude

// Access configuration values with dot notation
let port = CONF::get_int("server.port").unwrap_or(8000);
let host = CONF::get_string("server.host").unwrap_or_else(|| "127.0.0.1".to_string());
let db_url = CONF::get_string("database.url");

// Check if a configuration path exists
if CONF::has("database.url") {
    // Database is configured
}

// Get values with defaults
let timeout = CONF::get_or("server.timeout", 30);
let max_files = CONF::get_or("uploads.max_files", 5);

// Environment helpers
if CONF::is_production() {
    // Enable production optimizations
}

if CONF::is_development() {
    // Enable development features
}
}

CONF Methods

MethodDescriptionExample
get<T>(path)Get typed value at pathCONF::get::<u16>("server.port")
get_string(path)Get string valueCONF::get_string("database.url")
get_int(path)Get integer valueCONF::get_int("server.port")
get_bool(path)Get boolean valueCONF::get_bool("server.ssl_enabled")
get_float(path)Get float valueCONF::get_float("custom.rate")
get_or(path, default)Get with defaultCONF::get_or("server.port", 8000)
has(path)Check if path existsCONF::has("database.url")
env()Get current environmentCONF::env()
is_production()Check if productionCONF::is_production()
is_development()Check if developmentCONF::is_development()
all()Get entire configCONF::all()

Accessing Configuration in Different Contexts

In Controllers

#![allow(unused)]
fn main() {
use rustf::prelude::*;  // CONF is included in the prelude

async fn handler(ctx: &mut Context) -> rustf::Result<()> {
    // Configuration is accessed via CONF, not through ctx
    let upload_dir = CONF::get_string("uploads.directory").unwrap_or_else(|| "uploads".to_string());
    let max_size = CONF::get_int("uploads.max_file_size").unwrap_or(10485760);

    // Use configuration values
    if file.size > max_size as usize {
        return ctx.throw400(Some("File too large"));
    }

    // Save file to upload_dir...
    ctx.json(json!({ "status": "ok" }))
}
}

In Modules/Services

#![allow(unused)]
fn main() {
use rustf::prelude::*;  // CONF is included in the prelude

pub struct EmailService;

impl EmailService {
    pub fn send_email(&self, to: &str, subject: &str, body: &str) {
        // Access custom configuration sections via CONF
        // All sections (framework or custom) use the same dot notation
        let smtp_host = CONF::get_string("smtp.host").unwrap_or_else(|| "localhost".to_string());
        let smtp_port = CONF::get_int("smtp.port").unwrap_or(25);
        let from_email = CONF::get_string("smtp.user").unwrap_or_else(|| "noreply@example.com".to_string());
        
        // Send email using configuration...
    }
}
}

In Event Handlers

#![allow(unused)]
fn main() {
use rustf::prelude::*;  // CONF is included in the prelude

app.on("startup", |ctx| Box::pin(async move {
    // Access configuration during startup
    let db_url = CONF::get_string("database.url");
    let pool_size = CONF::get_int("database.max_connections").unwrap_or(10);
    
    if let Some(url) = db_url {
        // Initialize database with configuration
        initialize_database(&url, pool_size).await?;
    }
    
    Ok(())
}))
}

In Middleware

#![allow(unused)]
fn main() {
use async_trait::async_trait;
use rustf::middleware::{InboundAction, InboundMiddleware};
use rustf::prelude::*;  // CONF is included in the prelude

pub struct RateLimitMiddleware;

#[async_trait]
impl InboundMiddleware for RateLimitMiddleware {
    async fn process_request(&self, ctx: &mut Context) -> rustf::Result<InboundAction> {
        // Access rate limit configuration
        let max_requests = CONF::get_int("custom.rate_limit_max").unwrap_or(100);
        let window_seconds = CONF::get_int("custom.rate_limit_window").unwrap_or(60);

        // Apply rate limiting... return InboundAction::Stop to reject.
        Ok(InboundAction::Continue)
    }
}
}

Configuration Structure

AppConfig Schema

The main configuration structure in RustF:

#![allow(unused)]
fn main() {
pub struct AppConfig {
    pub environment: Environment,        // development or production
    pub server: ServerConfig,           // Server settings
    pub views: ViewConfig,              // Template engine settings
    pub session: SessionConfig,         // Session management
    pub static_files: StaticConfig,    // Static file serving
    pub database: DatabaseConfig,      // Database connection
    pub cors: CorsConfig,              // CORS settings
    pub logging: LoggingConfig,        // Logging configuration
    pub uploads: UploadConfig,         // File upload settings
    pub sections: HashMap<String, toml::Value>, // User-defined configuration sections
}
}

Framework sections (above) are strongly typed for IDE support and compile-time checking. User-defined sections are stored as TOML values and can be deserialized on-demand using config.section::<T>("name").

Configuration Sections

Server Configuration

[server]
host = "127.0.0.1"          # Server bind address
port = 8000                 # Server port
timeout = 30                # Request timeout in seconds
ssl_enabled = false         # Enable HTTPS
ssl_cert = "cert.pem"       # SSL certificate path (if ssl_enabled)
ssl_key = "key.pem"         # SSL private key path (if ssl_enabled)
max_connections = 1000      # Maximum concurrent connections

Views Configuration

[views]
directory = "views"         # Template directory path
default_layout = "layouts/default"  # Default layout template
cache_enabled = false       # Enable template caching
extension = "html"          # Template file extension
storage = "filesystem"      # Storage method: "filesystem" or "embedded"

Session Configuration

[session]
enabled = true              # Enable session middleware
cookie_name = "rustf_session"       # Session cookie name
idle_timeout = 900          # Idle timeout in seconds (15 min default)
absolute_timeout = 28800    # Absolute timeout in seconds (8 hours default)
same_site = "Lax"           # SameSite cookie policy
fingerprint_mode = "soft"   # Fingerprint mode for session binding
exempt_routes = []          # Routes exempt from session requirement

[session.storage]
type = "memory"             # Storage backend: "memory", "redis", or "database"
cleanup_interval = 300      # Cleanup interval in seconds (for memory storage)

Database Configuration

[database]
url = "postgresql://user:pass@localhost/myapp"  # Database connection URL
max_connections = 10        # Connection pool size
timeout = 5000              # Connection timeout in seconds

Static Files Configuration

[static_files]
directory = "public"        # Static files directory
url_prefix = "/static"      # URL prefix for static files
cache_enabled = true        # Enable caching headers
cache_max_age = 86400       # Cache max-age in seconds

CORS Configuration

[cors]
enabled = false             # Enable CORS
allowed_origins = ["*"]     # Allowed origins
allowed_methods = ["GET", "POST"]  # Allowed HTTP methods
allowed_headers = ["Content-Type"] # Allowed headers

Logging Configuration

[logging]
level = "info"              # Log level: debug, info, warn, error
file = "logs/app.log"       # Optional log file path

Upload Configuration

[uploads]
directory = "uploads"       # Upload directory
max_file_size = 10485760    # Max file size in bytes (10MB)
max_files = 5               # Max files per upload
allowed_extensions = []     # Allowed file extensions (empty = all)
blocked_extensions = ["exe", "bat", "sh", "cmd"]  # Blocked extensions
create_directories = true   # Auto-create upload directories

Custom Application Configuration

Any sections you define in config.toml are automatically available as configuration sections:

[app]
name = "MyApplication"
version = "1.0.0"
debug_mode = false

[payment]
stripe_key = "sk_test_xxxxx"
paypal_email = "business@example.com"

[smtp]
host = "smtp.gmail.com"
port = 587
user = "noreply@example.com"
password = "(env) SMTP_PASSWORD"

Access custom sections in Rust code using the section() method:

#![allow(unused)]
fn main() {
use rustf::prelude::*;
use serde::Deserialize;

#[derive(Deserialize)]
struct AppConfig {
    name: String,
    version: String,
    debug_mode: bool,
}

#[derive(Deserialize)]
struct PaymentConfig {
    stripe_key: String,
    paypal_email: String,
}

// Get typed access to custom sections
let app_cfg = config.section::<AppConfig>("app")?;
println!("App: {} v{}", app_cfg.name, app_cfg.version);

let payment = config.section::<PaymentConfig>("payment")?;
println!("Stripe key: {}", payment.stripe_key);

// Or use CONF global for uniform access
let app_name = CONF::get_string("app.name")?;
let stripe_key = CONF::get_string("payment.stripe_key")?;
}

Configuration Files

File Locations and Loading Order

Config loading follows this pipeline at startup:

  1. Base config (config.toml) is loaded first β€” always required in release builds.
  2. Environment is resolved from: the RUSTF_ENV env var β†’ then [app] environment field in config.toml β†’ then development default.
  3. Overlay is merged (config.dev.toml or config.prod.toml) on top of the base using TOML-level deep merge β€” only the keys present in the overlay override the base.
  4. Environment variables (RUSTF_* prefix) override individual values after merging.

Release binary note: In release builds the binary looks for config.toml in the same directory as the binary itself, not in the current working directory. Place config.toml, config.prod.toml, public/, and views/ next to the binary in your deployment directory.

--config note: When using --config /path/to/config.toml, the overlay (config.prod.toml / config.dev.toml) is also automatically loaded from the same directory as the specified file.

Example config.toml

# Base configuration for all environments

[app]
environment = "development"   # Controls which overlay is loaded (dev or prod)

[server]
host = "127.0.0.1"
port = 8000
timeout = 30

[views]
directory = "views"
default_layout = "layouts/default"
cache_enabled = false
extension = "html"

[session]
cookie_name = "rustf_session"
idle_timeout = 900
absolute_timeout = 28800

[database]
url = "postgresql://localhost/myapp_dev"
max_connections = 5

[static_files]
directory = "public"
url_prefix = "/static"

[uploads]
directory = "uploads"
max_file_size = 10485760

[custom]
api_endpoint = "http://localhost:3000/api"
feature_x_enabled = "false"

Environment-Specific Overrides

The overlay is loaded automatically based on the [app] environment value in config.toml. Only the keys you specify override the base β€” everything else is inherited.

config.prod.toml

# Production overrides β€” merged on top of config.toml when environment = "production"

[server]
host = "0.0.0.0"
port = 80
ssl_enabled = true
ssl_cert = "/etc/ssl/certs/app.crt"
ssl_key = "/etc/ssl/private/app.key"
max_connections = 2000

[views]
cache_enabled = true

[database]
url = "(env) DATABASE_URL"  # Override with env var at runtime
max_connections = 20

[logging]
level = "warn"
file = "/var/log/rustf/app.log"

[custom]
api_endpoint = "https://api.production.com"
feature_x_enabled = "true"

Values from the Environment or Files

Any string value in config.toml (or an overlay such as config.prod.toml) can point outside the file. The value is replaced when the configuration is loaded:

[server]
port = "(env) PORT"                       # environment variable

[database]
url = "(env) DATABASE_URL"

[custom.mail]
smtp_password = "(file) /run/secrets/smtp_password"   # file contents
ReferenceValue
"(env) NAME"the environment variable NAME
"(file) PATH"the contents of PATH, trailing newlines removed; a relative path is relative to the configuration file’s directory. The file must be a regular file of at most 1 MiB. Suited to Docker and Kubernetes secrets mounted under /run/secrets/

Rules:

  • Missing means failure. If the variable is not set or the file cannot be read, the application refuses to start, and the error names the key and the variable or file. In loading errors, and in AppConfig::section errors, a resolved value is replaced by *** wherever it appears quoted β€” which is how type errors report values, e.g. a port that does not fit β€” and wherever it appears unquoted if it is at least 8 characters long. A shorter value that ends up unquoted in a message (a short directory name in β€œdirectory does not exist: …”) is shown as is.
  • An unknown tag is an error. "(evn) PORT" stops the application instead of loading the literal text.
  • Typing. A framework key takes its declared type: "(env) PORT" becomes an integer for server.port, "true" a boolean for a boolean key. Every other value stays a string β€” database.url = "(file) ..." stays a string even if the file holds 123456. In your own sections nothing says whether "0042" is a number or a password, so the value stays a string and the reader decides: CONF::get::<u16>, CONF::get_or, CONF::get_int, get_float, get_bool and AppConfig::section::<T>() parse it when the requested type is a number or a boolean, and CONF::get_string returns it unchanged. This works for plain struct fields, Option, lists and maps; it does not reach into #[serde(flatten)] fields or untagged enums, where serde does not pass the target type down β€” declare those fields directly. In an overlay (config.prod.toml), a reference also takes the type of the value config.toml already holds at that key, so retries = 3 in the base can be overridden by retries = "(env) RETRIES".
  • Only the start of a value is a marker, in the exact form (word) with a lowercase word. "(555) 123-4567" is a plain value. A value that must literally start with a marker doubles the opening parenthesis: "((env) text" loads as "(env) text". A doubled parenthesis that is not followed by a marker ("((foo)|(bar))") is left alone.
  • The same resolution runs for rustf-cli, so db commands see the same database URL as the application. rustf-cli validate loads the effective configuration, and checks the tags of config.prod.toml without resolving them (its variables and secret files are usually not on a development machine).

Templates can read the configuration. Views have access to CONF (@{CONF.server.port}, @{'%custom.key'}), and that includes values that came from (env) or (file). Never output a secret key in a template: a stray @{CONF} renders the whole configuration.

Docker example

# config.toml, shipped in the image β€” no secrets in it
[server]
host = "0.0.0.0"
port = "(env) PORT"

[database]
url = "(file) /run/secrets/database_url"
# docker-compose.yml
services:
  app:
    image: my-app
    environment:
      PORT: "8000"
      RUSTF_ENV: production
    secrets: [database_url]
secrets:
  database_url:
    file: ./secrets/database_url

Environment Variable Overrides

Independently of references, a fixed set of variables overrides specific keys after the files are loaded. Only the variables below are read; other RUSTF_* names are ignored β€” use "(env) NAME" for any other key.

# Environment and server
RUSTF_ENV=production            # development (dev) or production (prod)
RUSTF_HOST=0.0.0.0              # required to be reachable inside a container
RUSTF_PORT=3000
RUSTF_TIMEOUT=60
RUSTF_MAX_CONNECTIONS=5000
RUSTF_PUBLIC_URL=https://example.com
RUSTF_TRUSTED_PROXIES=10.0.0.0/8
RUSTF_SSL_ENABLED=true
RUSTF_SSL_CERT=/path/to/cert
RUSTF_SSL_KEY=/path/to/key

# Database
DATABASE_URL=postgresql://user:pass@host/db   # or RUSTF_DATABASE_URL
RUSTF_DB_MAX_CONNECTIONS=20
RUSTF_DB_TIMEOUT=10

# Views and static files
RUSTF_VIEWS_DIR=/app/views
RUSTF_DEFAULT_LAYOUT=layouts/main
RUSTF_VIEW_CACHE=true
RUSTF_VIEW_MINIFY=true
RUSTF_TEMPLATE_STORAGE=embedded
RUSTF_VIEW_ENGINE=totaljs
RUSTF_STATIC_DIR=/app/public
RUSTF_STATIC_PREFIX=/static
RUSTF_STATIC_CACHE=true
RUSTF_STATIC_MAX_AGE=86400

# Files
RUSTF_PRIVATE_DIR=/app/private
RUSTF_UPLOAD_DIR=uploads
RUSTF_MAX_FILE_SIZE=10485760

# CORS and logging
RUSTF_CORS_ENABLED=true
RUSTF_CORS_ORIGINS=https://a.example,https://b.example
RUSTF_CORS_METHODS=GET,POST
RUSTF_CORS_HEADERS=Content-Type,Authorization
RUSTF_LOG_LEVEL=info
RUSTF_LOG_FILE=/var/log/app.log

An exported variable applies to every application started from that shell. When several instances run on one host, set variables per process (RUSTF_PORT=8102 ./app --config site2/config.toml) or use references.

Loading Configuration

Application Startup

Configuration is automatically initialized during application startup:

use rustf::prelude::*;

#[rustf::auto_discover]
#[tokio::main]
async fn main() -> Result<()> {
    // Configuration is loaded and CONF is initialized automatically
    let app = RustF::with_args()?;  // Loads config with CLI support
    
    // Alternative loading methods:
    // let app = RustF::new();                    // Default config
    // let app = RustF::from_file("config.toml")?; // Specific file
    // let app = RustF::from_env()?;              // Environment only
    // let app = RustF::with_config(my_config);   // Programmatic
    
    app.start().await
}

CLI Arguments

The framework supports configuration via command-line arguments:

# Use default configuration loading
./myapp

# Specify custom config file
./myapp --config /path/to/config.toml
./myapp -c config.prod.toml

# Override views directory (if using filesystem storage)
./myapp --views /path/to/templates

Programmatic Configuration

use rustf::prelude::*;
use rustf::config::AppConfig;

#[tokio::main]
async fn main() -> rustf::Result<()> {
    // Create configuration programmatically
    let mut config = AppConfig::default();
    config.server.port = 3000;
    config.server.host = "0.0.0.0".to_string();
    config.database.url = Some("postgresql://localhost/mydb".to_string());

    // Use the configuration
    let app = RustF::with_config(config);
    app.start().await
}

Custom config sections are loaded from TOML into AppConfig::sections (HashMap<String, toml::Value>) and read back via config.section::<T>("name"), which deserializes the named section into your own struct. There is no config.custom field to insert into at runtime.

Environment Detection

RustF resolves the environment from these sources (in priority order):

  1. RUSTF_ENV environment variable
  2. [app] environment = "production" in config.toml β€” the recommended way for per-app declaration
  3. Default: development

The only names accepted are development (or dev) and production (or prod), case-insensitive. Any other value β€” staging, a typo β€” stops the application at startup instead of silently running as development. Variables of other tools (NODE_ENV, RAILS_ENV, …) are ignored, so a container that sets them for something else cannot change RustF’s mode.

Everything that depends on the environment reads this one value: the configuration overlay (config.dev.toml / config.prod.toml), production security defaults, the session cookie’s Secure flag, detailed error pages, DEBUG, and the environment seen by events and workers.

#![allow(unused)]
fn main() {
pub enum Environment {
    Development,  // Default for local development
    Production,   // Live production environment
}
}

The two valid string values are "production" (or "prod") and "development" (or "dev").

Environment-Specific Behavior

#![allow(unused)]
fn main() {
// Check environment in code
let env = CONF::env();  // Returns "development", "production", etc.

if CONF::is_production() {
    // Production-specific code
    enable_caching();
    disable_debug_endpoints();
}

if CONF::is_development() {
    // Development-specific code
    enable_hot_reload();
    show_detailed_errors();
}
}

Configuration Validation

RustF validates configuration during startup:

Automatic Validation

  • Required in Production:

    • Session secret must not be default value
    • SSL certificate/key paths must exist if SSL is enabled
    • Database URL is recommended (warns if missing)
  • Path Validation:

    • Views directory should exist (warns if missing)
    • Static files directory must exist
    • Upload directory is created if missing
  • Type Validation:

    • Port must be valid (1-65535)
    • Timeouts must be positive
    • File sizes must be reasonable

Custom Validation

#![allow(unused)]
fn main() {
use rustf::prelude::*;

app.on("config.loaded", |ctx| Box::pin(async move {
    // Validate custom configuration
    if !CONF::has("custom.api_key") {
        return Err(Error::internal("API key is required in configuration"));
    }
    
    let api_key = CONF::get_string("custom.api_key").unwrap();
    if api_key.len() < 32 {
        return Err(Error::internal("API key must be at least 32 characters"));
    }
    
    Ok(())
}))
}

Unified Configuration Access

RustF provides a completely unified approach to configuration access - all configuration sections (framework-defined and user-defined) can be accessed using the same patterns:

Three Ways to Access Configuration

The CONF singleton provides dot-notation access to ANY configuration section:

#![allow(unused)]
fn main() {
use rustf::prelude::*;

// Framework sections
let port = CONF::get_int("server.port")?;
let cache_enabled = CONF::get_bool("views.cache_enabled")?;

// Custom app sections - same syntax!
let app_name = CONF::get_string("app.name")?;
let stripe_key = CONF::get_string("payment.stripe_key")?;
let smtp_port = CONF::get_int("smtp.port")?;
}

2. AppConfig.section() Method (Type-Safe Access)

For custom sections, use the section() method to get type-safe deserialized access:

#![allow(unused)]
fn main() {
use rustf::prelude::*;
use serde::Deserialize;

#[derive(Deserialize)]
struct SmtpConfig {
    host: String,
    port: u16,
    user: String,
    password: String,
}

// Get the full section as a typed struct
let smtp = config.section::<SmtpConfig>("smtp")?;
println!("SMTP: {}:{}", smtp.host, smtp.port);
}

3. Templates (Automatic JSON Serialization)

Templates automatically have access to all configuration sections through the CONF global:

<!-- Framework sections -->
<meta name="viewport" content="width=device-width">
<script>
    const port = @{CONF.server.port};
    const cacheEnabled = @{CONF.views.cache_enabled};
</script>

<!-- Custom app sections - same access pattern -->
<h1>@{CONF.app.name} v@{CONF.app.version}</h1>
<script>
    const stripeKey = '@{CONF.payment.stripe_key}';
    const smtpHost = '@{CONF.smtp.host}';
</script>

Why Unified Access Matters

The unified approach eliminates cognitive overhead:

  • No special buckets: Custom sections aren’t forced into custom or extra maps
  • One pattern: Whether accessing server.port or app.name, the syntax is identical
  • IDE support: Framework sections have typed IDE support; app sections work with runtime access
  • Template consistency: Templates access all sections uniformly
  • AI-friendly: One way to do things reduces confusion for human developers and AI assistants

Best Practices

1. Keep Secrets out of the Files

# config.toml
[database]
url = "(env) DATABASE_URL"                    # environment variable

[custom.payments]
api_key = "(file) /run/secrets/payments_key"  # mounted secret

See Values from the Environment or Files.

2. Environment-Specific Files

config.toml          # Base configuration β€” set [app] environment = "production" here
config.dev.toml      # Development overrides (loaded when environment = "development")
config.prod.toml     # Production overrides (loaded when environment = "production")

3. Custom Settings Organization

[custom]
# Group related settings with prefixes
smtp_host = "smtp.gmail.com"
smtp_port = "587"
smtp_user = "user@gmail.com"
smtp_password = "(env) SMTP_PASSWORD"

redis_url = "redis://localhost:6379"
redis_prefix = "myapp:"

feature_new_ui = "false"
feature_beta_api = "true"

4. Access Patterns

#![allow(unused)]
fn main() {
// βœ… Good: Use CONF for all configuration access (available in prelude)
use rustf::prelude::*;

let port = CONF::get_int("server.port").unwrap_or(8000);
let db_url = CONF::get_string("database.url");

// ❌ Bad: Don't try to access config through Context
// ctx.config() // This method no longer exists!

// βœ… Good: Check existence before accessing
if CONF::has("custom.smtp_host") {
    setup_email_service();
}

// βœ… Good: Use typed getters for safety
let enabled = CONF::get_bool("custom.feature_enabled").unwrap_or(false);
let timeout = CONF::get_int("server.timeout").unwrap_or(30);

// βœ… Good: Use defaults for optional settings
let cache_size = CONF::get_or("custom.cache_size", 100);
}

5. Testing Configuration

#![allow(unused)]
fn main() {
#[cfg(test)]
mod tests {
    use super::*;
    use rustf::config::AppConfig;
    
    #[test]
    fn test_configuration_loading() {
        let config = AppConfig::from_file("config.test.toml").unwrap();
        
        // Initialize CONF for testing
        CONF::init(config).unwrap();
        
        // Test configuration values
        assert_eq!(CONF::get_int("server.port"), Some(8080));
        // Environment is "development" or "production" (default: "development")
        assert_eq!(CONF::env(), Some("development".to_string()));
        assert!(CONF::has("database.url"));
    }
}
}

Migration from Context Config

If you’re migrating from an older version of RustF that had ctx.config():

Before (Old Way)

#![allow(unused)]
fn main() {
async fn handler(ctx: &mut Context) -> rustf::Result<()> {
    let upload_dir = ctx.config().uploads.directory.clone();
    let max_size = ctx.config().uploads.max_file_size;
    // ...
}
}

After (New Way)

#![allow(unused)]
fn main() {
use rustf::prelude::*;  // CONF is included in the prelude

async fn handler(ctx: &mut Context) -> rustf::Result<()> {
    let upload_dir = CONF::get_string("uploads.directory").unwrap_or_else(|| "uploads".to_string());
    let max_size = CONF::get_int("uploads.max_file_size").unwrap_or(10485760);
    // ...
}
}

Configuration Examples

Minimal Configuration

# config.toml - Minimal configuration using defaults
[server]
port = 3000

[database]
url = "postgresql://localhost/myapp"

Full Production Configuration

# config.prod.toml β€” merges on top of config.toml when [app] environment = "production"

[server]
host = "0.0.0.0"
port = 443
timeout = 60
ssl_enabled = true
ssl_cert = "/etc/letsencrypt/live/example.com/fullchain.pem"
ssl_key = "/etc/letsencrypt/live/example.com/privkey.pem"
max_connections = 5000

[views]
directory = "/app/views"
default_layout = "layouts/default"
cache_enabled = true
storage = "embedded"  # Use embedded templates in production

[session]
cookie_name = "app_session"
idle_timeout = 86400      # 24 hours
absolute_timeout = 604800 # 7 days

[session.storage]
type = "redis"
url = "(env) REDIS_URL"
prefix = "session:"
pool_size = 10

[database]
url = "(env) DATABASE_URL"
max_connections = 50
timeout = 10000

[static_files]
directory = "/app/public"
url_prefix = "/static"
cache_enabled = true
cache_max_age = 2592000  # 30 days

[cors]
enabled = true
allowed_origins = ["https://example.com", "https://app.example.com"]
allowed_methods = ["GET", "POST", "PUT", "DELETE", "OPTIONS"]
allowed_headers = ["Content-Type", "Authorization", "X-Requested-With"]

[logging]
level = "info"
file = "/var/log/app/production.log"

[uploads]
directory = "/app/storage/uploads"
max_file_size = 52428800  # 50MB
max_files = 10
allowed_extensions = ["jpg", "jpeg", "png", "gif", "pdf", "doc", "docx"]
create_directories = true

[custom]
cdn_url = "https://cdn.example.com"
api_endpoint = "https://api.example.com/v1"
smtp_host = "smtp.sendgrid.net"
smtp_port = "587"
smtp_user = "apikey"
smtp_password = "(env) SENDGRID_API_KEY"
from_email = "noreply@example.com"
support_email = "support@example.com"
google_analytics_id = "UA-XXXXXXXXX-X"
stripe_public_key = "(env) STRIPE_PUBLIC_KEY"
stripe_secret_key = "(env) STRIPE_SECRET_KEY"
redis_url = "(env) REDIS_URL"
elasticsearch_url = "(env) ELASTICSEARCH_URL"
feature_new_dashboard = "true"
feature_beta_api = "false"
maintenance_mode = "false"
rate_limit_requests = "1000"
rate_limit_window = "3600"

Troubleshooting

Configuration Not Loading

#![allow(unused)]
fn main() {
// Check if CONF is initialized
if !CONF::is_initialized() {
    panic!("Configuration not initialized!");
}

// Check what environment is loaded
let env = CONF::env().unwrap_or_else(|| "unknown".to_string());
println!("Running in {} environment", env);

// Debug configuration values
if let Some(config) = CONF::all() {
    println!("Server port: {}", config.server.port);
    println!("Database URL: {:?}", config.database.url);
}
}

Environment Variables Not Working

# Make sure to export variables
export RUSTF_PORT=3000
export DATABASE_URL="postgresql://localhost/mydb"

# Or set them when running
RUSTF_ENV=production DATABASE_URL="..." cargo run

Custom Values Not Accessible

#![allow(unused)]
fn main() {
// Custom values must be in [custom] section
// config.toml:
// [custom]
// my_value = "test"

// Access with "custom." prefix:
let value = CONF::get_string("custom.my_value");  // βœ… Correct
let value = CONF::get_string("my_value");         // ❌ Wrong
}

Summary

RustF’s configuration system provides:

βœ… Single Access Point - Global CONF for uniform configuration access
βœ… Dot Notation - Clean path-based access to nested values
βœ… Multiple Sources - Files, environment variables, and code
βœ… Environment Support - Development and production configs
βœ… Type Safety - Typed getters for different value types
βœ… Validation - Automatic validation for production requirements
βœ… Extensibility - Custom settings for application-specific config
βœ… AI-Friendly - One way to do things reduces confusion

The configuration system follows the principle of β€œconvention over configuration” while still providing the flexibility needed for complex applications. By using the global CONF accessor exclusively, the codebase remains consistent and easy to understand for both humans and AI assistants.

RustF CSRF Protection Guide

πŸ”’ Comprehensive Cross-Site Request Forgery Protection

This guide covers RustF’s automatic CSRF protection system, designed for both security and developer productivity with zero-configuration defaults and extensive customization options.

Table of Contents

Overview

Cross-Site Request Forgery (CSRF) attacks trick users into performing unintended actions by exploiting their authenticated sessions. RustF provides comprehensive CSRF protection through:

Key Features

βœ… One-Time Use Tokens - Tokens are consumed after successful verification (prevents replay attacks)
βœ… Token Expiration - Tokens automatically expire after 1 hour
βœ… Multiple Concurrent Tokens - Support different token IDs for different forms
βœ… Automatic HTTP Method Detection - Only unsafe methods (POST, PUT, PATCH, DELETE) require validation
βœ… Session Integration - Tokens stored and validated via the session system
βœ… Route Exemption Patterns - Flexible wildcard and exact matching
βœ… Multiple Token Sources - Headers and form fields
βœ… Smart Error Handling - Context-aware responses (JSON for APIs, HTML for web)
βœ… Zero Configuration - Works out-of-the-box with sensible defaults
βœ… Context Methods - Convenient verify_csrf() and generate_csrf() methods

Protection Scope

Protected Methods (Require CSRF token):

  • POST - Create operations
  • PUT - Full resource updates
  • PATCH - Partial resource updates
  • DELETE - Resource deletion

Safe Methods (Bypass CSRF):

  • GET - Read operations
  • HEAD - Header-only requests
  • OPTIONS - CORS preflight requests

Quick Start

Basic Setup

Add CSRF protection with zero configuration:

Routes live in controllers (each controller exposes pub fn install() -> Vec<Route>), and middleware is registered on the app builder with .middleware_from(...):

#![allow(unused)]
fn main() {
// src/controllers/users.rs
use rustf::prelude::*;

pub fn install() -> Vec<Route> {
    routes![
        GET    "/users"      => list_users,    // Not protected (GET)
        POST   "/users"      => create_user,   // Protected
        PUT    "/users/{id}" => update_user,   // Protected
        DELETE "/users/{id}" => delete_user,   // Protected
    ]
}

async fn create_user(ctx: &mut Context) -> rustf::Result<()> {
    // CSRF already validated by the middleware
    let form_data = ctx.body_form()?;

    let user = create_user_record(&form_data).await?;
    ctx.json(json!({"message": "User created", "id": user.id}))
}
}
// src/main.rs
use rustf::prelude::*;
use rustf::security::CsrfMiddleware;

#[tokio::main]
async fn main() -> rustf::Result<()> {
    RustF::new()
        .controllers(auto_controllers!())
        // Enable CSRF protection (default configuration)
        .middleware_from(|registry| {
            registry.register_inbound("csrf", CsrfMiddleware::new());
        })
        .serve(Some("127.0.0.1:8080"))
        .await
}

Default Behavior

With zero configuration, the CSRF middleware:

  • Protects POST, PUT, PATCH, DELETE requests
  • Exempts no routes by default
  • Stores tokens in the session
  • Returns appropriate error responses

Automatic Protection

HTTP Method-Based Protection

CSRF protection is applied automatically based on HTTP methods:

#![allow(unused)]
fn main() {
// In a controller's install():
routes![
    // These routes are automatically protected:
    POST   "/users"      => create_user,     // βœ… CSRF Required
    PUT    "/users/{id}" => update_user,      // βœ… CSRF Required
    PATCH  "/users/{id}" => partial_update,   // βœ… CSRF Required
    DELETE "/users/{id}" => delete_user,      // βœ… CSRF Required

    // These routes bypass CSRF protection:
    GET    "/users"      => list_users,       // ⏭️ CSRF Bypassed
    HEAD   "/users/{id}" => check_user,       // ⏭️ CSRF Bypassed
    OPTIONS "/users"     => cors_preflight,   // ⏭️ CSRF Bypassed
]
}

Session Integration

CSRF tokens are automatically managed through the session system:

#![allow(unused)]
fn main() {
// Token lifecycle (handled automatically):
// 1. Generate token: stored in session["_csrf_token"]
// 2. Validate token: compare submitted vs stored
// 3. Token persistence: lives with the session
// 4. Token regeneration: on session regeneration
}

Configuration

Custom Configuration

Create a custom CSRF configuration for advanced scenarios:

#![allow(unused)]
fn main() {
use rustf::security::{CsrfMiddleware, CsrfConfig};

let csrf_config = CsrfConfig::new()
    // Route exemptions
    .exempt("/webhook/github")              // Specific webhook
    .exempt("/webhook/*")                   // All webhook routes  
    .exempt("/api/public/*")               // Public API endpoints
    .exempt("/uploads/process")             // File processing endpoint
    
    // Error handling
    .error_message("Security validation failed. Please refresh and try again.")
    .redirect_on_failure("/login")          // Redirect instead of error page
    
    // HTTP method customization
    .protect_method("CUSTOM")               // Add custom method protection
    .exempt_method("DELETE");               // Remove DELETE protection

let csrf_middleware = CsrfMiddleware::with_config(csrf_config);

// Register on the app builder:
RustF::new()
    .controllers(auto_controllers!())
    .middleware_from(move |registry| {
        registry.register_inbound("csrf", csrf_middleware.clone());
    });
}

Configuration Builder Methods

MethodDescriptionExample
exempt(route)Add route exemption pattern.exempt("/api/*")
error_message(msg)Custom error message.error_message("Token expired")
redirect_on_failure(url)Redirect URL on failure.redirect_on_failure("/login")
disabled()Disable CSRF globally.disabled()
protect_method(method)Add protected HTTP method.protect_method("CUSTOM")
exempt_method(method)Remove method protection.exempt_method("PUT")

Route Exemptions

Pattern Matching

CSRF route exemptions support exact matches and a single trailing /* prefix wildcard. A * anywhere other than the end (e.g. /admin/*/public) is not supported and never matches.

#![allow(unused)]
fn main() {
let csrf_config = CsrfConfig::new()
    // Exact matches
    .exempt("/webhook")                     // Only /webhook
    .exempt("/public/upload")               // Only /public/upload

    // Trailing /* prefix wildcards
    .exempt("/api/*")                       // /api/users, /api/v1/posts, etc.
    .exempt("/webhook/*");                  // /webhook/github, /webhook/stripe, etc.
}

Pattern Examples

PatternMatchesDoesn’t Match
/api/*/api/users, /api/v1/data/api, /public/api
/webhook/github/webhook/github/webhook/github/push
/public/upload/public/upload/public/uploads
/admin/*/public(nothing β€” mid-path * is unsupported)everything

Default Exemptions

CsrfConfig::new() (and default()) starts with an empty exemption list. .exempt(...) appends routes to that list. So this:

#![allow(unused)]
fn main() {
let csrf_config = CsrfConfig::new()
    .exempt("/external/webhooks/*")
    .exempt("/integrations/*");
// exempt_routes is now ["/external/webhooks/*", "/integrations/*"]
}

To replace the full exemption list from configuration, set middleware.csrf.exempt_routes in config.toml.

Common Exemption Patterns

#![allow(unused)]
fn main() {
// Webhooks and integrations
.exempt("/webhook/*")
.exempt("/integration/*") 
.exempt("/callback/*")

// Public APIs  
.exempt("/api/public/*")
.exempt("/api/v1/status")
.exempt("/api/health")

// File uploads from external sources
.exempt("/upload/external/*")
.exempt("/cdn/callback")

// Payment gateways
.exempt("/payment/stripe/webhook")
.exempt("/payment/paypal/ipn")
}

Token Management

Automatic Token Generation

CSRF tokens are generated and managed automatically:

#![allow(unused)]
fn main() {
// Token generation happens automatically when:
// 1. First CSRF-protected request is made
// 2. ctx.generate_csrf() is called explicitly

async fn show_form(ctx: &mut Context) -> rustf::Result<()> {
    // Automatically generates and stores token in session.
    // generate_csrf takes Option<&str>; pass None for the default token id.
    ctx.generate_csrf(None)?;
    
    // Token is accessible in templates via @{csrf_token} and @{csrf}
    ctx.view("user/form", json!({
        "user": load_user_data().await?
    }))
}
}

Token Properties

  • Format: Base64-encoded random bytes (32 bytes = ~44 characters)
  • Storage: Session key _csrf_token (or custom ID) with JSON structure: {"token": "...", "valid_to": timestamp}
  • Lifetime: 1 hour from generation (configurable)
  • Usage: One-time use - consumed after successful verification
  • Security: Cryptographically secure random generation

Token Lifecycle

Tokens follow a secure lifecycle:

#![allow(unused)]
fn main() {
// 1. Generation - Token created with expiration
let token = ctx.generate_csrf(None)?;  // Default token
let custom = ctx.generate_csrf(Some("upload_csrf"))?;  // Custom ID

// 2. Verification - Token consumed (one-time use)
if ctx.verify_csrf(None)? {  // Default token
    // Token is valid and now removed from session
}

// 3. Expiration - Tokens expire after 1 hour
// Expired tokens are automatically removed on verification attempt

// 4. Session destruction - All tokens cleared
if let Some(session) = ctx.session() {
    session.destroy();  // All tokens removed
}
}

Context Integration

Context Methods

RustF provides convenient methods on the Context for CSRF operations:

#![allow(unused)]
fn main() {
async fn form_controller(ctx: &mut Context) -> rustf::Result<()> {
    // Generate CSRF token (stored in session); None = default token id
    let csrf_token = ctx.generate_csrf(None)?;
    
    // Manual verification (usually not needed due to middleware)
    if !ctx.verify_csrf(None)? {
        return ctx.throw403(Some("CSRF validation failed"));
    }
    
    // Token is accessible in templates
    ctx.view("form", json!({
        "user_data": load_user().await?
    }))
}
}

Method Details

ctx.generate_csrf(token_id: Option<&str>)

Generates a new CSRF token with optional custom ID and stores it in the session:

#![allow(unused)]
fn main() {
async fn api_csrf_token(ctx: &mut Context) -> rustf::Result<()> {
    // Default token
    let token = ctx.generate_csrf(None)?;
    
    // Custom token for specific form
    let upload_token = ctx.generate_csrf(Some("upload_csrf"))?;
    
    ctx.json(json!({
        "csrf_token": token,
        "upload_token": upload_token,
        "expires_in": "1 hour",
        "usage": "one-time"
    }))
}
}

ctx.verify_csrf(token_id: Option<&str>)

Manually verify and consume CSRF token (rarely needed due to middleware):

#![allow(unused)]
fn main() {
async fn manual_verification(ctx: &mut Context) -> rustf::Result<()> {
    // Verify default token (consumed after successful verification)
    match ctx.verify_csrf(None)? {
        true => {
            // Token was valid and is now consumed
            ctx.json(json!({"message": "Token valid and consumed"}))
        }
        false => {
            // Token is invalid, expired, or missing
            ctx.throw403(Some("CSRF token validation failed"))
        }
    }
}

// Verify custom token
async fn verify_upload(ctx: &mut Context) -> rustf::Result<()> {
    if ctx.verify_csrf(Some("upload_csrf"))? {
        // Upload token valid and consumed
        process_upload(&ctx).await
    } else {
        ctx.throw403(Some("Invalid upload token"))
    }
}
}

CSRF Token in Templates

CSRF tokens support multiple forms with different token IDs:

#![allow(unused)]
fn main() {
async fn show_forms(ctx: &mut Context) -> rustf::Result<()> {
    // Generate multiple tokens for different forms
    ctx.generate_csrf(None)?;  // Default token
    ctx.generate_csrf(Some("upload_csrf"))?;  // Upload form
    ctx.generate_csrf(Some("api_csrf"))?;  // API calls
    
    // Tokens accessible in templates:
    // - @{csrf} - hidden input with default token
    // - @{csrf("upload_csrf")} - hidden input with custom token
    // - @{csrf_token} - default token value
    // - @{csrf_token.upload_csrf} - custom token value
    
    ctx.view("forms/multi", json!({
        "user": load_user_data().await?
    }))
}
}

Template Usage:

<!-- Default token -->
<form method="POST">
    @{csrf}  <!-- <input type="hidden" name="_csrf_token" value="..."> -->
</form>

<!-- Custom token -->
<form method="POST" action="/upload">
    @{csrf("upload_csrf")}  <!-- <input type="hidden" name="upload_csrf" value="..."> -->
</form>

<!-- Token values for JavaScript -->
<script>
    const defaultToken = "@{csrf_token}";
    const uploadToken = "@{csrf_token.upload_csrf}";
    const apiToken = "@{csrf_token.api_csrf}";
</script>

Error Handling

Automatic Error Responses

CSRF failures are handled intelligently based on the request type:

API Requests (JSON Response)

For requests expecting JSON (detected by headers):

{
    "error": "csrf_token_invalid",
    "message": "CSRF token validation failed. Please try again."
}

HTTP Status: 403 Forbidden

Web Requests (HTML Response)

For regular web requests:

  • Returns HTTP 403 Forbidden with error page
  • OR redirects to configured URL with flash message

Custom Error Handling

Configure custom error responses:

#![allow(unused)]
fn main() {
let csrf_config = CsrfConfig::new()
    // Custom error message
    .error_message("Security token expired. Please refresh the page.")
    
    // Redirect instead of error page
    .redirect_on_failure("/login");

let csrf_config = csrf_config; // built above

RustF::new()
    .controllers(auto_controllers!())
    .middleware_from(move |registry| {
        registry.register_inbound("csrf", CsrfMiddleware::with_config(csrf_config.clone()));
    });

// In your login template (Total.js), show the flash message:
// @{if flash.error}
//     <div class="alert alert-danger">@{flash.error}</div>
// @{fi}
}

Error Detection

The middleware detects request type using:

  1. Accept header containing application/json
  2. Content-Type header containing application/json
  3. Request path starting with /api/ (if not exempted)

AJAX Integration

Frontend CSRF Token Fetching

Create an endpoint to provide CSRF tokens for AJAX requests:

#![allow(unused)]
fn main() {
// CSRF token endpoint
async fn csrf_token_api(ctx: &mut Context) -> rustf::Result<()> {
    let token = ctx.generate_csrf(None)?;
    
    ctx.json(json!({
        "csrf_token": token,
        "field_name": "_csrf_token",
        "header_name": "X-CSRF-Token"
    }))
}

// Register the endpoint in a controller's install() (GET bypasses CSRF):
// routes![ GET "/api/csrf-token" => csrf_token_api ]
}

JavaScript Integration

// Fetch CSRF token
async function getCsrfToken() {
    const response = await fetch('/api/csrf-token');
    if (!response.ok) throw new Error('Failed to fetch CSRF token');
    const data = await response.json();
    return data.csrf_token;
}

// Method 1: HTTP Header (Recommended)
const csrfToken = await getCsrfToken();

const response = await fetch('/api/users', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'X-CSRF-Token': csrfToken  // Header method
    },
    body: JSON.stringify({
        name: 'John Doe',
        email: 'john@example.com'
    })
});

// Method 2: Form Data
const formData = new FormData();
formData.append('name', 'John Doe');
formData.append('email', 'john@example.com');
formData.append('_csrf_token', csrfToken);  // Form field method

await fetch('/api/users', {
    method: 'POST',
    body: formData
});

Global AJAX Setup

Set up CSRF token globally for all AJAX requests:

class CsrfManager {
    constructor() {
        this.token = null;
        this.tokenPromise = null;
    }
    
    async getToken() {
        if (!this.tokenPromise) {
            this.tokenPromise = this.fetchToken();
        }
        return this.tokenPromise;
    }
    
    async fetchToken() {
        const response = await fetch('/api/csrf-token');
        const data = await response.json();
        this.token = data.csrf_token;
        return this.token;
    }
    
    async apiCall(url, options = {}) {
        const token = await this.getToken();
        
        const headers = {
            ...options.headers,
            'X-CSRF-Token': token
        };
        
        return fetch(url, { ...options, headers });
    }
}

// Global instance
const csrf = new CsrfManager();

// Usage
await csrf.apiCall('/api/users', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(userData)
});

Form Integration

HTML Forms

Include CSRF tokens in HTML forms using the context helper:

#![allow(unused)]
fn main() {
async fn show_user_form(ctx: &mut Context) -> rustf::Result<()> {
    // Ensure CSRF token exists
    ctx.generate_csrf(None)?;
    
    ctx.view("users/form", json!({
        "user": load_user_data().await?,
        "action": "/users/create"
    }))
}
}

Template (Total.js syntax):

<!-- Default token -->
<form action="@{action}" method="POST">
    @{csrf}  <!-- Auto-generated hidden input -->
    
    <div class="form-group">
        <label>Name:</label>
        <input type="text" name="name" value="@{user.name}" required>
    </div>
    
    <div class="form-group">
        <label>Email:</label>
        <input type="email" name="email" value="@{user.email}" required>
    </div>
    
    <button type="submit">Save User</button>
</form>

<!-- Multiple forms with different tokens -->
<form id="userForm" method="POST" action="/users">
    @{csrf}  <!-- Default token -->
    <!-- form fields -->
</form>

<form id="uploadForm" method="POST" action="/upload">
    @{csrf("upload_csrf")}  <!-- Custom upload token -->
    <input type="file" name="file">
</form>

Manual Token Inclusion

If you need to include tokens manually in data:

#![allow(unused)]
fn main() {
async fn manual_form(ctx: &mut Context) -> rustf::Result<()> {
    let csrf_token = ctx.generate_csrf(None)?;
    
    ctx.view("forms/manual", json!({
        "csrf_token": csrf_token,
        "form_data": load_form_data().await?
    }))
}
}

Template:

<!-- Default token manual inclusion -->
<form action="/users" method="POST">
    <input type="hidden" name="_csrf_token" value="@{csrf_token}">
    <!-- form fields... -->
</form>

<!-- Custom token manual inclusion -->
<form action="/api/action" method="POST">
    <input type="hidden" name="api_csrf" value="@{csrf_token.api_csrf}">
    <!-- form fields... -->
</form>

<!-- Mixed approach -->
<div>
    <form method="POST" action="/form1">
        @{csrf}  <!-- Auto-generated -->
    </form>
    
    <form method="POST" action="/form2">
        <input type="hidden" name="form2_csrf" value="@{csrf_token.form2_csrf}">
    </form>
</div>

Form Processing

Form processing requires no changes - CSRF is handled by middleware:

#![allow(unused)]
fn main() {
async fn process_user_form(ctx: &mut Context) -> rustf::Result<()> {
    // CSRF already validated by middleware
    let form_data = ctx.body_form()?;
    
    // Validate form data
    let user_data = validate_user_form(&form_data)?;
    
    // Save user
    let user = create_user(&user_data).await?;
    
    // Success response
    ctx.flash_success("User created successfully!")?;
    ctx.redirect("/users")
}
}

Advanced Usage

Conditional CSRF Protection

Apply CSRF protection conditionally:

#![allow(unused)]
fn main() {
use rustf::security::CsrfConfig;

// Environment-based configuration
let csrf_config = match env::var("ENVIRONMENT").as_deref() {
    Ok("development") => {
        // Relaxed CSRF in development
        CsrfConfig::new()
            .exempt("/debug/*")
            .exempt("/test/*")
    }
    Ok("production") => {
        // Strict CSRF in production  
        CsrfConfig::new()
            .error_message("Security validation failed")
            .redirect_on_failure("/login")
    }
    _ => CsrfConfig::new()  // Default
};
}

Custom HTTP Methods

Protect custom HTTP methods:

#![allow(unused)]
fn main() {
let csrf_config = CsrfConfig::new()
    .protect_method("CUSTOM")       // Add protection
    .protect_method("MERGE")        // Custom REST method
    .exempt_method("DELETE");       // Remove DELETE protection

RustF::new()
    .controllers(auto_controllers!())
    .middleware_from(move |registry| {
        registry.register_inbound("csrf", CsrfMiddleware::with_config(csrf_config.clone()));
    });
}

Differentiating CSRF Across Routes

RustF registers a single CSRF middleware globally; there is no RouteGroup type or per-group middleware. To apply different behavior to different paths, configure exemptions (and protected methods) on one CsrfConfig and let path patterns decide. Routes themselves are declared in controllers via install():

#![allow(unused)]
fn main() {
// One CSRF config: public API paths are exempt, everything else is protected.
let csrf_config = CsrfConfig::new()
    .exempt("/api/public/*")              // public endpoints bypass CSRF
    .error_message("CSRF validation failed");

RustF::new()
    .controllers(auto_controllers!())
    .middleware_from(move |registry| {
        registry.register_inbound("csrf", CsrfMiddleware::with_config(csrf_config.clone()));
    });
}
#![allow(unused)]
fn main() {
// src/controllers/api.rs
pub fn install() -> Vec<Route> {
    routes![
        // Exempt by the /api/public/* pattern above:
        POST "/api/public/contact"    => contact_handler,
        POST "/api/public/newsletter" => newsletter_handler,
        // Protected (not exempt):
        POST "/api/private/users"     => create_user,
        PUT  "/api/private/users/{id}" => update_user,
    ]
}
}

Exempting Webhook Routes

Webhooks usually come from external systems that cannot send a CSRF token, so exempt their paths in the config:

#![allow(unused)]
fn main() {
let csrf_config = CsrfConfig::new()
    .exempt("/webhook/*")          // all webhook routes
    .exempt("/integration/*")      // all integration callbacks
    .exempt("/external/callback"); // a single exact route

RustF::new()
    .controllers(auto_controllers!())
    .middleware_from(move |registry| {
        registry.register_inbound("csrf", CsrfMiddleware::with_config(csrf_config.clone()));
    });
}

Troubleshooting

Common Issues

1. 403 CSRF Token Errors

Problem: Getting 403 errors on valid requests

Solutions:

#![allow(unused)]
fn main() {
// Check if route is properly exempted
let csrf_config = CsrfConfig::new()
    .exempt("/your/route/*");  // Add exemption

// Verify token submission method
// For default token:
// - Header: X-CSRF-Token
// - Form field: _csrf_token or _token

// For custom token (e.g., "upload_csrf"):
// - Header: X-CSRF-Token
// - Form field: upload_csrf

// Check token expiration (tokens expire after 1 hour)
// Generate a fresh token if needed

// Remember: Tokens are one-time use
// After successful verification, generate a new token for the next request
}

2. AJAX Requests Failing

Problem: AJAX requests returning 403 CSRF errors

Solutions:

// Method 1: Include CSRF header
fetch('/api/endpoint', {
    method: 'POST',
    headers: {
        'X-CSRF-Token': await getCsrfToken()  // Most reliable
    },
    body: formData
});

// Method 2: Check API route exemptions
// Add explicit exemptions only for routes that truly cannot carry CSRF tokens

3. Webhooks Failing

Problem: External webhooks returning 403 errors

Solutions:

#![allow(unused)]
fn main() {
// Add webhook exemptions
let csrf_config = CsrfConfig::new()
    .exempt("/webhook/*")           // All webhook routes
    .exempt("/integration/*")       // Integration callbacks
    .exempt("/callback/*");         // External callbacks
}

4. Token Generation Issues

Problem: CSRF tokens not being generated or stored

Solutions:

#![allow(unused)]
fn main() {
// Check session configuration
// CSRF relies on sessions - ensure sessions are enabled

// Manual token generation
let token = ctx.generate_csrf(None)?;  // Default token
let custom = ctx.generate_csrf(Some("custom_id"))?;  // Custom token

// Verify session storage
// Check that session storage backend is working
// Tokens are stored as: {"token": "...", "valid_to": timestamp}
}

5. Token Reuse Issues

Problem: Token validation fails on second attempt

Solution: Tokens are one-time use - they are consumed after successful verification

#![allow(unused)]
fn main() {
// Generate new token for each form submission
async fn show_form_after_submit(ctx: &mut Context) -> rustf::Result<()> {
    // Generate fresh token for the next submission
    ctx.generate_csrf(None)?;
    ctx.view("form", data)
}

// For AJAX: Fetch new token after each successful request
}

Debugging

Enable debug logging to troubleshoot CSRF issues:

#![allow(unused)]
fn main() {
// Add logging middleware to see request flow
RustF::new()
    .middleware_from(|registry| {
        registry.register_dual("logging", LoggingMiddleware::new());
    });

// Check CSRF middleware execution
// Look for log entries showing CSRF validation
}

Check CSRF token presence and expiration:

#![allow(unused)]
fn main() {
async fn debug_csrf(ctx: &mut Context) -> rustf::Result<()> {
    // Check default token (session() returns Option<&Session>)
    let token_data: Option<serde_json::Value> =
        ctx.session().and_then(|s| s.get("_csrf_token"));
    let token_info = if let Some(data) = token_data {
        json!({
            "token": data.get("token"),
            "expires_at": data.get("valid_to"),
            "expired": {
                let now = std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH).unwrap()
                    .as_secs();
                data.get("valid_to")
                    .and_then(|v| v.as_u64())
                    .map(|exp| now > exp)
                    .unwrap_or(true)
            }
        })
    } else {
        json!(null)
    };
    
    ctx.json(json!({
        "token_info": token_info,
        "headers": ctx.req.headers.clone(),
        "form_data": ctx.body_form().ok()
    }))
}
}

Best Practices

1. Default Configuration

Start with default CSRF configuration and customize as needed:

#![allow(unused)]
fn main() {
// Good: Start simple
RustF::new()
    .middleware_from(|registry| {
        registry.register_inbound("csrf", CsrfMiddleware::new());
    });

// Then customize for specific needs
let csrf_config = CsrfConfig::new()
    .exempt("/specific/webhook")
    .error_message("Custom error message");
}

2. Route Organization

Organize routes to minimize exemptions:

#![allow(unused)]
fn main() {
// Good: Group exempt routes under common prefixes (in a controller's install()).
// These become exempt only if you configure the matching prefix:
routes![
    POST "/api/webhook/stripe"   => stripe_handler,
    POST "/api/webhook/github"   => github_handler,
    POST "/api/integration/slack" => slack_handler,
]

// Better than scattered exemptions in the config:
let csrf_config = CsrfConfig::new()
    .exempt("/webhook/stripe")      // Scattered
    .exempt("/integration/github")  // Scattered  
    .exempt("/callback/slack");     // Scattered
}

3. Token Management

Use context methods for token management:

#![allow(unused)]
fn main() {
// Good: Generate tokens before rendering
async fn show_form(ctx: &mut Context) -> rustf::Result<()> {
    ctx.generate_csrf(None)?;  // Default token
    ctx.generate_csrf(Some("api_csrf"))?;  // API token
    ctx.view("form", data)  // Tokens accessible in templates
}

// Good: Regenerate after consumption
async fn handle_form(ctx: &mut Context) -> rustf::Result<()> {
    if !ctx.verify_csrf(None)? {
        return ctx.throw403(Some("Invalid token"));
    }
    // Token consumed, generate new one for next request
    ctx.generate_csrf(None)?;
    ctx.redirect("/form")
}

// Avoid: Reusing tokens
// Tokens are one-time use - always generate fresh tokens
}

4. Error Handling

Provide user-friendly error messages:

#![allow(unused)]
fn main() {
let csrf_config = CsrfConfig::new()
    .error_message("Your session has expired. Please refresh the page and try again.")
    .redirect_on_failure("/login");  // Better UX than error page
}

5. Testing

Test CSRF protection in your application. RustF does not ship a built-in HTTP test client, so the snippet below is illustrative pseudo-code β€” adapt it to whatever HTTP client/test harness you use to exercise your running app:

// Illustrative only: `app.post(...).send()` and `test_app_with_csrf()` are not
// RustF APIs. Drive your app through a real HTTP client (e.g. reqwest) instead.
#[cfg(test)]
mod tests {
    use super::*;
    
    #[tokio::test]
    async fn test_csrf_protection() {
        let app = test_app_with_csrf();
        
        // Test protected route without token (should fail)
        let response = app.post("/users").send().await;
        assert_eq!(response.status(), 403);
        
        // Test with valid token (should succeed)
        let csrf_token = get_csrf_token(&app).await;
        let response = app.post("/users")
            .header("X-CSRF-Token", csrf_token)
            .json(json!({"name": "Test User"}))
            .send().await;
        assert_eq!(response.status(), 200);
    }
    
    #[tokio::test]
    async fn test_exempt_routes() {
        let app = test_app_with_csrf();
        
        // Test exempt route (should succeed without token)
        let response = app.post("/api/webhook/test").send().await;
        assert_eq!(response.status(), 200);
    }
}

6. Performance Considerations

  • CSRF middleware has minimal performance impact
  • Session reads/writes only occur on protected requests
  • Pattern matching is optimized for common cases
  • Consider using should_run() for conditional execution

7. Security Considerations

  • Always use HTTPS in production to protect tokens in transit
  • Tokens are automatically one-time use (prevents replay attacks)
  • Tokens expire after 1 hour (limits attack window)
  • Support for multiple concurrent tokens (different security contexts)
  • Monitor for unusual CSRF failure patterns (potential attacks)
  • Regularly review and update route exemptions

Summary

RustF’s CSRF protection provides:

βœ… One-Time Use Tokens - Consumed after verification (prevents replay attacks)
βœ… Token Expiration - Automatic 1-hour expiration
βœ… Multiple Concurrent Tokens - Different tokens for different forms
βœ… Zero Configuration - Works out-of-the-box with sensible defaults
βœ… Automatic Protection - HTTP method-based validation
βœ… Flexible Configuration - Extensive customization options
βœ… Session Integration - Seamless token storage and validation
βœ… Multiple Token Sources - Headers and forms
βœ… Smart Error Handling - Context-aware error responses
βœ… Developer Friendly - Convenient context methods and helpers


Additional Security Features

See the Security Configuration section for more security options.

RustF Error System Documentation

Overview

RustF provides a comprehensive, production-ready error handling system designed for building robust web applications. The error system emphasizes safety, observability, and developer experience while providing enterprise-grade features like retry logic, error chaining, and circuit breakers.

Core Principles

  • Type Safety: Strongly typed errors with exhaustive pattern matching
  • Production Safety: Sanitized error messages, no sensitive data leakage
  • Observability: Rich context and structured logging for debugging
  • Resilience: Built-in retry logic and circuit breaker patterns
  • Developer Experience: Clear error messages and intuitive APIs

Error Types

Main Error Enum

The rustf::error::Error enum provides comprehensive error variants for all common scenarios:

#![allow(unused)]
fn main() {
use rustf::error::Error;
}

Core Error Variants

HTTP and Network Errors

  • Http(hyper::Error) - HTTP protocol errors
  • Network(String) - Network connectivity issues
  • Timeout(String) - Request timeout errors
  • ExternalService { service, message } - External API failures

Data Processing Errors

  • Json(serde_json::Error) - JSON serialization/deserialization
  • Validation(String) - Data validation failures
  • InvalidInput(String) - User input errors
  • Template(String) - Template rendering errors

Database Errors

  • DatabaseConnection(String) - Connection pool issues
  • DatabaseQuery(String) - SQL query errors
  • DatabaseTransaction(String) - Transaction failures
  • DatabaseMigration(String) - Migration errors
  • DatabasePool(String) - Connection pool exhaustion

Authentication & Authorization

  • Authentication(String) - Authentication failures (401)
  • Authorization(String) - Permission denied (403)
  • RateLimit(String) - Rate limiting (429)
  • Session(String) - Session management errors

Application Errors

  • RouteNotFound(String) - Route not found (404)
  • ModelNotFound(String) - Model/resource not found (404)
  • Internal(String) - Internal server errors (500)
  • Io(std::io::Error) - File system I/O errors

Special Errors

  • WithContext { message, source } - Error with context chain
  • Redis(redis::RedisError) - Redis errors (feature-gated)
  • RedisPool(String) - Redis connection pool errors

Error Creation and Handling

Creating Errors

RustF provides convenient constructors for all error types:

#![allow(unused)]
fn main() {
// Database errors
Error::database_connection("Failed to connect to PostgreSQL")
Error::database_query("Invalid SQL syntax near 'FORM'")
Error::database_transaction("Transaction rolled back")

// Authentication errors
Error::authentication("Invalid credentials")
Error::authorization("Insufficient permissions for this resource")
Error::rate_limit("API rate limit exceeded: 100 requests per minute")

// External service errors
Error::external_service("payment_gateway", "Service temporarily unavailable")
Error::timeout("Request timed out after 30 seconds")

// Validation errors β€” `Error::validation` covers all input-validation cases
Error::validation("Email address is invalid")
Error::validation("Age must be a positive number")
}

Note: Error::validation is the single constructor for input/validation failures. There is no Error::invalid_input. For HTTP-specific short-circuits (404, 400, 403, 500, …), use ctx.throw404(...), ctx.throw400(...), etc. β€” those set the response on ctx.res and return Err so the ? operator propagates correctly.

Error Propagation

Use the ? operator for clean error propagation:

#![allow(unused)]
fn main() {
async fn process_user_registration(data: UserData) -> Result<User> {
    // Validate input
    validate_email(&data.email)?;
    validate_password(&data.password)?;
    
    // Check for existing user
    if User::exists_by_email(&data.email).await? {
        return Err(Error::validation("Email already registered"));
    }
    
    // Create user in database
    let user = User::create(data).await?;
    
    // Send welcome email
    email_service::send_welcome(&user).await
        .map_err(|e| Error::external_service("email", e.to_string()))?;
    
    Ok(user)
}
}

Error Properties

Each error has useful properties:

#![allow(unused)]
fn main() {
let error = Error::authentication("Invalid token");

// Get machine-readable error code
assert_eq!(error.error_code(), "E_AUTH");

// Get appropriate HTTP status code
assert_eq!(error.status_code(), 401);

// Check if error is retryable
assert!(!error.is_retryable());
}

Error Context and Chaining

Adding Context to Errors

Use the ErrorContext trait to add contextual information:

#![allow(unused)]
fn main() {
use rustf::error::ErrorContext;

async fn fetch_user_profile(id: u64) -> Result<Profile> {
    let user = fetch_user_from_db(id).await
        .context("Failed to fetch user from database")?;
    
    let profile = build_profile(user).await
        .context(format!("Failed to build profile for user {}", id))?;
    
    Ok(profile)
}

// With lazy evaluation
result.with_context(|| format!("Operation failed at {}", timestamp))
}

Error Chains

Build and inspect error chains for better debugging:

#![allow(unused)]
fn main() {
use rustf::error::ErrorChain;

// When an error occurs with context
let error = database_operation()
    .context("Failed to update user")
    .context("Cannot complete profile update")
    .unwrap_err();

// Inspect the error chain
let chain = ErrorChain::new(&error);

// Get all messages in the chain
for message in chain.chain() {
    println!("- {}", message);
}

// Get the root cause
let root = chain.root_cause();
println!("Root cause: {}", root);

// Format for logging
log::error!("{}", chain.format_for_log());
}

Option to Error Conversion

Convert Option to Error with context:

#![allow(unused)]
fn main() {
use rustf::error::OptionExt;

let value = some_option
    .context("Expected value to be present")?;

// With lazy evaluation
let config = config_value
    .with_context(|| format!("Missing config key: {}", key))?;
}

Retry Logic

Retry Policies

RustF provides configurable retry policies for handling transient failures:

#![allow(unused)]
fn main() {
use rustf::error::{RetryPolicy, with_retry};

// Exponential backoff (recommended for network operations)
let policy = RetryPolicy::exponential(3);  // 3 attempts with exponential backoff

// Fixed delay
let policy = RetryPolicy::fixed(5, Duration::from_secs(1));  // 5 attempts, 1 second apart

// Linear backoff
let policy = RetryPolicy::linear(4, Duration::from_millis(500));  // Linear increase

// Custom configuration
let policy = RetryPolicy {
    max_attempts: 3,
    initial_delay: Duration::from_millis(100),
    max_delay: Duration::from_secs(30),
    backoff_multiplier: 2.0,
    jitter: true,  // Add randomization to prevent thundering herd
};
}

Using Retry Logic

#![allow(unused)]
fn main() {
// Simple retry with policy
let result = with_retry(policy, || async {
    fetch_from_external_api().await
}).await?;

// Using RetryBuilder for fluent configuration
use rustf::error::RetryBuilder;

let data = RetryBuilder::new()
    .max_attempts(3)
    .initial_delay(Duration::from_millis(100))
    .backoff_multiplier(2.0)
    .jitter(true)
    .execute(|| async {
        unstable_network_call().await
    })
    .await?;
}

Retryable Errors

Only certain errors are automatically retried:

#![allow(unused)]
fn main() {
// These errors are retryable by default:
Error::Network(_)            // Network issues
Error::DatabaseConnection(_) // Connection failures
Error::Timeout(_)           // Timeouts
Error::ExternalService(..)  // External service failures
Error::DatabasePool(_)      // Pool exhaustion

// These are NOT retryable:
Error::Validation(_)        // Input validation
Error::Authentication(_)    // Auth failures
Error::Authorization(_)     // Permission denied
}

Circuit Breaker Pattern

Prevent cascading failures with circuit breakers:

#![allow(unused)]
fn main() {
use rustf::error::retry::CircuitBreaker;

// Create a circuit breaker
let breaker = CircuitBreaker::new(
    5,                          // Open after 5 failures
    2,                          // Close after 2 successes
    Duration::from_secs(30),    // Timeout before half-open
    3,                          // Max calls in half-open state
);

// Use the circuit breaker
let result = breaker.execute(|| async {
    call_unreliable_service().await
}).await;

// Circuit states:
// - Closed: Normal operation
// - Open: Rejecting calls (after threshold failures)
// - Half-Open: Testing with limited calls
}

Error Pages and Responses

HTML Error Pages

RustF provides beautiful, customizable error pages:

#![allow(unused)]
fn main() {
use rustf::error::ErrorPages;

let error_pages = ErrorPages::new(view_engine, config);

// Render error page
let response = error_pages.render_error_page(
    404,                    // Status code
    Some(&error),          // Error object
    Some("req-123"),       // Request ID
)?;

// Custom error templates in views/errors/
// - views/errors/404.html
// - views/errors/500.html
// - views/errors/generic.html
}

JSON Error Responses

For API endpoints, return structured JSON errors:

#![allow(unused)]
fn main() {
// Automatic based on Accept header
let response = error_pages.create_error_response(
    status_code,
    Some(&error),
    Some(request_id),
    request.header("Accept"),
)?;

// Force JSON response
let json_response = error_pages.create_json_error_response(
    400,
    Some(&error),
    Some("api-request-123"),
)?;

// Response format:
{
    "error": true,
    "status": 400,
    "code": "E_VALIDATION",
    "message": "User-friendly error message",
    "request_id": "api-request-123",
    "timestamp": "2024-01-20T10:30:00Z",
    "details": {  // Only in development mode
        "error_message": "Detailed error",
        "error_type": "Validation Error"
    }
}
}

Development vs Production

Error responses adapt based on environment:

#![allow(unused)]
fn main() {
// Development mode (debug builds or RUSTF_ENV=development)
- Full error messages with context
- Stack traces included
- Detailed error information
- Source file locations

// Production mode
- Sanitized, user-friendly messages
- No stack traces or sensitive data
- Generic error messages for internal errors
- Request IDs for support correlation
}

Error Logging

Structured Logging

RustF provides comprehensive error logging:

#![allow(unused)]
fn main() {
use rustf::error::{ErrorLogger, LogLevel, LogConfig};

// Configure logging
let config = LogConfig {
    level: LogLevel::Info,
    output: LogOutput::Both("/var/log/rustf.log"),
    include_stack_trace: false,  // Only in development
    include_request_context: true,
    max_file_size: Some(10 * 1024 * 1024),  // 10MB
    max_files: Some(5),  // Keep 5 rotated files
};

// Initialize logger
let logger = ErrorLogger::new(config, app_config);

// Log errors with context
logger.log_error(
    LogLevel::Error,
    &error,
    Some(&request),
    Some("req-123"),
    Some(additional_data),
);
}

Log Levels

#![allow(unused)]
fn main() {
LogLevel::Debug     // Detailed debugging information
LogLevel::Info      // Informational messages
LogLevel::Warn      // Warning conditions
LogLevel::Error     // Error conditions
LogLevel::Critical  // Critical failures requiring immediate attention
}

Request Context in Logs

Automatically captured request information:

{
    "timestamp": "2024-01-20T10:30:00Z",
    "level": "ERROR",
    "message": "Database connection failed",
    "error_type": "DatabaseConnection",
    "request_id": "req-123",
    "request_context": {
        "method": "POST",
        "uri": "/api/users",
        "client_ip": "192.168.1.100",
        "user_agent": "Mozilla/5.0..."
    },
    "stack_trace": "..."  // Only in development
}

Sensitive Data Protection

Automatic sanitization of sensitive information:

#![allow(unused)]
fn main() {
// These are automatically redacted in logs:
- Passwords in URLs and headers
- API keys and tokens
- Authorization headers
- Cookie headers
- Credit card numbers
- Social security numbers
}

Health Checks

Built-in health check endpoint:

#![allow(unused)]
fn main() {
use rustf::error::HealthCheck;

let health_check = HealthCheck::new(config);
let result = health_check.check_health().await;

// Health check response:
{
    "status": "healthy",
    "timestamp": "2024-01-20T10:30:00Z",
    "version": "1.0.0",
    "checks": {
        "database": {
            "status": "healthy",
            "message": "Connection successful"
        },
        "memory": {
            "status": "healthy",
            "message": "Memory usage within limits"
        }
    }
}
}

Best Practices

1. Never Use unwrap() in Production

#![allow(unused)]
fn main() {
// ❌ Bad - Can panic
let value = some_option.unwrap();

// βœ… Good - Proper error handling
let value = some_option
    .ok_or_else(|| Error::validation("Value is required"))?;
}

2. Add Context to Errors

#![allow(unused)]
fn main() {
// ❌ Bad - No context
database_query().await?;

// βœ… Good - With context
database_query().await
    .context("Failed to fetch user permissions")?;
}

3. Use Specific Error Types

#![allow(unused)]
fn main() {
// ❌ Bad - Generic error
Error::internal("Something went wrong")

// βœ… Good - Specific error
Error::database_query("Failed to execute SELECT query: connection timeout")
}

4. Handle Errors at the Right Level

#![allow(unused)]
fn main() {
// ❌ Bad - Swallowing errors
let _ = send_email().await;

// βœ… Good - Proper handling
if let Err(e) = send_email().await {
    log::warn!("Failed to send email: {}", e);
    // Continue - email is not critical
}
}

5. Test Error Conditions

#![allow(unused)]
fn main() {
#[test]
fn test_validation_error() {
    let result = validate_email("invalid");
    assert!(result.is_err());
    
    let error = result.unwrap_err();
    assert_eq!(error.status_code(), 400);
    assert_eq!(error.error_code(), "E_VALIDATION");
}
}

Examples

Complete Request Handler with Error Handling

#![allow(unused)]
fn main() {
async fn create_order(ctx: &mut Context) -> Result<()> {
    // Parse and validate input (body_json is synchronous)
    let order_data: OrderData = ctx.body_json()
        .map_err(|e| e.with_context("Failed to parse order data"))?;
    
    order_data.validate()
        .map_err(|e| Error::validation(e))?;
    
    // Check authentication (read the logged-in user from the session)
    let user: User = ctx.session_get("user")
        .ok_or_else(|| Error::authentication("Login required"))?;
    
    // Check authorization
    if !user.can_create_orders() {
        return Err(Error::authorization("Insufficient permissions"));
    }
    
    // Retry external payment service
    let payment_result = RetryBuilder::new()
        .max_attempts(3)
        .backoff_multiplier(2.0)
        .execute(|| async {
            payment_service::process(&order_data).await
                .map_err(|e| Error::external_service("payment", e.to_string()))
        })
        .await
        .context("Payment processing failed")?;
    
    // Create order in database
    let order = Order::create(order_data, payment_result)
        .await
        .context("Failed to create order")?;
    
    // Return success response
    ctx.json(json!({
        "success": true,
        "order_id": order.id,
        "status": order.status,
    }))
}
}

Middleware Error Handling

RustF uses a dual-phase middleware model rather than a next(ctx) chain. Inbound runs before the handler; outbound runs after. A single struct can implement both phases to attach a request ID and inspect/adjust the response.

#![allow(unused)]
fn main() {
use async_trait::async_trait;
use rustf::prelude::*;
use rustf::middleware::{InboundMiddleware, OutboundMiddleware, InboundAction};

#[derive(Clone)]
pub struct RequestIdMiddleware;

#[async_trait]
impl InboundMiddleware for RequestIdMiddleware {
    async fn process_request(&self, ctx: &mut Context) -> Result<InboundAction> {
        let request_id = uuid::Uuid::new_v4().to_string();
        // Store the id so the outbound phase can read it.
        ctx.set("request_id", request_id.clone())?;

        // Method and path are available on ctx.req (ctx.req.uri is a String).
        log::info!("[{}] {} {}", request_id, ctx.req.method, ctx.req.uri);

        // Capture guarantees this middleware's outbound phase runs.
        Ok(InboundAction::Capture)
    }
}

#[async_trait]
impl OutboundMiddleware for RequestIdMiddleware {
    async fn process_response(&self, ctx: &mut Context) -> Result<()> {
        if let Some(request_id) = ctx.get::<String>("request_id").cloned() {
            // Echo the request id back to the client.
            ctx.add_header("X-Request-ID", request_id);
        }
        Ok(())
    }
}
}

Handler errors are rendered by the framework’s error pages automatically based on the error’s status_code(), so middleware does not need to catch them. To fail a request from inbound middleware, set a response and return InboundAction::Stop.

Database Operation with Retry

#![allow(unused)]
fn main() {
async fn get_user_with_retry(id: u64) -> Result<User> {
    RetryBuilder::new()
        .max_attempts(3)
        .initial_delay(Duration::from_millis(100))
        .execute(|| async {
            User::find(id)
                .await
                .map_err(|e| Error::database_query(format!("Failed to fetch user {}: {}", id, e)))?
                .ok_or_else(|| Error::ModelNotFound(format!("User {} not found", id)))
        })
        .await
        .context(format!("Failed to retrieve user {}", id))
}
}

Configuration

Environment Variables

# Logging configuration
RUSTF_LOG_LEVEL=info                    # debug, info, warn, error, critical
RUSTF_LOG_OUTPUT=both:/var/log/rustf.log  # console, file:<path>, both:<path>, none
RUSTF_LOG_STACK_TRACE=false             # Include stack traces
RUSTF_LOG_REQUEST_CONTEXT=true          # Include request context

# Error page configuration
RUSTF_ENV=production                    # development or production
RUSTF_ERROR_VERBOSE=false              # Verbose error messages in production

Configuration File

[error]
# Error page templates directory
template_dir = "views/errors"

# Default error messages
default_404 = "The page you're looking for could not be found"
default_500 = "An internal error occurred. Please try again later"

[logging]
level = "info"
output = "file:/var/log/rustf/app.log"
max_file_size = 10485760  # 10MB
max_files = 5
include_stack_trace = false
include_request_context = true

[retry]
default_max_attempts = 3
default_initial_delay_ms = 100
default_max_delay_ms = 30000
default_backoff_multiplier = 2.0

Performance Considerations

Error Creation Cost

  • Use static strings for fixed messages: Error::validation("Invalid email")
  • Defer formatting until needed: Error::internal(format!(...)) only when necessary
  • Consider caching error messages for hot paths

Retry Overhead

  • Use circuit breakers to prevent cascading failures
  • Configure reasonable timeouts and max attempts
  • Add jitter to prevent thundering herd

Logging Performance

  • Use appropriate log levels (don’t log everything as ERROR)
  • Configure log rotation to prevent disk space issues
  • Consider async logging for high-throughput applications

Testing

Testing Error Conditions

#![allow(unused)]
fn main() {
#[cfg(test)]
mod tests {
    use super::*;
    use rustf::error::{Error, ErrorContext};
    
    #[test]
    fn test_error_chain() {
        let error = database_operation()
            .context("Failed in service")
            .context("Failed in controller")
            .unwrap_err();
        
        let chain = ErrorChain::new(&error);
        assert_eq!(chain.chain().len(), 3);
    }
    
    #[tokio::test]
    async fn test_retry_logic() {
        let mut attempts = 0;
        
        let result = with_retry(RetryPolicy::fixed(3, Duration::from_millis(10)), || async {
            attempts += 1;
            if attempts < 3 {
                Err(Error::network("Temporary failure"))
            } else {
                Ok("Success")
            }
        }).await;
        
        assert!(result.is_ok());
        assert_eq!(attempts, 3);
    }
}
}

Migration Guide

From Simple Errors to RustF Errors

#![allow(unused)]
fn main() {
// Before
fn process() -> Result<Data, Box<dyn std::error::Error>> {
    let data = fetch_data()?;
    Ok(data)
}

// After
fn process() -> rustf::error::Result<Data> {
    let data = fetch_data()
        .map_err(|e| Error::internal(e.to_string()))
        .context("Failed to fetch data")?;
    Ok(data)
}
}

Adding Retry Logic to Existing Code

#![allow(unused)]
fn main() {
// Before
let result = unreliable_operation().await?;

// After
let result = RetryBuilder::new()
    .max_attempts(3)
    .execute(|| unreliable_operation())
    .await?;
}

Conclusion

RustF’s error system provides a comprehensive, production-ready solution for error handling in web applications. By following the patterns and best practices outlined in this guide, you can build robust, maintainable applications with excellent error handling and observability.

Key takeaways:

  • Use specific error types for clarity
  • Add context to errors for better debugging
  • Implement retry logic for transient failures
  • Configure appropriate logging and monitoring
  • Never expose sensitive information in error messages
  • Test error conditions thoroughly

For more information, see the Context API reference and the Examples section.

RustF Definitions System Documentation

Overview

The RustF Definitions System provides a powerful, convention-based framework for extending RustF with custom functionality. Inspired by modern web frameworks like Rails and Laravel, it enables developers to customize framework behavior through simple, discoverable patterns without modifying core code.

Core Philosophy

The definitions system follows these principles:

  1. Convention Over Configuration - Place files in expected locations, and they’re automatically discovered
  2. Type Safety - All extensions are type-checked at compile time
  3. Zero Boilerplate - No registration code needed with auto-discovery
  4. Composable - Mix and match different definition types as needed
  5. Framework Integration - Definitions integrate seamlessly with RustF’s core systems

What Are Definitions?

Definitions are modular extensions that customize framework behavior:

  • Helpers - Custom template functions for views
  • Validators - Data validation logic for forms and APIs
  • Session Storage - Custom session backend implementations

Quick Start

1. Create a Definitions Module

Create a file in src/definitions/ directory:

#![allow(unused)]
fn main() {
// src/definitions/app.rs
use rustf::definitions::{Definitions, Helper, Validator};
use rustf::error::Result;
use serde_json::Value;

/// Install function called by auto-discovery
/// This function MUST be named 'install' and have this exact signature
pub fn install(defs: &mut Definitions) {
    // Register a custom helper
    defs.register_helper("format_money", FormatMoneyHelper);
    
    // Register a custom validator
    defs.register_validator("email", EmailValidator);
}

// Helper implementation
struct FormatMoneyHelper;

impl Helper for FormatMoneyHelper {
    fn call(&self, args: &[Value], _context: Option<&Value>) -> Result<Value> {
        if let Some(Value::Number(n)) = args.first() {
            if let Some(amount) = n.as_f64() {
                return Ok(Value::String(format!("${:.2}", amount)));
            }
        }
        Ok(Value::Null)
    }
    
    fn name(&self) -> &str { "format_money" }
    fn description(&self) -> &str { "Formats numbers as currency" }
}

// Validator implementation
struct EmailValidator;

impl Validator for EmailValidator {
    fn validate(&self, value: &Value, _options: Option<&Value>) -> Result<()> {
        if let Some(email) = value.as_str() {
            if !email.contains('@') || !email.contains('.') {
                return Err(rustf::error::Error::validation("Invalid email format"));
            }
        }
        Ok(())
    }
    
    fn name(&self) -> &str { "email" }
    fn description(&self) -> &str { "Validates email addresses" }
}
}

2. Register Definitions in Your App

Use auto-discovery in main.rs:

use rustf::prelude::*;

#[rustf::auto_discover]
#[tokio::main]
async fn main() -> rustf::Result<()> {
    let app = RustF::new()
        .definitions_from(auto_definitions!())  // Auto-discovers all definitions
        .controllers(auto_controllers!());
    
    app.start().await
}

3. Use Your Definitions

In views (for helpers), using Total.js syntax:

<!-- Price: @{format_money(price)} -->
<!-- Outputs: Price: $99.99 -->

In controllers (for validators):

#![allow(unused)]
fn main() {
async fn create_user(ctx: &mut Context) -> rustf::Result<()> {
    let email = ctx.param_str("email")?;
    
    // Get validators from global definitions
    let definitions = rustf::definitions::get().await;
    let defs = definitions.read().await;
    // `validators.get` returns Option<Arc<dyn Validator>>, not Result.
    let validator = defs.validators.get("email")
        .ok_or_else(|| rustf::Error::internal("email validator not registered"))?;
    validator.validate(&json!(email), None)?;
    
    // Proceed with user creation...
    ctx.json(json!({"status": "user created"}))
}
}

Component Types

Template Helpers

Helpers are functions that transform data in views. They’re perfect for formatting, calculations, and generating HTML snippets.

Creating a Helper

#![allow(unused)]
fn main() {
use rustf::definitions::Helper;
use rustf::error::Result;
use serde_json::Value;

struct DateFormatHelper;

impl Helper for DateFormatHelper {
    fn call(&self, args: &[Value], _context: Option<&Value>) -> Result<Value> {
        // args[0] = date string/timestamp
        // args[1] = format string (optional)
        
        if let Some(date_value) = args.first() {
            let format = args.get(1)
                .and_then(|v| v.as_str())
                .unwrap_or("%Y-%m-%d");
            
            // Format the date...
            let formatted = format_date(date_value, format)?;
            return Ok(Value::String(formatted));
        }
        
        Ok(Value::Null)
    }
    
    fn name(&self) -> &str { "date_format" }
    
    fn description(&self) -> &str { 
        "Formats dates according to strftime patterns" 
    }
}
}

Using Helpers in Views

<!-- Total.js syntax (the only supported template engine) -->
@{date_format(user.created_at, "%B %d, %Y")}

<!-- With default format -->
@{date_format(timestamp)}

Built-in Helper Registry

RustF provides a HelperRegistry that registers the following built-in helpers out of the box (registered internally with register_fn closures):

  • format_currency
  • truncate
  • pluralize
  • time_ago
  • format_date
  • url_encode
  • url_decode
  • json
  • capitalize
  • slugify
  • default
  • file_size

All of these are available in templates via @{helper_name(...)}.

Validators

Validators ensure data integrity before processing. They’re essential for form validation, API input validation, and business rule enforcement.

Creating a Validator

#![allow(unused)]
fn main() {
use rustf::definitions::Validator;
use rustf::error::{Result, Error};
use serde_json::Value;

struct PasswordStrengthValidator;

impl Validator for PasswordStrengthValidator {
    fn validate(&self, value: &Value, options: Option<&Value>) -> Result<()> {
        let min_length = options
            .and_then(|o| o.get("min_length"))
            .and_then(|v| v.as_u64())
            .unwrap_or(8) as usize;
        
        if let Some(password) = value.as_str() {
            if password.len() < min_length {
                return Err(Error::validation(
                    format!("Password must be at least {} characters", min_length)
                ));
            }
            
            let has_upper = password.chars().any(|c| c.is_uppercase());
            let has_lower = password.chars().any(|c| c.is_lowercase());
            let has_digit = password.chars().any(|c| c.is_numeric());
            let has_special = password.chars().any(|c| !c.is_alphanumeric());
            
            if !(has_upper && has_lower && has_digit && has_special) {
                return Err(Error::validation(
                    "Password must contain uppercase, lowercase, digit, and special character"
                ));
            }
        }
        
        Ok(())
    }
    
    fn name(&self) -> &str { "password_strength" }
    
    fn description(&self) -> &str { 
        "Validates password meets security requirements" 
    }
}
}

Using Validators

#![allow(unused)]
fn main() {
async fn update_password(ctx: &mut Context) -> rustf::Result<()> {
    let new_password = ctx.param_str("new_password")?;
    
    // Get validator from global definitions
    let definitions = rustf::definitions::get().await;
    let defs = definitions.read().await;
    // `validators.get` returns Option, not Result.
    let validator = defs.validators.get("password_strength")
        .ok_or_else(|| rustf::Error::internal("password_strength validator not registered"))?;
    
    // Validate with options
    let options = json!({
        "min_length": 12,
        "require_special": true
    });
    
    validator.validate(&json!(new_password), Some(&options))?;
    
    // Password is valid, proceed with update
    update_user_password(&new_password).await?;
    
    ctx.json(json!({"status": "password updated"}))
}
}

Custom Session Storage

The definitions system enables custom session storage backends through a factory pattern. This is the modern, recommended approach for implementing database or custom storage backends.

Creating Custom Session Storage

Create src/definitions/session_storage.rs:

#![allow(unused)]
fn main() {
use rustf::definitions::Definitions;
use rustf::session::{SessionStorage, SessionData, StorageStats};
use rustf::config::SessionConfig;
use rustf::error::Result;
use async_trait::async_trait;
use sqlx::PgPool;
use std::sync::Arc;
use std::time::Duration;

/// Install function called by auto-discovery
/// This registers our custom session storage factory with the definitions system
pub fn install(defs: &mut Definitions) {
    log::info!("Installing custom session storage from definitions");
    defs.set_session_storage_factory(create_session_storage);
}

/// Factory function that creates our custom session storage
/// This is called by the framework when initializing sessions
fn create_session_storage(config: &SessionConfig) -> Result<Arc<dyn SessionStorage>> {
    log::info!("Creating custom PostgreSQL session storage");
    
    // You can access configuration here
    let database_url = std::env::var("DATABASE_URL")
        .unwrap_or_else(|_| "postgresql://localhost/myapp".to_string());
    
    // Create and return your custom storage
    let storage = PostgresSessionStorage::new(&database_url)?;
    Ok(Arc::new(storage))
}

/// PostgreSQL session storage implementation
pub struct PostgresSessionStorage {
    pool: PgPool,
}

impl PostgresSessionStorage {
    pub fn new(database_url: &str) -> Result<Self> {
        // Note: For simplicity, using block_on here
        // In production, consider initializing the pool elsewhere
        let pool = futures::executor::block_on(
            PgPool::connect(database_url)
        ).map_err(|e| rustf::error::Error::internal(
            format!("Failed to connect to database: {}", e)
        ))?;
        
        // Create table if needed
        futures::executor::block_on(async {
            sqlx::query(
                "CREATE TABLE IF NOT EXISTS sessions (
                    id VARCHAR(64) PRIMARY KEY,
                    data JSONB NOT NULL,
                    expires_at TIMESTAMP NOT NULL,
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
                )"
            ).execute(&pool).await
        }).map_err(|e| rustf::error::Error::internal(
            format!("Failed to create sessions table: {}", e)
        ))?;
        
        Ok(Self { pool })
    }
}

#[async_trait]
impl SessionStorage for PostgresSessionStorage {
    async fn get(&self, session_id: &str) -> Result<Option<SessionData>> {
        let row = sqlx::query!(
            "SELECT data FROM sessions 
             WHERE id = $1 AND expires_at > NOW()",
            session_id
        )
        .fetch_optional(&self.pool)
        .await?;
        
        match row {
            Some(row) => {
                let mut data: SessionData = serde_json::from_value(row.data)?;
                data.touch(); // Update last accessed
                
                // Update timestamp in database
                sqlx::query!(
                    "UPDATE sessions SET updated_at = NOW() WHERE id = $1",
                    session_id
                )
                .execute(&self.pool)
                .await?;
                
                Ok(Some(data))
            }
            None => Ok(None)
        }
    }
    
    async fn set(
        &self, 
        session_id: &str, 
        data: &SessionData, 
        ttl: Duration
    ) -> Result<()> {
        let expires_at = chrono::Utc::now() + 
            chrono::Duration::seconds(ttl.as_secs() as i64);
        let json_data = serde_json::to_value(data)?;
        
        sqlx::query!(
            "INSERT INTO sessions (id, data, expires_at, updated_at)
             VALUES ($1, $2, $3, NOW())
             ON CONFLICT (id) DO UPDATE
             SET data = $2, expires_at = $3, updated_at = NOW()",
            session_id,
            json_data,
            expires_at
        )
        .execute(&self.pool)
        .await?;
        
        Ok(())
    }
    
    async fn delete(&self, session_id: &str) -> Result<()> {
        sqlx::query!(
            "DELETE FROM sessions WHERE id = $1",
            session_id
        )
        .execute(&self.pool)
        .await?;
        Ok(())
    }
    
    async fn exists(&self, session_id: &str) -> Result<bool> {
        let exists = sqlx::query!(
            "SELECT 1 as exists FROM sessions 
             WHERE id = $1 AND expires_at > NOW()",
            session_id
        )
        .fetch_optional(&self.pool)
        .await?
        .is_some();
        
        Ok(exists)
    }
    
    async fn cleanup_expired(&self) -> Result<usize> {
        let result = sqlx::query!(
            "DELETE FROM sessions WHERE expires_at <= NOW()"
        )
        .execute(&self.pool)
        .await?;
        
        Ok(result.rows_affected() as usize)
    }
    
    fn backend_name(&self) -> &'static str {
        "postgresql"
    }
    
    async fn stats(&self) -> Result<StorageStats> {
        let total: i64 = sqlx::query_scalar!(
            "SELECT COUNT(*) FROM sessions"
        )
        .fetch_one(&self.pool)
        .await?;
        
        let active: i64 = sqlx::query_scalar!(
            "SELECT COUNT(*) FROM sessions WHERE expires_at > NOW()"
        )
        .fetch_one(&self.pool)
        .await?;
        
        Ok(StorageStats {
            total_sessions: total as usize,
            active_sessions: active as usize,
            expired_sessions: (total - active) as usize,
            backend_metrics: HashMap::new(),
        })
    }
}
}

Integration with Auto-Discovery

The session storage factory is automatically discovered and used when you include it in your definitions:

// main.rs
#[rustf::auto_discover]
#[tokio::main]
async fn main() -> rustf::Result<()> {
    let app = RustF::new()
        .definitions_from(auto_definitions!())  // Discovers session_storage.rs
        .controllers(auto_controllers!());
    
    // Your custom session storage is now active!
    app.start().await
}

Auto-Discovery System

How Auto-Discovery Works

The auto_definitions!() macro scans your src/definitions/ directory and automatically:

  1. Finds all .rs files with an install function
  2. Generates the necessary module declarations
  3. Calls each install function to register definitions
  4. Makes them available throughout your application

IMPORTANT: Every file in src/definitions/ must export a public install function with this exact signature:

#![allow(unused)]
fn main() {
pub fn install(defs: &mut Definitions) {
    // Register your definitions here
}
}

This function is where you register all your helpers, validators, or storage factories. The auto-discovery system will call this function during application initialization.

File Convention

Place definition files in src/definitions/:

src/
  definitions/
    app.rs           # General helpers and validators
    helpers.rs       # Template helpers only
    validators.rs    # Validators only
    session_storage.rs  # Custom session storage factory

Each file should export an install function:

#![allow(unused)]
fn main() {
pub fn install(defs: &mut Definitions) {
    // Register your definitions here
}
}

Manual Registration

If you prefer explicit control, register definitions manually:

// main.rs
use my_app::definitions;

#[tokio::main]
async fn main() -> rustf::Result<()> {
    let app = RustF::new()
        .definitions_from(definitions::app::install)
        .definitions_from(definitions::auth::install)
        .controllers(auto_controllers!());
    
    app.start().await
}

Advanced Topics

Accessing Definitions in Code

In Controllers

#![allow(unused)]
fn main() {
async fn my_controller(ctx: &mut Context) -> rustf::Result<()> {
    // Get definitions from global registry
    let definitions = rustf::definitions::get().await;
    let defs = definitions.read().await;
    
    // Access helpers (`get` returns Option<Arc<dyn Helper>>, not Result)
    let helper = defs.helpers.get("format_money")
        .ok_or_else(|| rustf::Error::internal("format_money helper not registered"))?;
    let formatted = helper.call(&[json!(99.99)], None)?;
    
    // Access validators (`get` returns Option<Arc<dyn Validator>>, not Result)
    let validator = defs.validators.get("email")
        .ok_or_else(|| rustf::Error::internal("email validator not registered"))?;
    validator.validate(&json!("user@example.com"), None)?;
    
    ctx.json(json!({"formatted": formatted}))
}
}

In Middleware

#![allow(unused)]
fn main() {
use async_trait::async_trait;
use rustf::middleware::{InboundMiddleware, InboundAction};
use rustf::context::Context;
use rustf::error::Result;
use serde_json::json;

pub struct ValidationMiddleware;

#[async_trait]
impl InboundMiddleware for ValidationMiddleware {
    async fn process_request(&self, ctx: &mut Context) -> Result<InboundAction> {
        // Get email from request (param_str errors when absent or empty)
        let email = match ctx.param_str("email") {
            Ok(e) => e,
            Err(_) => return Ok(InboundAction::Continue),
        };
        
        // Get validator from global definitions
        let definitions = rustf::definitions::get().await;
        let defs = definitions.read().await;
        // `validators.get` returns Option, not Result.
        if let Some(validator) = defs.validators.get("email") {
            validator.validate(&json!(email), None)?;
        }
        
        Ok(InboundAction::Continue)
    }
}
}

Testing Definitions

#![allow(unused)]
fn main() {
#[cfg(test)]
mod tests {
    use super::*;
    use rustf::definitions::Definitions;
    
    #[test]
    fn test_format_money_helper() {
        let mut defs = Definitions::new();
        super::install(&mut defs);
        
        let helper = defs.helpers.get("format_money").unwrap();
        let result = helper.call(&[json!(42.50)], None).unwrap();
        
        assert_eq!(result, json!("$42.50"));
    }
    
    #[test]
    fn test_email_validator() {
        let mut defs = Definitions::new();
        super::install(&mut defs);
        
        let validator = defs.validators.get("email").unwrap();
        
        // Valid email
        assert!(validator.validate(&json!("user@example.com"), None).is_ok());
        
        // Invalid email
        assert!(validator.validate(&json!("invalid"), None).is_err());
    }
}
}

Async Helpers and Validators

For async operations, wrap them appropriately:

#![allow(unused)]
fn main() {
struct AsyncDataHelper;

impl Helper for AsyncDataHelper {
    fn call(&self, args: &[Value], _context: Option<&Value>) -> Result<Value> {
        // For async operations, you might need to use block_on
        // or restructure to handle async differently
        let data = futures::executor::block_on(async {
            fetch_async_data().await
        })?;
        
        Ok(json!(data))
    }
    
    fn name(&self) -> &str { "async_data" }
    fn description(&self) -> &str { "Fetches async data" }
}
}

Best Practices

1. Keep Definitions Focused

Each definition should have a single, clear purpose:

#![allow(unused)]
fn main() {
// Good: Specific, reusable
struct FormatCurrencyHelper;
struct ValidateEmailValidator;

// Less ideal: Too generic
struct GeneralHelper;
struct DoEverythingValidator;
}

2. Use Descriptive Names

Names should clearly indicate function:

#![allow(unused)]
fn main() {
// Good
"format_date"
"validate_phone"
"sanitize_html"

// Less clear
"process"
"check"
"helper1"
}

3. Handle Errors Gracefully

Always provide helpful error messages:

#![allow(unused)]
fn main() {
impl Validator for PhoneValidator {
    fn validate(&self, value: &Value, _options: Option<&Value>) -> Result<()> {
        if let Some(phone) = value.as_str() {
            if !is_valid_phone(phone) {
                return Err(Error::validation(
                    format!("'{}' is not a valid phone number. Expected format: +1-555-555-5555", phone)
                ));
            }
        } else {
            return Err(Error::validation(
                "Phone number must be a string"
            ));
        }
        Ok(())
    }
}
}

4. Document Your Definitions

Always implement the description() method:

#![allow(unused)]
fn main() {
impl Helper for MyHelper {
    fn name(&self) -> &str { "my_helper" }
    
    fn description(&self) -> &str {
        "Formats user data for display. \
         Usage: @{my_helper(user)} or @{my_helper(user, 'option')}"
    }
}
}

5. Make Definitions Testable

Design definitions to be easily testable:

#![allow(unused)]
fn main() {
// Separate business logic from the definition
fn format_phone_number(phone: &str) -> String {
    // Formatting logic here
}

struct FormatPhoneHelper;

impl Helper for FormatPhoneHelper {
    fn call(&self, args: &[Value], _context: Option<&Value>) -> Result<Value> {
        if let Some(Value::String(phone)) = args.first() {
            Ok(Value::String(format_phone_number(phone)))
        } else {
            Ok(Value::Null)
        }
    }
    // ...
}

#[test]
fn test_phone_formatting() {
    assert_eq!(format_phone_number("5555555555"), "+1 (555) 555-5555");
}
}

Integration with RustF Systems

View System Integration

Helpers are automatically available in Total.js templates (the only supported template engine):

#![allow(unused)]
fn main() {
// Registered in definitions
defs.register_helper("user_avatar", UserAvatarHelper);

// Available in Total.js views
// @{user_avatar(user.email, 200)}
}

Validation System Integration

Validators work with RustF’s error handling:

#![allow(unused)]
fn main() {
async fn api_endpoint(ctx: &mut Context) -> rustf::Result<()> {
    let data: serde_json::Value = ctx.body_json()?;
    
    // Get validators from global definitions
    let definitions = rustf::definitions::get().await;
    let defs = definitions.read().await;
    
    // Validate multiple fields. `validators.get` returns Option, not Result,
    // so resolve each validator with `ok_or_else` before calling validate.
    let get = |name: &str| {
        defs.validators.get(name)
            .ok_or_else(|| rustf::Error::internal(format!("{name} validator not registered")))
    };
    get("email")?.validate(&data["email"], None)?;
    get("password")?.validate(&data["password"], None)?;
    get("age")?.validate(&data["age"], Some(&json!({"min": 18})))?;
    
    // All validations passed
    process_data(data).await?;
    
    ctx.json(json!({"status": "success"}))
}
}

Session System Integration

Custom session storage integrates seamlessly with RustF’s session middleware:

#![allow(unused)]
fn main() {
// Your custom storage is automatically used when defined
// src/definitions/session_storage.rs exists and has an install() function

// In controllers, sessions work normally
async fn login(ctx: &mut Context) -> rustf::Result<()> {
    ctx.session_set("user_id", user.id)?;
    ctx.session_set("username", user.username)?;
    
    // Your custom storage handles persistence
    ctx.json(json!({"status": "logged in"}))
}
}

Troubleshooting

Definitions Not Found

If your definitions aren’t being discovered:

  1. Ensure files are in src/definitions/
  2. Check that files have an install function
  3. Verify you’re using auto_definitions!() or manual registration
  4. Make sure the function signature matches: pub fn install(defs: &mut Definitions)

Helper Not Available in Views

  1. Confirm the helper is registered in install()
  2. Check the helper name matches exactly (case-sensitive)
  3. Verify the view engine is configured correctly
  4. Check helper’s name() method returns the expected string

Validator Errors Not Showing

  1. Ensure you’re returning proper Error::validation() errors
  2. Check that error messages are descriptive
  3. Verify the validator is registered with the correct name
  4. Test the validator independently to ensure it works

Session Storage Not Being Used

  1. Verify src/definitions/session_storage.rs exists
  2. Check the file has an install(defs: &mut Definitions) function
  3. Ensure install() calls defs.set_session_storage_factory(your_factory_fn)
  4. Verify your factory function signature matches: fn(&SessionConfig) -> Result<Arc<dyn SessionStorage>>
  5. Confirm auto-discovery is enabled with auto_definitions!() in main.rs
  6. Check that session middleware is enabled in configuration
  7. Look for log messages: β€œUsing custom session storage from definitions”

Important: The SessionConfig parameter is from rustf::config::SessionConfig, not rustf::session::manager::SessionConfig

Examples Repository

For complete working examples of all definition types, see the RustF examples repository:

  • Basic Definitions: Simple helpers and validators
  • Advanced Helpers: Complex formatting and HTML generation
  • Custom Validators: Business rule validation
  • Database Session Storage: PostgreSQL, MySQL implementations
  • Redis Session Storage: High-performance session storage
  • Multi-tenant Definitions: Per-tenant customization

Summary

The RustF Definitions System provides a powerful, type-safe way to extend the framework with custom functionality. By following conventions and using auto-discovery, you can build modular, reusable extensions that integrate seamlessly with RustF’s core systems.

Key takeaways:

  1. Use conventions - Place files in src/definitions/ for auto-discovery
  2. Implement traits - Helper, Validator, and SessionStorage provide the contracts
  3. Leverage auto-discovery - Let the framework handle registration
  4. Keep it simple - Each definition should do one thing well
  5. Test thoroughly - Definitions are easy to unit test

With definitions, you can build powerful, customized applications while keeping your code organized, maintainable, and reusable across projects.

Advanced Topics

This section covers advanced features and optimization techniques for experienced RustF developers.

The CLI is no longer grouped here. It now has its own top-level section because it is part of the normal day-to-day workflow, not an advanced-only tool.

Topics

Performance Optimization

Learn how to optimize your RustF application for production:

  • View caching
  • Database query optimization
  • Session storage strategies
  • Static file serving
  • Response compression
  • Profiling and benchmarking

Workers

Background job processing with RustF workers:

  • Creating workers
  • Task scheduling
  • Error handling
  • Monitoring and logging

Events

Event-driven architecture with RustF:

  • Event system overview
  • Creating event handlers
  • Event priorities
  • Built-in events

Modules

Shared business logic modules:

  • Creating modules
  • Module registration
  • Dependency injection
  • Best practices
  • CLI - Project scaffolding, generation, analysis, and schema workflows
  • Core Guides - Essential framework concepts
  • API Reference - Complete API documentation
  • Examples - Practical tutorials

Performance Optimization

This guide covers performance optimization techniques for RustF applications.

Overview

RustF is designed for performance, but there are several strategies to optimize your application further.

View Caching

Enable View Caching

In production, enable view caching:

[views]
cache_enabled = true

This caches compiled templates to avoid recompilation on every request.

Database Optimization

Connection Pooling

Configure appropriate pool size:

[database]
max_connections = 50

Query Optimization

  • Use indexes on frequently queried columns
  • Avoid N+1 queries
  • Use pagination for large datasets
  • Cache frequently accessed data

Example: Optimized Query

#![allow(unused)]
fn main() {
// Bad: N+1 queries
for post in posts {
    let author = get_author(post.author_id)?; // Query per post
}

// Good: Single query with join
// Posts::query() returns Result, so use `?`. join() takes (table, on_expr).
// select() takes a slice of columns (use select_raw for raw expressions).
// Use .get().await? to fetch the list.
let posts_with_authors = Posts::query()?
    .join("users", "posts.author_id = users.id")
    .select_raw(&["posts.*", "users.name as author_name"])
    .get()
    .await?;
}

Session Storage

Use Redis for Sessions

For better performance and scalability:

[session.storage]
type = "redis"
url = "redis://localhost:6379"

Benefits:

  • Faster than database storage
  • Shared across multiple instances
  • Automatic expiration

Static File Serving

Serve via Nginx/CDN

Don’t serve static files through the application:

# Nginx configuration
location /static/ {
    alias /path/to/public/;
    expires 30d;
    add_header Cache-Control "public, immutable";
}

Response Compression

Enable Gzip

Configure nginx for compression:

gzip on;
gzip_types text/plain text/css application/json application/javascript;
gzip_min_length 1000;

Caching Strategies

Application-Level Caching

Use in-memory caching for frequently accessed data:

#![allow(unused)]
fn main() {
use std::sync::Arc;
use std::sync::RwLock;
use std::collections::HashMap;

static CACHE: LazyLock<Arc<RwLock<HashMap<String, Value>>>> = 
    LazyLock::new(|| Arc::new(RwLock::new(HashMap::new())));

fn get_cached_data(key: &str) -> Option<Value> {
    CACHE.read().unwrap().get(key).cloned()
}

fn set_cached_data(key: String, value: Value) {
    CACHE.write().unwrap().insert(key, value);
}
}

HTTP Caching

Set appropriate cache headers:

#![allow(unused)]
fn main() {
ctx.add_header("Cache-Control", "public, max-age=3600");
}

Request Pooling (Intentionally Not Used)

RustF does not use object pooling for Request objects, and it is not a recommended optimization. Benchmarks (rustf/benches/pool.rs) show pooling is roughly 2x slower than direct allocation here: the mutex-lock and reset overhead outweigh any reuse benefit, and Rust’s allocator already handles small objects efficiently. Prefer direct allocation.

A RequestPool type still exists (rustf::pool::global_request_pool()), but its get() is synchronous and returns a PooledRequest (no .await, no ?):

#![allow(unused)]
fn main() {
use rustf::pool::global_request_pool;

// Note: kept for benchmarking/documentation; not used on the hot path.
let pooled_req = global_request_pool().get(); // sync, returns PooledRequest
}

Async Operations

Use Async for I/O

Always use async for database and network operations. Database access goes through the async query builder or the parameterized helpers β€” there is no db.query("SELECT ...") that takes a raw SQL string (DB::query() takes no arguments and returns a QueryBuilder):

#![allow(unused)]
fn main() {
// Query builder (async)
let users = Users::query()?.get().await?;

// Or run parameterized raw SQL via the async helpers
use rustf::db::DB;
let rows = DB::fetch_all_with_params("SELECT * FROM users WHERE active = $1", vec![true.into()]).await?;
let affected = DB::execute_with_params("DELETE FROM sessions WHERE expired = $1", vec![true.into()]).await?;
}

Memory Management

Avoid Unnecessary Cloning

#![allow(unused)]
fn main() {
// Bad: Unnecessary clone
let data = expensive_data.clone();
process(data);

// Good: Use reference
process(&expensive_data);
}

Use String Capacity Hints

#![allow(unused)]
fn main() {
// Pre-allocate string capacity
let mut output = String::with_capacity(estimated_size);
}

Profiling

Use Cargo Instruments

cargo install cargo-instruments
cargo instruments --template time

Benchmark Critical Paths

#![allow(unused)]
fn main() {
#[cfg(test)]
mod benches {
    use super::*;
    use criterion::{black_box, criterion_group, criterion_main, Criterion};

    fn bench_query(c: &mut Criterion) {
        c.bench_function("query_users", |b| {
            b.iter(|| {
                black_box(Users::find_all().unwrap());
            });
        });
    }

    criterion_group!(benches, bench_query);
    criterion_main!(benches);
}
}

Monitoring

Track Performance Metrics

  • Request latency
  • Database query time
  • Memory usage
  • CPU usage
  • Error rates

Use APM Tools

Consider integrating:

  • Prometheus for metrics
  • Grafana for visualization
  • Sentry for error tracking

Best Practices

  1. Enable view caching in production
  2. Use connection pooling for databases
  3. Serve static files via nginx/CDN
  4. Enable compression (gzip)
  5. Use Redis for sessions in multi-instance deployments
  6. Optimize database queries (indexes, avoid N+1)
  7. Cache frequently accessed data
  8. Profile and benchmark critical paths
  9. Monitor performance in production
  10. Use async for all I/O operations

Example: Optimized Handler

#![allow(unused)]
fn main() {
async fn optimized_handler(ctx: &mut Context) -> Result<()> {
    // Use cached data if available
    if let Some(cached) = get_cached_data("recent_posts") {
        return ctx.json(cached);
    }
    
    // Optimized query with join
    // Posts::query() returns Result (use `?`); join() takes (table, on_expr);
    // use .get().await? to fetch the list (find(id) is for a single row by id).
    let posts = Posts::query()?
        .join("users", "posts.author_id = users.id")
        .where_eq("published", true)
        .order_by("created_at", OrderDirection::Desc)
        .limit(10)
        .get()
        .await?;
    
    // Cache result
    set_cached_data("recent_posts".to_string(), json!(posts));
    
    ctx.json(json!(posts))
}
}

RustF Worker System

Table of Contents


Introduction

The RustF Worker system provides a lightweight, Total.js-inspired approach to background task execution. Unlike traditional worker queues or job processors, RustF workers are on-demand tasks that execute asynchronously and automatically stop when complete.

Why Workers?

Workers are ideal for:

  • Background Processing: Long-running tasks that shouldn’t block HTTP responses
  • Async Operations: Email sending, file uploads, report generation
  • Scheduled Tasks: Cleanup, maintenance, data synchronization
  • Decoupled Logic: Separating business logic from HTTP request handling
  • Concurrent Execution: Running multiple independent tasks simultaneously

Key Features

  • 🌍 Global API: Access workers from anywhere using WORKER::
  • ⚑ On-Demand: Workers execute when called, no persistent processes
  • ⏱️ Timeout Support: Automatic cancellation after specified duration
  • πŸ“¨ Message Streaming: Real-time communication between worker and caller
  • πŸ“Š Statistics: Automatic tracking of runs, errors, and execution times
  • πŸ”„ Concurrent: Multiple workers can run simultaneously
  • 🎯 Type-Safe: Full Rust type safety with async/await

Design Philosophy

RustF workers follow Total.js conventions:

  • Registration-based: Define workers once, execute many times
  • Context-rich: Workers receive a WorkerContext with configuration and utilities
  • Fire-and-forget or await: Choose between async execution or waiting for results
  • Stateless: Each execution is independent with isolated state

Quick Start

1. Create Worker Directory

Create the required src/workers/ directory:

mkdir -p src/workers

2. Create Your First Worker

Create a worker file in src/workers/:

#![allow(unused)]
fn main() {
// src/workers/email.rs
use rustf::prelude::*;
use rustf::workers::WORKER;
use std::time::Duration;

pub async fn install() -> Result<()> {
    WORKER::register("send-email", |ctx| async move {
        ctx.info("Sending email...");

        // Simulate email sending
        tokio::time::sleep(Duration::from_secs(2)).await;

        ctx.info("Email sent successfully!");
        Ok(())
    }).await?;

    Ok(())
}
}

3. Enable Auto-Discovery

Use #[rustf::auto_discover] in your main function:

// src/main.rs
use rustf::prelude::*;

#[rustf::auto_discover]  // ← Automatically discovers workers in src/workers/
#[tokio::main]
async fn main() -> Result<()> {
    env_logger::init();

    let app = RustF::new()
        .auto_load()  // ← Loads all discovered workers
        .start()  // bind address comes from config
        .await?;

    Ok(())
}

4. Execute the Worker

Call the worker from any controller:

#![allow(unused)]
fn main() {
use rustf::workers::WORKER;

async fn send_welcome_email(ctx: &mut Context) -> Result<()> {
    // Execute worker and wait for completion
    WORKER::run("send-email", None).await?;

    ctx.json(json!({
        "status": "Email sent"
    }))
}
}

That’s it! The framework automatically discovers and registers all workers in src/workers/.


Core Concepts

Worker Lifecycle

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ Registrationβ”‚  ← Define worker once during startup
β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”˜
       β”‚
       β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚   Idle      β”‚  ← Worker definition exists, waiting to be called
β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”˜
       β”‚
       β–Ό WORKER::call()
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  Running    β”‚  ← Worker executing asynchronously
β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”˜
       β”‚
       β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ Completed   β”‚  ← Worker finishes, stats recorded
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Important: RustF workers are not persistent processes. Each execution:

  1. Starts fresh with new context
  2. Runs to completion
  3. Automatically stops and cleans up
  4. Records statistics

WorkerContext

Every worker receives a WorkerContext providing:

  • Identity: Worker name and run ID
  • Configuration: Access to app config
  • Payload: Input data passed during execution
  • Logging: Structured logging with worker identification
  • State: Per-execution state management
  • Messaging: Emit messages to caller
  • Environment: Development vs. production detection
  • Utilities: Sleep, timing, etc.
#![allow(unused)]
fn main() {
WORKER::register("example", |ctx| async move {
    ctx.info(&format!("Worker: {}, Run: {}",
        ctx.worker_name(),
        ctx.run_id()
    ));

    if ctx.is_development() {
        ctx.debug("Running in development mode");
    }

    // Access payload
    if let Some(data) = ctx.payload() {
        ctx.info(&format!("Received: {}", data));
    }

    Ok(())
}).await?;
}

WorkerHandle

When calling a worker with WORKER::call(), you receive a WorkerHandle:

#![allow(unused)]
fn main() {
let mut handle = WORKER::call("worker-name", None, None).await?;

// Get worker info
let run_id = handle.id();
let name = handle.worker_name();

// Receive messages from worker
while let Some(message) = handle.recv().await {
    println!("Worker sent: {}", message);
}

// Wait for completion
handle.await_result().await?;

// Or cancel if needed
handle.cancel().await?;
}

Worker Statistics

The system automatically tracks statistics for each worker:

#![allow(unused)]
fn main() {
#[derive(Debug, Clone, Serialize)]
pub struct WorkerStats {
    pub runs: u64,              // Total executions
    pub errors: u64,            // Failed executions
    pub last_run_ms: Option<u64>, // Duration of last run
    pub total_runtime_ms: u64,  // Cumulative runtime
}

// Access statistics
let stats = WORKER::stats("send-email").await;
if let Some(stats) = stats {
    println!("Runs: {}, Errors: {}, Avg: {}ms",
        stats.runs,
        stats.errors,
        stats.total_runtime_ms / stats.runs
    );
}
}

Worker Registration

Directory Structure (Required)

All workers MUST be placed in the src/workers/ directory. The framework uses compile-time auto-discovery to find and register workers.

your-app/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ workers/           # ⚠️ Required directory
β”‚   β”‚   β”œβ”€β”€ email.rs       # Worker file
β”‚   β”‚   β”œβ”€β”€ cleanup.rs     # Worker file
β”‚   β”‚   └── reports.rs     # Worker file
β”‚   β”œβ”€β”€ controllers/
β”‚   β”œβ”€β”€ models/
β”‚   └── main.rs
└── Cargo.toml

Worker File Structure

Each worker file in src/workers/ must have an install() function:

#![allow(unused)]
fn main() {
// src/workers/email.rs
use rustf::prelude::*;
use rustf::workers::WORKER;
use std::time::Duration;

/// Install email worker - this function is called automatically by the framework
pub async fn install() -> Result<()> {
    WORKER::register("send-email", |ctx| async move {
        let payload = ctx.payload()
            .ok_or_else(|| Error::validation("Email worker requires payload"))?;

        let to = payload["to"].as_str()
            .ok_or_else(|| Error::validation("Missing 'to' field"))?;

        ctx.info(&format!("Sending email to: {}", to));

        // Email sending logic...
        tokio::time::sleep(Duration::from_secs(1)).await;

        ctx.info("Email sent successfully");
        Ok(())
    }).await?;

    Ok(())
}
}

Auto-Discovery Methods

RustF provides three ways to enable worker auto-discovery:

The simplest approach - automatically discovers all workers:

// src/main.rs
use rustf::prelude::*;

#[rustf::auto_discover]  // ← Discovers src/workers/ automatically
#[tokio::main]
async fn main() -> Result<()> {
    let app = RustF::with_args()?.auto_load();
    app.start().await
}

Method 2: .auto_load() (Explicit)

Manually enable auto-loading with full control:

// src/main.rs
use rustf::prelude::*;

#[tokio::main]
async fn main() -> Result<()> {
    let app = RustF::new()
        .with_workers()
        .auto_load();  // ← Loads workers from src/workers/

    app.start().await
}

Method 3: auto_workers!() Macro (Advanced)

Direct macro usage for custom setups:

// src/main.rs
use rustf::prelude::*;

#[tokio::main]
async fn main() -> Result<()> {
    let app = RustF::new()
        .with_workers()
        .workers_from(auto_workers!())  // ← Scans src/workers/ at compile time
        .start()  // bind address comes from config
        .await?;

    Ok(())
}

Multiple Workers Per File

You can register multiple workers in a single file:

#![allow(unused)]
fn main() {
// src/workers/notifications.rs
use rustf::prelude::*;
use rustf::workers::WORKER;

pub async fn install() -> Result<()> {
    // Email notification worker
    WORKER::register("notify-email", |ctx| async move {
        ctx.info("Sending email notification");
        // Implementation...
        Ok(())
    }).await?;

    // SMS notification worker
    WORKER::register("notify-sms", |ctx| async move {
        ctx.info("Sending SMS notification");
        // Implementation...
        Ok(())
    }).await?;

    // Push notification worker
    WORKER::register("notify-push", |ctx| async move {
        ctx.info("Sending push notification");
        // Implementation...
        Ok(())
    }).await?;

    Ok(())
}
}

Nested Directory Organization

Workers can be organized in subdirectories:

src/workers/
β”œβ”€β”€ notifications/
β”‚   β”œβ”€β”€ email.rs
β”‚   β”œβ”€β”€ sms.rs
β”‚   └── push.rs
β”œβ”€β”€ reports/
β”‚   β”œβ”€β”€ daily.rs
β”‚   └── monthly.rs
└── maintenance/
    β”œβ”€β”€ cleanup.rs
    └── backup.rs

The framework automatically discovers workers in subdirectories up to 3 levels deep.

Skipping Files

Files are automatically skipped if they:

  • Are named mod.rs
  • End with .inc.rs
  • Start with underscore (_helper.rs)
#![allow(unused)]
fn main() {
// src/workers/mod.rs - βœ… Skipped automatically
// src/workers/helpers.inc.rs - βœ… Skipped automatically
// src/workers/_internal.rs - βœ… Skipped automatically
// src/workers/email.rs - ❌ Discovered and loaded
}

Worker Registration Best Practices

  1. Use src/workers/ directory: This is mandatory - workers outside this directory won’t be discovered
  2. One install() per file: Each worker file must export a public async install() function
  3. Descriptive file names: Use clear names like email.rs, cleanup.rs, reports.rs
  4. Descriptive worker names: Use kebab-case for worker names (send-email, generate-report)
  5. One responsibility per worker: Each worker should do one thing well
  6. Validate payloads early: Always validate input data at the start of the worker
  7. Handle errors properly: Use Result<()> and return meaningful errors
#![allow(unused)]
fn main() {
// βœ… Good: Clear name, validated input, error handling
WORKER::register("send-welcome-email", |ctx| async move {
    let payload = ctx.payload()
        .ok_or_else(|| Error::validation("Payload required"))?;

    let email = payload["email"].as_str()
        .ok_or_else(|| Error::validation("Email address required"))?;

    // Validate email format
    if !email.contains('@') {
        return Err(Error::validation("Invalid email format"));
    }

    send_email(email).await?;
    Ok(())
}).await?;

// ❌ Bad: Generic name, no validation, panics
WORKER::register("worker1", |ctx| async move {
    let email = ctx.payload().unwrap()["email"].as_str().unwrap();
    send_email(email).await.unwrap();
    Ok(())
}).await?;
}

Executing Workers

Method 1: Call and Await (Most Common)

Execute a worker and wait for completion:

#![allow(unused)]
fn main() {
// Simple execution
WORKER::run("send-email", None).await?;

// With payload
let payload = json!({
    "to": "user@example.com",
    "subject": "Welcome!"
});
WORKER::run("send-email", Some(payload)).await?;
}

Method 2: Call with Handle (Advanced Control)

Get a handle for message streaming and control:

#![allow(unused)]
fn main() {
let mut handle = WORKER::call("worker-name", None, Some(payload)).await?;

// Receive messages while worker runs
while let Some(message) = handle.recv().await {
    println!("Progress: {}", message);
}

// Wait for final result
handle.await_result().await?;
}

Method 3: Fire and Forget

Start a worker without waiting:

#![allow(unused)]
fn main() {
tokio::spawn(async move {
    let _ = WORKER::run("cleanup", None).await;
});
}

Timeout Support

Set a maximum execution time:

#![allow(unused)]
fn main() {
use std::time::Duration;

// Worker will be cancelled if it exceeds 5 seconds
let handle = WORKER::call(
    "slow-worker",
    Some(Duration::from_secs(5)),  // Timeout
    Some(payload)
).await?;

match handle.await_result().await {
    Ok(_) => println!("Completed successfully"),
    Err(e) => println!("Timeout or error: {}", e),
}
}

Passing Payloads

Workers accept JSON payloads for input data:

#![allow(unused)]
fn main() {
// Calling code
let payload = json!({
    "user_id": 123,
    "action": "process_upload",
    "file_path": "/tmp/upload.pdf"
});
WORKER::run("process-file", Some(payload)).await?;

// Worker code
WORKER::register("process-file", |ctx| async move {
    let payload = ctx.payload().ok_or_else(||
        Error::validation("Payload required")
    )?;

    let user_id = payload["user_id"].as_i64().unwrap();
    let file_path = payload["file_path"].as_str().unwrap();

    ctx.info(&format!("Processing file for user {}", user_id));
    // Process file...

    Ok(())
}).await?;
}

Concurrent Execution

Run multiple workers simultaneously:

#![allow(unused)]
fn main() {
use futures::future::join_all;

async fn process_batch(ctx: &mut Context) -> Result<()> {
    let items = vec![
        json!({"id": 1}),
        json!({"id": 2}),
        json!({"id": 3}),
    ];

    // Launch all workers concurrently
    let futures: Vec<_> = items.into_iter()
        .map(|item| WORKER::call("process-item", None, Some(item)))
        .collect();

    let handles = join_all(futures).await;

    // Wait for all to complete
    for handle in handles {
        handle?.await_result().await?;
    }

    ctx.json(json!({"status": "All items processed"}))
}
}

Worker Context

The WorkerContext provides rich functionality for worker execution.

Identity and Metadata

#![allow(unused)]
fn main() {
WORKER::register("example", |ctx| async move {
    // Unique identifier for this execution
    let run_id = ctx.run_id(); // "550e8400-e29b-41d4-a716-446655440000"

    // Worker definition name
    let name = ctx.worker_name(); // "example"

    ctx.info(&format!("Execution {} of {}", run_id, name));
    Ok(())
}).await?;
}

Logging

Workers have structured logging with automatic identification:

#![allow(unused)]
fn main() {
WORKER::register("logger-demo", |ctx| async move {
    ctx.info("Informational message");
    ctx.warn("Warning message");
    ctx.error("Error message");
    ctx.debug("Debug message (only in development)");

    // Generic logging with custom level
    ctx.log(log::Level::Info, "Custom log");

    Ok(())
}).await?;

// Output:
// [Worker:logger-demo run:550e8400...] Informational message
// [Worker:logger-demo run:550e8400...] Warning message
}

Environment Detection

#![allow(unused)]
fn main() {
WORKER::register("env-aware", |ctx| async move {
    if ctx.is_development() {
        ctx.info("Running in development - verbose logging enabled");
        // Use test APIs, skip external services, etc.
    }

    if ctx.is_production() {
        ctx.info("Running in production - using live services");
        // Use production APIs, send real emails, etc.
    }

    Ok(())
}).await?;
}

The environment is the application’s configured one (RUSTF_ENV, or [app] environment in config.toml); ctx.environment is "development" or "production".

Configuration Access

Access application configuration from workers:

There is no generic dotted-path getter on AppConfig. Read a whole custom section into a struct with section::<T>("api"), or grab the raw TOML value with get_value("api"):

#![allow(unused)]
fn main() {
#[derive(serde::Deserialize)]
struct ApiConfig {
    base_url: String,
}

WORKER::register("config-example", |ctx| async move {
    let config = ctx.config();

    // Deserialize the [api] section into a struct
    let base_url = config
        .section::<ApiConfig>("api")
        .map(|api| api.base_url)
        .unwrap_or_else(|_| "http://localhost".to_string());

    // Alternatively, read the raw TOML value:
    // let base_url = config
    //     .get_value("api")
    //     .and_then(|v| v.get("base_url"))
    //     .and_then(|v| v.as_str())
    //     .unwrap_or("http://localhost")
    //     .to_string();

    ctx.info(&format!("Using API: {}", base_url));
    Ok(())
}).await?;
}

State Management

Each worker execution has isolated state:

#![allow(unused)]
fn main() {
WORKER::register("stateful", |ctx| async move {
    // Set state values
    ctx.set_state("progress", json!(0)).await?;
    ctx.set_state("items_processed", json!([])).await?;

    for i in 1..=5 {
        // Update state
        ctx.set_state("progress", json!(i * 20)).await?;

        // Read state
        if let Some(progress) = ctx.get_state("progress").await {
            ctx.info(&format!("Progress: {}%", progress));
        }

        tokio::time::sleep(Duration::from_millis(500)).await;
    }

    // Clear all state
    ctx.clear_state().await?;
    Ok(())
}).await?;
}

Note: State is per-execution. Different runs of the same worker have independent state.

Message Emission

Send real-time messages to the caller:

#![allow(unused)]
fn main() {
// Worker code
WORKER::register("progress-reporter", |ctx| async move {
    for i in 1..=10 {
        // Emit progress updates
        ctx.emit(json!({
            "progress": i * 10,
            "message": format!("Processing item {}/10", i)
        }))?;

        tokio::time::sleep(Duration::from_millis(200)).await;
    }

    ctx.emit(json!({"status": "complete"}))?;
    Ok(())
}).await?;

// Calling code
let mut handle = WORKER::call("progress-reporter", None, None).await?;

// Receive progress updates
while let Some(message) = handle.recv().await {
    let progress = message["progress"].as_i64().unwrap_or(0);
    println!("Progress: {}%", progress);
}

handle.await_result().await?;
}

Utilities

#![allow(unused)]
fn main() {
WORKER::register("utilities", |ctx| async move {
    // Sleep/delay
    ctx.sleep(Duration::from_secs(1)).await;

    // Access payload
    if let Some(payload) = ctx.payload() {
        ctx.info(&format!("Received: {}", payload));
    }

    Ok(())
}).await?;
}

Advanced Features

Cancellation

Cancel running workers using the handle:

#![allow(unused)]
fn main() {
async fn cancelable_operation(ctx: &mut Context) -> Result<()> {
    // Start long-running worker
    let handle = WORKER::call("slow-worker", None, None).await?;
    let run_id = handle.id().to_string();

    // Start cancellation timer
    tokio::spawn(async move {
        tokio::time::sleep(Duration::from_secs(3)).await;

        // Cancel after 3 seconds
        if let Err(e) = WORKER::cancel(&run_id).await {
            eprintln!("Failed to cancel: {}", e);
        }
    });

    // Try to await result
    match handle.await_result().await {
        Ok(_) => ctx.json(json!({"status": "completed"})),
        Err(_) => ctx.json(json!({"status": "cancelled"})),
    }
}
}

Listing Workers

Query registered and running workers:

#![allow(unused)]
fn main() {
async fn worker_dashboard(ctx: &mut Context) -> Result<()> {
    // List all registered worker definitions
    let definitions = WORKER::definitions().await?;

    // List all currently running worker run IDs
    let running = WORKER::running().await?;

    // List runs for a specific worker
    let email_runs = WORKER::running_for("send-email").await?;

    ctx.json(json!({
        "definitions": definitions,
        "running_count": running.len(),
        "email_worker_runs": email_runs.len()
    }))
}
}

Statistics and Monitoring

Track worker performance:

#![allow(unused)]
fn main() {
async fn worker_stats(ctx: &mut Context) -> Result<()> {
    let definitions = WORKER::definitions().await?;
    let mut stats_map = serde_json::Map::new();

    for name in definitions {
        if let Some(stats) = WORKER::stats(&name).await {
            let avg_ms = if stats.runs > 0 {
                stats.total_runtime_ms / stats.runs
            } else {
                0
            };

            stats_map.insert(name, json!({
                "total_runs": stats.runs,
                "errors": stats.errors,
                "success_rate": if stats.runs > 0 {
                    (stats.runs - stats.errors) as f64 / stats.runs as f64 * 100.0
                } else {
                    0.0
                },
                "average_duration_ms": avg_ms,
                "last_run_ms": stats.last_run_ms
            }));
        }
    }

    ctx.json(json!(stats_map))
}
}

Graceful Shutdown

Workers automatically shutdown when the application stops:

#[tokio::main]
async fn main() -> Result<()> {
    let app = RustF::new()
        .with_workers()
        .workers_from(|_manager| async move {
            WORKER::register("long-task", |ctx| async move {
                ctx.info("Long task started");
                tokio::time::sleep(Duration::from_secs(60)).await;
                ctx.info("Long task completed");
                Ok(())
            }).await?;
            Ok(())
        })
        .start()  // bind address comes from config
        .await?;

    // When app shuts down (Ctrl+C, etc.):
    // 1. All running workers are cancelled
    // 2. No new workers can be started
    // 3. Resources are cleaned up

    Ok(())
}

Error Handling Patterns

#![allow(unused)]
fn main() {
WORKER::register("robust-worker", |ctx| async move {
    // Validate input early
    let payload = ctx.payload()
        .ok_or_else(|| Error::validation("Payload required"))?;

    let user_id = payload["user_id"].as_i64()
        .ok_or_else(|| Error::validation("user_id is required"))?;

    // Use Result propagation
    let user = fetch_user(user_id).await?;

    // Handle specific errors
    match process_user(&user).await {
        Ok(_) => {
            ctx.info("User processed successfully");
            Ok(())
        }
        Err(e) if e.is_validation() => {
            ctx.warn(&format!("Validation failed: {}", e));
            Err(e)
        }
        Err(e) => {
            ctx.error(&format!("Processing failed: {}", e));
            Err(e)
        }
    }
}).await?;
}

Real-World Examples

Example 1: Email Sending Worker

#![allow(unused)]
fn main() {
use rustf::prelude::*;
use rustf::workers::WORKER;

pub async fn install() -> Result<()> {
    WORKER::register("send-email", |ctx| async move {
        let payload = ctx.payload()
            .ok_or_else(|| Error::validation("Email payload required"))?;

        let to = payload["to"].as_str()
            .ok_or_else(|| Error::validation("'to' address required"))?;
        let subject = payload["subject"].as_str()
            .unwrap_or("No Subject");
        let body = payload["body"].as_str()
            .unwrap_or("");

        ctx.info(&format!("Sending email to: {}", to));

        // Simulate email sending
        if ctx.is_development() {
            ctx.info(&format!("πŸ“§ DEV MODE - Email to {} with subject: {}", to, subject));
            tokio::time::sleep(Duration::from_millis(100)).await;
        } else {
            // Production: use real SMTP service
            // send_smtp_email(to, subject, body).await?;
            tokio::time::sleep(Duration::from_secs(2)).await;
        }

        ctx.emit(json!({
            "status": "sent",
            "to": to,
            "timestamp": chrono::Utc::now().to_rfc3339()
        }))?;

        ctx.info("βœ… Email sent successfully");
        Ok(())
    }).await?;

    Ok(())
}

// Usage from controller
async fn register_user(ctx: &mut Context) -> Result<()> {
    let body = ctx.full_body();
    let email = body["email"].as_str().unwrap();

    // Create user...

    // Send welcome email in background
    WORKER::run("send-email", Some(json!({
        "to": email,
        "subject": "Welcome to Our App!",
        "body": "Thanks for registering..."
    }))).await?;

    ctx.json(json!({"status": "User registered"}))
}
}

Example 2: File Processing Worker

#![allow(unused)]
fn main() {
WORKER::register("process-upload", |ctx| async move {
    let payload = ctx.payload()
        .ok_or_else(|| Error::validation("Payload required"))?;

    let file_path = payload["file_path"].as_str()
        .ok_or_else(|| Error::validation("file_path required"))?;

    ctx.info(&format!("Processing file: {}", file_path));

    // Step 1: Validate file
    ctx.emit(json!({"step": "validate", "progress": 25}))?;
    validate_file(file_path).await?;
    tokio::time::sleep(Duration::from_secs(1)).await;

    // Step 2: Process file
    ctx.emit(json!({"step": "process", "progress": 50}))?;
    let result = process_file(file_path).await?;
    tokio::time::sleep(Duration::from_secs(2)).await;

    // Step 3: Generate thumbnail
    ctx.emit(json!({"step": "thumbnail", "progress": 75}))?;
    generate_thumbnail(file_path).await?;
    tokio::time::sleep(Duration::from_secs(1)).await;

    // Step 4: Save to database
    ctx.emit(json!({"step": "save", "progress": 100}))?;
    save_to_database(&result).await?;

    ctx.info("βœ… File processing complete");
    Ok(())
}).await?;

// Usage with progress tracking
async fn upload_file(ctx: &mut Context) -> Result<()> {
    let file_path = "/tmp/uploads/file.pdf";

    let mut handle = WORKER::call(
        "process-upload",
        Some(Duration::from_secs(30)),
        Some(json!({"file_path": file_path}))
    ).await?;

    // Stream progress to client
    while let Some(progress) = handle.recv().await {
        log::info!("Progress: {:?}", progress);
        // Could send SSE to client here
    }

    handle.await_result().await?;
    ctx.json(json!({"status": "Processing complete"}))
}
}

Example 3: Cleanup Worker

#![allow(unused)]
fn main() {
WORKER::register("cleanup-temp-files", |ctx| async move {
    ctx.info("🧹 Starting cleanup task");

    let temp_dir = "/tmp/app_uploads";
    let cutoff = chrono::Utc::now() - chrono::Duration::hours(24);

    let mut removed_count = 0;

    // Scan directory
    let entries = tokio::fs::read_dir(temp_dir).await?;
    // Process each file...

    ctx.emit(json!({
        "files_removed": removed_count,
        "directory": temp_dir
    }))?;

    ctx.info(&format!("βœ… Cleanup complete: {} files removed", removed_count));
    Ok(())
}).await?;

// Schedule via cron or event system
app.on("ready", |ctx| Box::pin(async move {
    // Run cleanup every hour
    tokio::spawn(async {
        loop {
            tokio::time::sleep(Duration::from_secs(3600)).await;
            let _ = WORKER::run("cleanup-temp-files", None).await;
        }
    });
    Ok(())
}))
}

Example 4: Report Generation Worker

#![allow(unused)]
fn main() {
WORKER::register("generate-report", |ctx| async move {
    let payload = ctx.payload()
        .ok_or_else(|| Error::validation("Report parameters required"))?;

    let report_type = payload["type"].as_str().unwrap_or("monthly");
    let user_id = payload["user_id"].as_i64().unwrap();

    ctx.info(&format!("Generating {} report for user {}", report_type, user_id));

    // Fetch data
    ctx.emit(json!({"stage": "fetching_data", "progress": 10}))?;
    let data = fetch_report_data(user_id, report_type).await?;

    // Process data
    ctx.emit(json!({"stage": "processing", "progress": 40}))?;
    let processed = process_report_data(&data).await?;

    // Generate PDF
    ctx.emit(json!({"stage": "generating_pdf", "progress": 70}))?;
    let pdf_path = generate_pdf_report(&processed).await?;

    // Upload to storage
    ctx.emit(json!({"stage": "uploading", "progress": 90}))?;
    let url = upload_to_storage(&pdf_path).await?;

    ctx.emit(json!({
        "stage": "complete",
        "progress": 100,
        "url": url
    }))?;

    ctx.info(&format!("βœ… Report generated: {}", url));
    Ok(())
}).await?;
}

Example 5: Batch Processing Worker

#![allow(unused)]
fn main() {
WORKER::register("batch-processor", |ctx| async move {
    let payload = ctx.payload()
        .ok_or_else(|| Error::validation("Batch items required"))?;

    let items = payload["items"].as_array()
        .ok_or_else(|| Error::validation("items must be an array"))?;

    let total = items.len();
    ctx.info(&format!("Processing {} items", total));

    for (index, item) in items.iter().enumerate() {
        let progress = ((index + 1) as f64 / total as f64 * 100.0) as u64;

        ctx.emit(json!({
            "current": index + 1,
            "total": total,
            "progress": progress,
            "item": item
        }))?;

        // Process item
        process_item(item).await?;

        // Small delay to avoid overwhelming external APIs
        tokio::time::sleep(Duration::from_millis(100)).await;
    }

    ctx.info(&format!("βœ… Processed {} items", total));
    Ok(())
}).await?;
}

Best Practices

When to Use Workers

βœ… Good Use Cases:

  • Long-running tasks: Anything taking >100ms that blocks the response
  • External API calls: Third-party services, webhooks, notifications
  • File operations: Uploads, conversions, compression
  • Email/SMS sending: Any messaging operations
  • Report generation: PDFs, exports, analytics
  • Data synchronization: Batch updates, imports
  • Cleanup tasks: Maintenance, garbage collection

❌ Not Suitable For:

  • Quick database queries: Just use models directly
  • Simple calculations: Pure functions don’t need workers
  • Request validation: Should happen synchronously
  • Response formatting: Part of controller logic
  • Configuration loading: Do at startup, not in workers

Error Handling

#![allow(unused)]
fn main() {
// βœ… Good: Specific error types, proper propagation
WORKER::register("good-errors", |ctx| async move {
    let payload = ctx.payload()
        .ok_or_else(|| Error::validation("Payload required"))?;

    match external_api_call().await {
        Ok(result) => {
            ctx.info("API call succeeded");
            Ok(())
        }
        Err(e) if e.is_timeout() => {
            ctx.warn("API timeout, will retry later");
            Err(Error::timeout("External API timeout"))
        }
        Err(e) => {
            ctx.error(&format!("Unexpected error: {}", e));
            Err(e)
        }
    }
}).await?;

// ❌ Bad: Swallowing errors, panics
WORKER::register("bad-errors", |ctx| async move {
    let data = ctx.payload().unwrap(); // Panic!
    external_api_call().await.ok(); // Error ignored!
    Ok(())
}).await?;
}

Resource Management

#![allow(unused)]
fn main() {
// βœ… Good: Cleanup resources, bounded operations
WORKER::register("resource-safe", |ctx| async move {
    let temp_file = create_temp_file().await?;

    let result = process_file(&temp_file).await;

    // Always cleanup
    tokio::fs::remove_file(&temp_file).await?;

    result
}).await?;

// ❌ Bad: Resource leaks, unbounded operations
WORKER::register("resource-leak", |ctx| async move {
    let file = create_temp_file().await?;
    process_file(&file).await?;
    // File never cleaned up!

    // Unbounded loop - could run forever
    loop {
        process_next().await?;
    }
}).await?;
}

Payload Validation

#![allow(unused)]
fn main() {
// βœ… Good: Validate early, clear errors
WORKER::register("validated", |ctx| async move {
    let payload = ctx.payload()
        .ok_or_else(|| Error::validation("Payload required"))?;

    // Validate all required fields upfront
    let email = payload["email"].as_str()
        .ok_or_else(|| Error::validation("email is required"))?;

    if !email.contains('@') {
        return Err(Error::validation("Invalid email format"));
    }

    let age = payload["age"].as_i64()
        .ok_or_else(|| Error::validation("age must be a number"))?;

    if age < 0 || age > 150 {
        return Err(Error::validation("Invalid age range"));
    }

    // Proceed with validated data
    process_user(email, age).await
}).await?;
}

Logging and Observability

#![allow(unused)]
fn main() {
WORKER::register("observable", |ctx| async move {
    let start = std::time::Instant::now();

    ctx.info("Worker started");

    // Log major steps
    ctx.info("Step 1: Fetching data");
    let data = fetch_data().await?;

    ctx.info(&format!("Step 2: Processing {} records", data.len()));
    let result = process_data(&data).await?;

    ctx.info("Step 3: Saving results");
    save_results(&result).await?;

    let duration = start.elapsed();
    ctx.info(&format!("βœ… Completed in {:.2}s", duration.as_secs_f64()));

    // Emit metrics
    ctx.emit(json!({
        "duration_ms": duration.as_millis(),
        "records_processed": data.len()
    }))?;

    Ok(())
}).await?;
}

Testing Workers

#![allow(unused)]
fn main() {
#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_email_worker() {
        // Setup
        let app = RustF::new().with_workers();

        // Register test worker
        WORKER::register("test-email", |ctx| async move {
            let payload = ctx.payload().unwrap();
            assert!(payload["to"].as_str().is_some());
            Ok(())
        }).await.unwrap();

        // Execute
        let result = WORKER::run("test-email", Some(json!({
            "to": "test@example.com"
        }))).await;

        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_worker_timeout() {
        WORKER::register("slow", |ctx| async move {
            tokio::time::sleep(Duration::from_secs(10)).await;
            Ok(())
        }).await.unwrap();

        let handle = WORKER::call(
            "slow",
            Some(Duration::from_secs(1)),
            None
        ).await.unwrap();

        let result = handle.await_result().await;
        assert!(result.is_err()); // Should timeout
    }
}
}

Performance Considerations

  1. Use timeouts: Always set reasonable timeouts for external operations
  2. Batch operations: Process multiple items in one worker run when possible
  3. Avoid blocking: Use async I/O, don’t block the thread
  4. Limit concurrency: Don’t spawn thousands of workers simultaneously
  5. Monitor statistics: Track execution times and error rates
#![allow(unused)]
fn main() {
// βœ… Good: Bounded concurrency
async fn process_many_items(items: Vec<Value>) -> Result<()> {
    use futures::stream::{self, StreamExt};

    stream::iter(items)
        .map(|item| async move {
            WORKER::run("process-item", Some(item)).await
        })
        .buffer_unordered(10) // Max 10 concurrent workers
        .collect::<Vec<_>>()
        .await;

    Ok(())
}

// ❌ Bad: Unbounded concurrency
async fn process_many_items_bad(items: Vec<Value>) -> Result<()> {
    for item in items {
        tokio::spawn(async move {
            WORKER::run("process-item", Some(item)).await
        });
    }
    Ok(())
}
}

API Reference

WORKER Global API

#![allow(unused)]
fn main() {
pub struct WORKER;

impl WORKER {
    /// Register a worker definition
    pub async fn register<F, Fut>(
        name: impl Into<String>,
        handler: F
    ) -> Result<()>
    where
        F: Fn(WorkerContext) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<()>> + Send + 'static;

    /// Call a worker and get a handle
    pub async fn call(
        worker_name: &str,
        timeout: Option<Duration>,
        payload: Option<Value>
    ) -> Result<WorkerHandle>;

    /// Run a worker and await completion
    pub async fn run(
        worker_name: &str,
        payload: Option<Value>
    ) -> Result<()>;

    /// Cancel a running worker
    pub async fn cancel(run_id: &str) -> Result<()>;

    /// List registered worker names
    pub async fn definitions() -> Result<Vec<String>>;

    /// List currently running worker IDs
    pub async fn running() -> Result<Vec<String>>;

    /// List running instances of a specific worker
    pub async fn running_for(worker_name: &str) -> Result<Vec<String>>;

    /// Get statistics for a worker
    pub async fn stats(worker_name: &str) -> Option<WorkerStats>;

    /// Shutdown all running workers
    pub async fn shutdown() -> Result<()>;
}
}

WorkerContext

#![allow(unused)]
fn main() {
pub struct WorkerContext {
    // Identity
    pub fn worker_name(&self) -> &str;
    pub fn run_id(&self) -> &str;

    // Configuration
    pub fn config(&self) -> &Arc<AppConfig>;

    // Payload
    pub fn payload(&self) -> Option<&Value>;

    // Environment
    pub fn is_development(&self) -> bool;
    pub fn is_production(&self) -> bool;

    // Logging
    pub fn log(&self, level: log::Level, message: &str);
    pub fn info(&self, message: &str);
    pub fn warn(&self, message: &str);
    pub fn error(&self, message: &str);
    pub fn debug(&self, message: &str);

    // State
    pub async fn set_state(
        &self,
        key: impl Into<String>,
        value: Value
    ) -> Result<()>;
    pub async fn get_state(&self, key: &str) -> Option<Value>;
    pub async fn clear_state(&self) -> Result<()>;

    // Messaging
    pub fn emit(&self, message: Value) -> Result<()>;

    // Utilities
    pub async fn sleep(&self, duration: Duration);
}
}

WorkerHandle

#![allow(unused)]
fn main() {
pub struct WorkerHandle {
    /// Get the unique run ID
    pub fn id(&self) -> &str;

    /// Get the worker name
    pub fn worker_name(&self) -> &str;

    /// Cancel this worker execution
    pub async fn cancel(&self) -> Result<()>;

    /// Receive next message from worker
    pub async fn recv(&mut self) -> Option<Value>;

    /// Wait for worker to complete
    pub async fn await_result(self) -> Result<()>;
}
}

WorkerStats

#![allow(unused)]
fn main() {
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkerStats {
    /// Total number of executions
    pub runs: u64,

    /// Number of failed executions
    pub errors: u64,

    /// Duration of last execution in milliseconds
    pub last_run_ms: Option<u64>,

    /// Total cumulative runtime in milliseconds
    pub total_runtime_ms: u64,
}
}

Troubleshooting

Worker Not Found

Error: Worker 'my-worker' not registered

Solutions:

  1. Ensure worker file is in src/workers/ directory:
src/
└── workers/
    └── my_worker.rs  ← Must be here!
  1. Check that the file has an install() function:
#![allow(unused)]
fn main() {
// src/workers/my_worker.rs
pub async fn install() -> Result<()> {
    WORKER::register("my-worker", |ctx| async move {
        // Worker implementation
        Ok(())
    }).await?;
    Ok(())
}
}
  1. Verify auto-discovery is enabled:
// src/main.rs
#[rustf::auto_discover]  // ← Required!
#[tokio::main]
async fn main() -> Result<()> {
    let app = RustF::new().auto_load();
    app.start().await
}
  1. Check that file isn’t being skipped (shouldn’t be mod.rs, _*.rs, or *.inc.rs)

Worker Manager Not Initialized

Error: Worker manager not initialised

Solution: Use .auto_load() or explicitly enable workers:

#![allow(unused)]
fn main() {
// Recommended: Use auto_load
let app = RustF::new()
    .auto_load()  // Automatically enables workers
    .start()  // bind address comes from config
    .await?;

// Or explicitly:
let app = RustF::new()
    .with_workers()
    .workers_from(auto_workers!())
    .start()  // bind address comes from config
    .await?;
}

Worker Timeout

Error: Worker 'slow-task' timed out after 5s

Solutions:

  1. Increase timeout:
#![allow(unused)]
fn main() {
WORKER::call("slow-task", Some(Duration::from_secs(30)), payload).await?;
}
  1. Optimize worker to run faster:
#![allow(unused)]
fn main() {
// Break work into smaller chunks
// Use async I/O instead of blocking
// Process in parallel where possible
}
  1. Remove timeout (not recommended for production):
#![allow(unused)]
fn main() {
WORKER::call("slow-task", None, payload).await?;
}

Messages Not Received

Problem: handle.recv() returns None immediately.

Solution: Worker must emit messages:

#![allow(unused)]
fn main() {
// Worker must explicitly emit
WORKER::register("messenger", |ctx| async move {
    ctx.emit(json!({"progress": 50}))?; // Emit message
    Ok(())
}).await?;

// Caller receives messages
let mut handle = WORKER::call("messenger", None, None).await?;
while let Some(msg) = handle.recv().await {
    println!("{}", msg);
}
}

Payload Access Issues

Problem: ctx.payload() returns None.

Solution: Pass payload when calling:

#![allow(unused)]
fn main() {
// Pass payload
WORKER::run("my-worker", Some(json!({"key": "value"}))).await?;

// Access in worker
WORKER::register("my-worker", |ctx| async move {
    if let Some(payload) = ctx.payload() {
        // Use payload
    }
    Ok(())
}).await?;
}

Worker Hangs Forever

Problem: Worker never completes.

Solutions:

  1. Add timeout:
#![allow(unused)]
fn main() {
WORKER::call("worker", Some(Duration::from_secs(30)), payload).await?;
}
  1. Debug with logging:
#![allow(unused)]
fn main() {
WORKER::register("debug", |ctx| async move {
    ctx.info("Step 1");
    step1().await?;
    ctx.info("Step 2");
    step2().await?;
    ctx.info("Complete");
    Ok(())
}).await?;
}
  1. Check for infinite loops or deadlocks in worker code.

High Memory Usage

Problem: Memory grows when running many workers.

Solutions:

  1. Limit concurrent workers:
#![allow(unused)]
fn main() {
use futures::stream::{self, StreamExt};

stream::iter(items)
    .map(|item| WORKER::run("process", Some(item)))
    .buffer_unordered(10) // Max 10 concurrent
    .collect::<Vec<_>>()
    .await;
}
  1. Clean up resources in workers:
#![allow(unused)]
fn main() {
WORKER::register("cleanup", |ctx| async move {
    let resource = allocate().await?;
    let result = process(&resource).await;
    drop(resource); // Explicit cleanup
    result
}).await?;
}
  1. Use streaming for large data:
#![allow(unused)]
fn main() {
// Process in chunks instead of loading everything
for chunk in data.chunks(1000) {
    process_chunk(chunk).await?;
}
}

Statistics Not Updating

Problem: WORKER::stats() returns outdated values.

Solution: Statistics update after worker completion. Ensure:

  1. Worker completes successfully or fails (not cancelled mid-execution)
  2. Await worker completion before checking stats
  3. Stats are per-definition, not per-run
#![allow(unused)]
fn main() {
// Execute worker
WORKER::run("task", None).await?;

// Now stats are updated
let stats = WORKER::stats("task").await;
}

Summary

The RustF Worker system provides:

  • Simple Registration: WORKER::register() with async handlers
  • Flexible Execution: Call and await, fire-and-forget, or stream messages
  • Rich Context: Logging, state, configuration, and messaging
  • Monitoring: Built-in statistics and running worker tracking
  • Robust: Timeout support, cancellation, and graceful shutdown

Quick Reference:

#![allow(unused)]
fn main() {
// Enable
app.with_workers()

// Register
WORKER::register("name", |ctx| async move { Ok(()) }).await?

// Execute
WORKER::run("name", Some(payload)).await?

// Monitor
WORKER::stats("name").await
WORKER::running().await?
}

Documentation Version: 1.0 Last Updated: 2025-01-22 RustF Version: 0.1.0

RustF Event System Guide

🎯 Total.js-Inspired Event-Driven Architecture

This guide covers RustF’s comprehensive event system, designed to provide Total.js-style ON('ready', function()) patterns for application lifecycle management and extensible startup code execution.

Table of Contents

Overview

RustF’s event system enables developers to hook into application lifecycle events using a familiar, Total.js-inspired pattern. This system provides:

Key Features

βœ… Total.js-Style Syntax - Familiar ON('ready', handler) pattern
βœ… Lifecycle Events - Built-in events for all major application stages
βœ… Priority-Based Execution - Control handler execution order
βœ… Parallel Execution - Concurrent handler execution within priority groups for optimal performance
βœ… Built-in Handlers - Ready-to-use handlers for common tasks
βœ… Event Context - Rich context with app config, environment, and utilities
βœ… Auto-Discovery - Automatic event handler registration
βœ… Type Safety - Full compile-time type checking
βœ… Async Native - Built for async/await from the ground up
βœ… Performance Optimized - Fast-path execution, configurable timeouts, and error isolation

Event-Driven Benefits

  • Decoupled Code: Event handlers don’t need to know about each other
  • Extensible: Easy to add new functionality without modifying core code
  • Testable: Individual event handlers can be tested in isolation
  • Organized: Clean separation between initialization logic
  • Flexible: Conditional execution based on environment or configuration

Quick Start

Basic Event Registration

use rustf::prelude::*;

#[tokio::main]
async fn main() -> rustf::Result<()> {
    let app = RustF::new()
        // Register event handlers using familiar Total.js syntax
        .on("ready", |ctx| Box::pin(async move {
            println!("πŸš€ Application ready in {} mode!", ctx.env());
            Ok(())
        }))
        
        .on("startup", |ctx| Box::pin(async move {
            println!("⚑ Startup tasks executing...");
            // Database seeding, directory creation, etc.
            Ok(())
        }))
        
        .controllers(auto_controllers!());
    
    app.start().await
}

Using Built-in Handlers

#![allow(unused)]
fn main() {
use rustf::prelude::*;

let app = RustF::new()
    // Built-in handlers for common tasks
    .on("startup", builtin::directory_setup(&["uploads", "temp", "logs"]))
    .on("startup", builtin::cleanup_manager("temp/", Duration::from_secs(3600)))
    .on("config.loaded", builtin::configuration_validator)
    .on("ready", builtin::health_check)
    
    .controllers(auto_controllers!());
}

Application Lifecycle Events

RustF emits events automatically during application startup, providing hooks for every stage of initialization:

Core Lifecycle Events

EventWhen EmittedUse Case
config.loadedConfiguration loaded and validatedConfig validation, environment checks
database.readyDatabase connection establishedDatabase seeding, migration checks
modules.readyShared modules initializedModule-dependent initialization
middleware.readyMiddleware chain configuredMiddleware-dependent setup
routes.readyRoutes registeredRoute-dependent initialization
startupBefore server starts listeningFinal startup tasks
readyFramework fully initializedApplication ready notifications

Event Execution Order

1. config.loaded    ← Configuration loaded
2. database.ready   ← Database connected  
3. modules.ready    ← Shared modules initialized
4. middleware.ready ← Middleware configured
5. routes.ready     ← Routes registered
6. startup          ← Pre-server startup tasks
7. ready            ← Application fully ready
   ↓
   Server starts listening

Custom Events

Note: ctx.emit(...) from within an event handler is not currently wired. EventContext::emit (rustf/src/events.rs) only forwards to an emitter when one has been injected into the context, and the built-in event executors do not inject one. As a result, emitting custom events from inside a handler is a silent no-op today. The example below illustrates the intended API but will not trigger the chained custom.initialization handler until this is wired.

You can also emit custom events from within handlers:

#![allow(unused)]
fn main() {
.on("ready", |ctx| Box::pin(async move {
    println!("Application ready!");
    
    // Emit a custom event
    ctx.emit("custom.initialization", Some(json!({
        "timestamp": chrono::Utc::now().to_rfc3339(),
        "environment": ctx.env()
    }))).await?;
    
    Ok(())
}))

.on("custom.initialization", |ctx| Box::pin(async move {
    if let Some(data) = &ctx.data {
        println!("Custom event data: {}", data);
    }
    Ok(())
}))
}

Event Registration

Registration Methods

.on(event, handler) - Basic Registration

#![allow(unused)]
fn main() {
app.on("ready", |ctx| Box::pin(async move {
    println!("Application ready!");
    Ok(())
}))
}

.on_priority(event, priority, handler) - Priority-Based

#![allow(unused)]
fn main() {
app.on_priority("startup", -100, |ctx| Box::pin(async move {
    println!("High priority task (runs first)");
    Ok(())
}))

.on_priority("startup", 100, |ctx| Box::pin(async move {
    println!("Low priority task (runs last)");
    Ok(())
}))
}

.events_from(register_fn) - Bulk Registration

#![allow(unused)]
fn main() {
app.events_from(|emitter| {
    emitter.on("ready", startup_logger);
    emitter.on("database.ready", database_seeder);
    emitter.once("ready", one_time_setup);
})
}

.once(event, handler) - One-Time Handlers

#![allow(unused)]
fn main() {
// This handler will only execute once, even if the event is emitted multiple times
emitter.once("ready", |ctx| Box::pin(async move {
    println!("This runs only once!");
    Ok(())
}))
}

Parallel Execution

RustF’s event system features high-performance parallel execution of handlers within the same priority group, while maintaining strict priority ordering between groups.

How Parallel Execution Works

#![allow(unused)]
fn main() {
// Multiple handlers at the same priority execute in parallel
app.on("ready", |_ctx| Box::pin(async move {
    println!("Handler 1 starting...");
    tokio::time::sleep(Duration::from_millis(100)).await; // Simulated work
    println!("Handler 1 done");
    Ok(())
}))

.on("ready", |_ctx| Box::pin(async move {
    println!("Handler 2 starting...");
    tokio::time::sleep(Duration::from_millis(100)).await; // Simulated work  
    println!("Handler 2 done");
    Ok(())
}))

.on("ready", |_ctx| Box::pin(async move {
    println!("Handler 3 starting...");
    tokio::time::sleep(Duration::from_millis(100)).await; // Simulated work
    println!("Handler 3 done");
    Ok(())
}));

// All 3 handlers execute concurrently!
// Total execution time: ~100ms (instead of ~300ms sequential)
}

Priority Groups and Parallel Execution

#![allow(unused)]
fn main() {
app
    // Priority -100: Infrastructure handlers (execute first, in parallel)
    .on_priority("startup", -100, database_init_handler)    // Runs in parallel
    .on_priority("startup", -100, cache_init_handler)       // with this one
    .on_priority("startup", -100, logging_init_handler)     // and this one
    
    // Wait for all priority -100 handlers to complete...
    
    // Priority 0: Application handlers (execute second, in parallel)  
    .on("startup", user_service_init)     // Runs in parallel
    .on("startup", email_service_init)    // with this one
    .on("startup", file_service_init)     // and this one
    
    // Wait for all priority 0 handlers to complete...
    
    // Priority 100: Cleanup handlers (execute last, in parallel)
    .on_priority("startup", 100, temp_cleanup)         // Runs in parallel
    .on_priority("startup", 100, session_cleanup)      // with this one
}

Performance Benefits

Example Performance Improvement:

  • 4 handlers, each taking 100ms
  • Sequential execution: 400ms total
  • Parallel execution: 100ms total (4x faster!)

Performance Configuration

Configure event system performance settings for optimal behavior:

Basic Configuration

#![allow(unused)]
fn main() {
use rustf::events::EventEmitterConfig;
use std::time::Duration;

let app = RustF::new()
    .event_config(EventEmitterConfig::parallel() // Enable parallel execution
        .with_timeout(Duration::from_secs(30))    // Handler timeout protection
        .with_debug_logging(false)                // Disable debug logging for performance
        .with_max_concurrent(8))                  // Limit concurrent handlers
}

Configuration Presets

#![allow(unused)]
fn main() {
// High-performance configuration (production)
let config = EventEmitterConfig::parallel()
    .with_timeout(Duration::from_secs(60))
    .with_debug_logging(false);

// Debug-friendly configuration (development)
let config = EventEmitterConfig::sequential()
    .with_timeout(Duration::from_secs(10))
    .with_debug_logging(true);

let app = RustF::new().event_config(config);
}

Configuration Options

OptionDescriptionDefaultRecommendation
parallel_executionEnable parallel handler executiontruetrue for production, false for debugging
handler_timeoutMaximum handler execution time30 seconds30-60s for production, 10s for development
debug_loggingEnable detailed execution loggingcfg!(debug_assertions)false for production (performance)
max_concurrent_handlersLimit concurrent handlers per priority0 (unlimited)4-12 based on workload

Built-in Event Handlers

RustF provides ready-to-use event handlers for common startup tasks:

Database Seeder

Scans a directory for .sql seed files:

#![allow(unused)]
fn main() {
.on("database.ready", builtin::database_seeder("seeds/"))
}

Note: This handler is currently a stub/placeholder. It discovers and sorts .sql files but does not execute them against the database β€” for each file it only logs "Would execute SQL from: ..." (see rustf/src/events/builtin.rs). Direct SQL execution is pending. Until then, seed your database by other means.

Behavior:

  • Discovers .sql files and sorts them alphabetically (intended execution order)
  • Only runs in development by default
  • Logs the intended action per file rather than executing it

Directory Setup

Ensures required directories exist with proper permissions:

#![allow(unused)]
fn main() {
.on("startup", builtin::directory_setup(&[
    "uploads", "temp", "logs", "cache", "sessions"
]))
}

Features:

  • Creates missing directories
  • Sets appropriate permissions (755 on Unix)
  • Logs creation status
  • Safe for repeated execution

Cleanup Manager

Removes old temporary files and performs cleanup:

#![allow(unused)]
fn main() {
.on("startup", builtin::cleanup_manager("temp/", Duration::from_secs(86400)))
}

Features:

  • Removes files older than specified duration
  • Handles both files and directories
  • Logs cleanup statistics
  • Safe error handling

Configuration Validator

Validates critical configuration settings:

#![allow(unused)]
fn main() {
.on("config.loaded", builtin::configuration_validator)
}

Features:

  • Validates production-specific settings
  • Checks for default/insecure values
  • Environment-specific validation rules
  • Fails fast on critical issues

Health Check

Performs basic application health checks:

#![allow(unused)]
fn main() {
.on("ready", builtin::health_check)
}

Features:

  • Database connectivity check
  • System resource validation
  • Environment-specific checks
  • Detailed health reporting

Environment Check

Validates the application is running in the expected environment:

#![allow(unused)]
fn main() {
.on("startup", builtin::environment_check("production"))
}

Features:

  • Environment validation
  • Fails in production if mismatch detected
  • Configurable expected environment
  • Detailed error reporting

Custom Event Handlers

Creating Custom Handlers

#![allow(unused)]
fn main() {
// Simple handler function
async fn database_migration_check(ctx: EventContext) -> rustf::Result<()> {
    if ctx.is_production() {
        println!("Checking database migrations in production...");
        // Check migration status
        run_migration_check().await?;
    }
    Ok(())
}

// Register the handler
app.on("database.ready", |ctx| Box::pin(database_migration_check(ctx)))
}

Handler Functions vs Closures

#![allow(unused)]
fn main() {
// Function-based handler (reusable)
async fn reusable_handler(ctx: EventContext) -> rustf::Result<()> {
    println!("Handler executed for: {}", ctx.event);
    Ok(())
}

app.on("ready", |ctx| Box::pin(reusable_handler(ctx)))

// Closure-based handler (inline)
app.on("startup", |ctx| Box::pin(async move {
    println!("Inline handler for {}", ctx.event);
    // Access closure variables
    let config = &ctx.config;
    Ok(())
}))
}

Conditional Handlers

#![allow(unused)]
fn main() {
app.on("ready", |ctx| Box::pin(async move {
    match ctx.env() {
        "development" => {
            println!("Development setup");
            setup_dev_data().await?;
        }
        "production" => {
            println!("Production validation");
            validate_production_config(&ctx.config)?;
        }
        _ => {
            println!("Default environment setup");
        }
    }
    Ok(())
}))
}

Event Context

The EventContext provides rich information and utilities for event handlers:

Context Properties

#![allow(unused)]
fn main() {
async fn handler_example(ctx: EventContext) -> rustf::Result<()> {
    // Event information
    println!("Event: {}", ctx.event);
    println!("Environment: {}", ctx.env());
    
    // Environment checks
    if ctx.is_development() {
        println!("Running in development mode");
    }
    
    if ctx.is_production() {
        println!("Running in production mode");
    }
    
    // Configuration access
    let server_port = ctx.config.server.port;
    let database_url = &ctx.config.database.url;
    
    // Event data (if provided)
    if let Some(data) = &ctx.data {
        println!("Event data: {}", data);
    }
    
    // Emit other events
    // NOTE: ctx.emit is currently a no-op unless an emitter is injected into
    // the context, which the built-in executors do not do. Emitting events
    // from inside a handler does not trigger other handlers today.
    ctx.emit("custom.event", Some(json!({"from": ctx.event}))).await?;
    
    Ok(())
}
}

Available Context Methods

MethodDescriptionExample
ctx.eventCurrent event name"ready"
ctx.env()Current environment"development"
ctx.is_development()Development checktrue
ctx.is_production()Production checkfalse
ctx.configApplication configctx.config.server.port
ctx.dataEvent datajson!({"key": "value"})
ctx.emit(event, data)Emit another event (currently a no-op unless an emitter is injected β€” see note in Custom Events)Custom event emission

Priority System

Control the execution order of event handlers using priorities:

Priority Values

  • -200 to -100: Infrastructure (database, core systems)
  • -99 to -50: Security and authentication
  • -49 to -1: Business logic prerequisites
  • 0: Default priority (recommended for most handlers)
  • 1 to 99: Business logic
  • 100+: Post-processing and cleanup

Priority Examples

#![allow(unused)]
fn main() {
app
    // Critical infrastructure (runs first)
    .on_priority("startup", -100, builtin::directory_setup(&["logs"]))
    
    // Security setup
    .on_priority("startup", -50, security_initialization)
    
    // Default priority (most handlers)
    .on("startup", application_setup)
    
    // Cleanup tasks (runs last)
    .on_priority("startup", 100, final_cleanup)
}

Execution Flow

Priority -100: Infrastructure setup
Priority -50:  Security initialization  
Priority 0:    Application setup (default)
Priority 100:  Final cleanup

Auto-Discovery

RustF can automatically discover and register event handlers from your codebase:

File Structure

src/
  events/           ← Event handler modules
    database.rs     ← Database-related events
    filesystem.rs   ← File system events
    security.rs     ← Security events
    custom.rs       ← Custom application events

Event Handler Module

#![allow(unused)]
fn main() {
// src/events/database.rs
use rustf::events::{EventEmitter, EventContext};

pub fn install(emitter: &mut EventEmitter) {
    emitter.on("database.ready", seed_development_data);
    emitter.on("ready", database_health_check);
}

async fn seed_development_data(ctx: EventContext) -> rustf::Result<()> {
    if ctx.is_development() {
        println!("Seeding development data...");
        // Database seeding logic
    }
    Ok(())
}

async fn database_health_check(ctx: EventContext) -> rustf::Result<()> {
    println!("Running database health check...");
    // Health check logic
    Ok(())
}
}

Auto-Discovery Registration

#![allow(unused)]
fn main() {
// main.rs
use rustf::prelude::*;

let app = RustF::new()
    .events_from(auto_events!())  // Auto-discovers src/events/*.rs
    .controllers(auto_controllers!());
}

Note: Auto-discovery requires the auto-discovery feature to be enabled.

Common Patterns

Database Initialization Pattern

#![allow(unused)]
fn main() {
app.on("database.ready", |ctx| Box::pin(async move {
    if ctx.is_development() {
        // Seed development data
        println!("Seeding development database...");
        seed_database().await?;
    } else if ctx.is_production() {
        // Validate production database
        println!("Validating production database...");
        validate_database_schema().await?;
    }
    Ok(())
}))
}

Multi-Environment Setup

#![allow(unused)]
fn main() {
app.on("ready", |ctx| Box::pin(async move {
    match ctx.env() {
        "development" => {
            setup_debug_tools().await?;
            enable_hot_reload().await?;
        }
        "staging" => {
            setup_staging_environment().await?;
            enable_performance_monitoring().await?;
        }
        "production" => {
            validate_security_settings(&ctx.config)?;
            enable_production_monitoring().await?;
        }
        env => {
            log::warn!("Unknown environment: {}", env);
        }
    }
    Ok(())
}))
}

Dependency Chain Pattern

Note: This pattern depends on ctx.emit(...) triggering the next handler in the chain. As described in Custom Events, in-handler ctx.emit is currently a no-op (no emitter is injected by the executors), so the services.ready / dependencies.ready handlers below will not fire from these emits today. Treat this as the intended design, not current behavior. For now, sequence work using priorities within a single event.

#![allow(unused)]
fn main() {
app
    // Step 1: Initialize core services
    .on_priority("startup", -100, |ctx| Box::pin(async move {
        initialize_core_services().await?;
        ctx.emit("services.ready", None).await?;
        Ok(())
    }))
    
    // Step 2: Setup dependent services
    .on("services.ready", |ctx| Box::pin(async move {
        setup_dependent_services().await?;
        ctx.emit("dependencies.ready", None).await?;
        Ok(())
    }))
    
    // Step 3: Final application setup
    .on("dependencies.ready", |ctx| Box::pin(async move {
        finalize_application_setup().await?;
        Ok(())
    }))
}

Error Recovery Pattern

Note: The ctx.emit("database.connected", ...) / ctx.emit("database.fallback", ...) calls below are currently no-ops (see Custom Events), so they will not notify other handlers today. The error-handling logic itself (returning Err in production, running a fallback in development) works as written.

#![allow(unused)]
fn main() {
app.on("database.ready", |ctx| Box::pin(async move {
    match connect_to_database().await {
        Ok(()) => {
            println!("βœ… Database connected");
            ctx.emit("database.connected", None).await?;
        }
        Err(e) => {
            log::error!("❌ Database connection failed: {}", e);
            
            if ctx.is_production() {
                // Fail fast in production
                return Err(e);
            } else {
                // Try fallback in development
                setup_fallback_database().await?;
                ctx.emit("database.fallback", None).await?;
            }
        }
    }
    Ok(())
}))
}

Best Practices

1. Use Descriptive Event Names

#![allow(unused)]
fn main() {
// Good: Clear and descriptive
.on("database.schema.validated", handler)
.on("security.certificates.loaded", handler)
.on("cache.warmed", handler)

// Avoid: Generic or unclear
.on("done", handler)
.on("init", handler)
.on("setup", handler)
}

2. Leverage Priority System

#![allow(unused)]
fn main() {
// Good: Logical priority ordering
.on_priority("startup", -100, create_directories)    // Infrastructure
.on_priority("startup", -50, load_certificates)      // Security
.on_priority("startup", 0, initialize_services)      // Business logic
.on_priority("startup", 100, warm_caches)           // Optimization
}

3. Handle Errors Gracefully

#![allow(unused)]
fn main() {
.on("ready", |ctx| Box::pin(async move {
    match risky_operation().await {
        Ok(()) => {
            log::info!("βœ… Operation completed successfully");
        }
        Err(e) => {
            log::error!("❌ Operation failed: {}", e);
            
            // Don't fail the entire application for non-critical errors
            if is_critical_error(&e) {
                return Err(e);
            }
            
            // Try fallback or continue
            attempt_fallback().await.ok();
        }
    }
    Ok(())
}))
}

4. Use Environment-Specific Logic

#![allow(unused)]
fn main() {
.on("ready", |ctx| Box::pin(async move {
    if ctx.is_development() {
        setup_development_tools().await?;
        seed_test_data().await?;
    }
    
    if ctx.is_production() {
        validate_production_config(&ctx.config)?;
        setup_monitoring().await?;
    }
    
    Ok(())
}))
}

5. Emit Custom Events for Extension Points

#![allow(unused)]
fn main() {
.on("ready", |ctx| Box::pin(async move {
    initialize_core_application().await?;
    
    // Emit custom event for plugins/extensions
    ctx.emit("application.plugins.load", None).await?;
    
    finalize_initialization().await?;
    Ok(())
}))

// Extensions can hook into the custom event
.on("application.plugins.load", |ctx| Box::pin(async move {
    load_custom_plugins().await?;
    Ok(())
}))
}

6. Document Event Contracts

#![allow(unused)]
fn main() {
/// Emitted when the user authentication system is fully initialized
/// 
/// Context Data: None
/// Prerequisites: database.ready, security.certificates.loaded
/// Guarantees: User authentication is available for requests
.on("auth.system.ready", auth_system_handler)
}

Troubleshooting

Common Issues

1. Handlers Not Executing

Problem: Event handlers don’t seem to run.

Solutions:

  • Verify event names match exactly (case-sensitive)
  • Check that events are being emitted by the framework
  • Ensure handler registration happens before app.start()
#![allow(unused)]
fn main() {
// ❌ Incorrect event name
.on("readdy", handler)  // Typo

// βœ… Correct event name  
.on("ready", handler)
}

2. Handler Execution Order Issues

Problem: Handlers run in unexpected order.

Solutions:

  • Use priority system to control execution order
  • Check priority values (lower = earlier execution)
  • Avoid depending on registration order
#![allow(unused)]
fn main() {
// ❌ Relying on registration order
.on("startup", handler_a)  // Might run second
.on("startup", handler_b)  // Might run first

// βœ… Using explicit priorities
.on_priority("startup", 10, handler_a)  // Runs first
.on_priority("startup", 20, handler_b)  // Runs second
}

3. Async Handler Issues

Problem: Async operations not completing or compiler errors.

Solutions:

  • Always wrap handlers with Box::pin(async move { ... })
  • Ensure all async operations are awaited
  • Return rustf::Result<()> from handlers
#![allow(unused)]
fn main() {
// ❌ Missing Box::pin
.on("ready", |ctx| async move {  // Compiler error
    Ok(())
})

// βœ… Proper async handler
.on("ready", |ctx| Box::pin(async move {
    some_async_operation().await?;
    Ok(())
}))
}

4. Context Data Not Available

Problem: ctx.data is always None.

Solutions:

  • Check that events are emitted with data
  • Verify JSON serialization of event data
  • Use built-in events with expected data structure
#![allow(unused)]
fn main() {
// Emitting event with data
// NOTE: ctx.emit is currently a no-op (see Custom Events) β€” the receiving
// handler below will not fire from this emit yet.
ctx.emit("custom.event", Some(json!({
    "message": "Hello",
    "timestamp": chrono::Utc::now()
}))).await?;

// Receiving event data
.on("custom.event", |ctx| Box::pin(async move {
    if let Some(data) = &ctx.data {
        println!("Received: {}", data);
    }
    Ok(())
}))
}

5. Environment Detection Issues

Problem: Environment methods return unexpected values.

Solutions:

  • Set environment variables properly
  • Check supported environment variable names
  • Use explicit environment checks
# The environment comes from the application's configuration:
# RUSTF_ENV, or [app] environment in config.toml
export RUSTF_ENV=production
#![allow(unused)]
fn main() {
// Debug environment detection
.on("ready", |ctx| Box::pin(async move {
    println!("Environment: {}", ctx.env());
    println!("Is development: {}", ctx.is_development());
    println!("Is production: {}", ctx.is_production());
    Ok(())
}))
}

Debugging Events

Enable debug logging to see event execution:

#![allow(unused)]
fn main() {
// In main.rs
env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("debug")).init();

// Events will log execution details:
// [DEBUG] Registered event handler for 'ready' with priority 0 (id: 1)
// [INFO]  Emitting event: 'ready'
// [DEBUG] Executing handler 1 for 'ready' (priority: 0)
// [INFO]  Event 'ready' executed 1 handler(s)
}

Performance Considerations

Parallel vs Sequential Execution

RustF automatically optimizes event handler execution for maximum performance:

Parallel Execution (Default):

  • Handlers within the same priority group execute concurrently
  • Significantly faster for I/O bound tasks (database calls, file operations)
  • Optimal for production environments
  • Example: 4 handlers Γ— 100ms each = 100ms total (4x speedup)

Sequential Execution (Debug Mode):

  • Handlers execute one after another
  • Easier to debug and trace execution
  • Recommended for development and testing
  • Example: 4 handlers Γ— 100ms each = 400ms total

Performance Optimization Tips

1. Enable Parallel Execution in Production

#![allow(unused)]
fn main() {
let app = RustF::new()
    .event_config(EventEmitterConfig::parallel()
        .with_debug_logging(false));  // Disable debug logging for performance
}

2. Use Priority Groups Strategically

#![allow(unused)]
fn main() {
// βœ… Good: Group related handlers by priority
.on_priority("startup", -100, database_init)     // Infrastructure first
.on_priority("startup", -100, cache_init)        // (parallel with above)
.on_priority("startup", 0, service_init)         // Services second
.on_priority("startup", 0, api_init)             // (parallel with above)

// ❌ Avoid: Mixed priorities force sequential execution
.on_priority("startup", -100, database_init)
.on_priority("startup", 0, service_init)         // Must wait for database_init
.on_priority("startup", -99, cache_init)         // Must wait for service_init
}

3. Configure Timeouts Appropriately

#![allow(unused)]
fn main() {
// Production: Longer timeouts for complex operations
.event_config(EventEmitterConfig::parallel()
    .with_timeout(Duration::from_secs(60)))

// Development: Shorter timeouts to catch hung handlers
.event_config(EventEmitterConfig::sequential()
    .with_timeout(Duration::from_secs(10)))
}

4. Optimize Handler Design

#![allow(unused)]
fn main() {
// βœ… Good: Fast, focused handlers
.on("ready", |ctx| Box::pin(async move {
    log::info!("Application ready in {} mode", ctx.env());
    Ok(())
}))

// βœ… Good: Async I/O operations benefit from parallel execution
.on("startup", |_ctx| Box::pin(async move {
    database::migrate().await?;  // Can run in parallel with other I/O
    Ok(())
}))

// ❌ Avoid: CPU-intensive work that doesn't benefit from parallelism
.on("startup", |_ctx| Box::pin(async move {
    // Heavy CPU work - consider moving to background task
    expensive_computation();
    Ok(())
}))
}

Performance Monitoring

Runtime Performance Metrics

Enable debug logging to monitor handler performance:

#![allow(unused)]
fn main() {
let app = RustF::new()
    .event_config(EventEmitterConfig::parallel()
        .with_debug_logging(true));  // Enable in development

// Console output:
// [INFO]  Emitting event: 'startup' (parallel: true)
// [DEBUG] Executing 3 handler(s) for 'startup' at priority -100 (parallel: true)
// [DEBUG] Handler 1 completed in 145ms
// [DEBUG] Handler 2 completed in 203ms 
// [DEBUG] Event 'startup' executed 3 handler(s) with 0 error(s)
}

Production Monitoring

#![allow(unused)]
fn main() {
.on("ready", |ctx| Box::pin(async move {
    let start = std::time::Instant::now();
    
    // Your handler logic here
    initialize_services().await?;
    
    let duration = start.elapsed();
    if duration > Duration::from_millis(1000) {
        log::warn!("Slow handler execution: {}ms", duration.as_millis());
    }
    
    Ok(())
}))
}

Performance Best Practices

  1. Keep Handlers Fast: Event handlers block application startup
  2. Use Parallel Execution: Default configuration optimizes for production
  3. Group by Priority: Related handlers at same priority execute concurrently
  4. Set Appropriate Timeouts: Prevent runaway handlers from hanging startup
  5. Monitor in Production: Track handler execution times
  6. Defer Heavy Work: Move non-essential tasks to background jobs
  7. Disable Debug Logging: Reduces overhead in production

Performance Anti-Patterns

#![allow(unused)]
fn main() {
// ❌ Bad: Synchronous blocking operations
.on("startup", |_ctx| Box::pin(async move {
    std::thread::sleep(Duration::from_secs(5));  // Blocks executor!
    Ok(())
}))

// βœ… Good: Async operations
.on("startup", |_ctx| Box::pin(async move {
    tokio::time::sleep(Duration::from_secs(5)).await;  // Non-blocking
    Ok(())
}))

// ❌ Bad: Sequential chains that could be parallel
.on_priority("startup", 1, handler_a)
.on_priority("startup", 2, handler_b)  // Must wait for handler_a
.on_priority("startup", 3, handler_c)  // Must wait for handler_b

// βœ… Good: Parallel execution when possible
.on("startup", handler_a)  // All execute in parallel
.on("startup", handler_b)  
.on("startup", handler_c)
}

Summary

RustF’s event system provides a powerful, Total.js-inspired approach to application lifecycle management with advanced parallel execution capabilities:

βœ… Familiar Syntax - Total.js-style ON('ready', handler) patterns
βœ… Complete Lifecycle - Events for every stage of application startup
βœ… Parallel Execution - Concurrent handler execution with 4x+ performance improvements
βœ… Built-in Handlers - Ready-to-use handlers for common tasks
βœ… Priority Control - Fine-grained execution order management with parallel optimization
βœ… Performance Optimized - Fast-path execution, timeout protection, and error isolation
βœ… Type Safety - Full compile-time checking with excellent error messages
βœ… Auto-Discovery - Automatic handler registration from your codebase
βœ… Rich Context - Comprehensive context with config, environment, and utilities
βœ… Production Ready - Configurable performance settings and comprehensive monitoring

RustF Module System User Guide

Complete documentation based on actual framework implementation

Overview

RustF provides a comprehensive module system for organizing business logic, services, and reusable components. The system combines standard Rust module patterns with an optional SharedModule trait and a Total.js-style global MODULE accessor for singleton services. Modules follow clean architecture principles, separating business logic from HTTP request handling.

Key Concepts

  • Standard Rust Modules - Uses regular Rust module system with use statements for direct instantiation
  • Global MODULE System - Total.js-style singleton access by name via MODULE::get("name") for shared services
  • Auto-Discovery - Automatic module scanning with auto_modules!() macro at compile time
  • SharedModule Trait - Optional trait for lifecycle management and type-safe registration
  • Business Logic Separation - Controllers handle HTTP, modules handle business logic
  • Flexible Access Patterns - Choose between direct instantiation or singleton access based on needs

Module Organization

Directory Structure

src/
β”œβ”€β”€ modules/
β”‚   β”œβ”€β”€ user_service.rs      # User business logic
β”‚   β”œβ”€β”€ email_service.rs     # Email operations
β”‚   β”œβ”€β”€ payment_service.rs   # Payment processing
β”‚   └── validation_utils.rs  # Utility functions
β”œβ”€β”€ controllers/             # HTTP handlers
β”œβ”€β”€ models/                  # Data models
└── _modules.rs             # Auto-generated (DO NOT EDIT)

Module Types

The framework recognizes four types of modules:

  1. Services - Stateful business logic with side effects (database operations, external API calls)
  2. Utilities - Stateless pure functions for data transformation and validation
  3. Helpers - Template and view helper functions
  4. Traits - Custom trait definitions and interfaces

Global MODULE System (New)

RustF provides a Total.js-style global MODULE system for singleton access to shared services:

Overview

The MODULE system enables global access to registered modules without passing them through Context or using dependency injection. This is ideal for stateful services that should have a single instance across the entire application.

Basic Usage

Modules are looked up by the name they were registered under (the first argument of MODULE::register), not by type. MODULE::get returns Arc<dyn SharedModule>; to call your own methods, downcast it to the concrete type through SharedModule::as_any():

#![allow(unused)]
fn main() {
// Access modules globally anywhere in your application (by registered name).
// MODULE::get returns Result<Arc<dyn SharedModule>>.
let module = MODULE::get("email-primary")?;

// Downcast to the concrete type to call its methods.
// Keep `module` (the Arc) alive while you use the borrowed `&EmailService`.
let email = module
    .as_any()
    .downcast_ref::<EmailService>()
    .ok_or_else(|| Error::internal("module 'email-primary' is not an EmailService"))?;
email.send_notification("user@example.com").await?;

// Check if a module is registered (by name)
if MODULE::exists("email-primary") {
    // ...
}

// Optional access: get_opt returns Option<Arc<dyn SharedModule>>
if let Some(module) = MODULE::get_opt("email-primary") {
    if let Some(email) = module.as_any().downcast_ref::<EmailService>() {
        email.send_notification("user@example.com").await?;
    }
}

// List all registered modules (useful for debugging)
let modules = MODULE::list();
for (name, module_type) in modules {
    println!("Module: {} ({})", name, module_type);
}
}

When to Use MODULE Registration

Good candidates for MODULE (singleton pattern):

  • Database Connection Pools - Expensive to create, should be shared
  • Cache Services - In-memory caches, Redis connections
  • Email/SMS Services - Configured once, used everywhere
  • WebSocket Managers - Track all active connections
  • Rate Limiters - Shared request counters
  • Background Job Queues - Single task scheduler
  • Metrics Collectors - Application-wide statistics

Use direct instantiation for:

  • Stateless Utilities - Pure functions, no shared state
  • Request-Specific Services - Need new instance per request
  • Simple Validators - Lightweight, no configuration
  • View Helpers - Template formatting functions

Registering Modules for Global Access

To enable MODULE access, register your modules during app initialization:

Modules are not auto-registered. You register each instance explicitly by name using MODULE::register("name", instance) during startup. This is what enables multiple instances of the same type under different names.

// src/main.rs
use rustf::prelude::*;

#[tokio::main]
async fn main() -> Result<()> {
    use crate::modules::{
        email_service::EmailService,
        cache_service::CacheService,
        database_pool::DatabasePool,
    };

    // MODULE::init() must be called once before any MODULE::register / MODULE::get;
    // the framework does not call it for you.
    MODULE::init()?;

    // Register modules explicitly by unique name. Each becomes a singleton
    // accessible via MODULE::get("name").
    MODULE::register("email-primary", EmailService::new())?;
    MODULE::register("cache", CacheService::new())?;
    MODULE::register("database-pool", DatabasePool::new())?;

    let app = RustF::new()
        .controllers(auto_controllers!())
        .start().await;

    app
}

Note: auto_modules!() only emits module declarations for IDE/auto-discovery support β€” it does not register modules and evaluates to (), so it cannot be passed to .modules_from(...). If you prefer the closure form, .modules_from takes a closure FnOnce(&mut SharedRegistry) and you call registry.register(...) inside it; modules registered that way get initialize()/shutdown() called by the app but are not reachable through MODULE::get. Explicit MODULE::register("name", instance) (shown above) is the standard approach.

Usage Patterns Comparison

Pattern 1: Direct Instantiation (Simple, Stateless)

#![allow(unused)]
fn main() {
// Best for stateless utilities and simple services
use crate::modules::validation_utils::ValidationUtils;

async fn handler(ctx: &mut Context) -> Result<()> {
    // Create new instance when needed
    let validator = ValidationUtils::new();
    
    if !validator.is_valid_email("user@example.com") {
        return ctx.throw400(Some("Invalid email"));
    }
    
    ctx.json(json!({"status": "valid"}))
}
}

Pattern 2: Global MODULE Access (Singleton, Stateful)

#![allow(unused)]
fn main() {
// Best for shared resources and configured services
async fn handler(ctx: &mut Context) -> Result<()> {
    // Access singleton instances by name, then downcast to the concrete type
    let email_module = MODULE::get("email-primary")?;
    let email_service = email_module
        .as_any()
        .downcast_ref::<EmailService>()
        .ok_or_else(|| Error::internal("module 'email-primary' is not an EmailService"))?;
    let cache_module = MODULE::get("cache")?;
    let cache = cache_module
        .as_any()
        .downcast_ref::<CacheService>()
        .ok_or_else(|| Error::internal("module 'cache' is not a CacheService"))?;
    
    // Check cache first
    if let Some(cached) = cache.get("user:123").await {
        return ctx.json(cached);
    }
    
    // Send email using shared service
    email_service.send_welcome("user@example.com").await?;
    
    ctx.json(json!({"status": "sent"}))
}
}

Pattern 3: Hybrid Approach (Best of Both)

#![allow(unused)]
fn main() {
use crate::modules::{user_service, validation_utils};

async fn handler(ctx: &mut Context) -> Result<()> {
    // Stateless utility - direct instantiation
    let validator = validation_utils::ValidationUtils::new();
    
    // Stateful service - use the MODULE singleton if registered
    let fallback;
    let module = MODULE::get_opt("email-primary");
    let email = match module.as_ref().and_then(|m| m.as_any().downcast_ref::<EmailService>()) {
        // Use singleton if available
        Some(email) => email,
        // Fall back to direct instantiation
        None => {
            fallback = email_service::EmailService::new();
            &fallback
        }
    };
    
    // Business logic...
    email.send_notification("user@example.com").await?;
    
    ctx.json(json!({"status": "processed"}))
}
}

Creating Modules

Basic Module Structure

Every module is a standard Rust module. A new() constructor is the convention. (An install() function is optional and convenient, but note that modules are not auto-registered β€” you register instances yourself with MODULE::register("name", instance); see Registering Modules for Global Access.)

#![allow(unused)]
fn main() {
// src/modules/user_service.rs
use rustf::prelude::*;

#[derive(Debug)]
pub struct UserService {
    name: String,
}

impl UserService {
    pub fn new() -> Self {
        Self {
            name: "UserService".to_string(),
        }
    }
    
    /// Register a new user with business logic validation
    pub async fn register_user(&self, email: &str, password: &str, profile: Value) -> Result<Value> {
        // Input validation
        if email.is_empty() || !email.contains('@') {
            return Err(Error::validation("Invalid email format"));
        }
        
        if password.len() < 8 {
            return Err(Error::validation("Password must be at least 8 characters"));
        }
        
        // Business logic implementation
        let user = json!({
            "user_id": 1,
            "email": email,
            "created_at": chrono::Utc::now(),
            "is_verified": false
        });
        
        Ok(user)
    }
}

// Optional convenience constructor (modules are NOT auto-registered;
// register explicitly with MODULE::register("user-service", UserService::new())).
pub fn install() -> UserService {
    UserService::new()
}
}

SharedModule Implementation (Optional)

For advanced lifecycle management, implement the SharedModule trait:

#![allow(unused)]
fn main() {
use rustf::prelude::*;
use async_trait::async_trait;

#[derive(Debug)]
pub struct EmailService {
    templates: HashMap<String, String>,
}

impl EmailService {
    pub fn new() -> Self {
        let mut templates = HashMap::new();
        templates.insert("welcome".to_string(), 
            "Welcome {{name}}! Please verify: {{link}}".to_string());
        
        Self { templates }
    }
    
    pub async fn send_verification_email(&self, email: &str, name: &str, token: &str) -> Result<Value> {
        let template = self.templates.get("welcome").unwrap();
        let rendered = template
            .replace("{{name}}", name)
            .replace("{{link}}", &format!("https://app.com/verify?token={}", token));
            
        // In production: integrate with email provider
        log::info!("Sending verification email to {}: {}", email, rendered);
        
        Ok(json!({
            "email": email,
            "status": "sent",
            "message_id": uuid::Uuid::new_v4()
        }))
    }
}

#[async_trait]
impl SharedModule for EmailService {
    fn name(&self) -> &'static str {
        "EmailService"
    }
    
    fn module_type(&self) -> SharedModuleType {
        SharedModuleType::Service
    }
    
    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
    
    async fn initialize(&self) -> Result<()> {
        log::info!("EmailService initialized with {} templates", self.templates.len());
        Ok(())
    }
}

pub fn install() -> EmailService {
    EmailService::new()
}
}

Utility Modules

For stateless utilities, use the convenience macro:

#![allow(unused)]
fn main() {
// src/modules/validation_utils.rs
use rustf::prelude::*;

pub struct ValidationUtils;

impl ValidationUtils {
    /// Validate email format
    pub fn is_valid_email(email: &str) -> bool {
        email.contains('@') && email.len() > 5
    }
    
    /// Validate password strength
    pub fn is_strong_password(password: &str) -> bool {
        password.len() >= 8 
            && password.chars().any(|c| c.is_uppercase())
            && password.chars().any(|c| c.is_lowercase())
            && password.chars().any(|c| c.is_numeric())
    }
    
    /// Sanitize user input
    pub fn sanitize_input(input: &str) -> String {
        input.trim()
            .replace("<", "&lt;")
            .replace(">", "&gt;")
            .replace("&", "&amp;")
    }
}

// Use convenience macro for simple implementation
impl_shared_util!(ValidationUtils);

pub fn install() -> ValidationUtils {
    ValidationUtils
}
}

Module Discovery and Registration

Module Discovery with auto_modules!()

auto_modules!() discovers modules at compile time for IDE support only. It emits the src/modules/* module declarations but does not register anything β€” it evaluates to (), so it cannot be passed to .modules_from(...). Registration is always explicit via MODULE::register(...):

// src/main.rs
use rustf::prelude::*;

#[tokio::main]
async fn main() -> Result<()> {
    MODULE::init()?;
    // Register stateful modules explicitly by name (singletons via MODULE::get).
    MODULE::register("user-service", crate::modules::user_service::UserService::new())?;

    let app = RustF::new()
        .controllers(auto_controllers!())
        .models(auto_models!())
        .start().await;

    app
}

What actually happens:

  1. auto_modules!() scans src/modules/ at compile time and emits module declarations for IDE/auto-discovery support only (no registration).
  2. You call MODULE::register("name", instance) for each module you want globally accessible. This is required β€” there is no automatic registration.
  3. MODULE::init() must be called by your app before registering; the framework does not call it.
  4. Registered modules become singletons accessible by name via MODULE::get("name") (downcast with as_any().downcast_ref::<T>() for the concrete type).

Manual Module Access

Recommended Pattern: Use standard Rust module system for accessing business logic:

#![allow(unused)]
fn main() {
// src/controllers/auth.rs
use rustf::prelude::*;
use crate::modules::{user_service, email_service};

pub fn install() -> Vec<Route> {
    routes![
        POST "/register" => register_user,
        POST "/login" => login_user,
    ]
}

async fn register_user(ctx: &mut Context) -> rustf::Result<()> {
    let form_data = ctx.body_form()?;
    let email = form_data.get("email").unwrap_or("");
    let password = form_data.get("password").unwrap_or("");
    
    // Access modules using standard Rust module system
    let user_svc = user_service::UserService::new();
    let email_svc = email_service::EmailService::new();
    
    // Business logic handled by modules
    match user_svc.register_user(email, password, json!({})).await {
        Ok(user) => {
            // Send verification email
            let _ = email_svc.send_verification_email(
                email, 
                "New User", 
                "verification_token_123"
            ).await;
            
            ctx.flash_success("Registration successful! Check your email.")?;
            ctx.redirect("/login")
        }
        Err(e) => {
            ctx.flash_error(format!("Registration failed: {}", e))?;
            ctx.redirect("/register")
        }
    }
}
}

Explicit Registration Pattern

The global MODULE system has its own registry (separate from the app’s SharedRegistry). Registration is explicit:

// src/main.rs
use rustf::prelude::*;

#[rustf::auto_discover]
#[tokio::main]
async fn main() -> Result<()> {
    // Explicit registration by name (no automatic registration).
    MODULE::init()?;
    MODULE::register("email-primary", crate::modules::email_service::EmailService::new())?;

    let app = RustF::new()
        .controllers(auto_controllers!())
        .models(auto_models!())
        .start().await;

    app
}

What happens:

  1. auto_modules!() only emits module declarations for IDE support β€” it does not register modules and cannot be passed to .modules_from(...).
  2. You register modules explicitly with MODULE::register("name", instance).
  3. app.start() does not call initialize() on MODULE-registered modules (it only does so for modules added to the app’s SharedRegistry via .modules_from(...)).
  4. Modules are available throughout the application lifecycle via MODULE::get("name").

Using Modules in Controllers

Pattern 1: Direct Instantiation (Simple)

Controllers create module instances directly for clear, simple code:

#![allow(unused)]
fn main() {
// src/controllers/users.rs
use rustf::prelude::*;
use crate::modules::{user_service, validation_utils};

async fn create_user(ctx: &mut Context) -> rustf::Result<()> {
    let form_data = ctx.body_form()?;
    let email = form_data.get("email").unwrap_or("");
    let password = form_data.get("password").unwrap_or("");
    
    // Use validation utilities
    if !validation_utils::ValidationUtils::is_valid_email(email) {
        ctx.flash_error("Invalid email format")?;
        return ctx.redirect("/users/new");
    }
    
    if !validation_utils::ValidationUtils::is_strong_password(password) {
        ctx.flash_error("Password must be at least 8 characters with mixed case and numbers")?;
        return ctx.redirect("/users/new");
    }
    
    // Use business service
    let user_svc = user_service::UserService::new();
    match user_svc.register_user(email, password, json!({})).await {
        Ok(user) => {
            ctx.flash_success("User created successfully!")?;
            ctx.redirect("/users")
        }
        Err(e) => {
            ctx.flash_error(format!("Failed to create user: {}", e))?;
            ctx.redirect("/users/new")
        }
    }
}
}

Pattern 2: Global MODULE Access (Singleton)

Use MODULE for shared services that should have one instance:

#![allow(unused)]
fn main() {
// src/controllers/api.rs
use rustf::prelude::*;

async fn process_order(ctx: &mut Context) -> Result<()> {
    // Access singleton services via MODULE (by registered name), downcast to concrete types
    let cache_module = MODULE::get("cache")?;
    let cache = cache_module.as_any().downcast_ref::<CacheService>()
        .ok_or_else(|| Error::internal("module 'cache' is not a CacheService"))?;
    let email_module = MODULE::get("email-primary")?;
    let email = email_module.as_any().downcast_ref::<EmailService>()
        .ok_or_else(|| Error::internal("module 'email-primary' is not an EmailService"))?;
    let payment_module = MODULE::get("payment")?;
    let payment = payment_module.as_any().downcast_ref::<PaymentService>()
        .ok_or_else(|| Error::internal("module 'payment' is not a PaymentService"))?;
    
    let order_data: Value = ctx.body_json()?;
    let order_id = order_data["id"].as_str().unwrap_or("");
    
    // Check cache for duplicate order
    if cache.exists(&format!("order:{}", order_id)).await {
        return ctx.throw400(Some("Duplicate order"));
    }
    
    // Process payment using singleton service
    let payment_result = payment.process(
        order_data["amount"].as_u64().unwrap_or(0),
        order_data["token"].as_str().unwrap_or("")
    ).await?;
    
    // Send confirmation email
    email.send_order_confirmation(
        order_data["email"].as_str().unwrap_or(""),
        order_id
    ).await?;
    
    // Cache the order
    cache.set(&format!("order:{}", order_id), &order_data, 3600).await?;
    
    ctx.json(json!({
        "status": "processed",
        "payment_id": payment_result.id
    }))
}
}

Pattern 3: Dependency Injection Pattern

For applications requiring shared state, pass dependencies explicitly:

#![allow(unused)]
fn main() {
// src/controllers/api.rs
use rustf::prelude::*;
use crate::modules::user_service::UserService;

// Service container approach
pub struct ApiServices {
    user_service: UserService,
    // other services...
}

impl ApiServices {
    pub fn new() -> Self {
        Self {
            user_service: UserService::new(),
        }
    }
}

async fn api_create_user(ctx: &mut Context) -> rustf::Result<()> {
    let services = ApiServices::new();
    let request_data: Value = ctx.body_json()?;
    
    let email = request_data["email"].as_str().unwrap_or("");
    let password = request_data["password"].as_str().unwrap_or("");
    
    match services.user_service.register_user(email, password, json!({})).await {
        Ok(user) => ctx.json(json!({
            "success": true,
            "user": user
        })),
        Err(e) => ctx.json(json!({
            "success": false,
            "error": e.to_string()
        }))
    }
}
}

Module Patterns and Best Practices

1. Service Pattern (Stateful Business Logic)

#![allow(unused)]
fn main() {
// src/modules/order_service.rs
use rustf::prelude::*;

#[derive(Debug)]
pub struct OrderService {
    config: OrderConfig,
}

#[derive(Debug)]
pub struct OrderConfig {
    pub max_items: usize,
    pub tax_rate: f64,
}

impl OrderService {
    pub fn new() -> Self {
        Self {
            config: OrderConfig {
                max_items: 100,
                tax_rate: 0.08,
            },
        }
    }
    
    pub async fn create_order(&self, user_id: i64, items: Vec<OrderItem>) -> Result<Order> {
        // Business validation
        if items.len() > self.config.max_items {
            return Err(Error::validation("Too many items in order"));
        }
        
        // Calculate totals
        let subtotal: f64 = items.iter().map(|item| item.price * item.quantity as f64).sum();
        let tax = subtotal * self.config.tax_rate;
        let total = subtotal + tax;
        
        // Create order (in real app: save to database)
        let order = Order {
            id: 1,
            user_id,
            items,
            subtotal,
            tax,
            total,
            status: OrderStatus::Pending,
            created_at: chrono::Utc::now(),
        };
        
        log::info!("Created order {} for user {} (total: ${:.2})", order.id, user_id, total);
        Ok(order)
    }
    
    pub async fn calculate_shipping(&self, order: &Order, address: &Address) -> Result<f64> {
        // Shipping calculation logic
        let base_rate = 5.99;
        let weight_factor = order.items.len() as f64 * 0.5;
        Ok(base_rate + weight_factor)
    }
}

#[derive(Debug, Serialize)]
pub struct Order {
    pub id: i64,
    pub user_id: i64,
    pub items: Vec<OrderItem>,
    pub subtotal: f64,
    pub tax: f64,
    pub total: f64,
    pub status: OrderStatus,
    pub created_at: chrono::DateTime<chrono::Utc>,
}

pub fn install() -> OrderService {
    OrderService::new()
}
}

2. Utility Pattern (Stateless Functions)

#![allow(unused)]
fn main() {
// src/modules/text_utils.rs
use rustf::prelude::*;

pub struct TextUtils;

impl TextUtils {
    /// Convert text to URL-friendly slug
    pub fn slugify(text: &str) -> String {
        text.to_lowercase()
            .chars()
            .map(|c| if c.is_alphanumeric() { c } else { '-' })
            .collect::<String>()
            .split('-')
            .filter(|s| !s.is_empty())
            .collect::<Vec<&str>>()
            .join("-")
    }
    
    /// Truncate text with ellipsis
    pub fn truncate(text: &str, max_length: usize) -> String {
        if text.len() <= max_length {
            text.to_string()
        } else {
            format!("{}...", &text[..max_length - 3])
        }
    }
    
    /// Extract mentions from text (@username)
    pub fn extract_mentions(text: &str) -> Vec<String> {
        let re = regex::Regex::new(r"@(\w+)").unwrap();
        re.captures_iter(text)
            .map(|cap| cap[1].to_string())
            .collect()
    }
    
    /// Generate random string
    pub fn random_string(length: usize) -> String {
        use rand::Rng;
        const CHARSET: &[u8] = b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        let mut rng = rand::thread_rng();
        (0..length)
            .map(|_| {
                let idx = rng.gen_range(0..CHARSET.len());
                CHARSET[idx] as char
            })
            .collect()
    }
}

impl_shared_util!(TextUtils);

pub fn install() -> TextUtils {
    TextUtils
}
}

3. Helper Pattern (View Helpers)

#![allow(unused)]
fn main() {
// src/modules/view_helpers.rs
use rustf::prelude::*;

pub struct ViewHelpers;

impl ViewHelpers {
    /// Format currency for display
    pub fn format_currency(amount: f64, currency: &str) -> String {
        match currency {
            "USD" => format!("${:.2}", amount),
            "EUR" => format!("€{:.2}", amount),
            "GBP" => format!("Β£{:.2}", amount),
            _ => format!("{:.2} {}", amount, currency),
        }
    }
    
    /// Format relative time (e.g., "2 hours ago")
    pub fn time_ago(datetime: &chrono::DateTime<chrono::Utc>) -> String {
        let now = chrono::Utc::now();
        let duration = now.signed_duration_since(*datetime);
        
        if duration.num_days() > 7 {
            datetime.format("%Y-%m-%d").to_string()
        } else if duration.num_days() > 0 {
            format!("{} days ago", duration.num_days())
        } else if duration.num_hours() > 0 {
            format!("{} hours ago", duration.num_hours())
        } else if duration.num_minutes() > 0 {
            format!("{} minutes ago", duration.num_minutes())
        } else {
            "Just now".to_string()
        }
    }
    
    /// Generate avatar URL from email
    pub fn gravatar_url(email: &str, size: u32) -> String {
        let hash = md5::compute(email.trim().to_lowercase().as_bytes());
        format!("https://www.gravatar.com/avatar/{:x}?s={}&d=identicon", hash, size)
    }
    
    /// Pluralize words based on count
    pub fn pluralize(word: &str, count: usize) -> String {
        if count == 1 {
            word.to_string()
        } else if word.ends_with('y') {
            format!("{}ies", &word[..word.len()-1])
        } else if word.ends_with(&['s', 'x', 'z']) || word.ends_with("ch") || word.ends_with("sh") {
            format!("{}es", word)
        } else {
            format!("{}s", word)
        }
    }
}

impl_shared_helper!(ViewHelpers);

pub fn install() -> ViewHelpers {
    ViewHelpers
}
}

Advanced Features

Module Lifecycle Management

For modules requiring initialization and cleanup:

#![allow(unused)]
fn main() {
// src/modules/cache_service.rs
use rustf::prelude::*;

#[derive(Debug)]
pub struct CacheService {
    redis_client: Option<redis::Client>,
    memory_cache: HashMap<String, CacheEntry>,
}

#[derive(Debug, Clone)]
struct CacheEntry {
    value: String,
    expires_at: chrono::DateTime<chrono::Utc>,
}

impl CacheService {
    pub fn new() -> Self {
        Self {
            redis_client: None,
            memory_cache: HashMap::new(),
        }
    }
    
    pub async fn get(&self, key: &str) -> Option<String> {
        // Try memory cache first
        if let Some(entry) = self.memory_cache.get(key) {
            if entry.expires_at > chrono::Utc::now() {
                return Some(entry.value.clone());
            }
        }
        
        // Fall back to Redis if available
        None // Simplified for example
    }
    
    pub async fn set(&mut self, key: &str, value: &str, ttl_seconds: u64) -> Result<()> {
        let expires_at = chrono::Utc::now() + chrono::Duration::seconds(ttl_seconds as i64);
        self.memory_cache.insert(key.to_string(), CacheEntry {
            value: value.to_string(),
            expires_at,
        });
        Ok(())
    }
}

#[async_trait]
impl SharedModule for CacheService {
    fn name(&self) -> &'static str {
        "CacheService"
    }
    
    fn module_type(&self) -> SharedModuleType {
        SharedModuleType::Service
    }
    
    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
    
    async fn initialize(&self) -> Result<()> {
        log::info!("CacheService initializing...");
        
        // Initialize Redis connection
        if let Ok(redis_url) = std::env::var("REDIS_URL") {
            match redis::Client::open(redis_url) {
                Ok(_client) => log::info!("Redis cache client initialized"),
                Err(e) => log::warn!("Failed to initialize Redis: {}", e),
            }
        }
        
        log::info!("CacheService initialized successfully");
        Ok(())
    }
    
    async fn shutdown(&self) -> Result<()> {
        log::info!("CacheService shutting down...");
        // Cleanup operations would go here
        Ok(())
    }
}

pub fn install() -> CacheService {
    CacheService::new()
}
}

Cross-Module Dependencies

Modules can depend on each other using standard Rust patterns:

#![allow(unused)]
fn main() {
// src/modules/notification_service.rs
use rustf::prelude::*;
use super::email_service::EmailService;

#[derive(Debug)]
pub struct NotificationService {
    email_service: EmailService,
}

impl NotificationService {
    pub fn new() -> Self {
        Self {
            email_service: EmailService::new(),
        }
    }
    
    pub async fn send_welcome_notification(&self, user_email: &str, user_name: &str) -> Result<()> {
        // Send email notification
        self.email_service.send_verification_email(user_email, user_name, "welcome_token").await?;
        
        // Could also send push notification, SMS, etc.
        log::info!("Welcome notification sent to {}", user_email);
        Ok(())
    }
    
    pub async fn send_order_confirmation(&self, user_email: &str, order_id: i64) -> Result<()> {
        // Complex notification logic using email service
        let subject = format!("Order #{} confirmed", order_id);
        // Implementation details...
        Ok(())
    }
}

pub fn install() -> NotificationService {
    NotificationService::new()
}
}

Testing Modules

Unit Testing Services

#![allow(unused)]
fn main() {
// src/modules/user_service.rs
#[cfg(test)]
mod tests {
    use super::*;
    
    #[tokio::test]
    async fn test_register_user_valid() {
        let service = UserService::new();
        let result = service.register_user(
            "test@example.com", 
            "password123", 
            json!({})
        ).await;
        
        assert!(result.is_ok());
        let user = result.unwrap();
        assert_eq!(user["email"], "test@example.com");
        assert_eq!(user["is_verified"], false);
    }
    
    #[tokio::test]
    async fn test_register_user_invalid_email() {
        let service = UserService::new();
        let result = service.register_user(
            "invalid-email", 
            "password123", 
            json!({})
        ).await;
        
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("Invalid email format"));
    }
    
    #[tokio::test]
    async fn test_register_user_weak_password() {
        let service = UserService::new();
        let result = service.register_user(
            "test@example.com", 
            "123", 
            json!({})
        ).await;
        
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("at least 8 characters"));
    }
}
}

Integration Testing

#![allow(unused)]
fn main() {
// tests/module_tests.rs
use rustf::prelude::*;
use your_app::modules::{user_service, email_service};

#[tokio::test]
async fn test_user_registration_flow() {
    // Setup
    let user_svc = user_service::UserService::new();
    let email_svc = email_service::EmailService::new();
    
    // Test user registration
    let user_result = user_svc.register_user(
        "integration@test.com",
        "TestPassword123",
        json!({"first_name": "Test", "last_name": "User"})
    ).await;
    
    assert!(user_result.is_ok());
    let user = user_result.unwrap();
    
    // Test email notification
    let email_result = email_svc.send_verification_email(
        "integration@test.com",
        "Test",
        "test_token_123"
    ).await;
    
    assert!(email_result.is_ok());
    let email_response = email_result.unwrap();
    assert_eq!(email_response["email"]["status"], "sent");
}
}

Configuration

Environment-Based Module Configuration

#![allow(unused)]
fn main() {
// src/modules/payment_service.rs
use rustf::prelude::*;

#[derive(Debug)]
pub struct PaymentService {
    stripe_key: Option<String>,
    sandbox_mode: bool,
}

impl PaymentService {
    pub fn new() -> Self {
        let stripe_key = std::env::var("STRIPE_SECRET_KEY").ok();
        let sandbox_mode = std::env::var("PAYMENT_SANDBOX")
            .unwrap_or_else(|_| "false".to_string())
            .parse()
            .unwrap_or(false);
            
        Self {
            stripe_key,
            sandbox_mode,
        }
    }
    
    pub async fn process_payment(&self, amount: u64, token: &str) -> Result<PaymentResult> {
        if self.sandbox_mode {
            log::info!("SANDBOX: Processing payment of ${} with token {}", amount, token);
            return Ok(PaymentResult {
                id: "sandbox_payment_123".to_string(),
                status: PaymentStatus::Succeeded,
                amount,
            });
        }
        
        // Real payment processing logic
        match &self.stripe_key {
            Some(key) => {
                // Use Stripe API
                log::info!("Processing real payment with Stripe");
                // Implementation...
                Ok(PaymentResult {
                    id: "real_payment_456".to_string(),
                    status: PaymentStatus::Succeeded,
                    amount,
                })
            }
            None => {
                Err(Error::configuration("STRIPE_SECRET_KEY not configured"))
            }
        }
    }
}

pub fn install() -> PaymentService {
    PaymentService::new()
}
}

Module Documentation Patterns

Self-Documenting Modules

#![allow(unused)]
fn main() {
// src/modules/analytics_service.rs
//! Analytics Service Module
//! 
//! Provides comprehensive analytics tracking and reporting functionality.
//! 
//! ## Features
//! - Event tracking with custom properties
//! - User behavior analytics
//! - Performance metrics collection
//! - A/B testing support
//! 
//! ## Usage
//! ```rust
//! use crate::modules::analytics_service::AnalyticsService;
//! 
//! let analytics = AnalyticsService::new();
//! analytics.track_event("user_signup", json!({"source": "web"})).await?;
//! ```

use rustf::prelude::*;

/// Analytics service for tracking user events and system metrics
/// 
/// The AnalyticsService provides methods for tracking various types of events:
/// - User actions (clicks, page views, form submissions)
/// - System events (errors, performance metrics)  
/// - Custom business events (purchases, subscriptions)
#[derive(Debug)]
pub struct AnalyticsService {
    /// Whether analytics is enabled (can be disabled for testing)
    enabled: bool,
    /// Buffer for batching events before sending
    event_buffer: Vec<AnalyticsEvent>,
}

#[derive(Debug, Serialize)]
pub struct AnalyticsEvent {
    pub event_name: String,
    pub properties: Value,
    pub user_id: Option<String>,
    pub session_id: Option<String>,
    pub timestamp: chrono::DateTime<chrono::Utc>,
}

impl AnalyticsService {
    /// Create new analytics service
    /// 
    /// # Example
    /// ```rust
    /// let analytics = AnalyticsService::new();
    /// ```
    pub fn new() -> Self {
        let enabled = std::env::var("ANALYTICS_ENABLED")
            .unwrap_or_else(|_| "true".to_string())
            .parse()
            .unwrap_or(true);
            
        Self {
            enabled,
            event_buffer: Vec::new(),
        }
    }
    
    /// Track a user event with optional properties
    /// 
    /// # Arguments
    /// * `event_name` - Name of the event (e.g., "page_view", "button_click")
    /// * `properties` - Additional event data as JSON
    /// 
    /// # Example
    /// ```rust
    /// analytics.track_event("user_signup", json!({
    ///     "source": "web",
    ///     "plan": "premium"
    /// })).await?;
    /// ```
    pub async fn track_event(&mut self, event_name: &str, properties: Value) -> Result<()> {
        if !self.enabled {
            return Ok(());
        }
        
        let event = AnalyticsEvent {
            event_name: event_name.to_string(),
            properties,
            user_id: None, // Would be set from context in real implementation
            session_id: None,
            timestamp: chrono::Utc::now(),
        };
        
        self.event_buffer.push(event);
        
        // Flush buffer if it gets too large
        if self.event_buffer.len() >= 100 {
            self.flush_events().await?;
        }
        
        Ok(())
    }
    
    /// Flush buffered events to analytics provider
    async fn flush_events(&mut self) -> Result<()> {
        if self.event_buffer.is_empty() {
            return Ok(());
        }
        
        log::info!("Flushing {} analytics events", self.event_buffer.len());
        
        // In real implementation: send to analytics provider
        // Google Analytics, Mixpanel, Segment, etc.
        
        self.event_buffer.clear();
        Ok(())
    }
}

pub fn install() -> AnalyticsService {
    AnalyticsService::new()
}
}

Error Handling in Modules

Consistent Error Patterns

#![allow(unused)]
fn main() {
// src/modules/file_service.rs
use rustf::prelude::*;
use std::path::PathBuf;

#[derive(Debug)]
pub struct FileService {
    upload_path: PathBuf,
    max_file_size: usize,
}

impl FileService {
    pub fn new() -> Self {
        let upload_path = std::env::var("UPLOAD_PATH")
            .unwrap_or_else(|_| "uploads".to_string())
            .into();
            
        let max_file_size = std::env::var("MAX_FILE_SIZE")
            .unwrap_or_else(|_| "10485760".to_string()) // 10MB default
            .parse()
            .unwrap_or(10485760);
            
        Self {
            upload_path,
            max_file_size,
        }
    }
    
    pub async fn save_upload(&self, file_data: &[u8], filename: &str) -> Result<FileUploadResult> {
        // Validation
        if file_data.is_empty() {
            return Err(Error::validation("File cannot be empty"));
        }
        
        if file_data.len() > self.max_file_size {
            return Err(Error::validation(&format!(
                "File size {} exceeds maximum allowed size {}", 
                file_data.len(), 
                self.max_file_size
            )));
        }
        
        // Security: validate filename
        if filename.contains("..") || filename.contains("/") || filename.contains("\\") {
            return Err(Error::security("Invalid filename"));
        }
        
        // Generate unique filename
        let unique_filename = format!("{}_{}", 
            uuid::Uuid::new_v4(), 
            filename
        );
        
        let file_path = self.upload_path.join(&unique_filename);
        
        // Ensure upload directory exists
        if let Some(parent) = file_path.parent() {
            std::fs::create_dir_all(parent)
                .map_err(|e| Error::filesystem(&format!("Failed to create upload directory: {}", e)))?;
        }
        
        // Save file
        std::fs::write(&file_path, file_data)
            .map_err(|e| Error::filesystem(&format!("Failed to save file: {}", e)))?;
        
        log::info!("File saved: {} ({} bytes)", unique_filename, file_data.len());
        
        Ok(FileUploadResult {
            filename: unique_filename,
            path: file_path.to_string_lossy().to_string(),
            size: file_data.len(),
            mime_type: self.detect_mime_type(filename),
        })
    }
    
    fn detect_mime_type(&self, filename: &str) -> String {
        match filename.split('.').last() {
            Some("jpg") | Some("jpeg") => "image/jpeg".to_string(),
            Some("png") => "image/png".to_string(),
            Some("gif") => "image/gif".to_string(),
            Some("pdf") => "application/pdf".to_string(),
            Some("txt") => "text/plain".to_string(),
            _ => "application/octet-stream".to_string(),
        }
    }
}

#[derive(Debug, Serialize)]
pub struct FileUploadResult {
    pub filename: String,
    pub path: String,
    pub size: usize,
    pub mime_type: String,
}

pub fn install() -> FileService {
    FileService::new()
}
}

Best Practices Summary

1. Module Design Principles

  • Single Responsibility - Each module handles one domain of business logic
  • Clear Interfaces - Public methods are well-documented and consistent
  • Error Handling - Use Result<T> for operations that can fail
  • Configuration - Use environment variables for runtime configuration
  • Logging - Include appropriate logging for debugging and monitoring

2. Code Organization

#![allow(unused)]
fn main() {
// βœ… Good: Clear module structure
// src/modules/
//   β”œβ”€β”€ user_service.rs        # User domain logic
//   β”œβ”€β”€ order_service.rs       # Order processing
//   β”œβ”€β”€ payment_service.rs     # Payment handling
//   β”œβ”€β”€ email_service.rs       # Email operations
//   └── validation_utils.rs    # Shared utilities

// ❌ Bad: Mixed concerns
// src/modules/
//   └── everything_service.rs  # Handles users, orders, payments, etc.
}

3. Dependencies and Coupling

#![allow(unused)]
fn main() {
// βœ… Good: Explicit dependencies
use crate::modules::email_service::EmailService;

pub struct UserService {
    email_service: EmailService,
}

// ❌ Bad: Hidden global state
pub struct UserService;

impl UserService {
    pub async fn register_user(&self, email: &str) -> Result<User> {
        // Hidden dependency on global email service
        GLOBAL_EMAIL_SERVICE.send_welcome(email).await?;
    }
}
}

4. Testing Strategy

#![allow(unused)]
fn main() {
// βœ… Good: Testable design
impl PaymentService {
    pub fn new_for_testing() -> Self {
        Self {
            stripe_key: None,
            sandbox_mode: true, // Always sandbox for tests
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    
    #[tokio::test]
    async fn test_payment_processing() {
        let service = PaymentService::new_for_testing();
        // Test implementation
    }
}
}

Migration and Compatibility

From Older Module Systems

If migrating from other Rust web frameworks:

#![allow(unused)]
fn main() {
// Actix Web style -> RustF style
// Old:
// web::Data<EmailService>

// New:
use crate::modules::email_service::EmailService;
let email_service = EmailService::new();
}

Framework Agnostic Modules

Keep business logic independent of RustF specifics:

#![allow(unused)]
fn main() {
// βœ… Good: Framework-independent core logic
impl UserService {
    pub async fn validate_and_create_user(&self, email: &str, password: &str) -> Result<User> {
        // Core business logic - no RustF dependencies
        // Can be used in CLI tools, tests, other frameworks
    }
}

// βœ… Good: the controller handler owns the HTTP side and builds the response
async fn create_user(ctx: &mut Context) -> Result<()> {
    let form = ctx.body_form()?;
    let email = form.get("email").unwrap_or("").to_string();
    let password = form.get("password").unwrap_or("").to_string();

    let user = UserService::new().validate_and_create_user(&email, &password).await?;
    ctx.json(json!({ "id": user.id }))
}

// ❌ Bad: Tightly coupled to RustF
impl UserService {
    pub async fn create_user(&self, ctx: &mut Context) -> Result<()> {
        // Mixing business logic with HTTP concerns (reads the request,
        // writes the response) - belongs in the controller, not the module
    }
}
}

Framework Integration Status

Based on the current RustF implementation:

βœ… SharedModule Trait - Complete implementation in src/shared.rs
βœ… SharedRegistry - Full registry with lifecycle management
βœ… Module Types - Service, Util, Helper, Trait categorization
βœ… Auto-discovery macro - auto_modules!() in rustf-macros
βœ… Standard Rust modules - Normal use statement access
βœ… Lifecycle management - Initialize/shutdown methods
βœ… App Integration - SharedRegistry integrated with RustF app builder pattern
βœ… CLI Support - rustf-cli new creates src/modules/ directory with README
βœ… Global MODULE System - Total.js-style singleton access by name via MODULE::get("name")
βœ… Name-Based Access - MODULE::get / MODULE::get_opt return Arc<dyn SharedModule>; downcast via as_any().downcast_ref::<T>()
βœ… MODULE Initialization - Explicit MODULE::init() call in your app startup
βœ… Dynamic Module Discovery - MODULE::list() and MODULE::exists("name") methods

Usage Recommendations

For most applications:

  1. Register stateful modules explicitly with MODULE::register("name", instance) at startup (auto_modules!() only provides IDE discovery; it does not register modules)
  2. Create services as structs with new() constructors
  3. For stateless utilities: Use direct instantiation with use statements
  4. For stateful services: Register and access by name via MODULE::get("name") + as_any().downcast_ref::<T>()

Choosing between direct instantiation and MODULE:

  1. Use MODULE for:

    • Database connection pools
    • Cache services (Redis, in-memory)
    • Configured services (email, SMS, payment)
    • Services with expensive initialization
    • Resources that should be shared application-wide
  2. Use direct instantiation for:

    • Stateless utility functions
    • Request-specific services
    • Simple validators and formatters
    • Services that don’t need configuration

For simple modules that don’t need lifecycle management:

  1. Create basic structs with static methods
  2. Use impl_shared_util!() macro for utilities
  3. Access directly via standard Rust module imports

For complex services requiring singleton behavior:

  1. Implement SharedModule trait with initialize() and shutdown() methods
  2. Register with MODULE::register("name", instance) (after MODULE::init()) to enable MODULE access
  3. Access by name via MODULE::get("name") + as_any().downcast_ref::<T>() throughout the application
  4. initialize() / shutdown() are called automatically only for modules registered through .modules_from()

The module system now provides full integration with the framework while maintaining flexibility for both simple and complex use cases, with clean separation of concerns between HTTP handling (controllers) and business logic (modules).

Summary

RustF’s module system provides:

βœ… Clean Architecture - Separation of business logic from HTTP concerns
βœ… Standard Rust Patterns - Uses familiar module system and traits
βœ… Auto-Discovery - Compile-time scanning of module directories
βœ… Type Safety - Compile-time validation of module interfaces
βœ… Lifecycle Management - Optional initialize/shutdown methods
βœ… Global MODULE System - Total.js-style singleton access for shared services
βœ… Flexible Access Patterns - Support for both direct instantiation and singleton access
βœ… Testing Support - Easy to unit test individual modules
βœ… Resource Efficiency - Singleton pattern for expensive resources

The system strikes a balance between simplicity and power, offering multiple patterns:

  • Direct instantiation for simple, stateless utilities
  • Global MODULE access for shared, stateful services
  • Hybrid approaches for maximum flexibility

This allows developers to organize business logic effectively while maintaining clean architecture principles that make applications maintainable, testable, and resource-efficient.

WebSocket

RustF speaks WebSocket through one route keyword and one Context method, in the shape Total.js gave the idea: one room per URL, configured once, shared by everyone who connects to it.

#![allow(unused)]
fn main() {
use rustf::prelude::*;

pub fn install() -> Vec<Route> {
    routes![
        GET    "/chat"        => page,     // the page
        SOCKET "/chat/{room}" => chat,     // the socket
    ]
}

async fn chat(ctx: &mut Context) -> rustf::Result<()> {
    ctx.socket(|room| {
        room.on_open(|client| async move {
            client.send_json(&json!({ "type": "welcome", "id": client.id() }))
        });
        room.on_message(|client, message| async move {
            client.room().send_except(message, client.id())
        });
        room.on_close(|client, _code| async move {
            client.room().send_json(&json!({ "type": "left", "id": client.id() }))
        });
    })
}
}

Generate that, plus a page and a browser client, with:

rustf-cli new socket --name chat

The SOCKET route keyword

SOCKET "/chat/{room}" => chat registers a GET route β€” the opening handshake is a GET β€” and marks it as a socket. What changes is the dispatch:

RequestResult
GET /chat/general with Upgrade: websockethandshake, then 101
GET /chat/general without it426 Upgrade Required, handler never runs
Handshake with a version other than 13426, advertising Sec-WebSocket-Version: 13
Handshake with a missing or malformed Sec-WebSocket-Key400
Handshake from a disallowed origin403

Route parameters, query strings, middleware and the before: hook all work exactly as on any other route, because until the 101 this is an ordinary HTTP request.

Per-route flags

Flags follow the handler, mirroring Total.js’s ROUTE('SOCKET /chat/', fn, ['json'], 1024):

#![allow(unused)]
fn main() {
routes![
    SOCKET "/chat"  => chat,                          // defaults
    SOCKET "/feed"  => feed, [json],                  // payload must be JSON
    SOCKET "/bulk"  => bulk, [json, max = 1 << 20],   // and a 1 MiB cap
    SOCKET "/raw"   => raw,  [text],                  // explicit default
]
}
  • json β€” a message whose payload is not valid JSON closes the connection with 1003 Unsupported Data; your handler never sees it. Both frame types are checked, so the flag cannot be sidestepped with a different opcode β€” and by the same token a binary frame carrying valid JSON is accepted and arrives as Message::Binary. Use msg.parse::<T>(), which reads either.
  • text β€” the default: messages arrive as sent.
  • max = <bytes> β€” overrides [websocket] max_message_size for this route. Anything larger closes with 1009 Message Too Big.

Authorization

Total.js writes '+SOCKET' for β€œauthorized only”. RustF has no new syntax for this, because the handshake is a normal request and the existing tools already apply:

#![allow(unused)]
fn main() {
async fn chat(ctx: &mut Context) -> rustf::Result<()> {
    if ctx.session().map(|s| s.is_authenticated()) != Some(true) {
        return ctx.throw401(Some("Sign in first"));
    }

    ctx.socket(|room| { /* ... */ })
}
}

Or, for a whole controller, the before: hook:

#![allow(unused)]
fn main() {
routes![
    before: require_login,
    SOCKET "/chat/{room}" => chat,
]
}

Either way the check runs before any upgrade: the client gets a 401 and no socket is created.

Rooms

ctx.socket(configure) looks up the room for the matched path β€” /chat/general, not /chat/{room} β€” creating it if this is the first client. configure runs once per room, exactly like the Total.js action. A second client on the same URL joins the room the first one configured.

Once per room, though, not once per process. With autodestroy on β€” the default β€” a room disappears when its last client leaves, so the next connection to that URL creates and configures a new one. A configure closure that panics ends its room the same way. Keep external side effects out of it.

One more detail: the room is published to SOCKET while it is being configured, which is what lets a configure closure call SOCKET::room. A registry lookup can therefore briefly see a room whose handlers are not installed yet, though joining always waits.

SocketRoom

MethodWhat it does
send(msg)to everyone
send_except(msg, id)to everyone but one β€” Total.js self.send(msg, sender)
send_to(id, msg)to one client
send_json(&v) / send_json_except(&v, id)the same, serialised as JSON
online() / is_empty()membership count
client_ids() / find(id)membership
autodestroy(bool)destroy when the last client leaves (on by default)
destroy()close everyone with 1001 and unregister
path()the URL this room serves

Sends never block. Each client has a bounded outbound queue; a client that has stopped reading is disconnected with 1008 Policy Violation rather than allowed to stall the broadcast.

SocketClient

on_close and on_error are best effort and bounded at five seconds: they run while the connection is being torn down, so one that takes longer is cancelled at its next await point and the fact logged. Cleanup that must complete belongs in a WORKER.

id(), room(), params() / param(name), query() / query_param(name), headers() / header(name), ip(), session(), send(), send_text(), send_json(), close(code, reason).

The handshake data is a snapshot taken before the upgrade β€” the Request is long gone by the time the connection is live.

Reaching a room from elsewhere

SOCKET is RustF’s F.connections[url]. Use it from an HTTP handler, a worker, a scheduled job β€” anywhere:

#![allow(unused)]
fn main() {
if let Some(room) = SOCKET::room("/chat/general") {
    room.send_json(&json!({ "type": "announcement", "text": text }))?;
}
}

SOCKET::rooms(), SOCKET::paths() and SOCKET::online() report what is live.

The raw socket

When you want the connection and not the room β€” a protocol bridge, a one-way feed β€” take it directly:

#![allow(unused)]
fn main() {
async fn echo(ctx: &mut Context) -> rustf::Result<()> {
    ctx.websocket(|mut socket| async move {
        while let Some(message) = socket.recv().await {
            socket.send(message?).await?;
        }
        Ok(())
    })
}
}

recv() yields only text and binary messages: pings are answered automatically and a close frame ends the loop. split() gives independent sending and receiving halves for a handler that pushes and reads at once β€” but see the note on keepalive below.

Three rules for handlers

  1. Call ctx.socket / ctx.websocket last. It writes the 101. Anything that replaces ctx.res afterwards is written to a connection already speaking WebSocket; RustF logs it and discards the upgrade rather than leaving it hanging.
  2. A rejected handshake is an ordinary response. Ok(()) comes back either way; check ctx.is_upgrading() if the distinction matters.
  3. Errors after the upgrade cannot reach the client. There is no HTTP response left to put them in, so they are logged.

Configuration

[websocket]
max_message_size    = 1048576   # 1 MiB. tungstenite's own default is 64 MiB
max_frame_size      = 262144    # 256 KiB
ping_interval       = 30        # seconds; 0 disables the keepalive
allowed_origins     = []        # empty = same-origin only; ["*"] disables the check
accept_subprotocols = []        # e.g. ["json"]; case-sensitive; first match is echoed
require_origin      = false     # refuse a handshake that carries no Origin at all
max_connections     = 0         # cap on concurrent sockets; 0 = no limit

max_connections is worth setting on anything public. A handshake is cheap and a connection is long-lived, so without a cap one client can hold open as many tasks and outbound queues as it likes; over the limit a handshake gets 503.

Security

Cross-Site WebSocket Hijacking is the one to know about. The handshake is a plain GET, so a browser attaches the visitor’s cookies to it β€” and CSRF tokens do not apply, because there is no form. The Origin check is the whole defence:

  • Default: same origin only. Scheme, host and port must match the Host the request was sent to.
  • allowed_origins extends that default, so naming a partner origin does not lock out your own pages.
  • Origin: null β€” sandboxed iframes, file:// pages β€” is never treated as same-origin. List it explicitly if you really mean it.
  • A request with no Origin is allowed by default: that is normally a non-browser client, which attaches no cookies of its own. It is a default, not a guarantee β€” a reverse proxy can strip Origin while still forwarding Cookie. Set require_origin = true on an endpoint that is only ever opened by a browser.
  • allowed_origins = ["*"] turns the check off. Only do that for an endpoint that carries no ambient authority.

Also worth knowing: RateLimitMiddleware runs on the handshake, so per-IP handshake limits work unchanged, and max_connections caps concurrent sockets server-wide. A per-IP concurrent-connection cap is not built in yet.

A stalled client’s outbound queue holds up to 64 messages, counted as messages rather than bytes β€” with the default 1 MiB cap that is 64 MiB for one stalled client in the worst case. Size max_message_size for what your routes actually carry, and max_connections for how many such clients you can afford.

Limits and things that are not here

  • HTTP/1.1 only. WebSocket over HTTP/2 (RFC 8441 extended CONNECT) is not supported by hyper’s server. Browsers open WebSocket over HTTP/1.1 anyway.
  • Keepalive pings: the room layer sends them from each connection’s writer task, and closes the connection with 1001 when nothing at all comes back between two pings β€” which is how a half-open connection is actually detected, since a TCP write to a vanished peer succeeds for a long time. A raw ctx.websocket socket pings while the handler waits in recv(); one that only sends, or that has split() the socket, gets none.
  • A slow on_message blocks that connection’s reads. Handlers are awaited inline, in order, so while one runs that client’s later messages and its close frame are not read. Other clients are unaffected and keepalive pings keep flowing, because they come from the connection’s separate writer task. Move slow work to a WORKER if the ordering guarantee is not worth it. A handler that never returns is cancelled when the connection ends for any reason the writer can see (unanswered pings, a close, shutdown), so it cannot hold a connection open forever.
  • Outbound middleware does not see the connection. Logging and timing middleware measure the handler, which ends at the 101; the minutes or hours that follow are not observed.
  • No cross-process broadcast. SOCKET::room reaches sockets on this instance. Fanning out across a cluster needs a Redis pub/sub backend, which is not built yet.
  • No permessage-deflate. Compression over attacker-controlled input is a CRIME-class risk; it is off and not configurable.
  • TLS is terminated by your reverse proxy, as with plain HTTP.

Shutdown

On graceful shutdown RustF stops accepting new handshakes (a late one on an existing keep-alive connection gets 503), closes every room socket with 1001 Going Away, and waits for the connections to finish, bounded by [server] shutdown_timeout. A close waits up to 5 seconds for the peer’s half of the closing handshake before the socket is dropped.

A raw ctx.websocket handler owns its own loop and cannot be closed from outside, so write it to return when recv() yields None. Anything still running when the shutdown timeout expires is aborted.

Total.js β†’ RustF

Total.jsRustF
ROUTE('SOCKET /chat/{room}/', action, ['json'], 1024)routes![SOCKET "/chat/{room}" => chat, [json, max = 1024]]
'+SOCKET' / '-SOCKET'ctx.throw401(..) in the handler, or routes![before: require_login, ...]
this inside the actionthe &SocketRoom passed to ctx.socket
self.on('open', fn)room.on_open(|client| async move { .. })
self.on('message', fn)room.on_message(|client, message| async move { .. })
self.on('close', fn)room.on_close(|client, code| async move { .. })
self.on('error', fn)room.on_error(|client, error| async move { .. })
self.send(msg, blacklist)room.send_except(msg, id)
self.connections / self.onlineroom.client_ids() / room.online()
self.find(id)room.find(id)
self.autodestroy()room.autodestroy(true) β€” already the default
self.destroy()room.destroy()
client.send(msg)client.send(msg)
client.query / client.paramsclient.query() / client.params()
client.user / client.sessionclient.session()
F.connections['/chat/room1/']SOCKET::room("/chat/room1")

Feature flag

WebSocket is behind the websocket feature, on by default. Building with --no-default-features drops tokio-tungstenite and removes Route::websocket, ctx.socket and ctx.websocket β€” a SOCKET route then fails to compile.

API Reference

Complete API documentation for all RustF framework components.

Available APIs

Context API

The Context struct provides access to request/response functionality:

  • Request data access
  • Response generation
  • Session management
  • Flash messages
  • Repository data
  • Client information

Model API

Database model operations and query building:

  • Model creation and configuration
  • Query builder methods
  • Relationships
  • Transactions
  • Migrations

Routing API

Route definition and registration:

  • Route creation
  • Route handlers
  • Route parameters
  • Route groups
  • Auto-discovery

Utilities

Helper functions and utilities:

  • String utilities
  • Date/time helpers
  • Validation functions
  • Type conversions
  • Common patterns

Context API Reference

The Context struct gives a handler everything it needs about the incoming request and lets it write the outgoing response. Every route handler receives &mut Context and returns rustf::Result<()> β€” the framework picks the response back up via ctx.take_response() after the handler returns.

Overview

#![allow(unused)]
fn main() {
pub struct Context {
    pub req: Request,             // HTTP request (headers, body, cookies, …)
    pub res: Option<Response>,    // HTTP response (mutated by ctx.json/view/etc.)
    // ... private fields: session, views, layout_name, repository, data, ...
}
}

Naming convention. All typed accessors come in a source-first form (param_str, query_int, body_bool) and a deprecated type-first alias (str_param, int_query, bool_body). The source-first names are the canonical choice β€” they sort and grep better and match what you’ll see in current code. The aliases still compile for backward compatibility.

Request Data

URL Parameters

#![allow(unused)]
fn main() {
ctx.param_str("id")               -> Result<String>
ctx.param_int("id")               -> Result<i32>
ctx.param_as::<T>("id")           -> Result<T>   // any FromStr type
ctx.param_str_or("id", "default") -> String
ctx.param_int_or("id", 0)         -> i32
ctx.param_as_or::<T>("id", def)   -> T
}

param_as covers everything param_int does not β€” i64, u32, Uuid, NaiveDate, IpAddr, Decimal. For an i64 model id write ctx.param_as::<i64>("id")? rather than casting.

There is no untyped ctx.param(). Raw access, when you genuinely need the whole map, is ctx.req.params.

Query Parameters

#![allow(unused)]
fn main() {
// e.g. ?page=2
ctx.query_str("page")              -> Result<String>
ctx.query_int("page")              -> Result<i32>
ctx.query_bool("active")           -> Result<bool>
ctx.query_as::<T>("start")         -> Result<T>   // any FromStr type
ctx.query_str_or("page", "1")      -> String
ctx.query_int_or("limit", 10)      -> i32
ctx.query_bool_or("active", false) -> bool
ctx.query_as_or::<T>("start", def) -> T
}

query_as covers f64, i64, Uuid, NaiveDate, DateTime<Utc>, IpAddr, Decimal β€” anything implementing FromStr:

#![allow(unused)]
fn main() {
let start: NaiveDate = ctx.query_as("start")?;
let radius = ctx.query_as_or::<f64>("radius", 5.0);
}

An empty value counts as missing, so ?page= behaves like no page at all.

There is no untyped ctx.query(). Raw access is ctx.req.query.

Request Body

JSON body

#![allow(unused)]
fn main() {
// Synchronous β€” no .await. Uses simd-json under the hood.
let data: MyStruct = ctx.body_json()?;

// Untyped β€” useful when shape is dynamic
let body: serde_json::Value = ctx.full_body()?;
}

Form data

#![allow(unused)]
fn main() {
// FormData keeps every value of a repeated field (checkboxes, `tags[]`).
let form = ctx.body_form()?;
let email = form.get("email");            // Option<&str> β€” the first value
let tags  = form.get_all("tags");         // Vec<&str>    β€” all of them
let price = form.get_as::<f64>("price")?; // typed getters: get_str/get_int/get_bool/get_as

// The raw map, when you want to inspect FormValue::Single vs Multiple
let raw = ctx.body_form_data()?;          // &HashMap<String, FormValue>

// Strongly-typed form parsing via serde. Non-string fields are parsed from
// their string form, and a repeated field fills a `Vec`.
#[derive(Deserialize)]
struct NewProduct { name: String, price: f64, tags: Vec<String> }
let product: NewProduct = ctx.body_form_typed()?;

// Individual field accessors (source-first, recommended)
let email   = ctx.body_str("email")?;                // Required, returns String
let age     = ctx.body_int("age")?;                  // Parse as i32
let active  = ctx.body_bool("active")?;              // Parse as bool
let due     = ctx.body_as::<NaiveDate>("due")?;      // Any FromStr type
let name    = ctx.body_str_or("name", "Anonymous");  // Optional with default
}

Headers

#![allow(unused)]
fn main() {
ctx.header("Authorization") -> Option<&str>     // read request header
ctx.add_header("X-Custom", "value");            // append response header
}

Cookies

Cookies live on Request, not directly on Context β€” but they’re a short hop away via ctx.req:

#![allow(unused)]
fn main() {
// Get one cookie value (parsed once, then cached for the whole request)
ctx.req.cookie("session") -> Option<String>

// All cookies as a borrowed map (same lazy cache)
ctx.req.cookies() -> &HashMap<String, String>
}

The Cookie header is parsed once per request and the result cached on Request, so multiple middleware reading different cookies (session, flash, CSRF) share one parse.

Client Information

#![allow(unused)]
fn main() {
ctx.ip()                         -> String           // Client IP
ctx.user_agent()                 -> Option<&str>
ctx.is_mobile()                  -> bool
ctx.is_robot()                   -> bool
ctx.is_secure()                  -> bool             // HTTPS
ctx.is_xhr()                     -> bool             // AJAX detected
ctx.language()                   -> Option<&str>     // Accept-Language
ctx.referrer()                   -> Option<&str>
ctx.url()                        -> &str             // path + query
ctx.path()                       -> &str             // path only
ctx.host()                       -> Option<&str>
ctx.hostname(path: Option<&str>) -> String           // full URL with scheme
ctx.extension()                  -> Option<&str>     // file extension
}

Response Methods

All response methods take &mut self and write to ctx.res in place. They return rustf::Result<()> so you can ?-propagate errors.

JSON

#![allow(unused)]
fn main() {
ctx.json(data: impl Serialize) -> Result<()>
}

HTML / Text

#![allow(unused)]
fn main() {
ctx.html(content: impl Into<String>)  -> Result<()>
ctx.plain(text: impl Into<String>)    -> Result<()>
}

View / Template

#![allow(unused)]
fn main() {
// Template name has NO file extension β€” the framework appends the
// configured one (default `.html`).
ctx.view(template: &str, data: Value) -> Result<()>
}

Redirect

#![allow(unused)]
fn main() {
ctx.redirect(path: &str) -> Result<()>
}

HTTP Error Responses

Each throwNNN sets ctx.res to an error response AND returns Err so the ? operator stops the handler chain naturally:

#![allow(unused)]
fn main() {
ctx.throw400(message: Option<&str>) -> Result<()>  // Bad Request
ctx.throw401(message: Option<&str>) -> Result<()>  // Unauthorized
ctx.throw403(message: Option<&str>) -> Result<()>  // Forbidden
ctx.throw404(message: Option<&str>) -> Result<()>  // Not Found
ctx.throw409(message: Option<&str>) -> Result<()>  // Conflict
ctx.throw500(message: Option<&str>) -> Result<()>  // Internal Server Error
ctx.throw501(message: Option<&str>) -> Result<()>  // Not Implemented
ctx.view404() -> Result<()>                        // Render the 404 view
}

Other Responses

#![allow(unused)]
fn main() {
ctx.empty()                              -> Result<()>     // 204 No Content
ctx.success(data: Option<T>)             -> Result<()>     // {success: true, data: ...}
ctx.status(status: hyper::StatusCode)                      // mutate status (no Result)
}

File Responses

#![allow(unused)]
fn main() {
ctx.file_download<P: AsRef<Path>>(path: P, filename: Option<&str>) -> Result<()>
ctx.file_inline<P: AsRef<Path>>(path: P) -> Result<()>

ctx.binary(
    data: Vec<u8>,
    content_type: &str,
    download_name: Option<&str>,
) -> Result<()>

// Streamed: 64 KiB chunks, flat memory regardless of file size
ctx.file_download_stream<P: AsRef<Path>>(path: P, filename: Option<&str>) -> Result<()>
ctx.file_inline_stream<P: AsRef<Path>>(path: P) -> Result<()>
// ..._from(base_dir, path, ..) variants exist for both, as for the buffered helpers
}

Streaming Responses

#![allow(unused)]
fn main() {
ctx.stream(
    body: impl Into<Body>,          // Vec<u8> β†’ buffered; Body::from_stream(..) β†’ chunked
    content_type: &str,
    download_name: Option<&str>,
) -> Result<()>
}

Body::from_stream(s) takes any Stream<Item = rustf::Result<Bytes>>. A stream of unknown length is sent with Transfer-Encoding: chunked; Body::from_sized_stream(s, len) declares the total and gets a Content-Length instead. Status and headers go out with the first chunk, so authorise and validate before handing over the stream β€” an Err yielded mid-flight can only truncate the body (it is logged at error level).

#![allow(unused)]
fn main() {
use rustf::prelude::*;
use bytes::Bytes;

async fn export(ctx: &mut Context) -> rustf::Result<()> {
    let rows = futures::stream::iter((1..=1_000_000).map(|n| {
        Ok(Bytes::from(format!("{n},row {n}\n")))
    }));
    ctx.stream(Body::from_stream(rows), "text/csv", Some("rows.csv"))
}
}

Outbound middleware that inspects the body (compression, for one) sees a stream as opaque and passes it through untouched.

Server-Sent Events

#![allow(unused)]
fn main() {
ctx.sse(events: impl Stream<Item = SseEvent | rustf::Result<SseEvent>> + Send + 'static) -> Result<()>
ctx.sse_with_keep_alive(events, interval: Duration)                                     -> Result<()>

SseEvent::new(data)          // one event; multi-line data β†’ one `data:` line per line
SseEvent::json(&value)?      // data = serde_json::to_string(value)
SseEvent::comment(text)      // `:text` line, ignored by clients (keep-alive)
    .id("42")                // echoed back as Last-Event-ID on reconnect
    .event("progress")       // dispatched to addEventListener("progress", ..)
    .retry(Duration)         // client reconnect delay
}

Sets Content-Type: text/event-stream, Cache-Control: no-cache and X-Accel-Buffering: no. The response stays open until the stream ends; if the stream yields Result<SseEvent>, the first Err aborts it (logged at error level, and EventSource reconnects). Use sse_with_keep_alive when the feed can go quiet for longer than a proxy’s idle timeout (15 s clears the common 30 s default); it emits one comment per interval of silence, the first a full interval after the stream starts, and never while events are flowing.

HEAD requests to any route run the GET handler and return its headers with no body. The static file server does not support Range requests.

WebSocket

Both take a SOCKET route and must be the last call in the handler: they write the 101, and anything that replaces ctx.res afterwards is discarded.

#![allow(unused)]
fn main() {
ctx.socket(configure: impl FnOnce(&SocketRoom) + Send + 'static) -> Result<()>
ctx.websocket(callback: impl FnOnce(WebSocket) -> Future<Output = Result<()>> + Send + 'static) -> Result<()>
ctx.is_upgrading() -> bool     // false when the handshake was rejected
}

ctx.socket is the Total.js model: RustF keeps one SocketRoom per matched URL, configure runs for the first client on that path, and everyone after joins the room it set up. It runs once per room, not once per process β€” a room with autodestroy on (the default) disappears when its last client leaves, and the next connection configures a new one. ctx.websocket hands over the raw connection instead.

A rejected handshake (400 / 403 / 426) still returns Ok(()), with the response already written to ctx.res. Errors after the upgrade cannot reach the client and are logged.

See WebSocket for rooms, SOCKET::room, the per-route [json] / [max = ..] flags, and the origin policy.

#![allow(unused)]
fn main() {
use rustf::prelude::*;
use tokio_stream::wrappers::ReceiverStream;

async fn progress(ctx: &mut Context) -> rustf::Result<()> {
    let (tx, rx) = tokio::sync::mpsc::channel(16);
    tokio::spawn(async move {
        for pct in (0..=100).step_by(10) {
            if tx.send(SseEvent::new(pct.to_string()).event("progress")).await.is_err() {
                break; // client disconnected
            }
            tokio::time::sleep(std::time::Duration::from_millis(200)).await;
        }
    });
    ctx.sse_with_keep_alive(ReceiverStream::new(rx), std::time::Duration::from_secs(15))
}
}

Session Management

Session Access

#![allow(unused)]
fn main() {
ctx.session()         -> Option<&Session>
ctx.has_session()     -> bool
ctx.require_session() -> Result<&Session>   // Err if no session is attached
ctx.require_auth()    -> Result<&Session>   // Err if no authenticated session
}

Session Data

#![allow(unused)]
fn main() {
// Set β€” value must be Serialize
ctx.session_set(key: &str, value: T) -> Result<()>

// Get β€” turbofish for the deserialised type
ctx.session_get::<T>(key: &str) -> Option<T>

// Remove returns the prior Value if there was one
ctx.session_remove(key: &str) -> Option<Value>

// Lifecycle
ctx.session_clear()
ctx.session_flush()                          // alias for clear
ctx.session_destroy()                        // full invalidation at end of request
}

Authentication

#![allow(unused)]
fn main() {
ctx.login(user_id: i64) -> Result<()>
ctx.logout()            -> Result<()>
}

Flash Messages

Flash messages are one-time messages stored in the session.

#![allow(unused)]
fn main() {
// Generic
ctx.flash(key: &str, value: impl Serialize) -> Result<()>

// Convenience (key is the level itself: "success", "error", ...)
ctx.flash_success(message: impl Into<String>) -> Result<()>
ctx.flash_error(message: impl Into<String>)   -> Result<()>
ctx.flash_info(message: impl Into<String>)    -> Result<()>
ctx.flash_warning(message: impl Into<String>) -> Result<()>

// Read (also clears)
ctx.get_flash(key: &str) -> Option<Value>
ctx.get_all_flash()      -> HashMap<String, Value>

// Manual clearing
ctx.flash_clear()                -> Result<()>
ctx.flash_clear_key(key: &str)   -> Result<()>
}

Repository Data β€” visible in views

Repository data is request-scoped data that the renderer surfaces in templates as @{R.<key>}. Use it for anything a view needs.

#![allow(unused)]
fn main() {
ctx.repository_set(key: &str, value: impl Into<Value>) -> &mut Self  // chainable
ctx.repository_get(key: &str) -> Option<&Value>
ctx.repository_clear() -> &mut Self
}

Layout Management

#![allow(unused)]
fn main() {
ctx.layout(name: &str) -> &mut Self  // empty string = no layout
}

File Uploads

#![allow(unused)]
fn main() {
ctx.files() -> Result<&FileCollection>
ctx.file(field_name: &str) -> Result<Option<&UploadedFile>>
}

Middleware Data β€” NOT visible in views

For middleware-internal state (timing, auth claims, etc.), use the set / get typed slot. These do NOT reach templates β€” that’s what repository_* is for.

#![allow(unused)]
fn main() {
ctx.set(key: &str, value: T) -> Result<()>
ctx.get::<T>(key: &str)      -> Option<&T>
ctx.has_data(key: &str)      -> bool
}

Response Management

#![allow(unused)]
fn main() {
ctx.set_response(response: Response)
ctx.get_response()  -> Option<&Response>
ctx.take_response() -> Option<Response>     // framework calls this after the handler
}

Examples

Basic Handler

#![allow(unused)]
fn main() {
async fn get_user(ctx: &mut Context) -> rustf::Result<()> {
    let user_id = ctx.param_as::<i64>("id")?;
    // ... fetch user via your service module ...
    ctx.json(json!({"user": user_id}))
}
}

Form Handling

#![allow(unused)]
fn main() {
async fn create_user(ctx: &mut Context) -> rustf::Result<()> {
    let form: CreateUserForm = ctx.body_form_typed()?;
    // ... call into your module ...
    ctx.flash_success("User created!")?;
    ctx.redirect("/users")
}
}

Session Usage

#![allow(unused)]
fn main() {
async fn dashboard(ctx: &mut Context) -> rustf::Result<()> {
    let user_id: i64 = ctx
        .session_get::<i64>("user_id")
        .ok_or_else(|| {
            // throw* sets ctx.res AND returns Err β€” perfect for ?
            let _ = ctx.throw401(Some("Login required"));
            rustf::Error::authentication("Login required")
        })?;

    ctx.repository_set("user_id", user_id);
    ctx.view("dashboard/index", json!({}))
}
}

Reading Cookies

#![allow(unused)]
fn main() {
async fn show_visitor(ctx: &mut Context) -> rustf::Result<()> {
    let last_visit = ctx.req.cookie("last_visit").unwrap_or_default();
    ctx.json(json!({ "last_visit": last_visit }))
}
}

Model API Reference

RustF provides a database model system with query builders and type-safe database access.

Model Traits

BaseModel

All database models implement the BaseModel trait. It uses associated constants (TABLE_NAME, PRIMARY_KEY) and an associated type (IdType) rather than methods. The trait is async (it uses #[async_trait]).

#![allow(unused)]
fn main() {
#[async_trait]
pub trait BaseModel: ChangeTracking + Sized + Clone + Send + Sync + 'static
where
    Self: Serialize + for<'de> Deserialize<'de>,
{
    /// The Rust type of the primary key (e.g. i32, i64, String, Uuid)
    type IdType: Clone + Send + Sync + Display + Into<SqlValue> + 'static;

    /// The database table name
    const TABLE_NAME: &'static str;

    /// The primary key column name (e.g. "id")
    const PRIMARY_KEY: &'static str;

    /// Get the ID value of this instance
    fn id(&self) -> Self::IdType;

    // ... plus static helpers (query, get_by_id, get_all, count, ...)
    // and instance methods (update, delete) shown below.
}
}

A generated model declares these like so:

#![allow(unused)]
fn main() {
impl BaseModel for Users {
    type IdType = i32;
    const TABLE_NAME: &'static str = "users";
    const PRIMARY_KEY: &'static str = "id";

    fn id(&self) -> Self::IdType {
        self.id
    }
    // ...
}
}

ModelQuery

ModelQuery<T> is a struct (not a trait) that wraps the query builder and returns typed results. You obtain one from Model::query() and chain methods on it.

#![allow(unused)]
fn main() {
pub struct ModelQuery<T> { /* ... */ }
}

Query Builder

Basic Queries

All of these are async and return rustf::Result.

#![allow(unused)]
fn main() {
use rustf::prelude::*;

// Fetch by primary key -> Result<Option<Users>>
let user = Users::get_by_id(1).await?;

// Fetch all rows -> Result<Vec<Users>>
let users = Users::get_all().await?;

// Query with conditions. `query()` returns Result, so it needs `?`.
// Terminate the chain with `.get()` (Vec) or `.get_first()` (Option).
let active_users = Users::query()?
    .where_eq("is_active", true)
    .get()
    .await?;
}

Where Clauses

#![allow(unused)]
fn main() {
Users::query()?
    .where_eq("status", "active")
    .where_ne("deleted", true)
    .where_gt("age", 18)
    .where_lt("created_at", "2024-01-01")
    .where_like("name", "%john%")
    .where_in("id", vec![1, 2, 3])
    .get()
    .await?;
}

Ordering

#![allow(unused)]
fn main() {
Users::query()?
    .order_by("created_at", OrderDirection::Desc)
    .get()
    .await?;
}

Pagination

#![allow(unused)]
fn main() {
// Simple pagination (legacy)
Users::query()?
    .limit(10)
    .offset(20)
    .get_all()
    .await?;

// Pagination with metadata (recommended)
let result = Users::query()?
    .where_eq("is_active", true)
    .get_paginated(2, 20)
    .await?;

// Access data and metadata
for user in &result.rows {
    println!("User: {}", user.username);
}
println!("Page {} of {}", result.page, result.total_pages);
println!("Total: {}", result.total_rows);

// Convert to Pagination for templates
let pagination = U::pagination_from_paged_result(&result, "/users?page={0}");
}

Aggregations

count() is an async terminator on ModelQuery. There are no dedicated max() / avg() helpers β€” for those, use select_raw(...) with get_raw(), which returns the rows as serde_json::Value.

#![allow(unused)]
fn main() {
// Count matching rows -> Result<i64>
let count = Users::query()?
    .where_eq("is_active", true)
    .count()
    .await?;

// MAX / AVG via raw SELECT expressions
let rows = Users::query()?
    .select_raw(&["MAX(age) as max_age", "AVG(score) as avg_score"])
    .get_raw()
    .await?;

let max_age = rows[0]["max_age"].as_i64().unwrap_or(0);
let avg_score = rows[0]["avg_score"].as_f64().unwrap_or(0.0);
}

Model Operations

BaseModel itself exposes only update(&mut self) and delete(self) for persistence β€” there is no create() or save() on the trait. New records are inserted through the generated builder, whose save() validates the fields and performs the INSERT.

Create

#![allow(unused)]
fn main() {
// Each generated model has a typed builder with one method per column.
let user = Users::builder()
    .username("jdoe")
    .email("john@example.com")
    .first_name("John")
    .last_name("Doe")
    .save()
    .await?; // -> rustf::Result<Users>
}

Update

update() uses change tracking and only writes the fields you modified via the generated set_* setters.

#![allow(unused)]
fn main() {
let mut user = Users::get_by_id(1).await?.unwrap();
user.set_first_name("Jane");
user.update().await?; // consumes &mut self
}

Delete

#![allow(unused)]
fn main() {
let user = Users::get_by_id(1).await?.unwrap();
user.delete().await?; // consumes self
}

Global Database Access

DB::query() takes no arguments and returns a Result<QueryBuilder> you build up programmatically. For raw parameterized SQL, use DB::fetch_all_with_params (returns rows as serde_json::Value) or DB::execute_with_params (returns the number of affected rows).

#![allow(unused)]
fn main() {
use rustf::db::DB;
use rustf::database::types::SqlValue;

// Start a programmatic query builder (no SQL string, no args)
let qb = DB::query()?;

// Raw parameterized SELECT -> Result<Vec<serde_json::Value>>
let rows = DB::fetch_all_with_params(
    "SELECT * FROM users WHERE id = ?",
    vec![SqlValue::Int(1)],
).await?;

// Raw parameterized INSERT/UPDATE/DELETE -> Result<u64> (rows affected)
let affected = DB::execute_with_params(
    "UPDATE users SET is_active = ? WHERE id = ?",
    vec![SqlValue::Bool(false), SqlValue::Int(1)],
).await?;
}

Transactions: there is no DB::transaction(...) helper in the current API. Use raw SQL (BEGIN / COMMIT / ROLLBACK) via DB::execute_with_params, or the underlying SQLx pool obtained from DB (e.g. DB::sqlite_pool()), if you need transactional control.

Model Registration

Models are auto-discovered:

#![allow(unused)]
fn main() {
let app = RustF::new()
    .models(auto_models!());
}

Examples

Complete Model Usage

#![allow(unused)]
fn main() {
// Find user by primary key
let user = Users::get_by_id(1).await?;

// Query with conditions
let active_users = Users::query()?
    .where_eq("is_active", true)
    .order_by("created_at", OrderDirection::Desc)
    .limit(10)
    .get()
    .await?;

// Create new user via the generated builder
let new_user = Users::builder()
    .username("alice")
    .email("alice@example.com")
    .first_name("Alice")
    .save()
    .await?;

// Update user (only changed fields are written)
let mut user = Users::get_by_id(1).await?.unwrap();
user.set_first_name("Bob");
user.update().await?;

// Delete user
let user = Users::get_by_id(1).await?.unwrap();
user.delete().await?;
}

Routing API Reference

RustF provides a clean routing system built around the routes! macro and Route struct, dispatched by a high-performance trie router.

Route Definition

The routes! Macro

Two arms β€” pick the one you need:

#![allow(unused)]
fn main() {
// Bare arm β€” the common case
routes![
    GET    "/path"      => handler_function,
    POST   "/path"      => handler_function,
    PUT    "/path/{id}" => handler_function,
    DELETE "/path/{id}" => handler_function,
    XHR    "/api/data"  => handler_function,   // XHR-only (AJAX)
]
}
#![allow(unused)]
fn main() {
// With an optional controller-level `before` hook
routes![
    before: before,
    GET  "/path"      => handler_function,
    POST "/path"      => handler_function,
]
}

The before: clause attaches a pre-handler hook to every route in this install(). See Controller-level before Hook in the controllers guide for the full pattern.

Route Struct

#![allow(unused)]
fn main() {
pub struct Route {
    pub method: String,           // HTTP method ("GET", "POST", ..., "XHR")
    pub path: String,             // URL pattern, e.g. "/users/{id}"
    pub handler: RouteHandler,    // Handler function pointer
    pub xhr_only: bool,           // Set when constructed via Route::xhr / `XHR` arm
    pub before: Option<BeforeFn>, // Optional controller-level pre-handler hook
}
}

Handler Types

#![allow(unused)]
fn main() {
// Handler β€” runs after `before` (if any) and writes the response in place.
pub type RouteHandler = for<'a> fn(&'a mut Context)
    -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'a>>;

// Optional pre-handler hook β€” controller-level setup or guard.
pub type BeforeFn = for<'a> fn(&'a mut Context)
    -> Pin<Box<dyn Future<Output = Result<BeforeAction>> + Send + 'a>>;

pub enum BeforeAction { Continue, Stop }
}

RouteHandler is a function pointer type, not a trait object β€” non- capturing closures coerce to it via the routes! macro.

Manual Route Creation

You can build routes without the macro using Route::* constructors:

#![allow(unused)]
fn main() {
use rustf::routing::Route;

Route::get("/users",      handler);
Route::post("/users",     handler);
Route::put("/users/{id}", handler);
Route::delete("/users/{id}", handler);
Route::xhr("/api/data",   handler);

// Generic constructor (any method including custom):
Route::new("PATCH", "/users/{id}", handler);
}

All constructors set before: None. Use the routes![before: ..., ...] macro arm to wire a hook (or set the field manually if you really need to).

URL Parameters

Routes use {parameter} syntax (not :parameter):

#![allow(unused)]
fn main() {
routes![
    GET "/users/{id}"                              => get_user,
    GET "/posts/{post_id}/comments/{comment_id}"   => get_comment,
]
}

Access parameters in handlers via the typed accessors on Context:

#![allow(unused)]
fn main() {
async fn get_user(ctx: &mut Context) -> rustf::Result<()> {
    // String parameter
    let id = ctx.param_str("id")?;            // -> String

    // Integer parameter (returns i32; cast to i64 if your model uses i64)
    // let id = ctx.param_as::<i64>("id")?;
    Ok(())
}
}

The typed accessors return Err when the parameter is missing or unparseable. For a genuinely optional parameter use param_str_or / param_int_or / param_as_or with a default, or read ctx.req.params directly.

Route Registration

#![allow(unused)]
fn main() {
let app = RustF::new()
    .controllers(auto_controllers!());
}

auto_controllers!() scans src/controllers/*.rs at compile time and calls each module’s install() function.

Manual Registration

#![allow(unused)]
fn main() {
let app = RustF::new()
    .controllers({
        let mut routes = Vec::new();
        routes.extend(controllers::home::install());
        routes.extend(controllers::users::install());
        routes
    });
}

Controller Pattern

Every controller exports an install() function returning Vec<Route>:

#![allow(unused)]
fn main() {
use rustf::prelude::*;

pub fn install() -> Vec<Route> {
    routes![
        GET  "/"       => index,
        POST "/submit" => submit,
    ]
}

async fn index(ctx: &mut Context) -> rustf::Result<()> { /* ... */ }
async fn submit(ctx: &mut Context) -> rustf::Result<()> { /* ... */ }
}

HTTP Methods

Supported in the routes! macro and as Route::* constructors:

Macro keywordRoute::*Notes
GETRoute::getRetrieve a resource
POSTRoute::postCreate a resource (form/JSON body)
PUTRoute::putUpdate a resource
DELETERoute::deleteDelete a resource
XHRRoute::xhrAJAX-only β€” registered for both GET and POST internally; rejects non-XHR requests with 403

Other methods (PATCH, HEAD, OPTIONS, …) are reachable via Route::new("PATCH", path, handler).

Route Matching

The router is a trie (rustf/src/routing/trie.rs) β€” matching is O(log n) in the number of path segments, not O(n) over registered routes. When several routes could match a given path, the trie picks the most specific match in this order:

  1. Exact (static) segment β€” e.g. /users/special always wins over /users/{id}.
  2. Parameter segment β€” {id} matches anything in that position.
  3. Wildcard (*) β€” least specific, matches the rest of the path.

Method matching is exact on the verb. A GET request to a route registered only for POST returns 404, not 405.

Examples

Basic Routes

#![allow(unused)]
fn main() {
pub fn install() -> Vec<Route> {
    routes![
        GET "/"      => index,
        GET "/about" => about,
    ]
}
}

RESTful Routes

#![allow(unused)]
fn main() {
pub fn install() -> Vec<Route> {
    routes![
        GET    "/api/users"      => list_users,
        GET    "/api/users/{id}" => get_user,
        POST   "/api/users"      => create_user,
        PUT    "/api/users/{id}" => update_user,
        DELETE "/api/users/{id}" => delete_user,
    ]
}
}

With a before Hook

#![allow(unused)]
fn main() {
pub fn install() -> Vec<Route> {
    async fn before(ctx: &mut Context) -> rustf::Result<BeforeAction> {
        if !ctx.has_session() {
            ctx.redirect("/login")?;
            return Ok(BeforeAction::Stop);
        }
        Ok(BeforeAction::Continue)
    }

    routes![
        before: before,
        GET    "/admin"          => dashboard,
        GET    "/admin/users"    => list_users,
        DELETE "/admin/users/{id}" => delete_user,
    ]
}
}

RustF Utilities (U) User Guide

Overview

RustF provides a global utilities system through the U module, offering commonly used functions for web development. Inspired by Total.js, it provides a convenient API for random generation, string processing, HTTP utilities, encoding, parsing, cryptographic hash functions, and more.

The utilities system supports two access patterns:

  • Direct access: U::function_name() for commonly used functions
  • Namespaced access: U::ModuleName::function_name() for extended functionality

Getting Started

Import and use the utilities:

#![allow(unused)]
fn main() {
use rustf::prelude::*;  // Includes U
// or
use rustf::U;

// Direct access - commonly used functions
let id = U::guid();
let encoded = U::encode("hello world");
let status = U::http_status(404); // "Not Found"
let hash = U::sha256("data");      // Secure hash function

// Namespaced access - extended functionality  
let slug = U::String::to_slug("Hello World!");
let html = U::Encoding::html_encode("<script>");
let duration = U::Parsing::parse_duration("1h", 0);
let md5_hash = U::Crypto::md5("data");  // Warning: Not secure
}

Available Utilities

The RustF utilities system provides two access patterns:

Direct Access Functions (U::function())

These are the most commonly used functions available directly through U:::

CategoryFunctionDescriptionExample
RandomU::guid()Generate UUID without hyphensU::guid() β†’ "a1b2c3d4e5f67890..."
U::random_string(len)Generate random alphanumeric stringU::random_string(8) β†’ "Kj8mN2pQ"
U::random_number(min, max)Generate random number in rangeU::random_number(1, 100) β†’ 42
HTTPU::http_status(code)Get HTTP status textU::http_status(404) β†’ "Not Found"
U::etag(content)Generate ETag for contentU::etag("hello") β†’ "5d41402a..."
U::get_content_type(ext)Get MIME type by extensionU::get_content_type("json") β†’ "application/json"
EncodingU::encode(str)URL encode stringU::encode("hello world") β†’ "hello%20world"
U::decode(str)URL decode stringU::decode("hello%20world") β†’ "hello world"
U::btoa(str)Base64 encodeU::btoa("hello") β†’ "aGVsbG8="
U::atob(str)Base64 decodeU::atob("aGVsbG8=") β†’ "hello"
StringU::trim(str)Clean whitespaceU::trim(" hello ") β†’ "hello"
U::keywords(text, max, min_len)Extract keywordsU::keywords("hello world", 10, 3) β†’ ["hello", "world"]
ParsingU::parse_bool(str, default)Parse boolean safelyU::parse_bool("true", false) β†’ true
U::parse_int(str, default)Parse integer safelyU::parse_int("123", 0) β†’ 123
U::parse_float(str, default)Parse float safelyU::parse_float("12.34", 0.0) β†’ 12.34
JSONU::get(obj, path)Get nested propertyU::get(&data, "user.name") β†’ Some(&Value)
U::set(obj, path, value)Set nested propertyU::set(&mut data, "user.name", json!("John"))
GeographicU::distance(lat1, lon1, lat2, lon2)Distance in kilometersU::distance(40.7, -74.0, 34.0, -118.2) β†’ 3944.42
CryptoU::md5(str)MD5 hash ⚠️ Not secureU::md5("hello world") β†’ "5eb63bbbe01..."
U::sha256(str)SHA256 hash (secure)U::sha256("hello world") β†’ "b94d27b993..."
PaginationU::paginate(total, page, per_page, url_pattern)Create pagination objectU::paginate(100, 2, 20, "/users?page={0}".to_string())
U::pagination_from_paged_result(paged_result, url_pattern)Convert PagedResult to PaginationU::pagination_from_paged_result(&result, "/users?page={0}".to_string())

Total: 22 direct access functions

Namespaced Access Functions (U::Module::function())

Extended functionality is available through nested modules:

Random Generation

Generate UUIDs

#![allow(unused)]
fn main() {
// Generate a simple UUID (without hyphens) - Direct access
let id = U::guid();
println!("ID: {}", id); // e.g., "a1b2c3d4e5f67890abcdef1234567890"

// Generate UUID with hyphens - Extended access
let uuid = U::Random::generate_guid_with_hyphens();
println!("UUID: {}", uuid); // e.g., "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
}

Generate Random Strings

#![allow(unused)]
fn main() {
// Generate random alphanumeric string - Direct access
let token = U::random_string(32);
println!("Token: {}", token); // e.g., "Kj8mN2pQ5rT9wX3yZ7aB4cD6fG1hI0kL"

// Use for session tokens, API keys, etc.
let api_key = U::random_string(64);
let session_id = U::random_string(16);

// Generate with custom character set - Extended access
let numeric_code = U::Random::generate_random_string_with_charset(6, "0123456789");
let secure_token = U::Random::generate_secure_token(32); // Cryptographically secure
}

Generate Random Numbers

#![allow(unused)]
fn main() {
// Generate random number in range (inclusive)
let dice = U::random_number(1, 6);
let port = U::random_number(8000, 9000);
let user_id = U::random_number(1000, 99999);
}

HTTP Utilities

Status Code Helpers

#![allow(unused)]
fn main() {
// Get human-readable status text
let status = U::http_status(200);  // "OK"
let error = U::http_status(404);   // "Not Found"
let server_error = U::http_status(500); // "Internal Server Error"

// Use in responses
async fn not_found(ctx: &mut Context) -> Result<()> {
    let message = U::http_status(404);
    ctx.throw404(Some(message))
}
}

ETag Generation

#![allow(unused)]
fn main() {
// Generate ETags for content caching
let content = "Hello, World!";
let etag = U::etag(content);

// Use in HTTP responses
async fn cached_content(ctx: &mut Context) -> Result<()> {
    let content = get_content();
    let etag = U::etag(&content);
    
    ctx.add_header("ETag", etag);
    ctx.plain(content)
}
}

MIME Type Detection

#![allow(unused)]
fn main() {
// Get content type by file extension
let html_type = U::get_content_type("html");   // "text/html"
let json_type = U::get_content_type("json");   // "application/json"
let css_type = U::get_content_type("css");     // "text/css"
let js_type = U::get_content_type("js");       // "application/javascript"

// Use when sending generated bytes
async fn export(ctx: &mut Context) -> Result<()> {
    let format = ctx.param_str("format")?; // e.g. "csv" or "json"
    let content = build_export(&format)?; // your own code
    ctx.binary(content, U::get_content_type(&format), None)
}

// To serve a file named by the request, never hand the parameter to
// `std::fs` (`../../etc/passwd`): `file_inline_from` / `file_download_from`
// confine the path to a base directory and set the content type themselves.
async fn serve_file(ctx: &mut Context) -> Result<()> {
    let filename = ctx.param_str("filename")?;
    ctx.file_inline_from("storage/public", &filename).await
}
}

Encoding & Decoding

URL Encoding

#![allow(unused)]
fn main() {
// URL encode strings - Direct access
let encoded = U::encode("hello world");
assert_eq!(encoded, "hello%20world");

let encoded = U::encode("user@example.com");
assert_eq!(encoded, "user%40example.com");

// URL decode strings - Direct access
let decoded = U::decode("hello%20world")?;
assert_eq!(decoded, "hello world");

// Extended encoding functions - Namespaced access
let html = U::Encoding::html_encode("<script>alert('xss')</script>");
let hex = U::Encoding::hex_encode(&[255, 0, 128]);  // "ff0080"
let base64_url = U::Encoding::base64_url_encode("data");

// Use in URL building
fn build_search_url(query: &str) -> String {
    format!("/search?q={}", U::encode(query))
}
}

Base64 Encoding

#![allow(unused)]
fn main() {
// Base64 encode (btoa = binary to ASCII)
let encoded = U::btoa("hello");
println!("Base64: {}", encoded); // "aGVsbG8="

// Base64 decode (atob = ASCII to binary)
let decoded = U::atob("aGVsbG8=")?;
assert_eq!(decoded, "hello");

// Use for API tokens, data encoding
let token = U::btoa(&format!("{}:{}", username, password));
}

String Processing

Text Cleaning

#![allow(unused)]
fn main() {
// Clean and normalize text - Direct access
let messy = "  hello    world  \n\t";
let clean = U::trim(messy);
assert_eq!(clean, "hello world");

// Extended string functions - Namespaced access
let slug = U::String::to_slug("Hello World!");        // "hello-world"
let camel = U::String::to_camel_case("hello world");   // "helloWorld"
let pascal = U::String::to_pascal_case("hello world"); // "HelloWorld"
let snake = U::String::to_snake_case("Hello World");   // "hello_world"
let title = U::String::title_case("hello world");      // "Hello World"
let truncated = U::String::truncate("Long text here", 10); // "Long te..."

// Use for user input processing
async fn process_comment(ctx: &mut Context) -> Result<()> {
    let raw_comment = ctx.body_str("comment")?;
    let clean_comment = U::trim(&raw_comment);
    
    // Save clean comment to database
    save_comment(&clean_comment).await?;
    ctx.redirect("/comments")
}
}

Keyword Extraction

#![allow(unused)]
fn main() {
// Extract keywords for search indexing
let text = "This is a sample blog post about web development";
let keywords = U::keywords(text, 10, 3);
// Returns: ["sample", "blog", "post", "web", "development"]
// (excludes common words like "This", "is", "a", "about")

// Use for content indexing
async fn create_post(ctx: &mut Context) -> Result<()> {
    let title = ctx.body_str("title")?;
    let content = ctx.body_str("content")?;
    
    // Extract keywords for search
    let search_keywords = U::keywords(&format!("{} {}", title, content), 20, 4);
    
    let post = Post {
        title,
        content,
        keywords: search_keywords.join(", "),
        ..Default::default()
    };
    
    post.save().await?;
    ctx.redirect("/posts")
}
}

Safe Parsing

Parse strings with fallback values using direct access for common types, or namespaced access for extended parsing:

Boolean Parsing

#![allow(unused)]
fn main() {
// Parse booleans safely
let enabled = U::parse_bool("true", false);   // true
let disabled = U::parse_bool("false", true);  // false
let default = U::parse_bool("invalid", false); // false (fallback)

// Use with form data
async fn update_settings(ctx: &mut Context) -> Result<()> {
    let notifications = U::parse_bool(&ctx.body_str_or("notifications", ""), false);
    let public_profile = U::parse_bool(&ctx.body_str_or("public", ""), true);
    
    update_user_settings(notifications, public_profile).await?;
    ctx.redirect("/settings")
}
}

Number Parsing

#![allow(unused)]
fn main() {
// Parse integers safely - Direct access
let page = U::parse_int("5", 1);        // 5
let invalid = U::parse_int("abc", 1);   // 1 (fallback)
let limit = U::parse_int("100", 10);    // 100

// Parse floats safely - Direct access
let price = U::parse_float("19.99", 0.0);    // 19.99
let invalid = U::parse_float("abc", 0.0);    // 0.0 (fallback)

// Extended parsing functions - Namespaced access
let duration = U::Parsing::parse_duration("1h", 0);     // 3600 seconds
let size = U::Parsing::parse_size("1MB", 0);            // 1048576 bytes
let percent = U::Parsing::parse_percentage("75%", 0.0); // 0.75
let unsigned = U::Parsing::parse_unsigned_integer("123", 0); // 123
let comma_separated = U::Parsing::parse_comma_separated("a,b,c"); // ["a", "b", "c"]

// Use with query parameters
async fn list_products(ctx: &mut Context) -> Result<()> {
    let page = U::parse_int(&ctx.query_str_or("page", ""), 1);
    let limit = U::parse_int(&ctx.query_str_or("limit", ""), 10);
    let min_price = U::parse_float(&ctx.query_str_or("min_price", ""), 0.0);
    
    let products = Product::paginate(page, limit)
        .where_gte("price", min_price)
        .get().await?;
    
    ctx.view("/products/list", json!({
        "products": products,
        "page": page,
        "limit": limit
    }))
}
}

JSON Object Manipulation

Getting Nested Values

#![allow(unused)]
fn main() {
use serde_json::json;

// Get nested properties safely
let data = json!({
    "user": {
        "profile": {
            "name": "John Doe",
            "age": 30
        },
        "settings": {
            "theme": "dark"
        }
    }
});

let name = U::get(&data, "user.profile.name");
// Returns: Some(&Value::String("John Doe"))

let theme = U::get(&data, "user.settings.theme");
// Returns: Some(&Value::String("dark"))

let missing = U::get(&data, "user.profile.email");
// Returns: None

// Use in templates or API responses
async fn user_profile(ctx: &mut Context) -> Result<()> {
    let user_data = get_user_data().await?;
    
    let display_name = U::get(&user_data, "profile.display_name")
        .and_then(|v| v.as_str())
        .unwrap_or("Anonymous");
    
    ctx.view("/profile", json!({
        "name": display_name,
        "data": user_data
    }))
}
}

Setting Nested Values

#![allow(unused)]
fn main() {
// Set nested properties
let mut data = json!({});

// Creates nested structure automatically
U::set(&mut data, "user.name", json!("Jane"))?;
U::set(&mut data, "user.profile.age", json!(25))?;
U::set(&mut data, "settings.theme", json!("light"))?;

// Result:
// {
//   "user": {
//     "name": "Jane",
//     "profile": {
//       "age": 25
//     }
//   },
//   "settings": {
//     "theme": "light"
//   }
// }

// Use for dynamic data building
async fn build_user_response(user: &User) -> Result<Value> {
    let mut response = json!({});
    
    U::set(&mut response, "user.id", json!(user.id))?;
    U::set(&mut response, "user.name", json!(user.name))?;
    U::set(&mut response, "user.email", json!(user.email))?;
    U::set(&mut response, "meta.timestamp", json!(chrono::Utc::now()))?;
    
    Ok(response)
}
}

Geographic Utilities

Distance Calculation

#![allow(unused)]
fn main() {
// Calculate distance between two points in kilometers - Direct access
let ny_lat = 40.7128;
let ny_lon = -74.0060;
let la_lat = 34.0522;
let la_lon = -118.2437;

let distance = U::distance(ny_lat, ny_lon, la_lat, la_lon);
println!("Distance: {:.2} km", distance); // Distance: 3944.42 km

// Extended geographic functions - Namespaced access
let distance_miles = U::Geo::distance_miles(ny_lat, ny_lon, la_lat, la_lon);
let is_in_bounds = U::Geo::in_bounds(40.7, -74.0, 40.0, 41.0, -75.0, -73.0);
let bearing = U::Geo::bearing(ny_lat, ny_lon, la_lat, la_lon);

// Use for location-based features
async fn find_nearby_stores(ctx: &mut Context) -> Result<()> {
    let user_lat = U::parse_float(&ctx.query_str_or("lat", ""), 0.0);
    let user_lon = U::parse_float(&ctx.query_str_or("lon", ""), 0.0);
    
    let stores = get_all_stores().await?;
    let mut nearby_stores = Vec::new();
    
    for store in stores {
        let distance = U::distance(user_lat, user_lon, store.lat, store.lon);
        if distance <= 50.0 { // Within 50km
            nearby_stores.push((store, distance));
        }
    }
    
    // Sort by distance
    nearby_stores.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap());
    
    ctx.json(&json!({
        "stores": nearby_stores.into_iter()
            .map(|(store, dist)| json!({
                "store": store,
                "distance": dist
            }))
            .collect::<Vec<_>>()
    }))
}
}

Cryptographic Hash Functions

RustF provides secure hash functions accessible both directly and through the Crypto namespace:

#![allow(unused)]
fn main() {
// Direct access to most common hash functions
let md5_hash = U::md5("hello world");        // ⚠️ Warning: MD5 not secure
let sha256_hash = U::sha256("hello world");  // βœ… Secure hash function

// Extended access to all hash functions via U::Crypto::
let sha1_hash = U::Crypto::sha1("data");       // ⚠️ Warning: SHA1 not secure  
let sha512_hash = U::Crypto::sha512("data");   // βœ… Very secure hash function

// Hash from byte arrays
let hash_from_bytes = U::Crypto::md5_bytes(&[1, 2, 3, 4, 5]);
let secure_hash_bytes = U::Crypto::sha256_bytes(b"binary data");

// Other crypto utilities
let hash_code = U::Crypto::hash_string("data");           // Fast non-crypto hash
let is_equal = U::Crypto::constant_time_compare("a", "b"); // Timing-safe comparison
let checksum = U::Crypto::simple_checksum("integrity check");

// Simple obfuscation (not encryption!)
let obfuscated = U::Crypto::obfuscate_string("secret", 5);
let deobfuscated = U::Crypto::deobfuscate_string(&obfuscated, 5);

// Basic XOR encryption/decryption (not secure - for obfuscation only)
let encrypted = U::Crypto::xor_encrypt("message", "key");
let decrypted = U::Crypto::xor_decrypt(&encrypted, "key");
}

Security Notice: MD5 and SHA1 are cryptographically broken and should not be used for security purposes. Use SHA256 or higher for security-sensitive applications.

Common Usage Patterns

Form Processing

#![allow(unused)]
fn main() {
async fn process_form(ctx: &mut Context) -> Result<()> {
    // Safe parsing with defaults - Direct access
    let name = U::trim(&ctx.body_str_or("name", ""));
    let age = U::parse_int(&ctx.body_str_or("age", ""), 0);
    let email = U::trim(&ctx.body_str_or("email", ""));
    let newsletter = U::parse_bool(&ctx.body_str_or("newsletter", ""), false);
    
    // Extended validation using namespaced functions
    let clean_email = U::String::strip_html(&email);
    let email_slug = U::String::to_slug(&name); // For URL-friendly usernames
    
    if name.is_empty() || age <= 0 {
        ctx.flash_error("Please fill in all required fields")?;
        return ctx.redirect("/form");
    }
    
    // Create user with secure hash for verification tokens
    let user_id = U::guid();
    let verification_token = U::sha256(&format!("{}:{}", user_id, email));
    
    let user = User {
        id: user_id,
        name,
        age,
        email: clean_email,
        newsletter_subscribed: newsletter,
        verification_token,
    };
    
    user.save().await?;
    ctx.flash_success("User created successfully!")?;
    ctx.redirect("/users")
}
}

API Response Building

#![allow(unused)]
fn main() {
async fn api_user_list(ctx: &mut Context) -> Result<()> {
    // Parse pagination parameters safely - Direct access
    let page = U::parse_int(&ctx.query_str_or("page", ""), 1);
    let limit = U::parse_int(&ctx.query_str_or("limit", ""), 10);
    
    // Extended parsing for filtering - Namespaced access  
    let search = U::String::trim(&ctx.query_str_or("search", ""));
    let sort_order = U::Parsing::parse_enum(&ctx.query_str_or("sort", ""), SortOrder::Asc);
    
    let users = User::paginate(page, limit).await?;
    let total = User::count().await?;
    
    // Build response with utilities - Direct access for JSON manipulation
    let mut response = json!({});
    U::set(&mut response, "data", json!(users))?;
    U::set(&mut response, "pagination.page", json!(page))?;
    U::set(&mut response, "pagination.limit", json!(limit))?;
    U::set(&mut response, "pagination.total", json!(total))?;
    U::set(&mut response, "meta.request_id", json!(U::guid()))?;
    U::set(&mut response, "meta.timestamp", json!(chrono::Utc::now()))?;
    
    // Extended object manipulation - Namespaced access
    let has_filters = U::Object::has_nested_property(&response, "filters");
    if !search.is_empty() {
        U::set(&mut response, "filters.search", json!(search))?;
    }
    
    // Generate ETag for caching - Direct access
    let content = response.to_string();
    let etag = U::etag(&content);
    
    ctx.add_header("ETag", etag);
    ctx.json(&response)
}
}

Search and Filtering

#![allow(unused)]
fn main() {
async fn search_content(ctx: &mut Context) -> Result<()> {
    // Basic input processing - Direct access
    let query = U::trim(&ctx.query_str_or("q", ""));
    let category = ctx.query_str_or("category", "");
    
    // Extended string processing - Namespaced access
    let clean_query = U::String::strip_html(&query);
    let query_slug = U::String::to_slug(&clean_query);
    
    if clean_query.is_empty() {
        return ctx.view("/search", json!({
            "message": "Please enter a search term"
        }));
    }
    
    // Extract search keywords - Direct access
    let search_terms = U::keywords(&clean_query, 10, 3);
    
    // Generate search hash for caching - Direct access
    let search_hash = U::sha256(&format!("{}:{}", clean_query, category));
    
    // Build search results
    let results = search_posts(&search_terms, &category).await?;
    
    // Extended parsing for result formatting - Namespaced access
    let result_limit = U::parse_int(&ctx.query_str_or("limit", ""), 10);
    let truncated_results: Vec<_> = results.into_iter()
        .take(result_limit as usize)
        .map(|mut post| {
            // Truncate content for search results
            post.content = U::String::truncate_words(&post.content, 100);
            post
        })
        .collect();
    
    ctx.view("/search", json!({
        "query": clean_query,
        "results": truncated_results,
        "keywords": search_terms,
        "total": truncated_results.len(),
        "search_hash": search_hash
    }))
}
}

File Upload Processing

#![allow(unused)]
fn main() {
async fn handle_upload(ctx: &mut Context) -> Result<()> {
    // Clone the upload so `ctx` is free again for the response calls below
    let file = match ctx.file("upload")? {
        Some(file) => file.clone(),
        None => return ctx.throw400(Some("No file uploaded")),
    };
    
    // Generate unique filename - Direct access
    let file_id = U::guid();
    let original_name = file.filename.clone().unwrap_or("upload".to_string());
    let extension = original_name.split('.').last().unwrap_or("bin");
    
    // Extended string processing - Namespaced access
    let safe_original_name = U::String::strip_html(&original_name);
    let filename_slug = U::String::to_slug(&safe_original_name);
    let secure_token = U::Random::generate_secure_token(16);
    let new_filename = format!("{}_{}_{}.{}", file_id, filename_slug, secure_token, extension);
    
    // Get content type and validate - Direct and namespaced access
    let content_type = U::get_content_type(extension);
    let is_valid_type = U::Http::is_success_status(200); // Example validation
    
    // Generate file hash for integrity checking - Direct access
    let file_hash = U::sha256(&format!("{:?}", file.data));
    
    // Extended parsing for file size - Namespaced access
    let max_size = U::Parsing::parse_size("10MB", 10485760); // 10MB default
    if file.data.len() > max_size as usize {
        return ctx.json(&json!({
            "error": "File too large",
            "max_size": format!("{}MB", max_size / 1048576)
        }));
    }
    
    // Save file metadata with enhanced information
    let file_record = FileRecord {
        id: file_id.clone(),
        original_name: safe_original_name,
        filename: new_filename.clone(),
        content_type: content_type.to_string(),
        size: file.data.len(),
        hash: file_hash,
        upload_token: secure_token,
        ..Default::default()
    };
    
    // Save to storage and database
    save_file(&new_filename, &file.data).await?;
    file_record.save().await?;
    
    ctx.json(&json!({
        "success": true,
        "file_id": file_id,
        "filename": new_filename,
        "size": file.data.len(),
        "content_type": content_type
    }))
}
}

Best Practices

Error Handling

#![allow(unused)]
fn main() {
// Always handle potential errors from parsing
match U::decode(&encoded_value) {
    Ok(decoded) => process_value(&decoded),
    Err(_) => {
        log::warn!("Failed to decode value: {}", encoded_value);
        use_default_value()
    }
}

// Or use parsing utilities with safe defaults
let safe_value = U::parse_int(&user_input, 0);
}

Performance Considerations

#![allow(unused)]
fn main() {
// Cache expensive operations
static KEYWORDS_CACHE: OnceCell<HashMap<String, Vec<String>>> = OnceCell::new();

fn get_cached_keywords(text: &str) -> Vec<String> {
    let cache = KEYWORDS_CACHE.get_or_init(HashMap::new);
    
    if let Some(cached) = cache.get(text) {
        return cached.clone();
    }
    
    let keywords = U::keywords(text, 20, 4);
    // In real implementation, you'd update the cache here
    keywords
}
}

Security

#![allow(unused)]
fn main() {
// Always validate and sanitize user input
async fn update_profile(ctx: &mut Context) -> Result<()> {
    let name = U::trim(&ctx.body_str_or("name", ""));
    let bio = U::trim(&ctx.body_str_or("bio", ""));
    
    // Validate lengths
    if name.len() > 100 {
        return ctx.json(&json!({
            "error": "Name too long"
        }));
    }
    
    if bio.len() > 1000 {
        return ctx.json(&json!({
            "error": "Bio too long"  
        }));
    }
    
    // Update user...
    ctx.json(json!({"success": true}))
}
}

Summary

The RustF utilities system provides comprehensive utility functions organized in a dual-access pattern:

Core Features

  • Random generation - UUIDs, strings, numbers, secure tokens
  • HTTP utilities - Status codes, ETags, MIME types, response validation
  • String processing - Cleaning, keyword extraction, case conversion, HTML stripping
  • Encoding/decoding - URL encoding, Base64, HTML entities, hexadecimal
  • Safe parsing - Numbers, booleans, durations, sizes, percentages with defaults
  • JSON manipulation - Get/set nested properties, deep merging, object flattening
  • Geographic calculations - Distance between coordinates, boundary checking, bearing
  • Cryptographic functions - MD5, SHA1, SHA256, SHA512 hashing, secure comparisons

Access Patterns

The RustF utilities system provides both direct access (U::function_name()) for commonly used functions and namespaced access (U::ModuleName::function_name()) for extended functionality.

Key Achievement: The exact U::ModuleName::function() syntax that was requested now works perfectly, providing powerful, organized access to all utility functions throughout your RustF application.

Security Features

  • βœ… Secure hash functions (SHA256, SHA512)
  • ⚠️ Legacy hash functions (MD5, SHA1) with clear warnings
  • πŸ”’ Timing-safe comparisons for sensitive data
  • πŸ›‘οΈ Input sanitization and validation helpers
  • πŸ” Cryptographically secure token generation

Use the utilities system to build secure, maintainable web applications with consistent, predictable utility functions that follow Rust best practices and web development standards.

U::Random:: - Random Generation (Extended)

#![allow(unused)]
fn main() {
U::Random::generate_guid_with_hyphens()           // UUID with hyphens
U::Random::generate_random_string_with_charset(len, charset) // Custom character set
U::Random::generate_random_float(min, max)        // Random float
U::Random::generate_random_text(word_count)       // Lorem ipsum text
U::Random::generate_secure_token(byte_len)        // Cryptographically secure token
}

U::Encoding:: - Encoding (Extended)

#![allow(unused)]
fn main() {
U::Encoding::encode_with_safe(str, safe_chars)    // URL encode with safe characters
U::Encoding::btoa_bytes(bytes)                    // Base64 encode bytes
U::Encoding::base64_decode_bytes(str)             // Base64 decode to bytes
U::Encoding::base64_url_encode(str)               // URL-safe base64 encode
U::Encoding::base64_url_decode(str)               // URL-safe base64 decode
U::Encoding::html_encode(str)                     // HTML entity encode
U::Encoding::html_decode(str)                     // HTML entity decode
U::Encoding::json_encode(str)                     // JSON string escape
U::Encoding::hex_encode(bytes)                    // Hexadecimal encode
U::Encoding::hex_decode(str)                      // Hexadecimal decode
U::Encoding::query_encode(params)                 // Query string encode
U::Encoding::query_decode(query)                  // Query string decode
}

U::String:: - String Processing (Extended)

#![allow(unused)]
fn main() {
U::String::to_slug(str)           // Convert to URL slug
U::String::to_camel_case(str)     // Convert to camelCase
U::String::to_pascal_case(str)    // Convert to PascalCase
U::String::to_snake_case(str)     // Convert to snake_case
U::String::truncate(str, len)     // Truncate by character count
U::String::truncate_words(str, len) // Truncate by word count
U::String::word_count(str)        // Count words
U::String::title_case(str)        // Convert to Title Case
U::String::strip_html(str)        // Remove HTML tags
U::String::wrap_text(str, width)  // Wrap text to width
}

U::Parsing:: - Parsing (Extended)

#![allow(unused)]
fn main() {
U::Parsing::parse_unsigned_integer(str, default) // Parse u64
U::Parsing::parse_i32(str, default)              // Parse i32
U::Parsing::parse_f32(str, default)              // Parse f32
U::Parsing::parse_enum(str, default)             // Parse enum from string
U::Parsing::parse_comma_separated(str)           // Parse comma-separated values
U::Parsing::parse_comma_separated_integers(str, default) // Parse comma-separated integers
U::Parsing::parse_key_value(str, separator)      // Parse key=value pairs
U::Parsing::parse_duration(str, default)         // Parse duration (1h, 30m, etc.)
U::Parsing::parse_size(str, default)             // Parse size (1KB, 2MB, etc.)
U::Parsing::parse_percentage(str, default)       // Parse percentage
}

U::Crypto:: - Cryptographic Functions

#![allow(unused)]
fn main() {
// Hash functions (includes all direct access functions plus extended ones)
U::Crypto::md5(str)                    // MD5 hash ⚠️ Not secure
U::Crypto::md5_bytes(bytes)           // MD5 hash from bytes ⚠️ Not secure
U::Crypto::sha1(str)                  // SHA1 hash ⚠️ Not secure
U::Crypto::sha1_bytes(bytes)         // SHA1 hash from bytes ⚠️ Not secure
U::Crypto::sha256(str)               // SHA256 hash (secure)
U::Crypto::sha256_bytes(bytes)       // SHA256 hash from bytes (secure)
U::Crypto::sha512(str)               // SHA512 hash (secure)
U::Crypto::sha512_bytes(bytes)       // SHA512 hash from bytes (secure)

// Other crypto utilities
U::Crypto::hash_string(str)                      // Hash string (non-crypto)
U::Crypto::hash_bytes(bytes)                     // Hash bytes (non-crypto)
U::Crypto::xor_encrypt(data, key)                // XOR encrypt (not secure)
U::Crypto::xor_decrypt(data, key)                // XOR decrypt (not secure)
U::Crypto::simple_checksum(data)                 // Simple checksum
U::Crypto::constant_time_compare(a, b)           // Timing-safe string compare
U::Crypto::constant_time_compare_bytes(a, b)     // Timing-safe byte compare
U::Crypto::obfuscate_string(str, offset)         // Simple obfuscation
U::Crypto::deobfuscate_string(str, offset)       // Simple deobfuscation
}

U::Http:: - HTTP (Extended)

#![allow(unused)]
fn main() {
U::Http::generate_strong_etag(content, modified) // Strong ETag with timestamp
U::Http::get_extension_from_content_type(mime)   // Get extension from MIME type
U::Http::is_success_status(code)                 // Check if 2xx status
U::Http::is_client_error(code)                   // Check if 4xx status
U::Http::is_server_error(code)                   // Check if 5xx status
U::Http::is_redirect_status(code)                // Check if 3xx status
}

U::Object:: - Object Manipulation (Extended)

#![allow(unused)]
fn main() {
U::Object::remove_nested_property(obj, path)     // Remove nested property
U::Object::deep_merge(target, source)            // Deep merge objects
U::Object::shallow_merge(target, source)         // Shallow merge objects
U::Object::deep_clone(value)                     // Deep clone JSON value
U::Object::flatten_object(obj, prefix)           // Flatten nested object
U::Object::has_nested_property(obj, path)        // Check if property exists
U::Object::get_all_keys(obj)                     // Get all object keys
}

U::Geo:: - Geographic (Extended)

#![allow(unused)]
fn main() {
U::Geo::distance_miles(lat1, lon1, lat2, lon2)   // Distance in miles
U::Geo::in_bounds(lat, lon, min_lat, max_lat, min_lon, max_lon) // Check if in bounds
U::Geo::bearing(lat1, lon1, lat2, lon2)          // Calculate bearing/direction
}

Usage Patterns

The RustF utilities system supports three usage patterns:

#![allow(unused)]
fn main() {
use rustf::U;

// Most commonly used functions - direct access
let id = U::guid();
let encoded = U::encode("hello world");
let hash = U::sha256("secure data");
let parsed = U::parse_int("123", 0);
}

2. Namespaced Access (Extended Functionality)

#![allow(unused)]
fn main() {
use rustf::U;

// Extended functions through nested modules - exact syntax requested!
let slug = U::String::to_slug("Hello World!");
let html = U::Encoding::html_encode("<p>Hello</p>");
let size = U::Parsing::parse_size("1MB", 0);
let secure_token = U::Random::generate_secure_token(32);
let sha1_hash = U::Crypto::sha1("legacy data"); // Warning: Not secure
}

3. Module-Level Access (Alternative)

#![allow(unused)]
fn main() {
// Alternative approach - direct module imports
use rustf::utils::{string, encoding, parsing};

let slug = string::to_slug("Hello World!");
let html = encoding::html_encode("<p>Hello</p>");
let size = parsing::parse_size("1MB", 0);
}

Examples & Tutorials

This section contains step-by-step tutorials and real-world examples to help you build applications with RustF.

Available Examples

Building a REST API

Learn how to build a complete REST API with CRUD operations, validation, and error handling. This tutorial covers:

  • Creating API controllers
  • Request/response handling
  • Input validation
  • Error responses
  • Testing your API

Authentication

Implement user authentication in your RustF application. This guide covers:

  • User login and registration
  • Session management
  • Protected routes
  • Security best practices
  • Password hashing

Real-World Application

Build a complete blog application using all major RustF features:

  • User authentication
  • Blog post management
  • Comments system
  • Admin panel
  • Search functionality

Next Steps

After working through these examples:

Building a REST API

This tutorial shows you how to build a complete REST API with RustF, including CRUD operations, validation, and error handling.

Overview

We’ll build a REST API for managing blog posts with the following endpoints:

  • GET /api/posts - List all posts
  • GET /api/posts/{id} - Get a specific post
  • POST /api/posts - Create a new post
  • PUT /api/posts/{id} - Update a post
  • DELETE /api/posts/{id} - Delete a post

Project Setup

1. Create Controller

Create src/controllers/api/posts.rs:

#![allow(unused)]
fn main() {
use rustf::prelude::*;
use serde::{Deserialize, Serialize};

pub fn install() -> Vec<Route> {
    routes![
        GET    "/api/posts"       => list_posts,
        GET    "/api/posts/{id}"   => get_post,
        POST   "/api/posts"       => create_post,
        PUT    "/api/posts/{id}"   => update_post,
        DELETE "/api/posts/{id}"   => delete_post,
    ]
}
}

2. Define Data Structures

#![allow(unused)]
fn main() {
#[derive(Serialize, Deserialize, Clone)]
struct Post {
    id: Option<i32>,
    title: String,
    content: String,
    author: String,
    published: bool,
    created_at: Option<String>,
}

#[derive(Deserialize)]
struct CreatePostRequest {
    title: String,
    content: String,
    author: String,
    published: Option<bool>,
}

#[derive(Deserialize)]
struct UpdatePostRequest {
    title: Option<String>,
    content: Option<String>,
    author: Option<String>,
    published: Option<bool>,
}
}

Implementation

List Posts

#![allow(unused)]
fn main() {
async fn list_posts(ctx: &mut Context) -> Result<()> {
    // Parse pagination parameters
    let page = ctx.int_query_or("page", 1);
    let limit = ctx.int_query_or("limit", 10);
    let offset = (page - 1) * limit;
    
    // In a real app, fetch from database
    let posts = vec![
        Post {
            id: Some(1),
            title: "First Post".to_string(),
            content: "Content here".to_string(),
            author: "Alice".to_string(),
            published: true,
            created_at: Some("2024-01-01T00:00:00Z".to_string()),
        },
        // ... more posts
    ];
    
    ctx.json(json!({
        "posts": posts,
        "pagination": {
            "page": page,
            "limit": limit,
            "total": posts.len(),
            "total_pages": (posts.len() as f64 / limit as f64).ceil() as i32
        }
    }))
}
}

Get Single Post

#![allow(unused)]
fn main() {
async fn get_post(ctx: &mut Context) -> Result<()> {
    let post_id = ctx.param_as::<i64>("id")?;
    
    // In a real app, fetch from database
    if post_id == 1 {
        let post = Post {
            id: Some(1),
            title: "First Post".to_string(),
            content: "Content here".to_string(),
            author: "Alice".to_string(),
            published: true,
            created_at: Some("2024-01-01T00:00:00Z".to_string()),
        };
        
        ctx.json(json!({
            "success": true,
            "post": post
        }))
    } else {
        ctx.throw404(Some("Post not found"))
    }
}
}

Create Post

#![allow(unused)]
fn main() {
async fn create_post(ctx: &mut Context) -> Result<()> {
    let request: CreatePostRequest = ctx.body_json()?;
    
    // Validation
    if request.title.trim().is_empty() {
        return ctx.throw400(Some("Title is required"));
    }
    
    if request.content.trim().is_empty() {
        return ctx.throw400(Some("Content is required"));
    }
    
    if request.author.trim().is_empty() {
        return ctx.throw400(Some("Author is required"));
    }
    
    // In a real app, save to database
    let post = Post {
        id: Some(2), // Generated by database
        title: request.title,
        content: request.content,
        author: request.author,
        published: request.published.unwrap_or(false),
        created_at: Some(chrono::Utc::now().to_rfc3339()),
    };
    
    ctx.status(hyper::StatusCode::CREATED);
    ctx.json(json!({
        "success": true,
        "message": "Post created successfully",
        "post": post
    }))
}
}

Update Post

#![allow(unused)]
fn main() {
async fn update_post(ctx: &mut Context) -> Result<()> {
    let post_id = ctx.param_as::<i64>("id")?;
    let request: UpdatePostRequest = ctx.body_json()?;
    
    // In a real app, fetch and update in database
    if post_id == 1 {
        let mut post = Post {
            id: Some(1),
            title: "First Post".to_string(),
            content: "Content here".to_string(),
            author: "Alice".to_string(),
            published: true,
            created_at: Some("2024-01-01T00:00:00Z".to_string()),
        };
        
        // Apply updates
        if let Some(title) = request.title {
            post.title = title;
        }
        if let Some(content) = request.content {
            post.content = content;
        }
        if let Some(author) = request.author {
            post.author = author;
        }
        if let Some(published) = request.published {
            post.published = published;
        }
        
        ctx.json(json!({
            "success": true,
            "message": "Post updated successfully",
            "post": post
        }))
    } else {
        ctx.throw404(Some("Post not found"))
    }
}
}

Delete Post

#![allow(unused)]
fn main() {
async fn delete_post(ctx: &mut Context) -> Result<()> {
    let post_id = ctx.param_as::<i64>("id")?;
    
    // In a real app, delete from database
    if post_id == 1 {
        ctx.json(json!({
            "success": true,
            "message": "Post deleted successfully",
            "deleted_id": post_id
        }))
    } else {
        ctx.throw404(Some("Post not found"))
    }
}
}

Testing the API

Using curl

# List posts
curl http://localhost:8000/api/posts

# Get single post
curl http://localhost:8000/api/posts/1

# Create post
curl -X POST http://localhost:8000/api/posts \
  -H "Content-Type: application/json" \
  -d '{
    "title": "New Post",
    "content": "Post content",
    "author": "Bob",
    "published": true
  }'

# Update post
curl -X PUT http://localhost:8000/api/posts/1 \
  -H "Content-Type: application/json" \
  -d '{
    "title": "Updated Title"
  }'

# Delete post
curl -X DELETE http://localhost:8000/api/posts/1

Error Handling

The API returns appropriate HTTP status codes:

  • 200 OK - Success
  • 201 Created - Resource created
  • 400 Bad Request - Validation error
  • 404 Not Found - Resource not found
  • 500 Internal Server Error - Server error

Error responses follow this format:

{
  "error": "Error message here"
}

Next Steps

Authentication Implementation

This guide shows how to implement authentication in a RustF application using sessions.

Overview

We’ll implement:

  • User login
  • User registration
  • Session management
  • Protected routes
  • Logout

Setup

1. Create Auth Controller

Create src/controllers/auth.rs:

#![allow(unused)]
fn main() {
use rustf::prelude::*;
use serde::Deserialize;

pub fn install() -> Vec<Route> {
    routes![
        GET  "/auth/login"    => view_login,
        POST "/auth/login"    => do_login,
        GET  "/auth/register" => view_register,
        POST "/auth/register" => do_register,
        POST "/auth/logout"   => do_logout,
    ]
}
}

2. Define Data Structures

#![allow(unused)]
fn main() {
#[derive(Deserialize)]
struct LoginForm {
    email: String,
    password: String,
}

#[derive(Deserialize)]
struct RegisterForm {
    name: String,
    email: String,
    password: String,
    password_confirm: String,
}
}

Implementation

Login View

#![allow(unused)]
fn main() {
async fn view_login(ctx: &mut Context) -> Result<()> {
    // Check if already logged in
    if ctx.has_session() {
        if let Some(session) = ctx.session() {
            if session.is_authenticated() {
                return ctx.redirect("/dashboard");
            }
        }
    }
    
    ctx.layout("")  // No layout for login page
       .view("/auth/login", json!({
           "title": "Login"
       }))
}
}

Login Handler

#![allow(unused)]
fn main() {
async fn do_login(ctx: &mut Context) -> Result<()> {
    let form: LoginForm = ctx.body_form_typed()?;
    
    // Validation
    if form.email.trim().is_empty() {
        ctx.flash_error("Email is required")?;
        return ctx.redirect("/auth/login");
    }
    
    if form.password.is_empty() {
        ctx.flash_error("Password is required")?;
        return ctx.redirect("/auth/login");
    }
    
    // In a real app, verify credentials against database
    // This is a simplified example
    if form.email == "admin@example.com" && form.password == "password123" {
        // Get or create session
        let session = ctx.require_session()?;
        
        // Store user data in session
        ctx.session_set("user", json!({
            "id": 1,
            "email": form.email,
            "name": "Admin User",
            "role": "admin"
        }))?;
        
        // Mark as authenticated
        ctx.login(1)?;
        
        ctx.flash_success("Login successful!")?;
        ctx.redirect("/dashboard")
    } else {
        ctx.flash_error("Invalid email or password")?;
        ctx.redirect("/auth/login")
    }
}
}

Registration View

#![allow(unused)]
fn main() {
async fn view_register(ctx: &mut Context) -> Result<()> {
    ctx.layout("")
       .view("/auth/register", json!({
           "title": "Create Account"
       }))
}
}

Registration Handler

#![allow(unused)]
fn main() {
async fn do_register(ctx: &mut Context) -> Result<()> {
    let form: RegisterForm = ctx.body_form_typed()?;
    
    // Validation
    if form.name.trim().is_empty() {
        ctx.flash_error("Name is required")?;
        return ctx.redirect("/auth/register");
    }
    
    if form.email.trim().is_empty() || !form.email.contains('@') {
        ctx.flash_error("Valid email is required")?;
        return ctx.redirect("/auth/register");
    }
    
    if form.password.len() < 8 {
        ctx.flash_error("Password must be at least 8 characters")?;
        return ctx.redirect("/auth/register");
    }
    
    if form.password != form.password_confirm {
        ctx.flash_error("Passwords do not match")?;
        return ctx.redirect("/auth/register");
    }
    
    // In a real app, create user in database
    // Hash password before storing
    
    ctx.flash_success("Account created successfully! Please login.")?;
    ctx.redirect("/auth/login")
}
}

Logout Handler

#![allow(unused)]
fn main() {
async fn do_logout(ctx: &mut Context) -> Result<()> {
    ctx.logout()?;
    ctx.flash_info("You have been logged out")?;
    ctx.redirect("/auth/login")
}
}

Protected Routes

Create Auth Middleware

Create src/middleware/auth.rs:

#![allow(unused)]
fn main() {
use rustf::prelude::*;
use async_trait::async_trait;

pub struct AuthMiddleware;

#[async_trait]
impl InboundMiddleware for AuthMiddleware {
    async fn process_request(&self, ctx: &mut Context) -> rustf::Result<InboundAction> {
        // Check if route requires authentication
        let path = ctx.path().to_string();
        let protected_paths = ["/dashboard", "/profile", "/settings"];

        if protected_paths.iter().any(|p| path.starts_with(p)) {
            let authenticated = ctx
                .session()
                .map(|s| s.is_authenticated())
                .unwrap_or(false);

            if !authenticated {
                // Not authenticated: set a redirect response on the context,
                // then stop the chain (Stop uses the response set on ctx).
                ctx.flash_error("Please login to access this page")?;
                ctx.redirect("/auth/login")?;
                return Ok(InboundAction::Stop);
            }
        }

        Ok(InboundAction::Continue)
    }
}

pub fn install(registry: &mut MiddlewareRegistry) {
    // Inbound-only middleware: register with register_inbound.
    registry.register_inbound("auth", AuthMiddleware);
}
}

Register Middleware

In src/main.rs:

#![allow(unused)]
fn main() {
let app = RustF::new()
    .controllers(auto_controllers!())
    .middleware_from(auto_middleware!());
}

Accessing User Data

In Controllers

#![allow(unused)]
fn main() {
async fn dashboard(ctx: &mut Context) -> Result<()> {
    // Get user from session
    let user: Option<serde_json::Value> = ctx.session_get("user");
    
    if let Some(user_data) = user {
        ctx.repository_set("user", user_data.clone());
        ctx.view("/dashboard/index", json!({
            "title": "Dashboard"
        }))
    } else {
        ctx.throw401(Some("Not authenticated"))
    }
}
}

In Templates

<!-- views/dashboard/index.html -->
@{if repository.user}
    <h1>Welcome, @{repository.user.name}!</h1>
    <p>Email: @{repository.user.email}</p>
    <p>Role: @{repository.user.role}</p>
@{fi}

Security Best Practices

  1. Password Hashing: Always hash passwords before storing

    #![allow(unused)]
    fn main() {
    use bcrypt;
    let hashed = bcrypt::hash(password, bcrypt::DEFAULT_COST)?;
    }
  2. Session Security: Tune session cookie and timeout settings in production

    [session]
    cookie_name = "rustf_session"
    same_site = "Strict"
    idle_timeout = 1800      # seconds of inactivity before expiry
    absolute_timeout = 28800 # max session lifetime in seconds
    
  3. CSRF Protection: Enable CSRF protection - See Security Guide

  4. Rate Limiting: Add rate limiting to login endpoints

  5. Input Validation: Always validate and sanitize user input

Next Steps

  • Add password reset functionality
  • Add email verification
  • Add two-factor authentication
  • Add role-based access control (RBAC)
  • Integrate with OAuth providers

Real-World Application Example

This guide demonstrates building a complete blog application with RustF, covering all major framework features.

Application Overview

We’ll build a blog application with:

  • User authentication
  • Blog post management
  • Comments system
  • Admin panel
  • Search functionality

Project Structure

blog-app/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ main.rs
β”‚   β”œβ”€β”€ controllers/
β”‚   β”‚   β”œβ”€β”€ home.rs
β”‚   β”‚   β”œβ”€β”€ auth.rs
β”‚   β”‚   β”œβ”€β”€ posts.rs
β”‚   β”‚   β”œβ”€β”€ comments.rs
β”‚   β”‚   └── admin/
β”‚   β”‚       └── dashboard.rs
β”‚   β”œβ”€β”€ models/
β”‚   β”‚   β”œβ”€β”€ users.rs
β”‚   β”‚   β”œβ”€β”€ posts.rs
β”‚   β”‚   └── comments.rs
β”‚   β”œβ”€β”€ modules/
β”‚   β”‚   β”œβ”€β”€ user_service.rs
β”‚   β”‚   └── post_service.rs
β”‚   └── middleware/
β”‚       └── auth.rs
β”œβ”€β”€ views/
β”‚   β”œβ”€β”€ layouts/
β”‚   β”‚   └── application.html
β”‚   β”œβ”€β”€ home/
β”‚   β”‚   └── index.html
β”‚   β”œβ”€β”€ posts/
β”‚   β”‚   β”œβ”€β”€ index.html
β”‚   β”‚   β”œβ”€β”€ show.html
β”‚   β”‚   └── create.html
β”‚   └── auth/
β”‚       β”œβ”€β”€ login.html
β”‚       └── register.html
└── config.toml

Main Application

src/main.rs

use rustf::prelude::*;

#[tokio::main]
async fn main() -> rustf::Result<()> {
    env_logger::init();
    
    let app = RustF::new()
        .controllers(auto_controllers!())
        .models(auto_models!())
        .middleware_from(auto_middleware!());
    
    println!("πŸš€ Blog application running at http://127.0.0.1:8000");
    app.start().await
}

Controllers

Home Controller

#![allow(unused)]
fn main() {
// src/controllers/home.rs
use rustf::prelude::*;

pub fn install() -> Vec<Route> {
    routes![
        GET "/" => index,
        GET "/search" => search,
    ]
}

async fn index(ctx: &mut Context) -> Result<()> {
    // Get recent posts
    let recent_posts = get_recent_posts(5)?;
    
    ctx.repository_set("recent_posts", json!(recent_posts));
    ctx.view("/home/index", json!({
        "title": "Welcome to My Blog"
    }))
}

async fn search(ctx: &mut Context) -> Result<()> {
    let query = ctx.query_str_or("q", "");
    
    if query.is_empty() {
        return ctx.redirect("/");
    }
    
    let results = search_posts(query)?;
    
    ctx.view("/home/search", json!({
        "title": format!("Search: {}", query),
        "query": query,
        "results": results
    }))
}
}

Posts Controller

#![allow(unused)]
fn main() {
// src/controllers/posts.rs
use rustf::prelude::*;

pub fn install() -> Vec<Route> {
    routes![
        GET  "/posts"          => index,
        GET  "/posts/{id}"     => show,
        GET  "/posts/create"   => create_form,
        POST "/posts"          => create,
        GET  "/posts/{id}/edit" => edit_form,
        PUT  "/posts/{id}"     => update,
        DELETE "/posts/{id}"   => delete,
    ]
}

async fn index(ctx: &mut Context) -> Result<()> {
    let page = ctx.int_query_or("page", 1);
    let posts = get_posts_paginated(page, 10)?;
    
    ctx.view("/posts/index", json!({
        "title": "All Posts",
        "posts": posts,
        "page": page
    }))
}

async fn show(ctx: &mut Context) -> Result<()> {
    let post_id = ctx.param_as::<i64>("id")?;
    let post = get_post_by_id(post_id)?;
    
    if post.is_none() {
        return ctx.throw404(Some("Post not found"));
    }
    
    let comments = get_comments_for_post(post_id)?;
    
    ctx.view("/posts/show", json!({
        "title": post.title.clone(),
        "post": post,
        "comments": comments
    }))
}

async fn create(ctx: &mut Context) -> Result<()> {
    // Require authentication
    ctx.require_auth()?;
    
    let form: CreatePostForm = ctx.body_form_typed()?;
    
    // Validation
    validate_post_form(&form)?;
    
    // Create post
    let post = create_new_post(&form, get_current_user_id(ctx)?)?;
    
    ctx.flash_success("Post created successfully!")?;
    ctx.redirect(&format!("/posts/{}", post.id))
}
}

Models

Post Model

#![allow(unused)]
fn main() {
// src/models/posts.rs
use rustf::prelude::*;

pub struct Posts {
    base: PostsBase,
}

impl Posts {
    pub fn new() -> Self {
        Self {
            base: PostsBase::new(),
        }
    }
    
    pub fn find_recent(&self, limit: i32) -> Result<Vec<Post>> {
        self.base.query()
            .where_eq("published", true)
            .order_by("created_at", OrderDirection::Desc)
            .limit(limit)
            .find()
    }
    
    pub fn search(&self, query: &str) -> Result<Vec<Post>> {
        self.base.query()
            .where_like("title", &format!("%{}%", query))
            .or_where_like("content", &format!("%{}%", query))
            .where_eq("published", true)
            .find()
    }
}
}

Modules

Post Service

#![allow(unused)]
fn main() {
// src/modules/post_service.rs
use rustf::prelude::*;

pub struct PostService;

impl PostService {
    pub fn create_post(&self, data: &CreatePostData, author_id: i32) -> Result<Post> {
        // Business logic for creating posts
        // Validation, formatting, etc.
    }
    
    pub fn can_edit(&self, post: &Post, user_id: i32) -> bool {
        post.author_id == user_id || is_admin(user_id)
    }
}

impl_shared_service!(PostService);
}

Middleware

Auth Middleware

#![allow(unused)]
fn main() {
// src/middleware/auth.rs
use rustf::prelude::*;

pub struct AuthMiddleware;

#[async_trait]
impl InboundMiddleware for AuthMiddleware {
    async fn process_request(&self, ctx: &mut Context) -> Result<InboundAction> {
        let path = ctx.path();

        // Protected paths (ctx.req.method is a String)
        if path.starts_with("/posts/create") ||
           (path.starts_with("/posts/") && ctx.req.method == "POST") {

            if !ctx.has_session() ||
               !ctx.session().map(|s| s.is_authenticated()).unwrap_or(false) {
                ctx.flash_error("Please login to continue")?;
                ctx.redirect("/auth/login")?;
                // Stop the chain; the redirect response set on ctx is used.
                return Ok(InboundAction::Stop);
            }
        }

        Ok(InboundAction::Continue)
    }
}

pub fn install(registry: &mut MiddlewareRegistry) {
    // Inbound-only middleware: register with register_inbound.
    registry.register_inbound("auth", AuthMiddleware);
}
}

Configuration

config.toml

[server]
host = "127.0.0.1"
port = 8000

[database]
url = "sqlite:blog.db"

[session]
cookie_name = "rustf_session"
same_site = "Lax"
idle_timeout = 1800
absolute_timeout = 28800

[views]
directory = "views"
cache_enabled = false
default_layout = "layouts/application"

Views

Layout

<!-- views/layouts/application.html -->
<!DOCTYPE html>
<html>
<head>
    <title>@{model.title} - My Blog</title>
    <link rel="stylesheet" href="/css/style.css">
</head>
<body>
    <nav>
        <a href="/">Home</a>
        <a href="/posts">Posts</a>
        @{if repository.user}
            <a href="/posts/create">New Post</a>
            <a href="/auth/logout">Logout</a>
        @{else}
            <a href="/auth/login">Login</a>
        @{fi}
    </nav>
    
    @{if flash.success}
        <div class="alert success">@{flash.success}</div>
    @{fi}
    
    @{if flash.error}
        <div class="alert error">@{flash.error}</div>
    @{fi}
    
    <main>
        {{@body}}
    </main>
</body>
</html>

Testing

Manual Testing

# Start server
cargo run

# Test endpoints
curl http://localhost:8000/
curl http://localhost:8000/posts
curl http://localhost:8000/posts/1

Integration Tests

#![allow(unused)]
fn main() {
#[cfg(test)]
mod tests {
    use super::*;
    
    #[tokio::test]
    async fn test_create_post() {
        // Test post creation
    }
    
    #[tokio::test]
    async fn test_search_posts() {
        // Test search functionality
    }
}
}

Deployment

See the Deployment Guide for production deployment instructions.

Next Steps

  • Add email notifications
  • Add RSS feed
  • Add social sharing
  • Add analytics
  • Add caching layer
  • Add CDN for static assets

Production Deployment

This guide covers deploying RustF applications to production environments.

Prerequisites

  • Rust 1.70+ installed
  • Production-ready database
  • Reverse proxy (nginx, Caddy, etc.)
  • SSL certificate (Let’s Encrypt recommended)

Build for Production

Release Build

# Build optimized release binary
cargo build --release

# Binary will be in target/release/your-app-name

Build Flags

For maximum optimization:

RUSTFLAGS="-C target-cpu=native" cargo build --release

Configuration

Deployment Layout

Place all files next to the binary β€” in release builds the binary looks for config.toml in the same directory as itself, not in the working directory:

/opt/myapp/
β”œβ”€β”€ myapp              ← binary
β”œβ”€β”€ config.toml        ← [app] environment = "production" set here
β”œβ”€β”€ config.prod.toml   ← production overrides, loaded automatically
β”œβ”€β”€ public/            ← static files
└── views/             ← templates (if using filesystem storage)

Production Config

In config.toml declare the environment under [app]:

[app]
environment = "production"   # triggers config.prod.toml overlay

[server]
host = "0.0.0.0"
port = 8080

Create config.prod.toml for production-specific overrides (merged on top of config.toml):

[server]
timeout = 60

[database]
url = "postgresql://user:pass@localhost/dbname"
max_connections = 20

[session]
idle_timeout = 7200
cookie_name = "app_session"

[views]
cache_enabled = true

[logging]
level = "warn"
file = "/var/log/app/error.log"

Environment Variables

Set environment variables:

export RUSTF_ENV=production
export DATABASE_URL=postgresql://user:pass@localhost/dbname
export SECRET_KEY=your-secret-key-here

Systemd Service

Create /etc/systemd/system/rustf-app.service:

[Unit]
Description=RustF Application
After=network.target

[Service]
Type=simple
User=www-data
WorkingDirectory=/opt/myapp
ExecStart=/opt/myapp/myapp
Restart=always
RestartSec=10
Environment="RUST_LOG=warn"

[Install]
WantedBy=multi-user.target

Note: RUSTF_ENV is not needed here β€” environment is declared via [app] environment = "production" in config.toml. The binary always finds config.toml next to itself regardless of the working directory.

Enable and start:

sudo systemctl enable rustf-app
sudo systemctl start rustf-app
sudo systemctl status rustf-app

Nginx Configuration

Reverse Proxy Setup

Create /etc/nginx/sites-available/rustf-app:

server {
    listen 80;
    server_name your-domain.com;
    
    # Redirect to HTTPS
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl http2;
    server_name your-domain.com;
    
    ssl_certificate /etc/letsencrypt/live/your-domain.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/your-domain.com/privkey.pem;
    
    # Security headers
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header X-XSS-Protection "1; mode=block" always;
    
    # Proxy to RustF app
    location / {
        proxy_pass http://127.0.0.1:8080;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_cache_bypass $http_upgrade;
    }
    
    # Static files
    location /static/ {
        alias /opt/rustf-app/public/;
        expires 30d;
        add_header Cache-Control "public, immutable";
    }
}

Enable site:

sudo ln -s /etc/nginx/sites-available/rustf-app /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl reload nginx

Database Setup

Apply schema changes

RustF is database-first: the live DB is the source of truth, not an ordered migration log. The supported flow is:

# 1. Define / update YAML schemas/<table>.yaml from your design.

# 2. Generate the full SQL DDL from the YAML (writes sql/schema.sql, a complete
#    CREATE TABLE snapshot of the whole schema, not an incremental diff/ALTER).
rustf-cli schema generate sql

# 3. Apply the generated SQL with your tool of choice (psql, mysql, sqlite3,
#    Flyway, Liquibase, etc.). RustF does not ship its own migration runner.

# 4. After the DB is updated, sync the YAML back from the live DB and
#    keep the canonical DDL in source control:
rustf-cli db generate-schema       # writes schemas/*.yaml + schemas/_database_dump.sql

For a one-off SQL dump without regenerating the YAML, use rustf-cli db dump-schema.

Backup Strategy

Set up regular database backups:

# PostgreSQL
pg_dump -U user dbname > backup_$(date +%Y%m%d).sql

# SQLite
cp db.sqlite backup_$(date +%Y%m%d).sqlite

Monitoring

Log Management

  • Use structured logging
  • Set up log rotation
  • Monitor error logs
  • Use log aggregation (ELK, Loki, etc.)

Health Checks

Add health check endpoint:

#![allow(unused)]
fn main() {
async fn health(ctx: &mut Context) -> Result<()> {
    // Check database connection
    let db_ok = check_database().is_ok();
    
    ctx.json(json!({
        "status": if db_ok { "healthy" } else { "unhealthy" },
        "database": if db_ok { "connected" } else { "disconnected" },
        "timestamp": chrono::Utc::now().to_rfc3339()
    }))
}
}

Metrics

Consider adding:

  • Request rate
  • Response times
  • Error rates
  • Database connection pool status

Security Checklist

  • Use HTTPS (SSL/TLS)
  • Set secure session cookies
  • Enable CSRF protection
  • Set security headers
  • Use environment variables for secrets
  • Keep dependencies updated
  • Use strong database passwords
  • Enable rate limiting
  • Set up firewall rules
  • Regular security audits

Performance Optimization

Enable View Caching

[views]
cache_enabled = true

Database Connection Pooling

[database]
max_connections = 50

Static File Serving

Serve static files via nginx/CDN, not the application.

Enable Compression

Configure nginx gzip:

gzip on;
gzip_types text/plain text/css application/json application/javascript;

Scaling

Horizontal Scaling

  • Use load balancer (nginx, HAProxy)
  • Use shared session storage (Redis)
  • Use shared database
  • Use CDN for static assets

Vertical Scaling

  • Increase server resources
  • Optimize database queries
  • Use connection pooling
  • Enable caching

Troubleshooting

Check Logs

# Application logs
sudo journalctl -u rustf-app -f

# Nginx logs
sudo tail -f /var/log/nginx/error.log

Common Issues

Issue: Application won’t start

  • Check systemd service status
  • Verify configuration file
  • Check database connection

Issue: 502 Bad Gateway

  • Check if app is running
  • Verify port configuration
  • Check firewall rules

Issue: Database connection errors

  • Verify database URL
  • Check database is running
  • Verify credentials

Next Steps

  • Set up CI/CD pipeline
  • Configure monitoring alerts
  • Set up automated backups
  • Plan for disaster recovery

Docker Deployment

This guide covers containerizing and deploying RustF applications with Docker.

Dockerfile

Multi-Stage Build

Create Dockerfile:

# Build stage
FROM rust:1.70 as builder

WORKDIR /app

# Copy dependency files
COPY Cargo.toml Cargo.lock ./
COPY rustf/Cargo.toml ./rustf/
COPY rustf-macros/Cargo.toml ./rustf-macros/

# Copy source code
COPY . .

# Build release binary
RUN cargo build --release

# Runtime stage
FROM debian:bookworm-slim

# Install runtime dependencies
RUN apt-get update && apt-get install -y \
    ca-certificates \
    libssl3 \
    && rm -rf /var/lib/apt/lists/*

WORKDIR /app

# Copy binary from builder
COPY --from=builder /app/target/release/rustf-app /app/rustf-app

# Copy configuration and static files
COPY config.toml ./
COPY views ./views
COPY public ./public

# Create non-root user
RUN useradd -m -u 1000 appuser && \
    chown -R appuser:appuser /app

USER appuser

EXPOSE 8000

CMD ["./rustf-app"]

Docker Compose

Create docker-compose.yml:

version: '3.8'

services:
  app:
    build: .
    ports:
      - "8000:8000"
    environment:
      - RUSTF_ENV=production
      - DATABASE_URL=postgresql://user:pass@db:5432/dbname
    depends_on:
      - db
      - redis
    volumes:
      - ./config.toml:/app/config.toml
      - ./views:/app/views
      - ./public:/app/public
    restart: unless-stopped

  db:
    image: postgres:15
    environment:
      - POSTGRES_USER=user
      - POSTGRES_PASSWORD=pass
      - POSTGRES_DB=dbname
    volumes:
      - postgres_data:/var/lib/postgresql/data
    restart: unless-stopped

  redis:
    image: redis:7-alpine
    volumes:
      - redis_data:/data
    restart: unless-stopped

volumes:
  postgres_data:
  redis_data:

Build and Run

Build Image

docker build -t rustf-app .

Run Container

docker run -d \
  -p 8000:8000 \
  -e RUSTF_ENV=production \
  -v $(pwd)/config.toml:/app/config.toml \
  --name rustf-app \
  rustf-app

Docker Compose

# Start all services
docker-compose up -d

# View logs
docker-compose logs -f

# Stop services
docker-compose down

Production Dockerfile

Optimized for production:

FROM rust:1.70 as builder

WORKDIR /app

# Install build dependencies
RUN apt-get update && apt-get install -y \
    pkg-config \
    libssl-dev \
    && rm -rf /var/lib/apt/lists/*

# Copy and build
COPY . .
RUN cargo build --release

FROM debian:bookworm-slim

RUN apt-get update && apt-get install -y \
    ca-certificates \
    libssl3 \
    && rm -rf /var/lib/apt/lists/* \
    && useradd -m -u 1000 appuser

WORKDIR /app

COPY --from=builder /app/target/release/rustf-app /app/
COPY --from=builder /app/config.toml ./
COPY --from=builder /app/views ./views
COPY --from=builder /app/public ./public

RUN chown -R appuser:appuser /app

USER appuser

EXPOSE 8000

HEALTHCHECK --interval=30s --timeout=3s \
  CMD curl -f http://localhost:8000/health || exit 1

CMD ["./rustf-app"]

.dockerignore

Create .dockerignore:

target/
.git/
.gitignore
*.md
.env
.env.local
*.log

Kubernetes

Deployment

Create k8s/deployment.yaml:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: rustf-app
spec:
  replicas: 3
  selector:
    matchLabels:
      app: rustf-app
  template:
    metadata:
      labels:
        app: rustf-app
    spec:
      containers:
      - name: rustf-app
        image: rustf-app:latest
        ports:
        - containerPort: 8000
        env:
        - name: RUSTF_ENV
          value: "production"
        - name: DATABASE_URL
          valueFrom:
            secretKeyRef:
              name: db-secret
              key: url
        resources:
          requests:
            memory: "256Mi"
            cpu: "250m"
          limits:
            memory: "512Mi"
            cpu: "500m"

Service

Create k8s/service.yaml:

apiVersion: v1
kind: Service
metadata:
  name: rustf-app
spec:
  selector:
    app: rustf-app
  ports:
  - port: 80
    targetPort: 8000
  type: LoadBalancer

Best Practices

  1. Use multi-stage builds to reduce image size
  2. Run as non-root user for security
  3. Use .dockerignore to exclude unnecessary files
  4. Set resource limits in production
  5. Use health checks for monitoring
  6. Keep images updated with security patches
  7. Use secrets management for sensitive data
  8. Enable logging for debugging

Troubleshooting

Container won’t start

# Check logs
docker logs rustf-app

# Run interactively
docker run -it rustf-app /bin/bash

Database connection issues

  • Verify database URL
  • Check network connectivity
  • Verify credentials

Performance issues

  • Increase resource limits
  • Enable connection pooling
  • Use caching layer