60 points · by joeycumines · 3y ago · 73 comments
I’m sharing ts-chan, an NPM package providing Go-like concurrency primitives, including channels and select statements, for TypeScript and JavaScript, supporting Node.js, Deno, Bun, and browsers.
This is something I've built to make implementing Go-style "control loops" feasible in JavaScript, but there are many possible applications.
Highlights:
- Features a FIFO processing Chan class and versatile Select class for concurrency control. - Supports buffered channel and channel close semantics very close to Go's. - TypeScript-first implementation. - Defines a simple "channel protocol" inspired by JavaScript's iteration protocols, that's used by `Select`, and implemented by `Chan`. - Makes an effort to mitigate cycles caused by the behavior of JavaScript's microtask queue. - Ongoing project with active iteration for a production-ready module (pre-v1, so the API isn't guaranteed to be stable, but the implementation itself is).
NPM: ts-chan GitHub: github.com/joeycumines/ts-chan
Thanks!
Honestly, I've been struggling to come up with examples that aren't extremely contrived, but are still self-contained enough to easily demonstrate. It might actually be easier to just document patterns, though.
Unfortunately it is a lot easier to write documentation for an audience that shares the same context / background / experience. The README was written with an audience in mind consisting primarily of those familiar with Go (or more convoluted "communicating sequential processes" implementations), who were frustrated that things that are very easy in Go, are so much harder in JS. It's not something I considered deeply, but I was imagining that it was unlikely that someone would be searching for "channels in JS" without a base level of understanding.
I work/have worked with some pretty talented people, but (in the past) I've found it difficult to convey the value of the sorts of patterns that `ts-chan` is intended to enable, to those without first-hand experience with such patterns.
Documentation is hard :P
[1] https://github.com/joeycumines/ts-chan#the-microtask-queue-a...
That might be completely wrong, but it’s the impression I get when someone says that something the rest of the world uses without issue sucks.
Fair call though, I guess. It doesn't really matter, but I'm certainly used to TypeScript and JavaScript.
Promises are for asynchronous programming, which are not concurrent.
The tl;dr is that there is some cross over, but the use cases and patterns they support are largely different. Message channels are two-way, channels are one way. (I believe) message channels are 1-1, while `ts-chan`'s channels are n-n, though each send corresponds to a single receive.
The primary use case I aim to address is coordination between independent, asynchronous operations (concurrency in JavaScript). Having an analogue to Go's "select statement" is fairly key to that, and I am not quite sure how to articulate the value it provides, but it does not overlap with message channels.
Example using a single channel: `ts-chan` may be used to implement a set of workers, which accept requests from n sources (e.g. incoming http requests in a web server), then perform some operation, as a mechanism to bound the concurrency of that operation. Personally, I find it much easier to model it as:
1. Start the desired number of workers
2. Wire up workers to await incoming requests then process them, in a loop
3. Send requests to said workers
Rather than (for example) tracking the number of running operations, starting a new worker only if possible, after enqueuing the operation, then having the workers need to operate like "check for any work, increment number of operations, perform operation, check for any work (loop), otherwise decrement number of operations".
The `ts-chan` pattern (which is, really, just a Go pattern) also makes it much easier when the requirements are more complex, e.g. if the requester needs to wait for a response, and might timeout before the operation is even started - in which case the operation should be cancelled.
I should probably include demonstrative examples for all that, heh.
Documentation is a lot of work!
Thanks for the detailed reply, that makes a lot of sense.
One of the earlier implementations is this one, albeit not maintained anymore: https://github.com/NodeGuy/channel I think I prefer its more concise API, e.g. for select (https://github.com/NodeGuy/channel/blob/main/API.md#examples). ts-chan's API looks a bit too verbose to my taste.
Here's an example from ts-chan:
import {recv, Chan, Select} from 'ts-chan';
const ch1 = new Chan<number>();
const ch2 = new Chan<string>();
void sendsToCh1ThenEventuallyClosesIt();
void sendsToCh2();
const select = new Select([recv(ch1), recv(ch2)]);
for (let running = true; running;) {
const i = await select.wait();
switch (i) {
case 0: {
const v = select.recv(select.cases[i]);
if (v.done) {
running = false;
break;
}
console.log(`rounded value: ${Math.round(v.value)}`);
break;
}
case 1: {
const v = select.recv(select.cases[i]);
if (v.done) {
throw new Error('ch2 unexpectedly closed');
}
console.log(`uppercase string value: ${v.value.toUpperCase()}`);
break;
}
default:
throw new Error('unreachable');
}
}
I would consider rewriting the API to something like this: import { receive, Channel, select } from 'ts-chan';
const ch1 = new Channel<number>();
const ch2 = new Channel<string>();
void sendsToCh1ThenEventuallyClosesIt();
void sendsToCh2();
for (let running = true; running;) {
switch(await select([receive(ch1), receive(ch2)])) {
case ch1: {
if (ch1.done) {
running = false;
break;
}
console.log(`rounded value: ${Math.round(ch1.value)}`);
}
case ch2: {
if (ch1.done) {
throw new Error('ch2 unexpectedly closed');
}
console.log(`uppercase string value: ${ch2.value.toUpperCase()}`);
break;
}
}
}With receives, there's a value attached, and that presents some difficulties regarding typing (for TypeScript).
You have given me an idea, however: I _might_ be able to wrangle together a mechanism that avoids making it a two-step deal (get the index, then resolve the type). It'd probably support only a subset of the functionality, though.
It's on my list to add a simple example to the README using the `Chan` class. Communicating with a single channel (with or without abort support) is very simple, and I'm happy with the API for that.
Furthermore; why not just *avoid doing concurrency intensive work in JS* in the first place? Isn’t that why people learned Go?
Seems like a solution looking for a problem kind of, but that’s my low effort critique so maybe I should stuff it.
(I also like Go's time.Ticker behavior quite a lot)
Secondly, there is async iteration which is already pretty good syntax wise.
I agree async iteration is pretty good - the `Chan` class implements both `Iterable` and `AsyncIterable`.
For quite a few scenarios, async generators are a better choice. They do have limitations, however. For example, you _can_ implement fan-in, but there's no easy mechanism to fan-in in a blocking manner, from sources that aren't known ahead of time. It's also hard to implement a "fair" mechanism, that doesn't bias certain inputs (like you might desire if multiplexing logs, for example).
I still like "pipelining" over that, but that can also be implemented with just an iterator, pretty trivially.
How do you extend JS to become multi threaded when it's not capable to do so?
I guess a JavaScript defer could just be enqueueMicrotask and an anonymous arrow function?
I've dabbled in that too, though I don't actually use it for anything, currently: https://github.com/Mcsavvy/contextlib/pull/1
JavaScript already supports concurrency, e.g. handling more than one HTTP request concurrently, despite the runtime being single-threaded in nature. Also provided by JavaScript is the ability to fork and join with other asynchronous tasks, e.g. using `Promise.all` to wait for multiple HTTP requests to complete.
The purpose of `ts-chan` is to make it easier to coordinate concurrent operations, via communication, which definitely isn't something JavaScript makes easy.
So part of this is addressing usability issues, and providing necessary boilerplate. I've modelled most of that after Go's channels.
Another is providing a mitigation for a common gotcha (well, it's gotten me), when attempting to implement behavior that involves multiple independent asynchronous operations, communicating with one another. Specifically, JS has a "microtask queue", an optimisation I believe was created to power async/await. Details / links to MDN here: https://github.com/joeycumines/ts-chan#the-microtask-queue-a...
There is no `result` variable - I was just attempting to convey that "some async stuff happens, then it waits if we can't verify that it's not the same tick as when the call started". The "async stuff", in the actual implementation, is sending or receiving.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
Asynchronous is not the same as concurrent.
Here is an example, that I based on an example from within the Go spec: https://github.com/joeycumines/ts-chan/blob/main/examples/co...
Here is the same example in Go: https://github.com/joeycumines/ts-chan/blob/main/examples/co...
The JS example is, obviously, much slower, and is fairly contrived - I wouldn't expect anyone to actually want to do that, specifically. The JS one is more complicated primarily because I used it in a benchmark, so needed a mechanism to stop the concurrent, asynchronous chains of operations, once it reached the target number of primes.
I hope that explains it for you.
Nothing happens concurrently (at the same time), only asynchronously (at different times).
From the documentation:
> Note that JavaScript is single-threaded by nature, so at a given instant, only one task will be executing, although control can shift between different promises, making execution of the promises appear concurrent. Parallel execution in JavaScript can only be achieved through worker threads.
I hope that explains it for you.
What does the JS “if x != x” check do? I don’t see the equivalent in the golang example?
That's just something I copy and pasted from the documentation for the benchmark package I used. Allegedly, it is to prevent "certain compiler optimisations", which is something I'm familiar with when it comes to benchmarking Go code, for example.
I lack specific knowledge as to whether it's actually necessary, sorry :)