The situation we are in
Kinode processes are in a strange position.
They are halfway between sync and async.
On the sync side, they cannot do standard async things, like selecting over a set of channels, or spawning new tasks or threads.
However, because they are run by an async runtime, some async-ness slips in as a result.
Notably, all the async-ness happens in the kernel; all the sync-ness constraints are in the Wasm processes.
For example, a process can spawn another process. If that second process can act like a task or thread, we now have something analogous to multithreading.
Another example: when handling incoming messages, a process has a choice between:
- "Blocking"/queueing future messages except for a single, specific Response (we often call this send_and_await, after the system call of the a similar name,
send_and_await_response()), - Handling that specific Response elsewhere in the code (i.e. in some general purpose
handle_message()orhandle_response()function). Each of these two choices has pros and cons.
| pro/con | send_and_await | send |
|---|---|---|
| Pros | The Response handling code is immediately following the Request in the source: much more readable | Messages are handled immediately upon receipt: suitable for low-latency applications |
| Cons | Other messages are queued up until the specific Response is handled in full: if this Response is a long-lived operation, this is unsuitable for low-latency applications | The Response handling code is elsewhere in the source: harder to read |
Is there a way that we can have the advantages of both send_and_await and send, without the costs? Namely, an ideal solution looks like:
- Response handling that follows the Request immediately in the source code,
- Other messages to the process are not blocked while waiting on a specific Response -> no latency penalty,
- Ergonomic & familiar to use: not boilerplate-y, complicated, or requiring new mental models.
The idea
Traditional channels and select
In more traditional async programming, e.g. in Golang and Rust's tokio, there are two primitives that make it ergonomic and easy to handle & synchronize the results or outputs of different goroutines/tasks/threads: channels & select.
I'm not going to go in depth here about them, but the high-level summary is that you have channels that different tasks use to communicate (in the case of a one-way channel, one task holds a sender and another holds a receiver), and you can wrap a number of channels in a select.
The select will block until one of the channels has a new value in it, and then execute code specific to that channel.
E.g., in Rust, this looks something like:
tokio::select! {
Some(the_thing_sent) = recv_from_other_task.recv() => {
// handle `the_thing_sent` here
},
Some(a_different_thing) = recv_from_a_different_task.recv() => {
// handle `a_different_thing` here
},
_ = tokio::time::sleep(SLEEP_DURATION) => {
// do some other stuff, maybe a keepalive or whatever
},
}
Something like this would be great: it is pretty close to our ideal solution above:
- You can have the tasks that populate the
channelsenders as close to thatselectas you want, - Not blocking,
- Resembles the Golang solution.
Kinode channels & select
Can we do a similar thing in Kinode?
It will be somewhat different due to our different constraints, but I think we can get a lot of the niceness of the select example above.
What is different in our situation?
In the above, you can imagine looping over the select, which approaches what our processes often do.
But then you haven't gained much, because you are really just mimicking our current (pretty good!) match pattern.
The MFA demo shows an example of our match pattern.
How can we do better than match?
- A
selectanalog, probably just calledselect. A key difference from theselectexample above is that thisselectwill be stateful: thechannels to beselected over will be stored by the kernel. - A
channelanalog, perhaps of two varieties,ChannelandOneShotChannel. - Some methods for manipulating what
channels are in theselectstate. E.g.,select_add()and maybe(?)select_remove().
Let's look at some pseudocode to show how I imagine this will look in practice:
#[serde(untagged)]
enum Req {
Foo(FooRequest),
Bar(BarRequest),
}
/// _inner so we can use Rust's `?` operator
fn make_foo_handler_inner(m: Message) -> anyhow::Result<> {
if m.is_request() {
return Err(anyhow::anyhow!("message_handler received unexpected Request"));
}
match m.body().try_into()? {
FooResponse::Lol => {}
FooResponse::Rofl => {}
// ...
}
}
/// call into _inner and convert the anyhow::Result
/// into a Result that WIT will be happy with
fn make_foo_handler(m: Message) -> Result<Vec<u8>, Vec<u8>> {
match make_foo_handler_inner(m) {
Err(e) => String::to_utf8(format!("{e:?}")),
Ok(_) => vec![],
}
}
fn make_bar_handler(m: Message) -> Result<Vec<u8>, Vec<u8>> {
// ...
}
/// _inner so we can use Rust's `?` operator
fn make_message_handler_inner(m: Message) -> anyhow::Result<> {
if !m.is_request() {
return Err(anyhow::anyhow!("message_handler received unexpected Response"));
}
match m.body().try_into()? {
Req::Foo(FooRequest) => {
// do some logic;
// ...
// now we want to ask another process for something & get the Response:
// add to select
let foo_channel = Request::to(some_other_process)
.body(message_body_to_other_process)
.send_and_get_channel()?;
select_add(
foo_channel,
make_foo_handler,
)
}
Req::Bar(BarRequest) => {
// similar to above, do some logic, then add handler
let bar_channel = Request::to(some_different_process)
.body(message_body_to_different_process)
.send_and_get_channel()?;
select_add(
bar_channel,
make_bar_handler,
)
}
}
Ok(())
}
/// call into _inner and convert the anyhow::Result
/// into a Result that WIT will be happy with
fn make_message_handler(m: Message) -> Result<Vec<u8>, Vec<u8>> {
match make_message_handler_inner(m) {
Err(e) => String::to_utf8(format!("{e:?}")),
Ok(_) => vec![],
}
}
fn add_message_handler() {
let message_channel = await_message_channel();
match select_add(
message_channel,
make_message_handler,
) {
Ok(_) => {}
Err(e) => panic!("got error setting up message handler: {e:?}"),
}
}
fn init() {
add_message_handler();
loop {
match select() {
Ok(_) => {}
Err(e) => println!("got error: {e:?}"),
}
}
}
So what is going on here?
We add a top-level message_handler to the select state.
In add_message_handler(), await_message_channel() creates a Channel that pops the first element off the message queue.
That message is handled by the handler specified in make_message_handler().
A handler, here, is a function from Message -> Result<Vec<u8>, Vec<u8>>.
We can see that in handling the message, we might add other handlers to the select state, e.g., a foo_channel and foo_handler.
The send_and_get_channel() method returns a OneShotChannel.
This is analogous to using send_and_await_request().
When a Response comes in with the same message id as the outgoing Request, it will be handled by the foo_handler rather than the message_handler.
So how did we do on the objectives?
- We can place the handler code immediately following the Request; here we just package it up into functions for modularity. Success!
- Not blocking. Success!
- Makes use of
channelandselectconcepts, but is different in that the state wrt the select is stored & the syntax is different. Semi-successful.
Will it work?
While writing this up, I realized that this probably won't work as written. The reason is that I don't think WIT allows functions to return functions! So we are getting close to a solution, but I think this is not quite it.
It might be worth writing a bit about how I got to this current proposal, since that may help us to get to a workable solution.
I had originally been imagining something that didn't have the select "state" described above.
It would look like calling a select at the send_and_get_channel point, where the select is over the one-shot channel or else the await_message_channel().
If the await_message_channel() fires, we recurse into the top-level message handler.
The issue with this recursive approach is that we end up only ever selecting between one channel and the await_message_channel(), when we really want to select against potentially arbitrarily many channels (e.g. if we have many long-standing Requests out).
That led me to the stateful method, the downside of which is that we end up having to call the handler code from the runtime, which I think will not work.