### Full Sliding Sync Example Source: https://github.com/matrix-org/matrix-rust-sdk/blob/main/crates/matrix-sdk/src/sliding_sync/README.md Demonstrates the setup and usage of Sliding Sync with various configurations, including lists, modes, and event handling. This example requires a running Matrix homeserver and client setup. ```rust use matrix_sdk::{Client, sliding_sync::{SlidingSyncList, SlidingSyncMode, Version}}; use ruma::{api::client::sync::sync_events::v5 as http, assign, events::StateEventType}; use tracing::{warn, error, info, debug}; use futures_util::{pin_mut, StreamExt}; use url::Url; use std::future::ready; async fn run() -> Result<(), Box> { let homeserver = Url::parse("http://example.com")?; let access_token = "YOUR_ACCESS_TOKEN"; let device_id = "YOUR_DEVICE_ID"; let client = Client::builder() .homeserver_url(homeserver) .access_token(access_token) .device_id(device_id) .build() .await?; let mut sliding_sync = client.sliding_sync(); // Example: Add a list for rooms with specific criteria sliding_sync .add_list( SlidingSyncList::new( "my-list".to_string(), SlidingSyncMode::new_range(0, 20), ) .filter(Some(http::SyncRequestListFilter { is_direct: None, is_left: None, is_invite: None, is_room: None, room_name: None, spaces: None, })) .sort(Some(http::SyncRequestListSort::Ascending)) .required_state(vec![ (StateEventType::RoomMember, "@user:example.com".to_string()), ]) .bump_ செயல_state(true) .include_timeline_limit(Some(10)), ); // Example: Add another list for rooms with different criteria sliding_sync .add_list( SlidingSyncList::new( "invite-list".to_string(), SlidingSyncMode::new_invite(), ) .filter(Some(http::SyncRequestListFilter { is_direct: None, is_left: None, is_invite: Some(true), is_room: None, room_name: None, spaces: None, })) .sort(Some(http::SyncRequestListFilterSort::Ascending)) .required_state(vec![]) .bump_ செயல_state(false) .include_timeline_limit(None), ); // Example: Add a list for rooms with a specific space sliding_sync .add_list( SlidingSyncList::new( "space-list".to_string(), SlidingSyncMode::new_range(0, 50), ) .filter(Some(http::SyncRequestListFilter { is_direct: None, is_left: None, is_invite: None, is_room: None, room_name: None, spaces: Some(vec!["!spaceid:example.com".to_string()]), })) .sort(Some(http::SyncRequestListFilterSort::Ascending)) .required_state(vec![]) .bump_ செயல_state(false) .include_timeline_limit(Some(5)), ); // Build and run the Sliding Sync stream let mut stream = sliding_sync.build().await?; pin_mut!(stream); while let Some(response) = stream.next().await { match response { Ok(update_summary) => { info!("Received update summary: {:?}", update_summary); // Process room and list updates here if let Some(lists) = update_summary.lists { for (list_name, list_update) in lists { info!("List \"{}\" updated: rooms = {:?}", list_name, list_update.rooms); } } if let Some(rooms) = update_summary.rooms { for (room_id, room_update) in rooms { info!("Room \"{}\" updated: timeline = {:?}", room_id, room_update.timeline); } } } Err(e) => { error!("Error receiving update: {:?}", e); } } } Ok(()) } # Example usage (requires a runtime like tokio) # #[tokio::main] # async fn main() { # if let Err(e) = run().await { # eprintln!("Error: {}", e); # } # } # // Dummy Url and Client setup for compilation # mod matrix_sdk { # pub mod sliding_sync { # pub use super::super::SlidingSyncList; # pub use super::super::SlidingSyncMode; # pub use super::super::Version; # } # pub struct Client {} # impl Client { # pub fn builder() -> ClientBuilder { ClientBuilder {}} # } # pub struct ClientBuilder {} # impl ClientBuilder { # pub fn homeserver_url(self, _url: Url) -> Self { self } # pub fn access_token(self, _token: &str) -> Self { self } # pub fn device_id(self, _id: &str) -> Self { self } # pub async fn build(self) -> Result { Ok(Client {}) } # } # pub struct SlidingSync { _private: () } # impl Client { # pub fn sliding_sync(self) -> SlidingSync { SlidingSync { _private: () } } # } # impl SlidingSync { # pub fn add_list(self, _list: SlidingSyncList) -> Self { self } # pub async fn build(self) -> Result>, ()> { Ok(futures_util::stream::empty()) } # } # pub struct UpdateSummary { pub lists: Option>, pub rooms: Option> } # pub struct ListUpdate { pub rooms: Vec } # pub struct RoomUpdate { pub timeline: Vec } # } # mod ruma { # pub mod api { pub mod client { pub mod sync { pub mod v5 { pub struct SyncRequestListFilter { pub is_direct: Option, pub is_left: Option, pub is_invite: Option, pub is_room: Option, pub room_name: Option, pub spaces: Option> } pub enum SyncRequestListSort { Ascending } } } } } # #[derive(Clone)] # pub struct RoomId(String); # #[derive(Clone)] # pub struct EventId(String); # #[derive(Clone)] # pub struct StateEventType(String); # impl StateEventType { # pub const fn RoomMember() -> Self { StateEventType("m.room.member".to_string()) } # } # pub fn assign(val: T) -> T { val } # } # mod url { pub struct Url(String); impl Url { pub fn parse(s: &str) -> Result { Ok(Url(s.to_string())) } } } # mod tracing { pub mod warn { pub fn warn(msg: &str) { println!("WARN: {}", msg); } } pub mod error { pub fn error(msg: &str) { println!("ERROR: {}", msg); } } pub mod info { pub fn info(msg: &str) { println!("INFO: {}", msg); } } pub mod debug { pub fn debug(msg: &str) { println!("DEBUG: {}", msg); } } } # mod futures_util { pub mod pin_mut { pub fn pin_mut(t: T) -> T { t } } pub mod stream { pub struct Empty { _private: std::marker::PhantomData } pub fn empty() -> Empty { Empty { _private: std::marker::PhantomData } } impl Iterator for Empty { fn next(&mut self) -> Option { None } } impl futures_util::Stream for Empty { type Item = T; fn poll_next(self: std::pin::Pin<&mut Self>, _cx: &mut std::task::Context<'_>) -> std::task::Poll> { std::task::Poll::Ready(None) } } } } # } # impl SlidingSyncList { # pub fn new(name: String, mode: SlidingSyncMode) -> Self { SlidingSyncList { name, mode, filter: None, sort: None, required_state: vec![], bump_ செயல_state: false, include_timeline_limit: None } } # pub fn filter(mut self, filter: Option) -> Self { self.filter = filter; self } # pub fn sort(mut self, sort: Option) -> Self { self.sort = sort; self } # pub fn required_state(mut self, state: Vec<(StateEventType, String)>) -> Self { self.required_state = state; self } # pub fn bump_ செயல_state(mut self, bump: bool) -> Self { self.bump_ செயல_state = bump; self } # pub fn include_timeline_limit(mut self, limit: Option) -> Self { self.include_timeline_limit = limit; self } # } # pub enum SlidingSyncMode { Range(u32, u32), Invite } # impl SlidingSyncMode { pub fn new_range(start: u32, end: u32) -> Self { SlidingSyncMode::Range(start, end) } pub fn new_invite() -> Self { SlidingSyncMode::Invite } } # pub struct SlidingSyncList { name: String, mode: SlidingSyncMode, filter: Option, sort: Option, required_state: Vec<(StateEventType, String)>, bump_ செயல_state: bool, include_timeline_limit: Option } # pub enum Version { V1, V2, V3, V4, V5 } # impl Version { pub fn v5() -> Self { Version::V5 } } # ``` -------------------------------- ### Changelog Fragment Examples Source: https://github.com/matrix-org/matrix-rust-sdk/blob/main/CONTRIBUTING.md Examples of valid changelog fragment filenames. ```text 4357.added.md ``` ```text 4357.fixed.md ``` ```text 4357.changed.md ``` -------------------------------- ### Start Synapse Server with Docker Compose Source: https://github.com/matrix-org/matrix-rust-sdk/blob/main/testing/matrix-sdk-integration-testing/README.md Use this command to start the Synapse backend server and its dependencies using Docker Compose. It also shows how to view the logs. ```bash docker compose -f assets/docker-compose.yml up -d docker compose -f assets/docker-compose.yml logs --tail 100 -f ``` -------------------------------- ### Install Insta.rs Snapshot Testing Tool (Windows) Source: https://github.com/matrix-org/matrix-rust-sdk/blob/main/CONTRIBUTING.md Installs the `cargo-insta` tool using a PowerShell script for snapshot testing on Windows. ```powershell powershell -c "irm https://insta.rs/install.ps1 | iex" ``` -------------------------------- ### Install Insta.rs Snapshot Testing Tool (Unix) Source: https://github.com/matrix-org/matrix-rust-sdk/blob/main/CONTRIBUTING.md Installs the `cargo-insta` tool using a curl script for snapshot testing on Unix-like systems. ```shell curl -LsSf https://insta.rs/install.sh | sh ``` -------------------------------- ### Install Development Dependencies Source: https://github.com/matrix-org/matrix-rust-sdk/blob/main/CONTRIBUTING.md Installs necessary tools like clippy, cargo-nextest, typos-cli, and wasm-pack for running tests and development tasks. ```bash rustup component add clippy cargo install cargo-nextest typos-cli wasm-pack ``` -------------------------------- ### Basic Matrix Client Usage Source: https://github.com/matrix-org/matrix-rust-sdk/blob/main/crates/matrix-sdk/README.md Demonstrates how to instantiate a Matrix client, log in a user, register an event handler for messages, and initiate a sync with the server. This is a fundamental example for typical client or bot development. ```rust use matrix_sdk::Client; use matrix_sdk::config::SyncSettings; use ruma::{user_id, events::room::message::SyncRoomMessageEvent}; #[tokio::main] async fn main() -> anyhow::Result<()> { let alice = user_id!("@alice:example.org"); let client = Client::builder().server_name(alice.server_name()).build().await?; // First we need to log in. client.matrix_auth().login_username(alice, "password").send().await?; client.add_event_handler(|ev: SyncRoomMessageEvent| async move { println!("Received a message {:?}", ev); }); // Syncing is important to synchronize the client state with the server. // This method will never return unless there is an error. client.sync(SyncSettings::default()).await?; Ok(()) } ``` -------------------------------- ### Widget Driver Setup and Message Handling Source: https://github.com/matrix-org/matrix-rust-sdk/blob/main/crates/matrix-sdk/src/widget/README.md Demonstrates how to set up a CapabilitiesProvider and WidgetDriver, and configure message routing for widget communication. This involves spawning tasks to handle incoming and outgoing messages. ```rust #[derive(Clone)] struct CapProv {} impl CapabilitiesProvider for CapProv { async fn acquire_capabilities(&self, requested_capabilities: Capabilities) -> Capabilities { // Only approve capabilities the user has approved interactively let approved_capabilities = prompt_user_for_capabilities(requested_capabilities).await; approved_capabilities } } let widget_settings = WidgetSettings { widget_id: "String", init_on_content_load: true, raw_url: "https://Url", }; // Create the required structs: let (driver, handle) = WidgetDriver::new(widget_settings); let cap_provider = CapProv {}; // Set up message routing let h = handle.clone(); spawn(async move { loop { let message = my_platform::postmessage_receiver.recv::().await; h.send(message).await; } }); spawn(async move { while let Some(msg) = handle.recv().await { let script = format!( "document.getElementById('widget').contentWindow.postMessage({}, '{}');", message, url, ); my_platform::eval(&script); } }); spawn(async move { let _ = driver.run(room, cap_provider).await; }); ``` -------------------------------- ### Bad Changelog Entry Example 2 Source: https://github.com/matrix-org/matrix-rust-sdk/blob/main/CONTRIBUTING.md An example of a changelog entry that is too brief and lacks detail. ```markdown Added the Bar function to Foo. ``` -------------------------------- ### Rust StoreCipher Usage Example Source: https://github.com/matrix-org/matrix-rust-sdk/blob/main/crates/matrix-sdk-store-encryption/README.md Demonstrates how to initialize a StoreCipher, encrypt and decrypt values, and hash keys for a key/value store. ```rust use matrix_sdk_store_encryption::StoreCipher; use serde_json::{json, value::Value}; fn main() -> anyhow::Result<()> { let store_cipher = StoreCipher::new()?; // Export the store cipher and persist it in your key/value store let export = store_cipher.export("secret-passphrase")?; let value = json!({ "some": "data", }); let encrypted = store_cipher.encrypt_value(&value)?; let decrypted: Value = store_cipher.decrypt_value(&encrypted)?; assert_eq!(value, decrypted); let key = "bulbasaur"; // Hash the key so people don't know which pokemon we have collected. let hashed_key = store_cipher.hash_key("list-of-pokemon", key.as_ref()); let another_table = store_cipher.hash_key("my-starter", key.as_ref()); let same_key = store_cipher.hash_key("my-starter", key.as_ref()); assert_ne!(key.as_ref(), hashed_key); assert_ne!(hashed_key, another_table); assert_eq!(another_table, same_key); Ok(()) } ``` -------------------------------- ### Good Changelog Entry Example Source: https://github.com/matrix-org/matrix-rust-sdk/blob/main/CONTRIBUTING.md A well-written changelog entry providing sufficient context for clarity. ```markdown Use the inviter's server name and the server name from the room alias as fallback values for the via parameter when requesting the room summary from the homeserver. This ensures requests succeed even when the room being previewed is hosted on a federated server. ``` -------------------------------- ### Bad Changelog Entry Example 1 Source: https://github.com/matrix-org/matrix-rust-sdk/blob/main/CONTRIBUTING.md An example of a changelog entry that lacks sufficient context. ```markdown - Fixed a panic. ``` -------------------------------- ### Rust End-to-End Encryption State Machine Example Source: https://github.com/matrix-org/matrix-rust-sdk/blob/main/crates/matrix-sdk-crypto/README.md Demonstrates how to initialize and use the OlmMachine for handling Matrix end-to-end encryption. It shows pushing sync changes and pulling outgoing requests. ```rust use std::collections::BTreeMap; use matrix_sdk_crypto::{ DecryptionSettings, EncryptionSyncChanges, OlmError, OlmMachine, TrustRequirement, }; use ruma::{api::client::sync::sync_events::DeviceLists, device_id, user_id}; #[tokio::main] async fn main() -> Result<(), OlmError> { let alice = user_id!("@alice:example.org"); let machine = OlmMachine::new(&alice, device_id!("DEVICEID")).await; let changed_devices = DeviceLists::default(); let one_time_key_counts = BTreeMap::default(); let unused_fallback_keys = Some(Vec::new()); let next_batch_token = "T0K3N".to_owned(); let decryption_settings = DecryptionSettings { sender_device_trust_requirement: TrustRequirement::Untrusted }; // Push changes that the server sent to us in a sync response. let decrypted_to_device = machine .receive_sync_changes( EncryptionSyncChanges { to_device_events: vec![], changed_devices: &changed_devices, one_time_keys_counts: &one_time_key_counts, unused_fallback_keys: unused_fallback_keys.as_deref(), next_batch_token: Some(next_batch_token), }, &decryption_settings, ) .await?; // Pull requests that we need to send out. let outgoing_requests = machine.outgoing_requests().await?; // Send the requests out here and call machine.mark_request_as_sent(). Ok(()) } ``` -------------------------------- ### Start Sliding Sync Session Source: https://github.com/matrix-org/matrix-rust-sdk/blob/main/crates/matrix-sdk/src/sliding_sync/README.md Initiates a new Sliding Sync session with a unique identifier and specifies the version. Requires an authenticated Client instance. ```rust use matrix_sdk::{Client, sliding_sync::Version}; use url::Url; async { let homeserver = Url::parse("http://example.com")?; let client = Client::new(homeserver).await?; let sliding_sync_builder = client .sliding_sync("main-sync")? .version(Version::Native); anyhow::Ok(()) }; ``` -------------------------------- ### Security Changelog Entry Example Source: https://github.com/matrix-org/matrix-rust-sdk/blob/main/CONTRIBUTING.md A security-related changelog entry including impact, CVE, and GitHub advisory details. ```markdown Use a constant-time Base64 encoder for secret key material to mitigate side-channel attacks leaking secret key material [CVE-2024-40640](https://www.cve.org/CVERecord?id=CVE-2024-40640), [GHSA-j8cm-g7r6-hfpq](https://github.com/matrix-org/vodozemac/security/advisories/GHSA-j8cm-g7r6-hfpq)). ``` -------------------------------- ### Add Rust Target for Cross Compilation Source: https://github.com/matrix-org/matrix-rust-sdk/blob/main/bindings/matrix-sdk-crypto-ffi/README.md Installs the Rust target for a specific Android architecture, enabling cross-compilation. ```bash # rustup target add aarch64-linux-android ``` -------------------------------- ### Set Android NDK Path Source: https://github.com/matrix-org/matrix-rust-sdk/blob/main/bindings/matrix-sdk-crypto-ffi/README.md Sets the ANDROID_NDK environment variable to the location of the Android NDK installation. Replace with the actual NDK version. ```bash $ export ANDROID_NDK=$HOME/Android/Sdk/ndk/ ``` -------------------------------- ### Security Fix Commit Example Source: https://github.com/matrix-org/matrix-rust-sdk/blob/main/CONTRIBUTING.md A commit message addressing a security vulnerability, including required git trailers. ```text fix(crypto): Use a constant-time Base64 encoder for secret key material This patch fixes a security issue around a side-channel vulnerability[1] when decoding secret key material using Base64. In some circumstances an attacker can obtain information about secret secret key material via a controlled-channel and side-channel attack. This patch avoids the side-channel by switching to the base64ct crate for the encoding, and more importantly, the decoding of secret key material. Security-Impact: Low CVE: CVE-2024-40640 GitHub-Advisory: GHSA-j8cm-g7r6-hfpq ``` -------------------------------- ### Configuring Sliding Sync with Extensions and Lists Source: https://github.com/matrix-org/matrix-rust-sdk/blob/main/crates/matrix-sdk/src/sliding_sync/README.md Demonstrates how to build a Sliding Sync configuration with various extensions (account data, E2EE, to-device) and define multiple sync lists with different synchronization modes and requirements. ```rust let full_sync_list_name = "full-sync".to_owned(); let active_list_name = "active-list".to_owned(); let sliding_sync_builder = client .sliding_sync("main-sync")? .version(Version::Native) .with_account_data_extension( assign!(http::request::AccountData::default(), { enabled: Some(true) }), ) // we enable the account-data extension .with_e2ee_extension(assign!(http::request::E2EE::default(), { enabled: Some(true) })) // and the e2ee extension .with_to_device_extension( assign!(http::request::ToDevice::default(), { enabled: Some(true) }), ); // and the to-device extension let full_sync_list = SlidingSyncList::builder(&full_sync_list_name) .sync_mode(SlidingSyncMode::Growing { batch_size: 50, maximum_number_of_rooms_to_fetch: Some(500) }) // sync up by growing the window .required_state(vec![ (StateEventType::RoomEncryption, "".to_owned()) ]); // only want to know if the room is encrypted let active_list = SlidingSyncList::builder(&active_list_name) // the active window .sync_mode(SlidingSyncMode::new_selective().add_range(0..=9)) // sync up the specific range only, first 10 items .timeline_limit(5u32) // add the last 5 timeline items for room preview and faster timeline loading .required_state(vec![ // we want to know immediately: (StateEventType::RoomEncryption, "".to_owned()), // is it encrypted (StateEventType::RoomTopic, "".to_owned()), // any topic if known (StateEventType::RoomAvatar, "".to_owned()), // avatar if set ]); let sliding_sync = sliding_sync_builder .add_list(active_list) .add_list(full_sync_list) .build() .await?; ``` -------------------------------- ### Create a Room Index on Disk Source: https://github.com/matrix-org/matrix-rust-sdk/blob/main/crates/matrix-sdk-search/README.md Constructs a `RoomIndex` instance on disk using `RoomIndexBuilder`. This is the recommended way to initialize a new index. ```rust use std::path::PathBuf; use matrix_sdk_search::{ error::IndexError, index::{ RoomIndex, builder::RoomIndexBuilder, }, }; use ruma::RoomId; fn create_index(path: PathBuf, room_id: &RoomId) -> Result { RoomIndexBuilder::new_on_disk(path, room_id).unencrypted().build() } ``` -------------------------------- ### Run All Benchmarks Source: https://github.com/matrix-org/matrix-rust-sdk/blob/main/benchmarks/README.md Execute all benchmarks for the rust-sdk crypto layer. This is the standard command to initiate the benchmarking process. ```bash $ cargo bench ``` -------------------------------- ### Building a Selective Sliding Sync List Source: https://github.com/matrix-org/matrix-rust-sdk/blob/main/crates/matrix-sdk/src/sliding_sync/README.md Demonstrates how to create a Sliding Sync list with a specific sync mode and filters, such as including only invites. ```rust use matrix_sdk::sliding_sync::{SlidingSyncList, SlidingSyncMode}; use ruma::{api::client::sync::sync_events::v5 as http, assign}; let list_builder = SlidingSyncList::builder("main_list") .sync_mode(SlidingSyncMode::new_selective().add_range(0..=9)) .filters(Some(assign!( http::request::ListFilters::default(), { is_invite: Some(true)} ))); ``` -------------------------------- ### Build Full SDK XCFramework Source: https://github.com/matrix-org/matrix-rust-sdk/blob/main/bindings/apple/README.md Use this command to build a complete XCFramework for the Matrix SDK. This process compiles libraries, bundles them, generates Swift files, and creates the final .xcframework. ```text cargo xtask swift build-framework ``` -------------------------------- ### Run Multiverse TUI Client Source: https://github.com/matrix-org/matrix-rust-sdk/blob/main/labs/README.md Launches the Multiverse TUI client for quick SDK feature development and debugging. Requires specifying the homeserver URL and a cache directory. ```bash cargo run --bin multiverse matrix.org ~/.cache/multiverse-cache ``` -------------------------------- ### Widget API Error Response Source: https://github.com/matrix-org/matrix-rust-sdk/blob/main/crates/matrix-sdk/src/widget/README.md An example of an error response within the widget postMessage API. It includes a 'response' object with a sole 'error' key containing a human-friendly message and the original error object. ```json { ... error: { message: "Unable to invite user into room.", } } ``` -------------------------------- ### Switch to a Release Branch Source: https://github.com/matrix-org/matrix-rust-sdk/blob/main/RELEASING.md Create a new branch for the release. Replace 'x.y.z' with the target version. ```bash git switch -c release-x.y.z ``` -------------------------------- ### Prepare Release Artifacts Source: https://github.com/matrix-org/matrix-rust-sdk/blob/main/RELEASING.md Update README, set versions in CHANGELOG, and bump version in Cargo.toml. Choose 'minor', 'patch', or 'rc' for the version bump. ```bash cargo xtask release prepare --execute minor|patch|rc ``` -------------------------------- ### Handling Sliding Sync Updates with Streams Source: https://github.com/matrix-org/matrix-rust-sdk/blob/main/crates/matrix-sdk/src/sliding_sync/README.md Shows how to spawn a task to listen for room updates and continuously poll for Sliding Sync updates using streams. ```rust tokio::spawn(async move { // subscribe to rooms updates let (_rooms, rooms_stream) = client.rooms_stream(); // do something with `_rooms` pin_mut!(rooms_stream); while let Some(_room) = rooms_stream.next().await { info!("a room has been updated"); } }); let stream = sliding_sync.sync(); // continuously poll for updates pin_mut!(stream); loop { let update = match stream.next().await { Some(Ok(u)) => { info!("Received an update. Summary: {u:?}"); }, Some(Err(e)) => { error!("loop was stopped by client error processing: {e}"); } None => { error!("Streaming loop ended unexpectedly"); break; } }; } ``` -------------------------------- ### Run and Review Snapshot Tests Source: https://github.com/matrix-org/matrix-rust-sdk/blob/main/CONTRIBUTING.md Commands to execute snapshot tests and enter the review mode to inspect changes using `cargo-insta`. ```bash cargo insta test cargo insta review ``` -------------------------------- ### Publish Release to crates.io Source: https://github.com/matrix-org/matrix-rust-sdk/blob/main/RELEASING.md After the release branch is merged, switch to main, pull changes, and then execute the publish command. This creates tags, publishes to crates.io, and pushes tags. ```bash # Switch to main first. git switch main # Pull in the now-merged release commit(s). git pull # Create tags, publish the release on crates.io, and push the tags. cargo xtask release publish --execute ``` -------------------------------- ### Add NDK Tools to PATH Source: https://github.com/matrix-org/matrix-rust-sdk/blob/main/bindings/matrix-sdk-crypto-ffi/README.md Includes the NDK tools directory in the system's PATH environment variable to make NDK executables accessible. ```bash $ export PATH="$ANDROID_NDK/toolchains/llvm/prebuilt/linux-x86_64/bin:$PATH" ``` -------------------------------- ### Push Release Branch Source: https://github.com/matrix-org/matrix-rust-sdk/blob/main/RELEASING.md After preparing the release and making any necessary edits to changelog and readme files, push the release branch to origin. ```bash git push --set-upstream origin/release-x.y.z ``` -------------------------------- ### Enable Flame Graph Generation Source: https://github.com/matrix-org/matrix-rust-sdk/blob/main/benchmarks/README.md Generate flame graphs for benchmarks by enabling profiling mode with the --profile-time flag. This requires adjusting kernel parameters for performance event monitoring. ```bash $ echo -1 | sudo tee /proc/sys/kernel/perf_event_paranoid ``` ```bash $ cargo bench --bench crypto_bench -- --profile-time=5 ``` -------------------------------- ### Configure Cargo Linker in .cargo/config.toml Source: https://github.com/matrix-org/matrix-rust-sdk/blob/main/bindings/matrix-sdk-crypto-ffi/README.md Configures the Cargo target linker within the .cargo/config.toml file for cross-compilation. Replace with the actual NDK path. ```toml [target.aarch64-linux-android] linker = "/toolchains/llvm/prebuilt/linux-x86_64/bin/aarch64-linux-android30-clang" ``` -------------------------------- ### Render Decision Tree (PDF and PNG) Source: https://github.com/matrix-org/matrix-rust-sdk/blob/main/contrib/key-forwarding-algorithm/README.md Use this command to render the decision tree for the key forwarding algorithm in both PDF and PNG formats. ```text make ``` -------------------------------- ### Build FFI Bindings for Android Target Source: https://github.com/matrix-org/matrix-rust-sdk/blob/main/bindings/matrix-sdk-crypto-ffi/README.md Compiles the FFI bindings for the specified Android target architecture (e.g., aarch64). ```bash $ cargo build --target aarch64-linux-android ``` -------------------------------- ### Configure Cargo Linker via Environment Variable Source: https://github.com/matrix-org/matrix-rust-sdk/blob/main/bindings/matrix-sdk-crypto-ffi/README.md Sets the Cargo target linker using an environment variable for cross-compilation. Replace with the actual NDK path. ```bash $ export CARGO_TARGET_AARCH64_LINUX_ANDROID_LINKER="/toolchains/llvm/prebuilt/linux-x86_64/bin/aarch64-linux-android30-clang" ``` -------------------------------- ### Run Multiverse with Proxy for Network Inspection Source: https://github.com/matrix-org/matrix-rust-sdk/blob/main/labs/README.md Launches the Multiverse TUI client with proxy support enabled for inspecting network requests using tools like mitmproxy. Specify the proxy address and the client's homeserver and cache directory. ```bash cargo run --bin multiverse -- --proxy http://localhost:8080 matrix.org ~/.cache/multiverse-cache ``` -------------------------------- ### Build Crypto SDK XCFramework Source: https://github.com/matrix-org/matrix-rust-sdk/blob/main/bindings/apple/README.md Execute this script to build an XCFramework specifically for the Matrix SDK's crypto module. It compiles and bundles the necessary libraries for iOS. ```shell build_crypto_xcframework.sh ``` -------------------------------- ### Render Decision Tree (PNG) Source: https://github.com/matrix-org/matrix-rust-sdk/blob/main/contrib/key-forwarding-algorithm/README.md Use this command to render the decision tree for the key forwarding algorithm specifically as a PNG. ```text make png ``` -------------------------------- ### Run Benchmarks with Profiling Profile Source: https://github.com/matrix-org/matrix-rust-sdk/blob/main/benchmarks/README.md Use the 'profiling' cargo profile to balance compile times and runtime performance for benchmarks. This is useful for reducing the overhead during development. ```bash $ cargo bench --profile profiling ``` -------------------------------- ### Render Decision Tree (PDF) Source: https://github.com/matrix-org/matrix-rust-sdk/blob/main/contrib/key-forwarding-algorithm/README.md Use this command to render the decision tree for the key forwarding algorithm specifically as a PDF. ```text make pdf ``` -------------------------------- ### Compare Against Benchmark Baseline Source: https://github.com/matrix-org/matrix-rust-sdk/blob/main/benchmarks/README.md Compare current benchmark results against a previously saved baseline using the --baseline flag. This helps track performance regressions or improvements. ```bash $ cargo bench --bench crypto_bench -- --baseline libolm ``` -------------------------------- ### Enable Logging with tracing-subscriber Source: https://github.com/matrix-org/matrix-rust-sdk/blob/main/crates/matrix-sdk/README.md Include this line in your application to enable log output. Log levels are controlled via the RUST_LOG environment variable. ```rust tracing_subscriber::fmt::init(); ``` -------------------------------- ### Changelog Fragment Directory Source: https://github.com/matrix-org/matrix-rust-sdk/blob/main/CONTRIBUTING.md Changelog fragments should be placed in the appropriate crate's changelog.d directory. ```text /crates//changelog.d/ ``` -------------------------------- ### Copy and Rename FFI Library for Android Project Source: https://github.com/matrix-org/matrix-rust-sdk/blob/main/bindings/matrix-sdk-crypto-ffi/README.md Copies the compiled dynamic library to the appropriate location and renames it for integration into an Android project's jniLibs directory. Adjust paths as necessary. ```bash $cp ../../target/aarch64-linux-android/debug/libmatrix_sdk_crypto_ffi.so \ /home/example/matrix-sdk-android/src/main/jniLibs/aarch64/libuniffi_olm.so ``` -------------------------------- ### Add IndexedDB Support to Matrix SDK Source: https://github.com/matrix-org/matrix-rust-sdk/blob/main/crates/matrix-sdk-indexeddb/README.md Include the matrix-sdk with the 'indexeddb' feature enabled for WASM targets. This is the most common way to integrate the IndexedDB backend. ```toml [target.'cfg(target_family = "wasm")'.dependencies] matrix-sdk = { version = "0.5, default-features = false, features = ["indexeddb", "e2e-encryption"] } ``` -------------------------------- ### Save Benchmark Baseline Source: https://github.com/matrix-org/matrix-rust-sdk/blob/main/benchmarks/README.md Create a baseline for a benchmark using the --save-baseline flag. This establishes a reference point for future performance comparisons. ```bash $ cargo bench --bench crypto_bench -- --save-baseline libolm ``` -------------------------------- ### Encode Data into a QR Code Source: https://github.com/matrix-org/matrix-rust-sdk/blob/main/crates/matrix-sdk-qrcode/README.md Use this snippet to encode verification data into a QR code. Ensure you have the `image` crate as a dependency for rendering. This function takes byte data and converts it into a renderable QR code image. ```rust use matrix_sdk_qrcode::{QrVerificationData, DecodingError}; use image::Luma; fn main() -> Result<(), DecodingError> { let data = b"MATRIX\ \x02\x02\x00\x07\ FLOW_ID\ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\ BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\ SHARED_SECRET"; let data = QrVerificationData::from_bytes(data)?; let encoded = data.to_qr_code().unwrap(); let image = encoded.render::>().build(); Ok(()) } ``` -------------------------------- ### Run a Specific Benchmark Source: https://github.com/matrix-org/matrix-rust-sdk/blob/main/benchmarks/README.md Execute only a particular benchmark by providing its name as an argument. This is useful for focusing on specific performance tests. ```bash $ cargo bench --bench crypto_bench "Room key sharing/" ``` -------------------------------- ### Continuously Poll Sliding Sync Stream Source: https://github.com/matrix-org/matrix-rust-sdk/blob/main/crates/matrix-sdk/src/sliding_sync/README.md This Rust code snippet demonstrates how to set up a Sliding Sync stream and continuously poll it for updates. It shows how to handle successful updates and errors, and how to break the loop if the stream ends unexpectedly. Ensure you have a Matrix client initialized and have built your Sliding Sync configuration. ```rust use futures_util::{pin_mut, StreamExt}; use matrix_sdk::Client; use tracing::{error, info}; use url::Url; async { let homeserver = Url::parse("http://example.com")?; let client = Client::new(homeserver).await?; let sliding_sync = client .sliding_sync("main-sync")? // any lists you want are added here. .build() .await?; let stream = sliding_sync.sync(); // continuously poll for updates pin_mut!(stream); loop { let update = match stream.next().await { Some(Ok(u)) => { info!("Received an update. Summary: {u:?}"); } Some(Err(e)) => { error!("loop was stopped by client error processing: {e}"); } None => { error!("Streaming loop ended unexpectedly"); break; } }; } anyhow::Ok(()) }; ``` -------------------------------- ### Create a fixup commit Source: https://github.com/matrix-org/matrix-rust-sdk/blob/main/CONTRIBUTING.md Use fixup commits to mark changes as corrections for specific previous commits in a pull request. This aids in rebasing and squashing later. ```shell git commit --fixup= ``` -------------------------------- ### Visualizing Unencrypted Message Flow Source: https://github.com/matrix-org/matrix-rust-sdk/blob/main/crates/matrix-sdk/src/docs/encryption.md Illustrates the basic flow of encrypted messages from one client to another via the homeserver, where the server cannot decrypt the content. ```text ┌──────────────┐ │ Homeserver │ ┌───────┐ │ │ ┌───────┐ │ Alice │═══════════════►│ unencrypted │═══════════════►│ Bob │ └───────┘ encrypted │ │ encrypted └───────┘ └──────────────┘ ``` -------------------------------- ### Pass Options to Specific Benchmark Source: https://github.com/matrix-org/matrix-rust-sdk/blob/main/benchmarks/README.md Specify the benchmark name to pass custom options to Criterion. This allows fine-grained control over individual benchmark runs. ```bash $ cargo bench --bench crypto_bench -- # Your options go here ``` -------------------------------- ### Rebuild Synapse Docker Image Source: https://github.com/matrix-org/matrix-rust-sdk/blob/main/testing/matrix-sdk-integration-testing/README.md Rebuilds the custom Synapse Docker image, pulling the latest version if available. This is necessary after updating the Synapse version. ```bash docker compose -f assets/docker-compose.yml build --pull synapse ``` -------------------------------- ### Rebase with autosquash Source: https://github.com/matrix-org/matrix-rust-sdk/blob/main/CONTRIBUTING.md After addressing all requested changes and before re-requesting a review, rebase your pull request to squash fixup commits. The autosquash option simplifies this process. ```shell git rebase main --interactive --autosquash ``` -------------------------------- ### Mass Sign-off using Git Rebase Source: https://github.com/matrix-org/matrix-rust-sdk/blob/main/CONTRIBUTING.md Command to automatically add sign-off lines to previous commits if you forgot to do so. Requires Git version 2.17 or later. ```bash git rebase --signoff origin/main ``` -------------------------------- ### Conventional Commit Format Source: https://github.com/matrix-org/matrix-rust-sdk/blob/main/CONTRIBUTING.md The standard format for commit messages, including type and scope. ```text (): ``` -------------------------------- ### Visualizing Encrypted Message Flow with Server Encryption Source: https://github.com/matrix-org/matrix-rust-sdk/blob/main/crates/matrix-sdk/src/docs/encryption.md Depicts the flow of messages that are encrypted for end-to-end decryption, showing that the homeserver itself handles encrypted data. ```text ┌──────────────┐ │ Homeserver │ ┌───────┐ │ │ ┌───────┐ │ Alice │≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡►│─────────────►│≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡►│ Bob │ └───────┘ encrypted │ encrypted │ encrypted └───────┘ └──────────────┘ ``` -------------------------------- ### Restart Synapse Service After Rebuild Source: https://github.com/matrix-org/matrix-rust-sdk/blob/main/testing/matrix-sdk-integration-testing/README.md Restarts the Synapse service after its Docker image has been rebuilt. ```bash docker compose -f assets/docker-compose.yml up -d synapse ```