Strongly typed, extensible event mediator.

Overview

mediatrix

Latest Release Documentation Dependencies

Strongly typed, extensible event mediator. For more info and explanation, please see the docs.

Usage

Sync

use mediatrix::synchronous::basic::*;

struct UserMessageRequest {
    msg: String,
    priority: u8,
}

#[derive(Debug)]
enum NotifyEvent {
    Ignore,
    SendEmail(String),
    SendTextMessage(String),
}

impl RequestHandler<UserMessageRequest, NotifyEvent> for BasicMediator<NotifyEvent> {
    fn handle(&self, req: UserMessageRequest) {
        match req.priority {
            0 => self.publish(NotifyEvent::Ignore),
            1..=5 => self.publish(NotifyEvent::SendEmail(req.msg)),
            _ => self.publish(NotifyEvent::SendTextMessage(req.msg)),
        };
    }
}

let mediator = BasicMediator::<NotifyEvent>::builder()
    .add_listener(move |ev: &NotifyEvent| {
        if let NotifyEvent::Ignore = ev {
            println!("Ignored some Message")
        }
    })
    .add_listener(move |ev: &NotifyEvent| {
        if let NotifyEvent::SendEmail(msg) = ev {
            println!("Send Email with Message: {}", msg)
        }
    })
    .add_listener(move |ev: &NotifyEvent| {
        if let NotifyEvent::SendTextMessage(msg) = ev {
            println!("Send SMS with Message: {}", msg)
        }
    })
    .build();

mediator.send(UserMessageRequest {
    msg: String::from("Hello World"),
    priority: 0,
});

mediator.send(UserMessageRequest {
    msg: String::from("Is Rust Memory Safe?"),
    priority: 2,
});

mediator.send(UserMessageRequest {
    msg: String::from("New Rust Version"),
    priority: 8,
});

// Prints: Ignored some Message
mediator.next().ok();
// Prints: Send Email with Message: Is Rust Memory Safe?
mediator.next().ok();
// Prints: Send SMS with Message: New Rust Version
mediator.next().ok();

Async

Click to open the asynchronous version
use mediatrix::asynchronous::basic::*;
use async_trait::async_trait;

struct UserMessageRequest {
    msg: String,
    priority: u8,
}

#[derive(Debug)]
enum NotifyEvent {
    Ignore,
    SendEmail(String),
    SendTextMessage(String),
}

#[async_trait]
impl AsyncRequestHandler<UserMessageRequest, NotifyEvent> for BasicAsyncMediator<NotifyEvent> {
    async fn handle(&self, req: UserMessageRequest) {
        match req.priority {
            0 => self.publish(NotifyEvent::Ignore).await,
            1..=5 => self.publish(NotifyEvent::SendEmail(req.msg)).await,
            _ => self.publish(NotifyEvent::SendTextMessage(req.msg)).await,
        };
    }
}

let async_mediator = BasicAsyncMediator::<NotifyEvent>::builder()
    .add_listener(move |ev: &NotifyEvent| {
        if let NotifyEvent::Ignore = ev {
            println!("Ignored some Message")
        }
    })
    .add_listener(move |ev: &NotifyEvent| {
        if let NotifyEvent::SendEmail(msg) = ev {
            println!("Send Email with Message: {}", msg)
        }
    })
    .add_listener(move |ev: &NotifyEvent| {
        if let NotifyEvent::SendTextMessage(msg) = ev {
            println!("Send SMS with Message: {}", msg)
        }
    })
    .build();

async_std::task::block_on(async {
    async_mediator.send(UserMessageRequest {
        msg: String::from("Hello World"),
        priority: 0,
    }).await;

    async_mediator.send(UserMessageRequest {
        msg: String::from("Is Rust Memory Safe?"),
        priority: 2,
    }).await;

    async_mediator.send(UserMessageRequest {
        msg: String::from("New Rust Version"),
        priority: 8,
    }).await;

    async_mediator.next().await.ok();
    async_mediator.next().await.ok();
    async_mediator.next().await.ok();
});

Features

  • sync and async (use async feature) mediators
  • CxAwareMediator (use async feature, carries a struct of your choice)
  • compiler-baked typing
  • extensible architecture

Todo

  • internally, make builders reuse other builders whose target is a comp. of this builder.

Contributions

Feel free to open an issue/PR explaining possible improvements or changes.

Help

Also, please do not hesitate and open an issue when needed. I am happy to help!

You might also like...
RefineDB - A strongly-typed document database that runs on any transactional key-value store.

RefineDB - A strongly-typed document database that runs on any transactional key-value store.

beat saber is a strongly typed, self-documenting and highly performant programming language

beatsaber beat saber is a strongly typed, self-documenting and highly performant programming language. With beat saber we aimed to create a language t

Strongly typed Gura library for Rust

Serde Gura This crate is a Rust library for using the Serde serialization framework with data in Gura file format. This library does not re-implement

Strongly typed Elasticsearch DSL written in Rust

Strongly typed Elasticsearch DSL written in Rust This is an unofficial library and doesn't yet support all the DSL, it's still work in progress. Featu

Make your IDs strongly typed!!

About TypedId introduces a single type, aptly named TypedId. This is a generic wrapper any type, often types that you would use as an identifier. Howe

A Rust library for interacting with OpenAI's ChatGPT API, providing an easy-to-use interface and strongly typed structures.

ChatGPT Rust Library A Rust library for interacting with OpenAI's ChatGPT API. This library simplifies the process of making requests to the ChatGPT A

Lightweight, Strongly Typed Xata Client written in Rust

xata-rs: Lightweight, Strongly Typed Xata Client xata-rs is a third party Xata client, allowing interaction with Xata's REST API. Adding xata-rs (WIP)

Use LLMs to generate strongly-typed values

Magic Instantiate Quickstart use openai_magic_instantiate::*; #[derive(MagicInstantiate)] struct Person { // Descriptions can help the LLM unders

A toy event store and event messaging system.

RDeeBee Follow this blog series for more details on this project. This system is inspired by Martin Kleppman's arguments that Event Sourcing system an

Lightweight, event-driven WebSockets for Rust.

WS-RS Lightweight, event-driven WebSockets for Rust. /// A WebSocket echo server listen("127.0.0.1:3012", |out| { move |msg| { out.send(ms

A Rust application which funnels external webhook event data to an Urbit chat.
A Rust application which funnels external webhook event data to an Urbit chat.

Urbit Webhook Funnel This is a simple Rust application which funnels external webhook event data to an Urbit chat. This application is intended to be

A utility for mapping events from Linux event devices.

What is evsieve? Evsieve (from "event sieve") is a low-level utility that can read events from Linux event devices (evdev) and write them to virtual e

Proof-of-concept for a memory-efficient data structure for zooming billion-event traces

Proof-of-concept for a gigabyte-scale trace viewer This repo includes: A memory-efficient representation for event traces An unusually simple and memo

 Rapidly Search and Hunt through Windows Event Logs
Rapidly Search and Hunt through Windows Event Logs

Rapidly Search and Hunt through Windows Event Logs Chainsaw provides a powerful ‘first-response’ capability to quickly identify threats within Windows

A scriptable MIDI event processor.

mep Introduction mep is a scriptable midi event processor. It uses koto scripts to process incoming midi events. I/O Every instance of mep introduces

A real-time event-oriented data-hub

Redcar A real-time event-oriented data-hub, inspired by the data hub. It is: Universal: the front end uses gRPC to provide services. Fast: benchmarked

 Rapidly Search and Hunt through Windows Event Logs
Rapidly Search and Hunt through Windows Event Logs

Rapidly Search and Hunt through Windows Event Logs Chainsaw provides a powerful ‘first-response’ capability to quickly identify threats within Windows

A simple event-driven library for parsing WebAssembly binary files

The WebAssembly binary file decoder in Rust A Bytecode Alliance project The decoder library provides lightweight and fast decoding/parsing of WebAssem

An event replay tool for the Trento storage backend.

photofinish - a little, handy tool to replay events This tiny CLI tool aims to fulfill the need to replay some events and get fixtures. Photofinish re

Owner
nyvs
star for star?
nyvs
A real-time event-oriented data-hub

Redcar A real-time event-oriented data-hub, inspired by the data hub. It is: Universal: the front end uses gRPC to provide services. Fast: benchmarked

null 6 Mar 2, 2022
tracing - a framework for instrumenting Rust programs to collect structured, event-based diagnostic information

tracing-appender Writers for logging events and spans Documentation | Chat Overview tracing is a framework for instrumenting Rust programs to collect

Cris Liao 1 Mar 9, 2022
Nexmark event generator in Rust.

Nexmark-rs The Nexmark benchmark data generator in Rust. Installation cargo install nexmark --features bin Usage Generate nexmark events. Print one pe

RisingWave Labs 11 Nov 27, 2022
Event listening, bubbling, and callbacks

Event listeners, bubbling, and callbacks for Bevy Oh my! License All code in this repository is dual-licensed under either: MIT License (LICENSE-MIT o

Aevyrie 4 May 8, 2023
Extensible, strongly-typed Rust OAuth2 client library

OAuth2 An extensible, strongly-typed implementation of OAuth2 (RFC 6749). Documentation is available on docs.rs. Release notes are available on GitHub

David Ramos 602 Dec 25, 2022
Strongly typed JSON library for Rust

Serde JSON   Serde is a framework for serializing and deserializing Rust data structures efficiently and generically. [dependencies] serde_json = "1.0

null 3.6k Jan 5, 2023
Strongly typed YAML library for Rust

Serde YAML This crate is a Rust library for using the Serde serialization framework with data in YAML file format. This library does not reimplement a

David Tolnay 669 Jan 1, 2023
Orion lang is a lispy programming language that is strongly and statically typed.

Orion Orion is a lisp inspired statically typed programming language written in Rust Install To install orion you can either: Download binary from the

Wafelack 226 Dec 17, 2022
Strongly typed routes for Rust

routetype This repository is a work in progress, experimental exploration of strongly typed routing in Rust. It follows my previous work with Yesod in

Michael Snoyman 32 Jul 22, 2022
Improve and strengthen your strings by making them strongly-typed with less boilerplate

aliri_braid Improve and strengthen your strings Strongly-typed APIs reduce errors and confusion over passing around un-typed strings.

Marcus Griep 27 Dec 29, 2022