Convert Figma logo to code with AI

matrix-org logomatrix-rust-sdk

Matrix Client-Server SDK for Rust

1,218
244
1,218
217

Top Related Projects

A Matrix collaboration client for Android.

A glossy Matrix collaboration client for iOS

Matrix Client-Server SDK for JavaScript

Quick Overview

Matrix Rust SDK is a high-level client-side library for the Matrix protocol, written in Rust. It provides a comprehensive set of tools and abstractions for building Matrix clients, bots, and other applications that interact with Matrix homeservers.

Pros

  • Written in Rust, offering memory safety and performance benefits
  • Comprehensive support for Matrix protocol features
  • Actively maintained and part of the official Matrix ecosystem
  • Supports both synchronous and asynchronous programming models

Cons

  • Steeper learning curve compared to some other Matrix SDKs due to Rust's complexity
  • Documentation could be more extensive, especially for advanced use cases
  • May have a larger binary size compared to simpler Matrix libraries
  • Rust ecosystem is still evolving, which may lead to occasional breaking changes

Code Examples

  1. Creating a client and logging in:
use matrix_sdk::{Client, config::SyncSettings};
use url::Url;

async fn login() -> anyhow::Result<()> {
    let homeserver_url = Url::parse("https://matrix.org")?;
    let client = Client::new(homeserver_url).await?;
    client.login("username", "password", None, None).await?;
    Ok(())
}
  1. Sending a message to a room:
use matrix_sdk::ruma::events::room::message::RoomMessageEventContent;

async fn send_message(client: &Client, room_id: &str, message: &str) -> anyhow::Result<()> {
    let room = client.get_joined_room(room_id).unwrap();
    let content = RoomMessageEventContent::text_plain(message);
    room.send(content, None).await?;
    Ok(())
}
  1. Listening for new messages:
use matrix_sdk::Client;
use matrix_sdk::async_trait;
use matrix_sdk::ruma::events::room::message::SyncRoomMessageEvent;

#[async_trait]
impl EventHandler for Client {
    async fn on_room_message(&self, room: Room, event: &SyncRoomMessageEvent) {
        if let Some(message) = event.content.body() {
            println!("Received message: {}", message);
        }
    }
}

Getting Started

To use the Matrix Rust SDK in your project, add the following to your Cargo.toml:

[dependencies]
matrix-sdk = "0.6"
tokio = { version = "1.0", features = ["full"] }
anyhow = "1.0"

Then, in your Rust code, you can create a client and start using the SDK:

use matrix_sdk::{Client, config::SyncSettings};
use url::Url;

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let homeserver_url = Url::parse("https://matrix.org")?;
    let client = Client::new(homeserver_url).await?;
    // Login, join rooms, send messages, etc.
    Ok(())
}

Competitor Comparisons

A Matrix collaboration client for Android.

Pros of Element Android

  • Native Android app with a user-friendly interface for Matrix communication
  • Implements end-to-end encryption for secure messaging
  • Supports rich media sharing and VoIP calls

Cons of Element Android

  • Limited to Android platform, not cross-platform like Matrix Rust SDK
  • Potentially larger app size and resource usage compared to a Rust-based solution
  • May have slower performance for certain operations compared to Rust

Code Comparison

Element Android (Kotlin):

class RoomListViewModel @Inject constructor(
    private val session: Session,
    private val roomSummaryHolder: RoomSummaryHolder
) : ViewModel() {
    // Room list management logic
}

Matrix Rust SDK (Rust):

pub struct Client {
    base_client: BaseClient,
    encryption: Arc<RwLock<Encryption>>,
    // Client implementation details
}

The Element Android codebase focuses on Android-specific UI and functionality, while Matrix Rust SDK provides a lower-level, cross-platform implementation of Matrix protocols. Element Android uses Kotlin for Android development, whereas Matrix Rust SDK leverages Rust's performance and safety features for core Matrix operations.

A glossy Matrix collaboration client for iOS

Pros of Element iOS

  • Native iOS development using Swift, providing a smooth and platform-specific user experience
  • Direct integration with iOS-specific features and APIs
  • Easier for iOS developers to contribute and maintain

Cons of Element iOS

  • Limited to iOS platform, requiring separate codebases for other platforms
  • Potentially slower development of cross-platform features compared to a unified SDK

Code Comparison

Element iOS (Swift):

class RoomViewController: UIViewController {
    @IBOutlet weak var tableView: UITableView!
    var room: MXRoom?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupTableView()
    }
}

Matrix Rust SDK (Rust):

use matrix_sdk::Room;

struct RoomView {
    room: Room,
}

impl RoomView {
    fn new(room: Room) -> Self {
        RoomView { room }
    }
}

The Element iOS code showcases iOS-specific UI elements and patterns, while the Matrix Rust SDK code demonstrates a more platform-agnostic approach. Element iOS is tailored for iOS development, offering native integration and a familiar environment for iOS developers. However, it's limited to a single platform, whereas the Matrix Rust SDK provides a foundation for cross-platform development, potentially allowing for more unified codebases across different platforms.

Matrix Client-Server SDK for JavaScript

Pros of matrix-js-sdk

  • Wider ecosystem compatibility due to JavaScript's ubiquity
  • Easier integration with web applications and Node.js projects
  • More mature and feature-complete, with a larger community

Cons of matrix-js-sdk

  • Generally slower performance compared to Rust implementations
  • Higher memory usage, especially for large-scale applications
  • Less suitable for systems programming or low-level operations

Code Comparison

matrix-js-sdk:

const client = matrixcs.createClient({
  baseUrl: "https://matrix.org",
  accessToken: "YOUR_ACCESS_TOKEN",
  userId: "@alice:matrix.org"
});

client.on("Room.timeline", function(event, room, toStartOfTimeline) {
  console.log(event.getContent().body);
});

matrix-rust-sdk:

let client = Client::new(
    HomeserverUrl::parse("https://matrix.org")?,
    Some(Credentials::new("@alice:matrix.org", "YOUR_ACCESS_TOKEN")),
)?;

client.sync_once(SyncSettings::default()).await?;

for room in client.rooms() {
    println!("Room: {}", room.room_id());
}

The JavaScript SDK offers a more event-driven approach, while the Rust SDK provides a more synchronous, iterator-based interface. The Rust implementation may offer better performance and memory efficiency, especially for larger applications or systems with limited resources.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Build Status codecov License #matrix-rust-sdk Docs - Main Docs - Stable

matrix-rust-sdk

matrix-rust-sdk is an implementation of a Matrix client-server library in Rust.

Project structure

The rust-sdk consists of multiple crates that can be picked at your convenience:

  • matrix-sdk - High level client library, with batteries included, you're most likely interested in this.
  • matrix-sdk-base - No (network) IO client state machine that can be used to embed a Matrix client in your project or build a full fledged network enabled client lib on top of it.
  • matrix-sdk-crypto - No (network) IO encryption state machine that can be used to add Matrix E2EE support to your client or client library.

Minimum Supported Rust Version (MSRV)

These crates are built with the Rust language version 2021 and require a minimum compiler version of 1.70.

Status

The library is in an alpha state, things that are implemented generally work but the API will change in breaking ways.

If you are interested in using the matrix-sdk now is the time to try it out and provide feedback.

Bindings

Some crates of the matrix-rust-sdk can be embedded inside other environments, like Swift, Kotlin, JavaScript, Node.js etc. Please, explore the bindings/ directory to learn more.

License

Apache-2.0