This document outlines the required rules and conventions for the rustybridge project. All contributors (human and AI) must adhere to these guidelines to ensure code quality, maintainability, and consistency.
- collapsed_if: If statements should always be collapsed if possible instead of nesting them.
- Bad:
if x { if y { // ... } }
- Good:
if x && y { // ... }
- Bad:
- Toolchain: Always use
cargo +nightly fmt. Nightly is required due to our specific configuration settings.
- Module Style: Prefer file-style modules (e.g.,
anchor.rsandanchor/) over folder-style modules (e.g.,anchor/mod.rs). This is the modern Rust convention and keeps the file tree cleaner, Nested modules should result inanchor.rsandanchor/submodule.rs.
- State Store: The
state-storecrate should encompass all database access functions. No direct DB queries should exist in consumer crates.
- Core Crates:
server-core: Handles all server-side business logic.client-core: Handles all client-side (CLI) business logic.
- The web/server crates should primarily handle routing and API interfacing, delegating logic to the core crates.
- Shared Types: All shared types should be implemented in
rb-types. Avoid defining types in leaf crates if there is any chance they will be needed elsewhere.
- Internal Types: Complex type annotations should be defined as internal types (e.g.,
type MyComplexMap = HashMap<String, Vec<Arc<Mutex<Data>>>>;) and stored inrb-types. This improves readability and refactoring.
- Maintainability: File sizes should be between 300-600 lines maximum.
- Refactoring: If a file grows beyond this limit, it must be refactored. Break it down into helpers, sub-modules, or separate components.
- Proactive Design: Think ahead. If a function might be useful in other areas, aggressively create helpers rather than inlining logic.
- DRY: Don't Repeat Yourself.
- Requirement: All functions must have clear documentation.
- Maintenance: Docs must be updated immediately if changes are made to the underlying function.
- Style: Use short, concise, and accurate descriptions.
- Workspace Dependencies: Cargo dependencies should be managed at the workspace level (in the root
Cargo.toml[workspace.dependencies]) to standardize features and versions across all crates.
- Search First: Before implementing new functionality, properly search the existing codebase to ensure you are not reimplementing functionality that already exists.
- Aggressive Deduplication: Actively look to deduplicate code through:
- Helper functions
- Smart use of macros
Unit tests that need access to private/internal items should be placed in sibling _tests.rs files:
src/
├── my_module.rs
└── my_module_tests.rs
Include the test file in the source module:
#[cfg(test)]
#[path = "my_module_tests.rs"]
mod tests;When to use: Testing private functions, internal state, or implementation details.
Integration tests that only use the public API should be placed in the tests/ directory at the crate root:
crate_root/
├── src/
└── tests/
└── feature_test.rs
When to use: Testing the crate's public API as an external consumer would.
Shared test utilities (fixtures, mocks, helpers) should be placed in src/test_support.rs and exported conditionally:
#[cfg(feature = "test-support")]
pub mod test_support;- Unit test files:
<module>_tests.rs - Integration test files:
<feature>_test.rsor<feature>.rs - Test functions:
test_<what_is_being_tested>()
- Avoid: Inline
#[cfg(test)] mod tests { ... }blocks in source files - Avoid: Test files mixed into
src/without the_tests.rssuffix
- Requirement: All server-side events, state changes, and sensitive actions must trigger audit events.
- Implementation: Use the project's Audit system (
rb-types::audit,server-core::audit). Ensure every API endpoint that modifies state logs an event. - Macro Usage: Use the
audit!()macro for consistent audit logging:audit!(context, UserCreated { user_id: id, username: name });
- Tracing Integration: The
audit!()macro automatically emits a correspondingtracingevent at the appropriate level (INFO for most actions, WARN/ERROR for failures). Do not add redundanttracingcalls immediately before or afteraudit!()calls.
- Crate: Use
tracingfor all logging. Do not uselog,println!, orweb_sys::consoledirectly. - Message Style:
- Lowercase: All log messages should start with a lowercase letter.
- Bad:
info!("User created"); - Good:
info!("user created");
- Bad:
- Structured Fields: Use structured fields instead of string concatenation:
- Bad:
info!("user {} created", user_id); - Good:
info!(user_id, "user created");
- Bad:
- Field Prefixes: Use appropriate display prefixes:
%valforDisplayformatting?valforDebugformatting- Example:
info!(user_id = %id, details = ?metadata, "operation complete");
- Lowercase: All log messages should start with a lowercase letter.
- Imports: Prefer direct imports over fully-qualified paths:
- Bad:
tracing::info!(...) - Good:
use tracing::{info, warn, error}; ... info!(...)
- Bad:
- Feature Guards: Logging is available on all platforms via
tracing-web(WASM) andtracing-subscriber(server). Do not add#[cfg(feature = "web")]guards around logging calls. - Log Levels:
ERROR: Unrecoverable errors, panics, critical failuresWARN: Recoverable issues, validation failures, deprecated usageINFO: Significant state changes, user actions, lifecycle eventsDEBUG: Detailed flow information for debuggingTRACE: Very verbose, step-by-step execution details
- Dynamic Configuration:
- Server log level is stored in the database (
server_options.log_level), configurable via Server Settings UI. - Client (WASM) log level is stored in
localStorage(rb_web_log_level), configurable via Profile page.
- Server log level is stored in the database (
- Macros: Use Dioxus 0.7+ server macros:
#[get],#[post],#[put],#[delete]. Do not use#[server]. - DI Style Imports: Use Dependency Injection style for extractors. Define them in the macro attributes and use them directly in the function body. Do not add them as function arguments.
- Example:
#[get("/api/example", auth: WebAuthSession)] pub async fn example_endpoint() -> Result<(), ServerFnError> { // 'auth' is available here automatically ensure_server_claim(&auth, ClaimLevel::View)?; Ok(()) }
- Example:
- Result Types: Prefer returning
Resulttypes for any fallible operations. - Propagation: Uses
?operator for clean error propagation. - Context: When wrapping errors, ensure sufficient context is preserved to debug the issue.
- Group cfg-gated imports: When multiple imports share the same
#[cfg(...)]attribute, group them into a single block using curly braces. This reduces clutter and makes it clear which imports are feature-gated.- Bad:
#[cfg(feature = "server")] use crate::server::audit::WebAuditContext; #[cfg(feature = "server")] use crate::server::auth::guards::{WebAuthSession, ensure_claim}; #[cfg(feature = "server")] use rb_types::auth::ClaimLevel;
- Good:
#[cfg(feature = "server")] use { crate::server::audit::WebAuditContext, crate::server::auth::guards::{WebAuthSession, ensure_claim}, rb_types::auth::ClaimLevel, };
- Bad:
- One block per feature: Each file should have at most one
#[cfg(feature = "server")]use block and one#[cfg(feature = "web")]use block at the top of the file.
- Compilation: AI Agents should always use
cargo --message-format=shortwhen running checks or builds to limit token usage and reduce noise in output.