Skip to content

Commit 6afcd5c

Browse files
committed
Add some protocol documentation
1 parent 970afb5 commit 6afcd5c

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

packages/protocol/README.md

+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
# Protocol
2+
3+
This module provides a way for the browser to run Node modules like `fs`, `net`,
4+
etc.
5+
6+
## Internals
7+
8+
### Server-side proxies
9+
The server-side proxies are regular classes that call native Node functions. The
10+
only thing special about them is that they must return promises and they must
11+
return serializable values.
12+
13+
The only exception to the promise rule are event-related methods such as
14+
`onEvent` and `onDone` (these are synchronous). The server will simply
15+
immediately bind and push all events it can to the client. It doesn't wait for
16+
the client to start listening. This prevents issues with the server not
17+
receiving the client's request to start listening in time.
18+
19+
However, there is a way to specify events that should not bind immediately and
20+
should wait for the client to request it, because some events (like `data` on a
21+
stream) cannot be bound immediately (because doing so changes how the stream
22+
behaves).
23+
24+
### Client-side proxies
25+
Client-side proxies are `Proxy` instances. They simply make remote calls for any
26+
method you call on it. The only exception is for events. Each client proxy has a
27+
local emitter which it uses in place of a remote call (this allows the call to
28+
be completed synchronously on the client). Then when an event is received from
29+
the server, it gets emitted on that local emitter.
30+
31+
When an event is listened to, the proxy also notifies the server so it can start
32+
listening in case it isn't already (see the `data` example above). This only
33+
works for events that only fire after they are bound.
34+
35+
### Client-side fills
36+
The client-side fills implement the Node API and make calls to the server-side
37+
proxies using the client-side proxy.
38+
39+
When a proxy returns a proxy (for example `fs.createWriteStream`), that proxy is
40+
a promise (since communicating with the server is asynchronous). We have to
41+
return the fill from `fs.createWriteStream` synchronously, so that means the
42+
fill has to contain a proxy promise. To eliminate the need for calling `then`
43+
and to keep the code looking clean every time you use the proxy, the proxy is
44+
itself wrapped in another proxy which just calls the method after a `then`. This
45+
works since all the methods return promises (aside from the event methods, but
46+
those are not used in the fills).

0 commit comments

Comments
 (0)