cloudflare / cloudflare/capnweb

clarify how bidirectional communication should work

Open
#30 6 comments 1 reaction 0 assignees View on GitHub
documentation
Dominant language
TypeScript
Stars
4k
Forks
143
Avg merge
4d 6h
Merged PRs (30d)
7

Description

Heya, neat library. Almost what I was asking for just a day ago 😆

I'm having a hard time understanding how to achieve bidirectional communication. It's almost worded like you can just push data back to the client, but I think that's not the right kind of thinking. So I dug deeper I ended up using the functionality that allows you to pass functions by reference- it seems like this is kind of what's intended?

Where it gets really confusing when you add things like timers into the equation. Without marking the method as `async` and awaiting a promise directly, it doesn't behave as you'd expect (from a "nieve" point of view, that is.)

I have an [example repository ](https://github.com/c43721/test-cap-n-web/tree/2e71235f2630358c2d66b5e5f1715cf86c5ad489) you can use to explore this in more depth

Example client:
```ts
using wsApi = newWebSocketRpcSession("ws://localhost:8000");

const d = (sm: string) => console.log("got something: " + sm)

const wsResult = await wsApi.test(d);

console.log(wsResult);
```

Example websocket "client":
```ts
class WsServer extends RpcTarget {
async test(fn: (data: string) => void) {
fn("testing");

setTimeout(1000, () => {
fn("hello from timeout");
});

return true;
}
}
```
It'll call the first function, then return `true`. That makes a lot of sense! I would expect this to be a "gotcha" here and not a bug of the protocol (how would you know timers are involved?)

Now replace the `setTimeout` with an import from `node:timers/promises`:

```ts
class WsServer extends RpcTarget {
async test(fn: (data: string) => void) {
fn("testing");

const msg = await setTimeout(1000, "da");
fn(msg);

return true;
}
}
```

We'll get what we want:

```
got something: testing
got something: da
true
```

The ask here is if we can get some examples of bidirectional communication and the "gotchas" those comes with. I can see how functions can be used to achieve the "notification" style API for a client and this is something I'm looking to explore :)

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.