An async-ready Phoenix Channels v2 client library in Rust

Overview

Phoenix Channels

This crate implements a Phoenix Channels (v2) client in Rust.

Status

NOTE: This client is still a work-in-progress, though it has enough features to support many use cases already. The following is a list of known missing features:

  • Reconnect on error/disconnect
  • Ability to send binary messages, receive is implemented however
  • More thorough integration testing
  • Add support for v1 protocol

About

This client was built to support its use in the LiveView Native core library, which is also implemented in Rust.

The client is implemented on top of tokio, and is designed for the Rust async ecosystem, though it is possible to use the client in a non-async application, with the caveat that you still have to pull in tokio and its dependencies to do so.

This client is brand new, so it likely has bugs and missing features. Bug reports/feature requests are welcome though, so if you do find any issues, please let us know on the issue tracker!

Usage

Add to your dependencies like so:

[dependencies]
phoenix_channels_client = { version = "0.1" }

And in your .cargo/config.toml, turn on unstable tokio features we need for eg. cooperative scheduling:

[build]
rustflags = ["--cfg", "tokio_unstable"]

You can also enable nightly features using features = ["nightly"], currently this only is used to make use of a few nightly APIs for operating on slices, which we use while parsing.

Example

use std::time::Duration;
use serde_json::json;

use phoenix_channels_client::{Config, Client};

#[tokio::main]
async fn main() {
    // Prepare configuration for the client
    let mut config = Config::new("ws://127.0.0.1:9002/socket/websocket").unwrap();
    config.set("shared_secret", "supersecret");

    // Create a client
    let mut client = Client::new(config).unwrap();

    // Connect the client
    client.connect().await.unwrap();

    // Join a channel with a timeout
    let channel = client.join("channel:mytopic", Some(Duration::from_secs(15))).await.unwrap();

    // Register an event handler, save the ref returned and use `off` to unsubscribe
    channel.on("some_event", |channel, payload| {
        println!("channel received {} from topic '{}'", payload, channel.topic());
    }).await.unwrap();

    // Send a message, waiting for a reply indefinitely
    let result = channel.send("send_reply", json!({ "name": "foo", "message": "hi"})).await.unwrap();

    // Send a message, waiting for a reply with an optional timeout
    let result = channel.send_with_timeout("send_reply", json!({ "name": "foo", "message": "hello"}), Some(Duration::from_secs(5))).await.unwrap();

    // Send a message, not waiting for a reply
    let result = channel.send_noreply("send_noreply", json!({ "name": "foo", "message": "jeez"})).await.unwrap();

    // Leave the channel
    channel.leave().await;
}

Contributing

Contributions are welcome! Before starting work on any big PRs, it is recommended you open an issue to discuss the work with the maintainers, or you may risk wasting your time implementing something that is already being worked on!

License

Apache 2.0

You might also like...
Rust async runtime based on io-uring.

Monoio A thread-per-core Rust runtime with io_uring. 中文说明 Design Goal As a runtime based on io_uring, Monoio is designed to be the most efficient and

🐚 An async & dynamic ORM for Rust
🐚 An async & dynamic ORM for Rust

SeaORM 🐚 An async & dynamic ORM for Rust SeaORM SeaORM is a relational ORM to help you build web services in Rust with the familiarity of dynamic lan

Quick Pool: High Performance Rust Async Resource Pool

Quick Pool High Performance Rust Async Resource Pool Usage DBCP Database Backend Adapter Version PostgreSQL tokio-postgres qp-postgres Example use asy

Dataloader-rs - Rust implementation of Facebook's DataLoader using async-await.

Dataloader Rust implementation of Facebook's DataLoader using async-await. Documentation Features Batching load requests with caching Batching load re

Automatically deleted async I/O temporary files in Rust

async-tempfile Provides the TempFile struct, an asynchronous wrapper based on tokio::fs for temporary files that will be automatically deleted when th

Go like sync.WaitGroup implementation in Rust. (sync/async)

WAG Go like sync.WaitGroup implementation in Rust. (sync/async) | Examples | Docs | Latest Note | wag = "0.3.0" How to use, use wag::WaitGroup; let w

Notification demon + web server using async Rust
Notification demon + web server using async Rust

Async Rust example Road to the asynchronous Rust Table of Contents About the Project Screenshots Tech Stack Features Getting Started Prerequisites Clo

An async executor based on the Win32 thread pool API

wae An async executor based on the Win32 thread pool API use futures::channel::oneshot; #[wae::main] async fn main() { let (tx, rx) = oneshot::ch

Async positioned I/O with io_uring.

uring-positioned-io Fully asynchronized positioned I/O with io_uring. Basic Usage let files = vec![File::open("test.txt").unwrap()]; let context = Uri

Comments
  • Is there a plan to release this library directly as a Swift Package or gradle dependency?

    Is there a plan to release this library directly as a Swift Package or gradle dependency?

    Looking through the structure of these libraries, it looks like liveview-native-core imports phoenix-channels-client and then liveview-native-core is compiled into multiple architectures and made available as a swift package. Are there any plans to release phoenix-channels-client as a stand-alone library that can be pulled in to an iOS or Android app without pulling in LiveView Native?

    opened by dsrees 2
  • fix a couple of setup snippets in README

    fix a couple of setup snippets in README

    2 tiny tweaks to the README

    • correct package name
    • add a .cargo/config.toml snippet they'll need (otherwise the eg. 'consume_budget' cooperative scheduling functions this uses won't be found)
    opened by mrluc 0
Owner
LiveView Native
Native platform implementations of the Phoenix LiveView protocol
LiveView Native
📺 Netflix in Rust/ React-TS/ NextJS, Actix-Web, Async Apollo-GraphQl, Cassandra/ ScyllaDB, Async SQLx, Kafka, Redis, Tokio, Actix, Elasticsearch, Influxdb Iox, Tensorflow, AWS

Fullstack Movie Streaming Platform ?? Netflix in RUST/ NextJS, Actix-Web, Async Apollo-GraphQl, Cassandra/ ScyllaDB, Async SQLx, Spark, Kafka, Redis,

null 34 Apr 17, 2023
Async Lightweight HTTP client using system native library if possible. (Currently under heavy development)

Async Lightweight HTTP Client (aka ALHC) What if we need async but also lightweight http client without using such a large library like reqwest, isahc

SteveXMH 7 Dec 15, 2022
High-level async Cassandra client written in 100% Rust.

CDRS tokio CDRS is production-ready Apache Cassandra driver written in pure Rust. Focuses on providing high level of configurability to suit most use

Kamil Rojewski 73 Dec 26, 2022
An async Rust client for SurrealDB's RPC endpoint

An async Rust client for SurrealDB's RPC endpoint This crate serves as a temporary yet complete implementation of an async Rust client to connect to a

Thibault H 12 Jan 21, 2023
Lightweight async Redis client with connection pooling written in pure Rust and 100% memory safe

redi-rs (or redirs) redi-rs is a Lightweight Redis client with connection pooling written in Rust and 100% memory safe redi-rs is a Redis client writt

Oğuz Türkay 4 May 20, 2023
The most efficient, scalable, and fast production-ready serverless REST API backend which provides CRUD operations for a MongoDB collection

Optimal CRUD Mongo Goals of This Project This is meant to be the most efficient, scalable, and fast production-ready serverless REST API backend which

Evaluates2 1 Feb 22, 2022
Affine-client is a client for AFFINE based on Tauri

Affine Client affine-client is a client for AFFINE based on Tauri Supported Platforms Windows Linux MacOS Download https://github.com/m1911star/affine

Horus 216 Dec 25, 2022
🧰 The Rust SQL Toolkit. An async, pure Rust SQL crate featuring compile-time checked queries without a DSL. Supports PostgreSQL, MySQL, SQLite, and MSSQL.

SQLx ?? The Rust SQL Toolkit Install | Usage | Docs Built with ❤️ by The LaunchBadge team SQLx is an async, pure Rust† SQL crate featuring compile-tim

launchbadge 7.6k Dec 31, 2022
TDS 7.2+ (mssql / Microsoft SQL Server) async driver for rust

Tiberius A native Microsoft SQL Server (TDS) client for Rust. Supported SQL Server versions Version Support level Notes 2019 Tested on CI 2017 Tested

Prisma 189 Dec 25, 2022
Simple, async embedded Rust

Cntrlr - Simple, asynchronous embedded Cntrlr is an all-in-one embedded platform for writing simple asynchronous applications on top of common hobbyis

Branan Riley 11 Jun 3, 2021