Giter Site home page Giter Site logo

nuts's Introduction

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 must be known at run-time.

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.

nuts's People

Contributors

fadedbee avatar jakmeier avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

nuts's Issues

Investigation: Use native event loop on the web

Nuts sequentially schedules jobs that are activated by published messages. It is essentially implementing an event loop.

When Nuts is used in the browser, it could potentially use the postMessage() function to schedule tasks on the native event loop.

Before merging a potential implementation, it would be good to assess the performance and size difference.

Subscribe without activity

Idea:

Allow subscriptions without an activity.

Current Status

With the current API, a subscription can only be created on an activity. This sometimes forces programmers to create a dummy activity to react on a specific message.

Example:

  let dummy = nuts::new_activity(());
  dummy.subscribe(|_: &mut(), msg: &Message| { /*...*/ });

Possible new syntax

  nuts::subscribe(|msg: &Message| { /*...*/ });

Also feasible to add:

  nuts::subscribe_domained(&MyDomain::DomainA, |domain, msg: &Message| { /*...*/ });

Investigation: Multi-threaded dispatch

Right now, nuts only works in a single thread. All data is stored in the thread-local storage object NUT. If there are multiple threads (non-web) then there will be multiple such nuts that are completely oblivious of each other.

The idea to be captured by this issue is that there could be multiple nuts that communicate with each other and the work split between them. Activities in different domains could live in different nuts. Messages would be forwarded to all nuts, but the state stored in domains could be kept in a single nut (= single thread).

Once this works on a non-web target, the feature can be extended to work on the web too, using web workers that communicate with the browser API's message passing. This would allow to have easy multi-threading in WASM, even without browser support for SharedArrayBuffer and WebAssembly threads.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.