Skip to content

Comparison with other frameworks ​

Sword, Summer and Loco allows build applications and services in Rust with different structures and scopes. The table lists what each framework provides in its latest published version.

CapabilitySword 0.6Summer 0.7Loco 1.3
HTTPaxumaxumaxum
gRPCtonictonic—
Socket.IOsocketioxidesocketioxide—
EventsIn-memory and NATS, same APIsea-streamer—
Jobstokio-cron-schedulerapalis and tokio-cron-schedulerloco scheduler
Dependency injectionProviders and componentsComponentsAppContext
Same model across transportsControllers, modules and DI shared by every enginePlugins with DI while the controller API is per pluginWeb only
MiddlewareUnified Interceptors and Tower layerstower-http and pluginstower-http
ConfigurationTOMLTOMLYAML
OpenAPIutoipa and Swagger UIaide—
CLIIn development—cargo loco

Advantages of Sword ​

The table summarizes features. The difference with Summer is architectural: in Sword the whole application rests on three pieces that stay the same across every transport.

A single dependency container. A provider or component is registered once and any controller receives it injected, whether web, gRPC, Socket.IO or events. There are no manual constructors and no global state. Dependencies resolve at startup and are shared.

The same abstraction for every transport. Controllers, modules and the container use the same model. Logic is written once and exposed through whichever transport is needed, without rewriting services. In Summer the plugins share the container, but the controller API changes per plugin.

Composition by modules. Each module declares what it contributes: controllers, components and providers. The application is built by assembling them. Adding a capability means adding a module, not wiring routes by hand.

The same UserService is injected into the web controller and the events handler without being touched:

sh
src/
├── main.rs
├── shared/
│   └── database.rs
└── users/
    ├── mod.rs
    ├── entity.rs
    ├── repository.rs
    ├── service.rs
    ├── controller.rs
    └── events.rs
rust
// Declares the components and controllers of the module

pub mod controller;
pub mod entity;
pub mod events;
pub mod repository;
pub mod service;

use sword::prelude::*;

use crate::shared::database::Database;
use crate::users::controller::WebUsersController;
use crate::users::events::UserEventsHandler;
use crate::users::repository::UserRepository;
use crate::users::service::UserService;

pub struct UsersModule;

impl Module for UsersModule {
    async fn register_providers(_config: &Config, providers: &ProviderRegistry) {
        providers.register(Database::new().await.expect("database"));
    }

    fn register_components(components: &ComponentRegistry) {
        components.register::<UserRepository>();
        components.register::<UserService>();
    }

    fn register_controllers(controllers: &ControllerRegistry) {
        controllers.register::<WebUsersController>();
        controllers.register::<UserEventsHandler>();
    }
}
rust
// Database provider

use std::sync::Arc;

use sqlx::SqlitePool;
use sqlx::sqlite::{SqliteConnectOptions, SqlitePoolOptions};

use sword::prelude::*;

#[injectable(provider)]
pub struct Database {
    pool: Arc<SqlitePool>,
}

impl Database {
    pub async fn new() -> sqlx::Result<Self> {
        let options = SqliteConnectOptions::new()
            .filename(":memory:")
            .create_if_missing(true);

        let pool = SqlitePoolOptions::new()
            .max_connections(1)
            .connect_with(options)
            .await?;

        sqlx::query(
            "CREATE TABLE IF NOT EXISTS users (id BLOB PRIMARY KEY, username TEXT NOT NULL)",
        )
        .execute(&pool)
        .await?;

        Ok(Self {
            pool: Arc::new(pool),
        })
    }

    pub fn get_pool(&self) -> &SqlitePool {
        &self.pool
    }
}
rust
// Domain entity

use serde::Serialize;
use sqlx::FromRow;
use uuid::Uuid;

#[derive(Serialize, FromRow)]
pub struct User {
    pub id: Uuid,
    pub username: String,
}
rust
// Data access layer

use std::sync::Arc;

use sword::prelude::*;

use crate::shared::database::Database;
use crate::users::entity::User;

#[injectable]
pub struct UserRepository {
    db: Arc<Database>,
}

impl UserRepository {
    pub async fn find_all(&self) -> sqlx::Result<Vec<User>> {
        sqlx::query_as::<_, User>("SELECT id, username FROM users")
            .fetch_all(self.db.get_pool())
            .await
    }

    pub async fn save(&self, user: &User) -> sqlx::Result<()> {
        sqlx::query("INSERT INTO users (id, username) VALUES (?, ?)")
            .bind(user.id)
            .bind(&user.username)
            .execute(self.db.get_pool())
            .await?;

        Ok(())
    }
}
rust
// Business logic layer, independent of the transport

use std::sync::Arc;

use sword::prelude::*;

use crate::users::entity::User;
use crate::users::events::UserCreated;
use crate::users::repository::UserRepository;

#[injectable]
pub struct UserService {
    repo: Arc<UserRepository>,
}

impl UserService {
    pub async fn list(&self) -> sqlx::Result<Vec<User>> {
        self.repo.find_all().await
    }

    pub async fn record_created(&self, event: &UserCreated) -> sqlx::Result<()> {
        let user = User {
            id: event.id,
            username: event.username.clone(),
        };

        self.repo.save(&user).await
    }
}
rust
// Exposes the service through an HTTP/Web controller.

use std::sync::Arc;

use sword::prelude::*;
use sword::web::*;

use crate::users::entity::User;
use crate::users::service::UserService;

#[controller(kind = Controller::Web, path = "/users")]
pub struct WebUsersController {
    service: Arc<UserService>,
}

impl WebUsersController {
    #[get("/")]
    async fn list(&self, _: Request) -> WebResult<Vec<User>> {
        let users = self.service.list().await.map_err(|error| {
            JsonResponse::InternalServerError().message(error.to_string())
        })?;

        Ok(users)
    }
}
rust
// Consumes the service from an event.
use std::sync::Arc;

use serde::{Deserialize, Serialize};
use uuid::Uuid;

use sword::events::*;
use sword::prelude::*;

use crate::users::service::UserService;

#[event(key = "user.created")]
#[derive(Debug, Serialize, Deserialize)]
pub struct UserCreated {
    pub id: Uuid,
    pub username: String,
}

#[controller(kind = Controller::Events, transport = EventTransport::Memory)]
pub struct UserEventsHandler {
    service: Arc<UserService>,
}

impl UserEventsHandler {
    #[subscribe(key = "user.created")]
    async fn on_created(&self, event: &UserCreated) -> EventHandlerResult<()> {
        self.service.record_created(event).await?;

        Ok(())
    }
}

And finally the main.rs:

rust
mod shared;
mod users;

use sword::prelude::*;

use crate::users::UsersModule;

#[sword::main]
async fn main() -> Result<(), Error> {
    let app = Application::builder()?
        .with_module::<UsersModule>()
        .build()?;

    app.run().await
}