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

Welcome to Rullst Framework!

Rullst is an extremely fast, modular, and friendly Full-Stack web framework for Rust. It includes everything you need to take your application from scratch to production without headaches.

β€œPragmatic, Built for Developer Happiness, and Production-Ready.”

Documentation Hub

Why Rullst?

  • πŸš€ Extreme Speed: Built in Rust, using tokio and axum.
  • 🧩 Wasm Islands: Write client-side components in Rust.
  • πŸ“¦ Batteries Included: ORM (rullst-orm), Jobs, Mail, Scheduler, Cache.
  • πŸ›‘οΈ Strong Typing: Compile-time checking.
  • πŸ“‘ Lightweight Telemetry: OpenTelemetry traces behind a lightweight feature flag.

πŸ’‘ The Rullst Philosophy

Unlike other frameworks, Rullst strives to be simultaneously simple and complete, with a relentless focus on security and developer experience (DX).

The origins of this philosophy can be traced back to the very creation of the Rust programming language. The story goes that Graydon Hoare, the original creator of Rust, lived in an apartment building with an elevator that kept crashing due to software bugs in its underlying C/C++ code. Frustrated by having to climb the stairs because of memory safety vulnerabilities, he set out to create a language that was incredibly fast, yet guaranteed memory safety by designβ€”so that developers could build things that β€œjust worked” without fear.

Rullst was forged with this exact mindset. We believe that web development shouldn’t be a constant struggle against the framework, the language, or runtime bugs. Rullst is built for those who want to build with ease and safety, harnessing the raw speed and resource efficiency of Rust.

Our Core Tenets

  1. Simple yet Complete: We solve the hardest web development problems out-of-the-box securely (routing, auth, ORM, background jobs, hot-reloading), without sacrificing simplicity or completeness. You shouldn’t have to piece together 15 different micro-libraries just to build a secure SaaS.

  2. Built for Humans and AIs: Rullst is architected to be highly legible and free of runtime β€œmagic”. By heavily utilizing static dispatch and compile-time guarantees, the codebase is transparent. This empowers both human developers and AI coding agents to collaborate and build production-ready systems rapidly, even without deep prior framework knowledge.

Rullst is not just a tool; it is a commitment to Emotional Productivity. We take care of the boilerplate and the security pitfalls so you can focus entirely on creating value.

Getting Started

Welcome to the Rullst Getting Started guide!

Rullst is a blazing-fast, strictly-typed Full-Stack web framework designed to give you a pristine developer experience while prioritizing security and zero-allocation performance.

1. Installation

First, ensure you have Rust installed. The official and recommended way is to visit rustup.rs.

For macOS and Linux:

curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

For Windows: Download and run rustup-init.exe from the website.

Next, install the Rullst CLI. The CLI is the heart of the developer experience, handling scaffolding, static sites (RullstPress), database migrations, and more.

cargo install cargo-rullst

2. Creating Your First Project

We have completely redesigned the project creation experience. Instead of remembering complex flags, just run:

cargo rullst

The Rullst App Creator will launch an interactive wizard. Let’s create a beautiful Portfolio:

  1. Select Create New App.
  2. App Name: Provide a simple lowercase name (e.g., my_portfolio).
  3. Starter Blueprint: Choose Portfolio πŸ”₯ (showcase for Rullst/AI developers) - HOT.
cd my_portfolio
cargo rullst dev

Tip

The cargo rullst dev command automatically compiles your code and spins up a local server. If you edit any .rs file, it will instantly recompile using Hot Reload!

3. Rullst Blueprints Showcase

The Rullst framework accelerates your development by providing Blueprints. A Blueprint is a highly-polished, pre-built application template that serves as the foundation for your project.

When you run cargo rullst, the wizard will ask you to select a Blueprint. All Blueprints feature the official Rullst color scheme (Emerald Green and Orange) and are built with zero-allocation HTML macros and HTMX.

1. Blank Starter

Use Case: Custom, from-scratch development. This is the minimal template. It includes a simple HTMX reactive counter to demonstrate the frontend-backend communication, but leaves the rest entirely up to you.

2. Portfolio πŸ”₯

Use Case: Developer showcases and personal branding. Status: HOT! A visually stunning, glassmorphic portfolio template designed specifically for Rullst/AI developers. It includes:

  • A responsive Hero section with glowing text.
  • Project cards with hover animations.
  • A built-in contact form.

3. LMS Platform

Use Case: Online course platforms and video streaming. A complete learning management system featuring:

  • Courses and Lessons database models.
  • Migrations pre-populated with seed data.
  • A glassmorphic video player layout integrated with HTMX.

4. SaaS App Starter

Use Case: Subscription-based products and billing. The ultimate boilerplate for SaaS products, pre-wired with:

  • User authentication (login, signup, session management).
  • Stripe pricing panels and subscription checkout views.
  • Secure user dashboard.

5. Blog / Press

Use Case: Content creation and articles. A static site generator pre-wired with Nexus CMS. It features:

  • A beautiful article reading view with typography optimized for readability.
  • A fully functional Markdown parser engine.
  • SEO-friendly metadata injection.

6. Uptime Monitor

Use Case: Infrastructure tracking and observability. A robust system designed to ping URLs and track their health. It features:

  • A dashboard with live status indicators.
  • A background worker (rullst::runtime::spawn) that loops every minute to check endpoints.
  • Note: Background workers include a startup delay to ensure the database pool is fully initialized before querying.

7. ERP Pocket

Use Case: Business management, stock, and inventory tracking. A complete back-office suite out of the box. It features:

  • A complex relational database schema (Products and Orders).
  • Full CRUD operations with HTMX.
  • A sleek, split-pane dashboard for simultaneous product listing and order creation.

Tip

Blueprint Evolution: We are constantly refining our Blueprints. In version 2.0.1, all Blueprints were rigorously audited to ensure 100% macro syntax compliance (routes! and html!) and perfect database initialization order. You can build upon them with absolute confidence.

Rullst AI: Developing with Autonomous Agents

Rullst was designed from the ground up to be the first β€œAI-native” Rust framework. What does this mean in practice?

Traditional frameworks rely heavily on runtime β€œmagic” (reflection, dynamic string-based dependency injection, weak typing, and heavy metaprogramming). While this is great for humans writing short scripts, it is terrible for AI Agents, as it prevents the AI from validating whether the code is correct before running it.

In Rullst, we opted for Strong Typing and Compile-Time Guarantees. This allows the Rust compiler to act as an β€œabsolute supervisor” for the AI. If the AI makes a mistake, the code won’t compile, and the AI can read the detailed error and fix the problem instantly, creating a perfect feedback loop.

1. The Agent Manifesto (AGENTS.md)

Every Rullst project generated via cargo rullst new automatically includes two vital files in the root: .ai-rules and AGENTS.md.

These are the heart of AI-assisted development. The AGENTS.md file acts as the β€œBible” of your project for any autonomous agent (like Cursor, Github Copilot, Gemini, or Claude). It tells the AI exactly how it should behave in your codebase.

Example of the default content:

1. **Static Dispatch over Dynamic**: Prefer static dispatch (`impl Trait` or generics) over `dyn Trait` to ensure explicit concrete types for AI context tracking and optimization.
2. **Explicit APIs**: Avoid hidden state. Every controller and middleware should be explicit in its arguments.
3. **HTML Macros**: Boolean attributes in the `html!` macro must be quoted (e.g., `required="true"`).
4. **No Panics**: Never use `unwrap()` or `expect()` in production routes.

2. Rullst’s AI-Friendly Patterns

Rullst’s API was designed so that the AI rarely hallucinates:

  • Explicit Routes: The routes![ ... ] macro is visual and delimited. The AI knows exactly where to add a new route without having to search across scattered files.
  • Rullst ORM: Based on Pure SQL (via SQLx) + Derives. AIs are much better at writing pure, correct SQL queries than learning an obscure query builder. Rullst takes advantage of this by using the database in a pure relational way.
  • Clean Background Workers: The queue system does not require complex global registration; you simply create an async function.

3. How to Get the Best Results

When instructing an AI to add a feature in Rullst:

  1. Ask it to read the docs/spec.md and AGENTS.md files first.
  2. Say: β€œCreate a new Controller following the pattern established in auth_controller.rs”. Today’s AIs are brilliant at pattern matching. Rullst provides the skeleton, the AI fills in the meat.
  3. Use the generators! Ask the AI to use cargo rullst make:controller in the terminal (if it’s an autonomous agent), ensuring the correct file structure.

Rullst Studio: Real-Time Monitoring

Rullst Studio is your development control room. It comes built-in with all Rullst Blueprints.

While you develop your application on port 3000, Rullst Studio automatically boots up on port 5555.

What is Rullst Studio?

The Studio acts as a local observability dashboard. It connects to your Rullst application via WebSockets in the background to capture runtime telemetry without affecting your app’s performance.

With the Studio, you can:

  • Monitor Traffic: See HTTP requests, response times, and status codes in real-time.
  • Audit SQL Queries: Observe every query generated by rullst-orm, including execution time and bindings. This is vital for hunting down N+1 query bottlenecks.
  • Analyze Logs: View the unified output of structured tracing without standard console pollution.
  • Debug Async Jobs: Visualize the worker queue and identify failing jobs.

How to Access

  1. Run your Rullst project:
    cargo rullst dev
    
  2. Open your browser at http://localhost:5555

Note: Rullst Studio was designed exclusively for local development environments (cargo rullst dev). In production (compiled via cargo build --release), Studio’s features are completely stripped away via conditional compilation (cfg(debug_assertions)), guaranteeing Zero Overhead for your server.

Rullst Nexus: Your Instant CMS

Rullst Nexus is a tightly coupled and dynamically generated Content Management System (CMS) for your Rullst project.

Instead of spending dozens of hours developing an administrative panel (CRUDs) for your database tables, Rullst Nexus reads the metadata from your database models (structs) and builds a stunning administrative interface (using Tailwind CSS and glassmorphism layouts) at the exact moment the application compiles.

How it Works

All you need to do is implement the NexusModel trait on your ORM struct:

#![allow(unused)]
fn main() {
use rullst::nexus::{NexusModel, FieldMeta, FieldKind};

impl NexusModel for User {
    fn nexus_table() -> &'static str { "users" }
    fn nexus_label() -> &'static str { "Users" }
    fn nexus_icon() -> &'static str { "πŸ‘₯" }
    fn nexus_fields() -> Vec<FieldMeta> {
        vec![
            FieldMeta { name: "id", label: "ID", kind: FieldKind::Number, hidden: true, readonly: true },
            FieldMeta { name: "name", label: "Name", kind: FieldKind::Text, hidden: false, readonly: false },
            FieldMeta { name: "email", label: "Email", kind: FieldKind::Text, hidden: false, readonly: false },
        ]
    }
}
}

And then, in your routing file (usually src/lib.rs or src/main.rs), you β€œhook up” the Nexus engine:

#![allow(unused)]
fn main() {
let nexus = rullst::nexus::Nexus::new()
    .with_brand("SaaS Admin")
    .register::<models::user::User>()
    .build();

// ... and add it to the final router:
let router = router.nest_axum("/nexus", nexus);
}

Benefits of Nexus

  1. Zero Front-end Effort: Nexus renders responsive tables, creation/edition modals, and delete buttons using HTML and HTMX without writing a single line of JS.
  2. Totally Secure: Nexus lives inside the same compiled binary. There is no need for separate APIs or complex permissions to access the database; it uses the secure global connection pool.
  3. Highly Customizable: The hidden and readonly flags in FieldMeta ensure you control exactly what the administrative team can see and modify.

To access it, open your browser at the /nexus route on your app.

Rullst Capital: SaaS Billing Made Easy

Rullst Capital is the billing and subscription orchestration layer for Rullst SaaS applications.

If you generated your project using the SaaS blueprint (cargo rullst new -> Select SaaS Starter), your application already comes wired with Capital, allowing you to charge your users from day one.

Core Features

  • Multi-Provider Support: Rullst Capital currently supports Stripe and LemonSqueezy. You can swap between them by simply changing the BILLING_PROVIDER environment variable. No code changes required!
  • Webhook Handling: Secure webhook endpoints are automatically set up to listen to subscription updates, payment successes, and cancellations.
  • Database Synchronization: When a payment succeeds, Capital automatically updates the subscriptions table in your local database via the rullst-orm, keeping user access in sync with their payment status.

Configuration

In your .env file, configure your keys:

BILLING_PROVIDER=stripe # or lemonsqueezy
BILLING_API_KEY=sk_test_...
BILLING_WEBHOOK_SECRET=whsec_...

How It Works in Your App

The generated billing_controller.rs provides two primary endpoints:

  1. Checkout Redirect: When a user clicks β€œUpgrade to Pro”, they hit /billing/checkout?plan=price_pro. Rullst Capital instantly communicates with Stripe/LemonSqueezy to create a secure checkout session and redirects the user.
  2. Webhook Listener: The /billing/webhook route securely verifies the signature of the incoming request and delegates it to the webhook_handler. The handler then updates the user’s plan_id and ends_at timestamp in your local database.

This architecture ensures your application stays extremely fast and never stores sensitive payment data on your servers.

Rullst Specification πŸ“„

β€œThe Single Source of Truth (SST) for Framework Architecture & Conventions”

This document is the Single Source of Truth (SST) for the Rullst Framework. It specifies the exact conventions, API structures, naming rules, and directory standards of Rullst.

Important

AI Alignment Instruction: Whenever updating, refactoring, or generating documentation and code for Rullst, always refer to this specification as the baseline. Do not invent or assume conventions outside of this document.


πŸ“‚ 1. Directory Structure Conventions

A standard Rullst application scaffold must strictly follow this folder hierarchy:

my-app/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ controllers/      # Route controllers (async modules)
β”‚   β”‚   └── mod.rs
β”‚   β”œβ”€β”€ models/           # Active Record Models (rullst-orm entities)
β”‚   β”‚   └── mod.rs
β”‚   β”œβ”€β”€ pages/            # Shared static HTML elements or full page layouts
β”‚   β”‚   └── mod.rs
β”‚   └── main.rs           # Entrypoint, DB initialization, and Central routing
β”œβ”€β”€ Cargo.toml            # Project cargo dependencies
└── Rullst.toml           # Framework configuration (databases, environment, etc.)

πŸ› οΈ 2. Naming Conventions

To guarantee consistency, both humans and AI coders must adhere to the following name normalization rules handled by the cargo-rullst generator:

  • File Names: Standard Rust snake_case (e.g. users_controller.rs, post_model.rs).
  • Struct / Model / Documentation Names: Standard PascalCase (e.g. UsersController, PostModel).
  • URL Paths: Lowercase kebab-case (e.g. /users, /user-profiles).

⚑ 3. Core API Specifications

3.1. Server & Routing (rullst::routing)

  • Routing Macro: central routing declared via the routes! macro, wrapping Axum routing handlers.
    #![allow(unused)]
    fn main() {
    let router = routes![
        get("/" => home),
        post("/posts" => posts_controller::store),
    ];
    }
  • Server Lifecycle:
    #![allow(unused)]
    fn main() {
    Server::new(router: Router)
        .run(port: u16) -> Result<(), Box<dyn std::error::Error>>
    }

3.2. Server-Side Rendering (rullst::macros)

  • Macro: html! procedural macro compiles HTML trees directly into static memory string concat builders.
  • XSS Protection: Automatic HTML escaping on all dynamic variables wrapped in {expr}.
  • Raw Unescaped HTML: Explicitly bypassed using the wrapper rullst::html::RawHtml(String).
  • Lists/Iterators:
    #![allow(unused)]
    fn main() {
    let mut list_builder = String::new();
    for item in items {
        list_builder.push_str(&html! { <li>{item}</li> });
    }
    html! { <ul>{ rullst::html::RawHtml(list_builder) }</ul> }
    }

3.3. Active Record ORM (rullst-orm)

  • Model definition:
    #![allow(unused)]
    fn main() {
    #[derive(Debug, Clone, FromRow, rullst_orm::Orm)]
    #[orm(table = "table_name")]
    pub struct Model {
        pub id: i32,
        // ... fields
    }
    }
  • Static queries:
    • Model::all().await -> Result<Vec<Model>, sqlx::Error>
    • Model::find(id).await -> Result<Model, sqlx::Error>
  • Instance Operations:
    • let mut instance = Model { ... };
    • instance.save().await -> Result<(), sqlx::Error> (handles auto-incrementing inserts or updates).
    • instance.delete().await -> Result<(), sqlx::Error>

πŸ’» 4. CLI Specifications (cargo-rullst)

  • Project Creation: cargo rullst new <name>
    • Convention: Automatically extracts the package name from path expressions (e.g., ..\dummy_test -> dummy_test).
  • Controller/Island Scaffolding: cargo rullst make:controller <Name> cargo rullst make:island <Name>
    • Behavior: Generates src/controllers/<snake_name>_controller.rs with index and show actions. Appends declaration to src/controllers/mod.rs. Adds pub mod controllers; to the top of src/main.rs.
  • Documentation SSG (RullstPress): cargo rullst docs build and cargo rullst docs dev
    • Behavior: Compiles markdown files in docs/ into a static site inside docs/dist/.

🧱 5. Controller Architecture

Controllers handle business logic and HTTP responses.

  • Module Structure: Each controller is a separate module inside src/controllers/ (e.g., users_controller.rs).
  • Function Signatures: Functions must be asynchronous and return a type that implements axum::response::IntoResponse (or Result<impl IntoResponse, AppError>).
  • Database Access: Controllers must never contain raw sqlx::query! macros inline. Database logic must be delegated to the Active Record ORM methods (.save(), .all(), etc.) or encapsulated within specific impl Model functions.
  • Standard Actions:
    • pub async fn index(): List all resources.
    • pub async fn show(Path(id): Path<i32>): Show a specific resource.
    • pub async fn store(Form(payload): Form<CreateDto>): Create a new resource.
    • pub async fn update(Path(id): Path<i32>, Form(payload): Form<UpdateDto>): Update a resource.
    • pub async fn delete(Path(id): Path<i32>): Delete a resource.

πŸ“„ 6. HTML Pages & Components

Rullst uses a functional approach for HTML rendering, relying on the html! macro.

  • Organization: Pages and components reside in src/pages/.
  • Functional Components: Pages and components are simply Rust functions. They are not structs or classes.
  • Props/Data: Pass data into pages and components as regular function arguments.
  • Return Type: Components should return a String (or rullst::html::RawHtml) so they can be embedded in other html! calls. Route-level pages should return axum::response::Html<String> to be served directly.
  • Example:
    #![allow(unused)]
    fn main() {
    pub fn button_component(label: &str, url: &str) -> String {
        html! { <a href={url} class="btn">{label}</a> }
    }
    
    pub fn home_page(user_name: &str) -> axum::response::Html<String> {
        let content = html! {
            <div>
                <h1>"Welcome, "{user_name}</h1>
                { rullst::html::RawHtml(button_component("Click Me", "/click")) }
            </div>
        };
        axum::response::Html(content)
    }
    }

🚨 7. Error Handling

Consistent error handling ensures safety and predictable API responses.

  • Default Error Type: The framework expects a standard error enum, typically AppError, located in src/error.rs or similar.
  • Implementation: AppError must implement axum::response::IntoResponse.
  • Controller Usage: Controllers that can fail should return Result<impl IntoResponse, AppError>.
  • HTTP Codes: The IntoResponse implementation maps internal errors to appropriate HTTP status codes (e.g., 404 Not Found, 500 Internal Server Error).

πŸ›‘οΈ 8. Middlewares

Middlewares intercept requests for authentication, logging, etc.

  • Location: Middlewares are placed in src/middlewares/.
  • Standard Signature: Following Axum’s from_fn pattern, a middleware function looks like:
    #![allow(unused)]
    fn main() {
    use axum::{extract::Request, middleware::Next, response::Response};
    
    pub async fn my_middleware(req: Request, next: Next) -> Response {
        // Pre-request logic here
        let response = next.run(req).await;
        // Post-request logic here
        response
    }
    }
  • Registration: Middlewares are registered on the router using Axum’s .layer() or through Rullst’s server configuration wrapper.

πŸ›‘οΈ 9. Architectural Guidelines for Backward Compatibility

To guarantee stress-free and self-healing updates for Rullst users, all framework code must strictly adhere to the following backward compatibility rules:

9.1. The Builder Pattern and #[non_exhaustive]

Any public configuration struct or extensible enum exposed by the framework must use the #[non_exhaustive] attribute. This prevents developers from instantiating the struct directly, ensuring that adding new fields in future minor versions will not break user code.

  • Mandatory Usage: All instantiation must be done via a constructor (new()) and the Builder Pattern (with_...()).
#![allow(unused)]
fn main() {
#[non_exhaustive]
pub struct RullstConfig {
    pub port: u16,
}

impl RullstConfig {
    pub fn new(port: u16) -> Self {
        Self { port }
    }
}
}

9.2. Deprecation Lifecycle (#[deprecated])

The framework will never abruptly remove or rename a public function, struct, or method. If a breaking change to an API is required, the old API must be kept alive for at least one minor version using the #[deprecated] attribute.

  • Mandatory Usage: The note field must explicitly tell the user what to use instead, enabling cargo fix to potentially automate the migration.
#![allow(unused)]
fn main() {
#[deprecated(since = "0.2.0", note = "Please use `Router::new()` instead")]
pub fn old_initializer() {
    Router::new();
}
}

9.3. Sealed Traits

If the framework exposes a Trait that is meant to be used by the user but not implemented by the user (e.g., core framework behavior), it must use the β€œSealed Trait” pattern. This ensures that adding new methods to the trait in the future will not break downstream implementations.

#![allow(unused)]
fn main() {
mod private {
    pub trait Sealed {}
}

pub trait RullstTrait: private::Sealed {
    fn execute(&self);
}
}

πŸ—οΈ 10. CLI Modular Architecture (cargo-rullst)

Important

The cargo-rullst CLI must never be allowed to grow into a monolithic main.rs. Once the file exceeds ~1000 lines, refactoring into the module structure below is mandatory. Mixing template strings, HTML, SQL schemas, spinner logic, and argument parsing in a single file is classified as a critical architecture violation.

10.1. Required Module Structure

The cargo-rullst source directory must be organized as follows:

cargo-rullst/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ main.rs               # ≀ 80 lines: Entry point only. Dispatches to cli or ui.
β”‚   β”œβ”€β”€ cli.rs                # Clap structs, Commands enum, argument definitions.
β”‚   β”œβ”€β”€ ui/                   # Everything visual: banners, spinners, menus, boxes.
β”‚   β”‚   β”œβ”€β”€ mod.rs
β”‚   β”‚   β”œβ”€β”€ banner.rs         # ASCII art, version display, neon color palette.
β”‚   β”‚   └── components.rs     # with_spinner(), prompt_select(), boxed_output().
β”‚   β”œβ”€β”€ generators/           # Scaffold logic: writes files to disk on user's project.
β”‚   β”‚   β”œβ”€β”€ mod.rs
β”‚   β”‚   β”œβ”€β”€ controller.rs     # create_new_controller()
β”‚   β”‚   β”œβ”€β”€ model.rs          # create_new_model()
β”‚   β”‚   β”œβ”€β”€ migration.rs      # create_new_migration(), regenerate_migrations_mod()
β”‚   β”‚   β”œβ”€β”€ project.rs        # create_new_project() β€” main wizard
β”‚   β”‚   β”œβ”€β”€ auth.rs           # scaffold_auth_system()
β”‚   β”‚   β”œβ”€β”€ billing.rs        # scaffold_billing_system()
β”‚   β”‚   β”œβ”€β”€ desktop.rs        # scaffold_omni_system() / run_omni_app()
β”‚   β”‚   └── foundry.rs        # scaffold_foundry_config() / run_foundry_deploy()
β”‚   └── blueprints/           # Blueprint template definitions (NOT inline strings).
β”‚       β”œβ”€β”€ mod.rs
β”‚       β”œβ”€β”€ blank.rs          # Blank Starter template files
β”‚       β”œβ”€β”€ lms.rs            # LMS / Course Platform template files
β”‚       β”œβ”€β”€ saas.rs           # SaaS Starter template files
β”‚       └── blog.rs           # Blog / Content System template files

10.2. The main.rs Purity Rule

main.rs is the maestro, not a musician. It must contain only:

  1. Crate-level #![allow(...)] attributes.
  2. Module declarations (pub mod cli; pub mod ui; pub mod generators; pub mod blueprints;).
  3. The fn main() function itself β€” which reads arguments and dispatches.
  4. Zero business logic, zero template strings, zero file I/O.
// βœ… CORRECT main.rs pattern
fn main() -> Result<(), Box<dyn std::error::Error>> {
    trigger_background_update_check();
    if std::env::args_trimmed().has_no_subcommand() {
        ui::show_interactive_dashboard()?;
    } else {
        cli::parse_and_run()?;
    }
    Ok(())
}

10.3. Template String Rules

Never embed large multi-line HTML, Rust, or SQL strings directly inside scaffold generator functions. Instead:

  • Option A (Preferred): Use include_str!() to load .rs.tmpl, .html, or .sql files from a templates/ directory compiled into the binary.
  • Option B: Define typed constants or functions inside the blueprints/ module (e.g., blueprints::lms::course_model_rs()) that return &'static str or String. These can be updated independently without touching generator logic.
  • Option C (Last Resort): Use r###"..."### raw string literals (triple-hash delimiters) to prevent early termination when templates contain "# sequences (common in HTML attributes like hx-target="#player-panel").

Warning

Using r#"..."# (single-hash) raw strings for HTML templates will cause a compiler error whenever the template contains "# (which is extremely common in HTML id attributes used with HTMX). Always use r###"..."### or move the template to the blueprints/ module.


🎨 11. Rullst Blueprints Engine β€” Design Rules

Blueprints are pre-configured project archetypes generated by the cargo rullst new wizard. They must follow strict rules to guarantee quality, safety, and ease of maintenance.

11.1. Available Blueprints

Blueprint IDNameDescription
0πŸ“ Blank StarterMinimal HTMX reactive counter. Clean baseline.
1πŸŽ“ LMS / Course PlatformCourses + Lessons models, migrations with seed data, glassmorphic video player via HTMX.
2πŸ›οΈ SaaS StarterAuth system + Stripe pricing panels + user dashboard.
3πŸ“° Blog / Content SystemPost model, auto-CMS via Nexus, glassmorphic press feed.

11.2. Blueprint Scaffolding Rules

  1. Only during new: Blueprint file injection (route wiring, lib.rs, main.rs) may only happen during cargo rullst new, when the project directory is freshly created and fully controlled. Never attempt to inject code into an existing user project.
  2. Isolated file generation: Each blueprint generates a fully self-contained set of files. No cross-file regex or AST manipulation is permitted.
  3. Template sourcing: All blueprint templates must live in src/blueprints/<name>.rs as typed functions, not inside generators/project.rs.
  4. Additive, not destructive: Blueprints append to or create new files. They never delete or overwrite files created by a previous step.

11.3. Blueprint File Manifest

Every blueprint module (e.g., blueprints::lms) must expose a FileManifest β€” a list of (relative_path, content) pairs β€” via a public function:

#![allow(unused)]
fn main() {
// src/blueprints/lms.rs
pub fn file_manifest() -> Vec<(&'static str, String)> {
    vec![
        ("src/models/course.rs",    course_model()),
        ("src/models/lesson.rs",    lesson_model()),
        ("src/models/mod.rs",       "pub mod course;\npub mod lesson;\n".to_string()),
        ("src/controllers/lms_controller.rs", lms_controller()),
        ("src/pages/lms.rs",        lms_page()),
        // ...migrations, etc.
    ]
}
}

The generator iterates over this manifest and writes each file β€” no HTML or Rust templates inline.


πŸ” 12. Environment Variables & Third-Party Secrets

Any blueprint or scaffold that integrates a paid third-party service (Stripe, LemonSqueezy, Cloudinary, etc.) must generate a .env file with clear, commented placeholder values.

12.1. Required .env Template

# ─────────────────────────────────────────────────────────────
#  Rullst Application Environment Configuration
#  Generated automatically by cargo rullst new
# ─────────────────────────────────────────────────────────────

# ⚠️ SECURITY: This file must NEVER be committed to git.
# It is automatically added to .gitignore by the Rullst CLI.

# ── Database ──────────────────────────────────────────────────
DATABASE_URL=sqlite://db.sqlite3

# ── Application ───────────────────────────────────────────────
APP_KEY=GENERATE_A_RANDOM_32_CHAR_SECRET_HERE
APP_ENV=development

# ── Stripe Billing (replace with your real keys from stripe.com/dashboard) ──
# STRIPE_SECRET_KEY=sk_test_REPLACE_WITH_YOUR_SECRET_KEY
# STRIPE_WEBHOOK_SECRET=whsec_REPLACE_WITH_YOUR_WEBHOOK_SECRET
# STRIPE_PRICE_ID_MONTHLY=price_REPLACE_WITH_YOUR_PRICE_ID

12.2. .gitignore Auto-Protection Rules

The CLI must automatically append the following entries to .gitignore during project creation:

# Rullst: Environment & Secrets
.env
.env.*
!.env.example

# Rullst: Foundry Deployment Manifest (contains SSH keys and cloud credentials)
Foundry.toml

12.3. .env.example Companion File

Every project generated by cargo rullst new must also produce an .env.example file with all the same keys but with the placeholder values clearly documented. This file is committed to version control and serves as the public onboarding guide for new contributors.

Rullst Blueprints Roadmap πŸ—ΊοΈ

β€œThe Ultimate High-Performance Blueprints Collection for Rullst”

This document maps the expansion plan for the Rullst Starter Blueprints ecosystem. The goal is to provide developers and agencies with complete, β€œproduction-ready” solutions that highlight the performance, security, and productivity advantages of the Rust + Rullst ecosystem.


πŸš€ Blueprints Design Philosophy

Every blueprint added to the CLI must meet three fundamental principles:

  1. Immediate Wow Factor: Beautiful, responsive interfaces (Dark Mode, Glassmorphism, Micro-animations) and highly interactive via HTMX/Tailwind.
  2. Native Rust/Rullst Features: Practically demonstrate Rust’s unfair advantage (low RAM usage, safe concurrency, parallel processing, type safety, robust WebSockets).
  3. Production-Ready: Automatically generate .env.example, database configurations with concurrency locks, and a bulletproof .gitignore.

πŸ—ΊοΈ New Blueprints Roadmap (Ordered from Easiest to Hardest)

IDBlueprint NameTechnical Focus in RullstCommercial Differentiator
4πŸ’Ό ERP Pocket (Inventory)Embedded SQLite + rullst::nexus (Auto-CMS) + Single BinarySmall/Medium businesses with an offline-first, crash-immune system.
5πŸ“‘ Uptime Monitoring ServiceAsynchronous Workers (rullst::queue) + Health ChecksUptime Kuma alternative running on a $5 VPS with zero memory usage.
6πŸ“‹ Member/Club Management#[derive(Validate)] + Nexus + PDF Receipt GenerationMember registration and billing for gyms, clubs, and condominiums.
7πŸ€– AI Agent & RAG Boilerplaterullst::ai (Ollama/Gemini/OpenAI) + Local Vector EmbeddingIntelligent parsing of local and private PDF/TXT documents.
8πŸͺ™ AI Credit-Based SaaSStreaming (SSE) + rullst-orm (Concurrency Lock) + StripeAI SaaS platforms with token consumption secured against race conditions.
9πŸ₯ Scheduling & ClinicsHTMX Calendar + Cron Scheduler + Double-Booking LocksBarbershops, doctors, and freelancers with duplicate reservation prevention.
10πŸšͺ Biometric Access Controlrullst::routing (WebSockets) + Real-time Concierge PanelConcierge systems, gyms, and electronic timeclocks with zero lag.
11πŸ“ˆ Affiliate CheckoutFast SSR (<100ms) + Commission Splits + Landing PageSales pages with a 100 Lighthouse Score for maximum conversion.
12🏒 B2B Multi-Tenant Platformrullst::multitenant (subdomains) + RBAC (Enums) + rullst::mailSecure, isolated enterprise software for selling corporate licenses.
13πŸ’¬ Discord-Like Realtime ChatRullst Live (Server-Driven UI) + WebSockets on TokioScalable, concurrent chat rooms with low infrastructure cost.
14πŸ›΅ Delivery / Food AppBackground Queue (rullst::queue) + Order StateAsynchronous delivery status processing and email notifications.

πŸ” Highlighted Architectural Details

πŸͺ™ 8. AI Credit-Based SaaS (The Token-Burner)

  • Architecture: Clean chat interface consuming data via native Server-Sent Events (SSE) for fluid AI response streaming.
  • Data Security: rullst-orm implements strict transaction locks to ensure that if a user’s credit balance reaches zero simultaneously in two different tabs, the system aborts token generation before finalizing costly calls to the LLM.
  • Monetization: Integrated Stripe checkout with usage-based billing and a self-managed billing portal.

🏒 12. B2B Multi-Tenant Platform (The Corporate Boilerplate)

  • Isolation: Uses the native rullst::multitenant module, which intercepts HTTP requests and dynamically injects the tenant_id scope into all SQL queries throughout the request lifecycle, preventing accidental data leaks between companies.
  • Permissions (RBAC): Role structures (Admin, Member, Billing) based on safe Rust enums, validated via middlewares before dispatching to controllers.
  • Invitations: Cryptographically tokenized email invitation flow with a 24-hour expiration using the native rullst::mail mailer.

πŸ’¬ 13. Discord-Like Realtime Chat

  • No Complex JS: Uses Rullst Live to maintain the chat room state on the server. Every message submitted via an HTMX form is processed, added to the thread’s broadcasting channel, and rendered directly by the server, updating client DOMs via real-time WebSockets.
  • Scale: Utilizes Rust’s efficient Tokio runtime threads, allowing thousands of persistent active WebSocket connections while consuming less than 50MB of RAM on the server.

πŸ₯ 9. Scheduling & Clinics (The Scheduler)

  • Conflict Prevention: Database transactions executed with a strict SERIALIZABLE isolation level or pessimistic locking to prevent double-booking at the exact millisecond of confirmation.
  • Integrated Cron: Reminder registration via Rullst’s native Cron to fetch appointments in the next 2 hours and trigger automatic notifications without the need for external schedulers like Sidekiq or Celery.

πŸ€– 7. AI Agent & RAG Boilerplate (AI-Native)

  • Structure: Intuitive file upload interface where Rullst converts the document, calculates embeddings using local models or configured APIs, and stores the vector data in the embedded SQLite database.
  • Flexibility: Flexible configuration via rullst::ai allowing instant toggling between external commercial LLMs (Gemini, OpenAI) and local instances (Ollama / Llama 3) with a single environment variable.

πŸ’‘ Rullst CLI - Full Command Reference

The Command Line Interface (cargo-rullst) is the heart of the Rullst ecosystem. It doesn’t just create files; it acts as a static analyzer, infrastructure orchestrator, and Wasm compiler.

Below is the exhaustively detailed reference for absolutely all commands and their flags.


πŸ—οΈ 1. Project Initialization & Maintenance

cargo rullst new <name>

Creates a Rullst project from scratch. This command doesn’t just clone a template; it builds the directory tree, injects the database connection into .env, creates the Cargo.toml with the correct features, and generates a main.rs prepared with routing configurations.

  • Arguments:
    • <name>: The folder and package name (e.g., my_startup).
  • Optional Flags:
    • --api: Changes the default scaffolding behavior. Instead of preparing a Full-Stack project with HTML rendering, it generates a headless project (JSON API only), focusing strictly on JSON and removing template dependencies.
    • --docker: Automatically adds a highly optimized multi-stage Dockerfile for Rust, a docker-compose.yml (with the database), and the .dockerignore.
    • --nix: Adds flake.nix and .envrc (direnv) files to create a 100% reproducible development environment isolated from the host OS.

cargo rullst upgrade

Globally updates the CLI on your machine (cargo install cargo-rullst) and simultaneously scans your current project’s Cargo.toml to ensure Rullst and its internal macros (like rullst-macros and rullst-connect) are updated to the corresponding stable version, running automatic codemods if breaking changes are detected.


πŸ› οΈ 2. Architecture Scaffolding (make:*)

Rullst is heavily opinionated. All make:* commands automatically update references (e.g., registering a controller in the main router) and regenerate the AI Context (.llms.txt).

cargo rullst make:controller <name>

Generates a new Controller in the src/controllers/ directory. It creates the standard CRUD methods (index, show, create, update, delete) and automatically registers the route in main.rs.

  • Arguments: <name> (e.g., UsersController or users).
  • Optional Flags:
    • --api: Instead of returning HTML Views via the html! macro, the generated methods will automatically extract/return Json<T>.

cargo rullst make:model <name>

Creates a Model Struct in the src/models/ directory with the ORM annotations (#[derive(Model)]).

  • Arguments: <name> (e.g., BlogPost).
  • Optional Flags:
    • --migration or -m: Simultaneously generates an empty SQL migration file (src/migrations/YYYYMMDD_create_blog_posts.sql) with the correctly pluralized table name.

cargo rullst make:middleware <name>

Generates a standard Axum/Rullst Middleware struct in src/middlewares/. Perfect for injecting headers, checking authentication, rate limiting, or logging.

cargo rullst make:island <name>

Creates a frontend interactive β€œIslands Architecture” component (similar to Fresh or Astro) in src/islands/. It generates the Rust infrastructure that, during build, will be transparently compiled to WebAssembly to run in the browser.

cargo rullst make:worker <name>

Creates an asynchronous background Job (Worker) in src/workers/. If you pass Email, it generates an EmailWorker that consumes queues in the background (Redis/RabbitMQ).

cargo rullst make:migration <name>

Generates a raw SQL migration file (Up and Down) prefixed with a timestamp, guaranteeing the correct chronological execution order in the database.

cargo rullst make:billing

Scaffolds a complete SaaS system. It generates Subscription models, webhook integrations, billing dashboard routes, and prepares the shell for providers like Stripe or LemonSqueezy.

cargo rullst make:jwt

Injects a pre-configured boilerplate Middleware into your project for strict JWT Authentication (verifying Bearer tokens in the Authorization header).

cargo rullst make:cors

Generates and configures full CORS (Cross-Origin Resource Sharing) options in your project with recommended security defaults (blocking unused methods, restricting origins).

cargo rullst make:omni

Prepares your project to become a Desktop or Mobile App. It generates Tauri/Omni manifests, creating the native bridge so you can package your website as an .exe or .apk.

cargo rullst auth

The Supreme Command. With just one command, it creates an entire Authentication system in your codebase, including:

  • User Model and Migration (with bcrypt/argon2 password hashing).
  • Auth Controllers (Login, Registration, Logout).
  • Session or Token Middleware.
  • Complete HTML Views for Login and Signup (unless --api is used).

πŸ—„οΈ 3. Database and Migrations (db:*)

cargo rullst db:migrate

Analyzes the internal _rullst_migrations table in your database and executes all SQL files in the migrations/ directory that haven’t been run yet.

cargo rullst db:rollback

Reverts the last applied migration batch. It looks at the latest executed batch, extracts the β€œDown” section of the SQL file, and executes it to undo changes and remove tables/columns.

cargo rullst db:status

Checks the database connection and prints a table in the terminal comparing the local migrations/ folder with the database status, detailing exactly what has been run and what is pending.

cargo rullst db:seed

Populates the database using seeder files created in src/db/seeds.rs, ideal for injecting an initial administrator or dummy testing data.

cargo rullst studio

Launches an internal web server on port :5555 that functions as the Rullst Visual Database Studio. It is a visual administration panel where you can edit records, run queries, and visualize table relationships directly in the browser.


🧠 4. Analyzers and Code Generators (generate:*)

cargo rullst generate:openapi

Reads your source code via Regular Expressions and AST without needing to compile the project. It extracts routes, decipher URL parameters, extracts /// Rustdoc comments from controllers, and generates a fully compliant OpenAPI V3 openapi.json file.

cargo rullst generate:ts

Scans your models, DTOs (Data Transfer Objects), and mapped routes. Transcribes all Rust structs into a strictly typed TypeScript file (sdk.ts), eliminating contract breaks between frontend and backend.

cargo rullst generate:diagram

Analyzes primary and foreign keys defined in your Models and exports a diagram.md file containing Mermaid.js code, visually generating an Entity-Relationship (ER) diagram.

cargo rullst generate:models

Connects to a legacy database (that already exists and has tables), maps the entire β€œInformation Schema”, and automatically outputs Rust Struct files based on the columns and types found in the database.

  • Required Flags:
    • --driver: postgres, mysql, or sqlite.
    • --url: The complete connection string.
  • Optional Flags:
    • --output: Where to save the generated structs (Default: src/models).

cargo rullst generate:ai-context

Creates the brain map of your project (.llms.txt). It summarizes the folder structure, conventions, and dependencies so that AI Assistants (like Cursor and Github Copilot) perfectly understand the framework when you ask them for help.


πŸš€ 5. Development, Infrastructure, and Build

cargo rullst dash

Opens the Interactive Dashboard (TUI - Terminal User Interface) powered by Ratatui. It splits your screen in half, displaying colorful server logs, the build system events, stats, and allows running migrations at the touch of a key (hotkeys).

cargo rullst dev

Runs the classic Rullst development server in the terminal with Hot-Reload. Any modification to .rs or HTML files will instantly restart the server at lightning speed.

cargo rullst build:client

Extracts all β€œIslands” (client-side interactivity) from your code and compiles them via wasm-pack into tiny WebAssembly binaries, ready to run at the speed of light in the browser.

  • Flags: --debug (Avoids extreme minification so you can inspect and debug Wasm sourcemaps).

cargo rullst build

Creates the monolithic final Production binary of the backend and executes pre-compression tools (GZIP and Brotli) on your static assets.

  • Flags: --debug (Compiles with debug information, generating a larger binary).

cargo rullst dockerize / cargo rullst nixify

Injects infrastructure files (Dockerfile or Nix Flake) directly into a pre-existing project (similar to the flags used in new).

cargo rullst foundry:init

Prepares the Foundry.toml manifest, which maps environment variables and Cloud provider configurations (AWS, DigitalOcean) for 1-click deployment.

cargo rullst foundry:deploy

Reads your Foundry.toml and, using the configured credentials, packages and orchestrates the deployment via API directly to your cloud, returning the final public URL of your application.

cargo rullst omni

Initializes your native application client (after using make:omni), launching the operating system window.

  • Optional Arguments: <target> specifies where to run (e.g., desktop, android, ios).