#pub-sub #events #event-listener #global-data #simple-wasm

nuts

Nuts is a library that offers a simple publish-subscribe API, featuring decoupled creation of the publisher and the subscriber

4 releases

0.2.1 Feb 28, 2021
0.2.0 Dec 6, 2020
0.1.1 Oct 3, 2020
0.1.0 Oct 3, 2020

#805 in Web programming

34 downloads per month
Used in paddle

MIT/Apache

130KB
2.5K SLoC

Nuts

Nuts is a library that offers a simple publish-subscribe API, featuring decoupled creation of the publisher and the subscriber.

Quick first example

struct Activity;
let activity = nuts::new_activity(Activity);
activity.subscribe(
    |_activity, n: &usize|
    println!("Subscriber received {}", n)
);
nuts::publish(17usize);
// "Subscriber received 17" is printed
nuts::publish(289usize);
// "Subscriber received 289" is printed

As you can see in the example above, no explicit channel between publisher and subscriber is necessary. The call to publish is a static method that requires no state from the user. The connection between them is implicit because both use usize as message type.

Nuts enables this simple API by managing all necessary state in thread-local storage. This is particularly useful when targeting the web. However, Nuts can be used on other platforms, too. In fact, Nuts has no dependencies aside from std.

State of Library

With the release of Nuts version 0.2 on crates.io, it has reached an important milestone. The single-threaded features have all been implemented. Maybe a method here and there needs to be added. But I would not expect to go through major API overhauls again in the existing interface at this point.

There is one big pending feature left, however. This is parallel dispatch, covered in #2. Ideally, that would be implemented under the hood. But likely it will make sense to add some more methods to the API.

If and when parallel dispatch get implemented, Nuts probably looks at a stable 1.0 release.

Activities

Activities are at the core of Nuts. From the globally managed data, they represent the active part, i.e. they can have event listeners. The passive counter-part is defined by DomainState.

Every struct that has a type with static lifetime (anything that has no lifetime parameter that is determined only at runtime) can be used as an Activity. You don't have to implement the Activity trait yourself, it will always be automatically derived if possible.

To create an activity, simply register the object that should be used as activity, using nuts::new_activity or one of its variants.

It is important to understand that Activities are uniquely defined by their type. You cannot create two activities from the same type. (But you can, for example, create a wrapper type around it.) This allows activities to be referenced by their type, which mus be know at run-time. reference by their type

Publish

Any instance of a struct or primitive can be published, as long as its type is known at compile-time. (The same constraint as for Activities.) Upon calling nuts::publish, all active subscriptions for the same type are executed and the published object will be shared with all of them.

Example

struct ChangeUser { user_name: String }
pub fn main() {
    let msg = ChangeUser { user_name: "Donald Duck".to_owned() };
    nuts::publish(msg);
    // Subscribers to messages of type `ChangeUser` will be notified
}

Subscribe

Activities can subscribe to messages, based on the Rust type identifier of the message. Closures or function pointers can be used to create a subscription for a specific type of messages.

Nuts uses core::any::TypeId internally to compare the types. Subscriptions are called when the type of a published message matches the message type of the subscription.

There are several different methods for creating new subscriptions. The simplest of them is simply called subscribe(...) and it can be used like this:

struct MyActivity { id: usize };
struct MyMessage { text: String };

pub fn main() {
    let activity = nuts::new_activity(MyActivity { id: 0 } );
    activity.subscribe(
        |activity: &mut MyActivity, message: &MyMessage|
        println!("Subscriber with ID {} received text: {}", activity.id, message.text)
    );
}

In the example above, a subscription is created that waits for messages of type MyMessage to be published. So far, the code inside the closure is not executed and nothing is printed to the console.

Note that the first argument of the closure is a mutable reference to the activity object. The second argument is a read-only reference to the published message. Both types must match exactly or otherwise the closure will not be accepted by the compiler.

A function with the correct argument types can also be used to subscribe.

struct MyActivity { id: usize };
struct MyMessage { text: String };

pub fn main() {
    let activity = nuts::new_activity(MyActivity { id: 0 } );
    activity.subscribe(MyActivity::print_text);
}

impl MyActivity {
    fn print_text(&mut self, message: &MyMessage) {
        println!("Subscriber with ID {} received text: {}", self.id, message.text)
    }
}

Example: Basic Activity with Publish + Subscribe

#[derive(Default)]
struct MyActivity {
    round: usize
}
struct MyMessage {
    no: usize
}

// Create activity
let activity = MyActivity::default();
// Activity moves into globally managed state, ID to handle it is returned
let activity_id = nuts::new_activity(activity);

// Add event listener that listens to published `MyMessage` types
activity_id.subscribe(
    |my_activity, msg: &MyMessage| {
        println!("Round: {}, Message No: {}", my_activity.round, msg.no);
        my_activity.round += 1;
    }
);

// prints "Round: 0, Message No: 1"
nuts::publish( MyMessage { no: 1 } );
// prints "Round: 1, Message No: 2"
nuts::publish( MyMessage { no: 2 } );

Example: Private Channels

In what I have shown you so far, all messages have been shared reference and it is sent to all listeners that registered to a specific message type. An alternative is to use private channels. A sender can then decide which listening activity will receive the message. In that case, the ownership of the message is given to the listener.

struct ExampleActivity {}
let id = nuts::new_activity(ExampleActivity {});
// `private_channel` works similar to `subscribe` but it owns the message.
id.private_channel(|_activity, msg: usize| {
    assert_eq!(msg, 7);
});
// `send_to` must be used instead of `publish` when using private channels.
// Which activity receives the message is decide by the first type parameter.
nuts::send_to::<ExampleActivity, _>(7usize);

Activity Lifecycle

Each activity has a lifecycle status that can be changed using set_status. It starts with LifecycleStatus::Active. In the current version of Nuts, the only other status is LifecycleStatus::Inactive.

The inactive status can be used to put activities to sleep temporarily. While inactive, the activity will not be notified of events it has subscribed to. A subscription filter can been used to change this behavior. (See subscribe_masked)

If the status of a changes from active to inactive, the activity's on_leave and on_leave_domained subscriptions will be called.

If the status of a changes from inactive to active, the activity's on_enter and on_enter_domained subscriptions will be called.

Domains

A Domain stores arbitrary data for sharing between multiple Activities. Library users can define the number of domains but each activity can only join one domain.

Domains should only be used when data needs to be shared between multiple activities of the same or different types. If data is only used by a single activity, it is usually better to store it in the activity struct itself.

In case only one domain is used, you can also consider to use DefaultDomain instead of creating your own enum.

For now, there is no real benefit from using multiple Domains, other than data isolation. But there are plans for the future that will schedule Activities in different threads, based on their domain.

Creating Domains

Nuts creates domains implicitly in the background. The user can simply provide an enum or struct that implements the DomainEnumeration trait. This trait requires only the fn id(&self) -> usize function, which maps every object to a number representing the domain.

Typically, domains are defined by an enum and the DomainEnumeration trait is derived using using domain_enum!.

#[macro_use] extern crate nuts;
use nuts::{domain_enum, DomainEnumeration};
#[derive(Clone, Copy)]
enum MyDomain {
    DomainA,
    DomainB,
}
domain_enum!(MyDomain);

Using Domains

The function nuts::store_to_domain allows to initialize data in a domain. Afterwards, the data is available in subscription functions of the activities.

Only one instance per type id can be stored inside a domain. If an old value of the same type already exists in the domain, it will be overwritten.

If activities are associated with a domain, they must be registered using the nuts::new_domained_activity. This will allow to subscribe with closures that have access to domain state. subscribe_domained is used to add those subscriptions. subscribe can still be used for subscriptions that do not access the domain.

Example of Activity with Domain

use nuts::{domain_enum, DomainEnumeration};

#[derive(Default)]
struct MyActivity;
struct MyMessage;

#[derive(Clone, Copy)]
enum MyDomain {
    DomainA,
    DomainB,
}
domain_enum!(MyDomain);

// Add data to domain
nuts::store_to_domain(&MyDomain::DomainA, 42usize);

// Register activity
let activity_id = nuts::new_domained_activity(MyActivity, &MyDomain::DomainA);

// Add event listener that listens to published `MyMessage` types and has also access to the domain data
activity_id.subscribe_domained(
    |_my_activity, domain, msg: &MyMessage| {
        // borrow data from the domain
        let data = domain.try_get::<usize>();
        assert_eq!(*data.unwrap(), 42);
    }
);

// make sure the subscription closure is called
nuts::publish( MyMessage );

Advanced: Understanding the Execution Order

When calling nuts::publish(...), the message may not always be published immediately. While executing a subscription handler from previous publish, all new messages are queued up until the previous one is completed.

struct MyActivity;
let activity = nuts::new_activity(MyActivity);
activity.subscribe(
    |_, msg: &usize| {
        println!("Start of {}", msg);
        if *msg < 3 {
            nuts::publish( msg + 1 );
        }
        println!("End of {}", msg);
    }
);

nuts::publish(0usize);
// Output:
// Start of 0
// End of 0
// Start of 1
// End of 1
// Start of 2
// End of 2
// Start of 3
// End of 3

Full Demo Examples

A simple example using nuts to build a basic clicker game is available in examples/clicker-game. It requires wasm-pack installed and npm. To run the example, execute wasm-pack build and then cd www; npm install; npm run start. This example only shows minimal features of nuts.

Right now, there are no more examples (some had to be removed due to outdated dependencies). Hopefully that will change at some point.

All examples are set up as their own project. (To avoid polluting the libraries dependencies.) Therefore the standard cargo run --example will not work. One has to go to the example's directory and build it from there.

Dependencies

~0–2MB
~40K SLoC