Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
286 changes: 206 additions & 80 deletions Cargo.lock

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,5 @@ async-trait = "0.1.83"
tower-http = { version = "0.6.6", features = ["limit", "cors", "trace"] }
tracing = "0.1.41"
tracing-subscriber = { version = "0.3.19", features = ["env-filter"] }

socketioxide = { version = "0.18.0", features = ["axum-websockets"] }
5 changes: 5 additions & 0 deletions examples/socketio-server/.env
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
POSTGRES_USER=user
POSTGRES_PASSWORD=password
POSTGRES_DB=postgres_db
POSTGRES_DATABASE_URL="postgres://user:password@localhost:5432/postgres_db"
DATABASE_URL="postgres://user:password@localhost:5432/postgres_db"
11 changes: 11 additions & 0 deletions examples/socketio-server/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
[package]
name = "socketio-server"
version = "0.1.0"
edition = "2021"

[dependencies]
sword = { workspace = true, features = ["websocket"] }
sword-macros = { workspace = true }
sqlx = { version = "0.8.6", features = ["postgres", "runtime-tokio", "time"] }
serde = { workspace = true }
dotenv = "0.15.0"
20 changes: 20 additions & 0 deletions examples/socketio-server/compose.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
version: '3.8'

services:
postgres:
image: postgres:15
env_file:
- "./.env"
container_name: sword_postgres_example
restart: unless-stopped
environment:
POSTGRES_USER: ${POSTGRES_USER}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
POSTGRES_DB: ${POSTGRES_DB}
ports:
- "5432:5432"
volumes:
- postgres_data:/var/lib/postgresql/data

volumes:
postgres_data:
9 changes: 9 additions & 0 deletions examples/socketio-server/config/config.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
[application]
host = "0.0.0.0"
port = 8080
body_limit = "10MB"
name = "Dependency Injection Example"

[db-config]
uri = "${POSTGRES_DATABASE_URL}"
migrations_path = "config/migrations"
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
-- Add migration script here

CREATE TABLE tasks(
id INT PRIMARY KEY,
title TEXT NOT NULL
)
42 changes: 42 additions & 0 deletions examples/socketio-server/src/database.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
use std::{path::Path, sync::Arc};

use serde::Deserialize;
use sqlx::{migrate::Migrator, PgPool};
use sword::prelude::*;

#[derive(Clone, Deserialize)]
#[config(key = "db-config")]
pub struct DatabaseConfig {
uri: String,
migrations_path: String,
}

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

impl Database {
pub async fn new(db_conf: DatabaseConfig) -> Self {
let pool = PgPool::connect(&db_conf.uri)
.await
.expect("Failed to create Postgres connection pool");

let migrator = Migrator::new(Path::new(&db_conf.migrations_path))
.await
.unwrap();

migrator
.run(&pool)
.await
.expect("Failed to run database migrations");

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

pub fn get_pool(&self) -> &PgPool {
&self.pool
}
}
134 changes: 134 additions & 0 deletions examples/socketio-server/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
use dotenv::dotenv;
use std::sync::Arc;
use sword::prelude::*;
use sword_macros::{
on_connection, on_disconnect, on_fallback, subscribe_message, web_socket,
web_socket_gateway,
};

use crate::database::{Database, DatabaseConfig};
mod database;

#[controller("/ohno")]
struct AppController {}

#[routes]
impl AppController {
#[get("/test")]
async fn get_data(&self, _req: Request) -> HttpResponse {
let data = vec![
"This is a basic web server",
"It serves static data",
"You can extend it with more routes",
];

HttpResponse::Ok().data(data)
}
}

#[web_socket_gateway]
struct SocketController {
db: Arc<Database>,
}

#[web_socket_gateway]
struct OtherSocketController {}

#[web_socket("/other_socket")]
impl OtherSocketController {
#[on_connection]
async fn on_connect(&self, _socket: SocketRef) {
println!("New client connected to OtherSocketController");
}
}

#[web_socket("/socket")]
impl SocketController {
#[on_connection]
async fn on_connect(&self, _socket: SocketRef) {
println!("New client connected");
}

#[subscribe_message("message")]
async fn on_message(&self, _socket: SocketRef, Data(_data): Data<Value>) {
println!("New message received");

let now = sqlx::query("SELECT NOW() as now")
.fetch_one(self.db.get_pool())
.await
.expect("Oh no");

println!("Database time: {:?}", now);
}

#[subscribe_message("message2")]
async fn other_message(&self, _socket: SocketRef, Data(_data): Data<Value>) {
println!("Other message received");
}

#[subscribe_message("message-with-ack")]
async fn message_with_ack(
&self,
Event(_event): Event,
Data(_data): Data<Value>,
ack: AckSender,
) {
println!("Message with ack received");
let response = Value::from("Acknowledged!");
ack.send(&response).ok();
}

#[subscribe_message("message-with-event")]
async fn message_with_event(
&self,
Event(event): Event,
Data(data): Data<Value>,
) {
println!("Message with event '{}' and data: {:?}", event, data);
}

#[subscribe_message("another-message")]
async fn and_another_one_message(&self, _socket: SocketRef, ack: AckSender) {
println!("Another message received");

ack.send("response for another-message").ok();
}

#[subscribe_message("just-another-message")]
async fn just_another_message(&self) {
println!("Message with just-another-message received");
}

#[on_disconnect]
async fn on_disconnect(&self, _socket: SocketRef) {
println!("Socket disconnected");
}

#[on_fallback]
async fn on_fallback(&self, Event(event): Event, Data(data): Data<Value>) {
println!(
"Fallback handler invoked for event: {} with data: {:?}",
event, data
);
}
}

#[sword::main]
async fn main() {
dotenv().ok();

let app = Application::builder();
let db_config = app.config::<DatabaseConfig>().unwrap();
let db = Database::new(db_config).await;

let container = DependencyContainer::builder().register_provider(db).build();

let app = Application::builder()
.with_dependency_container(container)
.with_socket::<OtherSocketController>()
.with_socket::<SocketController>()
.with_controller::<AppController>()
.build();

app.run().await;
}
145 changes: 145 additions & 0 deletions sword-macros/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ mod middlewares;

mod injectable;

mod websocket;

/// Defines a handler for HTTP GET requests.
/// This macro should be used inside an `impl` block of a struct annotated with the `#[controller]` macro.
///
Expand Down Expand Up @@ -643,3 +645,146 @@ pub fn main(_args: TokenStream, item: TokenStream) -> TokenStream {

output.into()
}

/// Marks a struct as a WebSocket gateway controller.
/// This macro should be used in combination with the `#[web_socket]` macro for handler implementation.
///
/// ### Usage
/// ```rust,ignore
/// #[web_socket_gateway]
/// struct ChatSocket;
///
/// #[web_socket("/chat")]
/// impl ChatSocket {
/// #[on_connection]
/// async fn on_connect(&self, socket: SocketRef) {
/// println!("Client connected");
/// }
/// }
/// ```
#[proc_macro_attribute]
pub fn web_socket_gateway(attr: TokenStream, item: TokenStream) -> TokenStream {
websocket::expand_websocket_gateway(attr, item)
}

/// Defines WebSocket handlers for a struct.
/// This macro should be used inside an `impl` block of a struct annotated with the `#[web_socket_gateway]` macro.
///
/// ### Parameters
/// - `path`: The path for the WebSocket endpoint, e.g., `"/socket"`
///
/// ### Usage
/// ```rust,ignore
/// #[web_socket_gateway]
/// struct SocketController;
///
/// #[web_socket("/socket")]
/// impl SocketController {
/// #[on_connection]
/// async fn on_connect(&self, socket: SocketRef) {
/// println!("Client connected");
/// }
///
/// #[subscribe_message("message")]
/// async fn on_message(&self, socket: SocketRef, Data(msg): Data<String>) {
/// println!("Received: {}", msg);
/// }
///
/// #[on_disconnect]
/// async fn on_disconnect(&self, socket: WebSocket) {
/// println!("Client disconnected");
/// }
/// }
/// ```
#[proc_macro_attribute]
pub fn web_socket(attr: TokenStream, item: TokenStream) -> TokenStream {
websocket::expand_websocket(attr, item)
}

/// Marks a method as a WebSocket connection handler.
/// This method will be called when a client establishes a WebSocket connection.
///
/// ### Parameters
/// The handler receives a `SocketRef` parameter for interacting with the connected client.
///
/// ### Usage
/// ```rust,ignore
/// #[on_connection]
/// async fn on_connect(&self, socket: SocketRef) {
/// println!("Client connected: {}", socket.id);
/// }
/// ```
#[proc_macro_attribute]
pub fn on_connection(attr: TokenStream, item: TokenStream) -> TokenStream {
let _ = attr;
item
}

/// Marks a method as a WebSocket disconnection handler.
/// This method will be called when a client disconnects from the WebSocket.
///
/// ### Parameters
/// The handler receives a `WebSocket` parameter with the disconnected client's information.
///
/// ### Usage
/// ```rust,ignore
/// #[on_disconnect]
/// async fn on_disconnect(&self, socket: WebSocket) {
/// println!("Client disconnected: {}", socket.id());
/// }
/// ```
#[proc_macro_attribute]
pub fn on_disconnect(attr: TokenStream, item: TokenStream) -> TokenStream {
let _ = attr;
item
}

/// Marks a method as a WebSocket message handler.
/// This method will be called when the client emits an event with the specified message type.
///
/// ### Parameters
/// - `message_type`: The name of the event to handle, e.g., `"message"` or `"*"` for any event
///
/// ### Parameters in handler
/// - `socket: SocketRef` - The connected client's socket
/// - `Data(data): Data<T>` - The message payload deserialized to type T
/// - `ack: AckSender` (optional) - For sending acknowledgments back to the client
///
/// ### Usage
/// ```rust,ignore
/// #[subscribe_message("message")]
/// async fn on_message(&self, socket: SocketRef, Data(msg): Data<String>) {
/// println!("Received: {}", msg);
/// }
///
/// #[subscribe_message("request")]
/// async fn on_request(&self, Data(req): Data<Request>, ack: AckSender) {
/// ack.send("response").ok();
/// }
/// ```
#[proc_macro_attribute]
pub fn subscribe_message(attr: TokenStream, item: TokenStream) -> TokenStream {
let _ = attr;
item
}

/// Marks a method as a WebSocket fallback handler.
/// This method will be called for any event that doesn't match a specific `#[subscribe_message]` handler.
/// It's useful for debugging or handling dynamic events.
///
/// ### Parameters in handler
/// - `Event(name): Event` - The event name
/// - `Data(data): Data<T>` - The message payload
///
/// ### Usage
/// ```rust,ignore
/// #[on_fallback]
/// async fn on_fallback(&self, Event(event): Event, Data(data): Data<Value>) {
/// println!("Unhandled event: {} with data: {:?}", event, data);
/// }
/// ```
#[proc_macro_attribute]
pub fn on_fallback(attr: TokenStream, item: TokenStream) -> TokenStream {
let _ = attr;
item
}
Loading