Concurrency

Rook — 1.0 specification

JavaScript runs a program in one thread. Rook keeps that thread for waiting and gives the work that keeps a processor busy to other threads, with the means of Go: an async function waits for a timer or the network in the same thread, go f(x) runs a function as a goroutine, on another processor, and channels and select pass values between goroutines in any thread. The compiler checks that what goes to another thread can be copied there.

Async functions

async func loadText(url string) (string, error) {
    const response = await fetch(url)
    if !response.ok {
        return "", error(`HTTP ${response.status}`)
    }
    return await response.text(), null
}

const text, err = await loadText("/hello.txt")
async function loadText(url) {
  const response = await fetch(url)
  if (!response.ok) {
    return ['', new Error(`HTTP ${response.status}`)]
  }
  return [await response.text(), null]
}

const [text, err] = await loadText('/hello.txt')

async is written before func, before a method of a class (async load() string), before a func literal and before an arrow function (async x => ...).

A Promise made by hand gets its type from the declared one:

async func sleep(ms number) {
    const done Promise<number> = new Promise(resolve => setTimeout(() => resolve(ms), ms))
    await done
}

Without a declared type, what it gives is inferred from the calls of resolve in the callback: new Promise(resolve => resolve(1)) is a Promise<number>, and calls with a number and a string make it Promise<number | string>. A resolve that is not called, or is passed on, as a pause is written, await new Promise(resolve => setTimeout(resolve, 5)), gets values the callback does not show: then the promise gives nothing, Promise<void>, and a value given to resolve elsewhere is an error that asks for the type. That is so for the parameters of the functions that a callback gets, as resolve; a parameter of the callback itself, apply(x => ...) of func apply<T>(f func(T)), still needs its type.

Goroutines

func countPrimes(from, to number) number {
    // ...
}

const PART = 1_000_000
const parts = await Promise.all([0, 1, 2, 3].map(i => go countPrimes(i * PART, (i + 1) * PART)))
go countPrimes(0, 100)              // nothing waits for it
const parts = await Promise.all(
  [0, 1, 2, 3].map((i) => $$go('countPrimes', [i * PART, (i + 1) * PART])),
)
$$go('countPrimes', [0, 100])

go f(x) calls f as a goroutine, in another thread, and the program goes on without waiting for it. Goroutines run at once, on different processors: the threads are a pool of workers, Web Workers in the browser and worker threads in Node, and a worker can run several goroutines (see "The pool" below).

The worker module goes next to the module: rook build app.rk writes app.js and app.worker.js, rook run compiles it on the fly, and the Vite plugin gives it to Vite, which bundles it as a worker.

go is for work that keeps a processor busy. Waiting, for a timer or the network, needs no thread: the call of an async function without await, search(query, out), runs in the same thread at once with the rest of the program, sharing its memory, as goroutines of Go share theirs. It talks to the others through channels as well.

go for

async func lighten(pixels Uint8ClampedArray, amount number) {
    go for i, v in pixels {
        pixels[i] = v + (255 - v) * amount
    }
}
async function lighten(pixels, amount) {
  await $$goFor($$go, '$$goroutine0', pixels, amount)
}

// app.worker.js
async function $$goroutine0(pixels, $$from, amount) {
  for (let $$i = 0; $$i < pixels.length; $$i++) {
    const i = $$from + $$i
    const v = pixels[$$i]
    pixels[$$i] = v + (255 - v) * amount
  }
  return $$transfer(pixels)
}

go for i, v in items is a parallel loop over an array: the array is split into parts, each part runs as a goroutine, and the loop waits for all of them, as a WaitGroup would. After it, the array has what the body wrote into it.

Channels

async func square(jobs chan number, results chan number) {
    for n in jobs {
        results <- n * n
    }
}

const jobs = chan<number>(10)          // room for 10 values
const results = chan<number>()          // no room: a send waits for a receiver
go square(jobs, results)
go square(jobs, results)
for let n = 1; n <= 4; n++ {
    jobs <- n
}
close(jobs)
for let i = 0; i < 4; i++ {
    console.log(<-results)
}
close(results)                          // every result is received
const jobs = $$channels.make(10, 0)
const results = $$channels.make(0, 0)
// ...
await $$channels.send(jobs, n)
// ...
console.log(await $$channels.receive(results, false, 0))

Channels pass values between goroutines, as in Go. chan T is the type of a channel of T, and chan<T>(size) makes one with room for size values; chan<T>() has none. chan(stream, size) makes one that receives a stream (see "Streams" below).

select

select {
case job = <-jobs:
    work(job)
case msg, ok = <-control:
    if !ok {
        return
    }
case results <- last:
    console.log("sent")
case <-quit:
    return
default:
    console.log("nothing is ready")
}
{
  const [$$case, $$received, $$ok] = await $$channels.select(
    [{ channel: jobs }, { channel: control }, { channel: results, value: last }, { channel: quit }],
    true,
  )
  switch ($$case) {
    case 0: {
      const job = $$received
      work(job)
      break
    }
    // ...
  }
}

select waits until one of several operations on channels can go on, does it and runs its case, as in Go. A case receives, case v = <-ch: or case <-ch:, or sends, case ch <- v:.

Timers and cancel

const ticks = tick(100)
const done = chan<number>(1)
const task = go async func() {
    done <- countPrimes(100_000_000)
    close(done)                         // one value, and nothing more
}()

select {
case n = <-done:
    console.log(n)
case <-after(500):
    cancel(task)
}
close(ticks)
const ticks = $$channels.tick(100)
// ...
const [$$case, $$received, $$ok] = await $$channels.select(
  [
    { channel: done, zero: 0 },
    { channel: $$channels.after(500), zero: 0 },
  ],
  false,
)
// ...
$$cancel(task)

Signals and cancellation

Experimental: may change between releases; see the status at the top.

import { createServer } from "node:http"

const stop = signal("SIGINT", "SIGTERM")
const server = createServer(handle).listen(8080)
console.log("stopping on", <-stop)          // waits for Ctrl+C or for the process manager
close(stop)
server.close()

async func load(url string, request Request) (string, error) {
    const response, err = try await fetch(url, { signal: request.signal })
    // ...
}

select {
case body = <-results:
    reply(body)
case reason = <-done(request.signal):       // the client has gone
    console.log("cancelled:", reason)
}
const stop = $$channels.signal('SIGINT', 'SIGTERM')
// ...
const [$$case, $$received, $$ok] = await $$channels.select(
  [{ channel: results, zero: '' }, { channel: $$channels.done(request.signal) }],
  false,
)

A server stops when the process manager tells it to, with a signal, and a request stops when its client goes, with an AbortSignal. Both become channels, so that select waits for them with the rest, as signal.Notify and the Done() of a context.Context do in Go.

Streams

Experimental: may change between releases; see the status at the top.

async func countWords(chunks <-chan string) number {
    let words = 0
    for chunk in chunks {
        words += chunk.split(" ").length
    }
    return words
}

const response = await fetch("book.txt")
const text = response.body?.pipeThrough(new TextDecoderStream())
const chunks, failed = chan(text, 4)
const words = await go countWords(chunks)
const err = <-failed
const [chunks, failed] = $$channels.fromStream(text, 4, '')
const words = await $$go('countWords', [chunks])
const err = await $$channels.receive(failed)

A ReadableStream, such as the body of a fetch response, goes into a channel, and a channel becomes a stream, so that goroutines make pipelines over the network.

Topics

Experimental: may change between releases; see the status at the top.

interface CartEvent {
    kind "add" | "remove"
    id number
}

const cart = topic<CartEvent>("cart")
let items number[] = []

func add(id number) {
    items.push(id)
    cart <- { kind: "add", id }      // to the other tabs; waits for nobody
}

async func follow() {
    for e in cart {                  // what the other tabs send
        if e.kind == "add" {
            items.push(e.id)
        }
    }
}

func stop() {
    close(cart)                      // follow() ends
}
const cart = $$topics.make("cart", null);
// ...
$$topics.publish(cart, { kind: "add", id });
// ...
for await (const e of $$channels.range($$topics.listen(cart))) {

A topic passes values between the tabs of a site, as a channel passes them between goroutines: topic T is the type of a topic of T, and topic<T>(name) makes one, over the BroadcastChannel of that name. Every tab of the site, and every worker, that makes a topic of the name and listens to it gets each value. It is a type of its own, not a chan: a channel gives each value to one receiver and its sender waits for room, while a topic gives each value to all who listen and its sender waits for nobody.

Channel and Topic

Experimental: may change between releases; see the status at the top.

const jobs = Channel.make(10, 0)       // chan<number>(10)
await Channel.send(jobs, 1)             // jobs <- 1
const n = await Channel.receive(jobs)   // <-jobs, but a ?number
Channel.close(jobs)                     // close(jobs)
let none chan string = Channel.EMPTY    // what `let none chan string` gives
const jobs = $$channels.make(10, 0)
await $$channels.send(jobs, 1)
const n = await $$channels.receive(jobs)
$$channels.close(jobs)
let none = $$channels.EMPTY

Channel and Topic are predeclared objects with the functions that channels and topics compile to, by name, for code that needs them as values: to pass Channel.close on, or to receive without await in the same line. In JS they are $$channels and $$topics of the runtime, so a program may declare names Channel and Topic of its own, which hide them.

Markdown source on GitHub