nuts 0.1.1

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

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.

Nuts has reached a minimal viable product (MVP) with version 0.1 published on crates.io. But there are more features planned for the future and breaking API changes are very much possible.

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.

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 either 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 } );

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 to install the package and then npm run start in the www folder can be run to start a server running the game. This example only shows minimal features of nuts.

There is another example available in examples/webstd-example. It shows how Nuts can be combined with just stdweb to build a web application. It uses multiple activities with domains and lifecycle status changes. This example uses cargo-web and can be compiled without wasm-pack or npm installed.

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.