Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

23 Commits

Folders and files

Repository files navigation

transient-stack-rust

Composable computations that run in several threads and in several computer nodes, survive a restart, and run the same code in the server and in the browser.

It is made to prototype distributed and peer-to-peer systems quickly: a node is a process that runs the program; it calls other nodes (run_at), asks all of them (clustered) and waits for the answers, and the same program runs in all of them. A network of cooperating nodes is a few lines, not a protocol.

Transient is a different computation model made for modularity and direct mode programming, where everithing that happens can be tracked as natural sequences of statements since there are no ruptures of control and any code can be combined using standard or user-defined operators.

Threading, streaming, cloud computing, durability etc are included to achieve that goal and give the programmer a high-level platform for expressing the domain-problem.

What you can do with it

  • One type for a value, a late result and a stream. A Trans<A> gives zero or more results, in this thread or in another one, and the code that uses them does not change. There is no async fn next to fn.
  • Binary operators over computations, in parallel and distributed. Any function of two values (+, max, your own) becomes an operator over two computations, and each term decides where it runs: another thread, another node, all the nodes. The formula is written once. See the operators.
  • Alternatives. a | b runs both and gives the results as they arrive.
  • Calls between nodes. run_at(node, ...) runs a computation in another node and comes back to the next line; clustered(...) does it in all the nodes known and gives the results as a stream.
  • Restart-proof. A computation that is killed (kill -9) goes on from its last checkpoint when it is started again, without repeating the steps that were done. See restart-proof computations.
  • The same program in the server and in the browser. The widgets of axiom are drawn by Rust compiled to wasm, and the part of the computation that runs in the server is in the same function. See the browser.
  • Modular. A feature is a function that returns a Cloud<()>; adding it to the program is one line (| my_feature()).
  • Web applications. Each minput is an HTTP endpoint, and a program that chains them is a web application; its endpoints are restart-proof with the same mechanism as the rest. See web applications.
  • A console (option, input) and encrypted communications between nodes (TLS).

Computations in several threads

tdo! writes a sequence of steps; abduce() moves the rest of the computation to another thread; | is the alternative. keep_all waits for all the threads and gives all the results (transient-core/examples/parallel_terms.rs).

// a term that takes `ms` milliseconds, in a thread of its own, and gives `n`
fn slow(n: u64, ms: u64) -> Trans<u64> {
    tdo! {
        abduce();
        lift_io(move || { sleep(Duration::from_millis(ms)); n })
    }
}

let sum  = keep_all(slow(1, 30) + slow(2, 10) + slow(3, 20));   // [6], in about 50 ms: the three run at once, it is not 60
let race = keep_all(slow(1, 30) | slow(2, 10));                 // [2, 1]: the results as they arrive

Threads, blocking and the scheduler

A computation is a chain of short steps. When it goes on in another thread (abduce, |, a stream, a reply from the network) the rest of the chain is handed to the scheduler as a task, and a task runs on one of the workers of a shared Tokio runtime (feature tokio-sched, on by default). Tens of thousands of tasks share a few workers: 100 000 abduce take about 0.2 s, and 100 000 tasks that sleep 200 ms take about 0.4 s, because nothing waits in a thread.

What follows from this is a contract:

  • lift_io and the steps of tdo! must not block. A step that sleeps, reads a blocking socket or waits for a lock holds a worker; enough of them stop the program.
  • async_ is for what blocks. The io of async_, parallel and wait_events runs where it can wait (block_in_place), so the other tasks go on. It costs an operating-system thread while it waits, and the number of those is limited (about 512): 20 000 async_ of 200 ms take about 8 s.
  • What comes from outside needs no thread. sleep, the sockets of minput, run_at, teleport, clustered and the WebSockets are waited for in the reactor of Tokio: the continuation stays parked, like in react, and a thread is used only while it runs. With 3 000 HTTP/1.1 connections open and idle the server has about 20 threads, and a node serves several thousand requests per second (a static page: 3 000 to 4 000 per second with a new connection each; a minput that reuses its connection: about 1 600 per second with a new session each time, measured with a load generator written in Python, which was probably the limit). Connections under TLS still use a thread each.

An action that blocks can not be turned into one that does not by wrapping it in an async block: only the code that waits with an .await (or here, with sleep, a socket or react) gives its thread back.

Binary operators over parallel and distributed terms

The operator + above is not special: lift2(f, a, b) makes an operator out of any function f of two values. It starts both terms at once and calls f when both have a result (and for each new result, if a term is a stream). + is lift2 with the addition, and with your own function it is the same:

let max = keep_all(lift2(u64::max, slow(7, 20), slow(4, 10)));               // [7]
let mix = keep_all((slow(1, 40) + slow(2, 40)) | (slow(10, 5) + slow(20, 5)));   // [30, 3]: two sums in parallel, the first that is ready first

What makes it useful is that the formula does not know where its terms run. Each term is a computation, and it is the term, not the operator, that says if it is in this thread, in a node or in all of them. With Cloud, the computations that can go to another node, the operator is clift2:

// the stock of one item in the node that runs this
fn stock(item: &'static str) -> Cloud<i64> {
    local_io(move || if item == "bolts" { 40 } else { 2 })
}

// the same formula, each term asked to a different node; both go at once and the sum is made here
fn total(a: Node, b: Node) -> Cloud<i64> {
    clift2(|x: i64, y: i64| x + y, run_at(a, stock("bolts")), run_at(b, stock("nuts")))
}

To change the architecture, change the definition of a term (run_at(a, ...) for abduce(), a node for another one), not the formula. This is how a map-reduce, a quorum of answers or a distributed query are written: terms in the nodes, and an operator that joins them.

Prototyping peer-to-peer networks

Every node runs the same program and knows the other nodes: they are added from the console (add <host> <port> <y|n>) or from the program (add_nodes). A node calls one of them with run_at and all of them with clustered, and the answers come as a stream.

A stream from every node of the cluster. When fire is entered in the console, each known node sends ten "hello world" and this node prints them as they arrive. The program has no result: it prints (transient-core/examples/stream.rs).

fn distrib_stream() -> Cloud<()> {
    cdo! {
        local(option("fire", "fire"));
        let r = clustered(local(choose(vec!["hello world".to_string(); 10])));
        local_io(move || println!("{r}"))
    }
}

fn main() {
    let _: Result<(), String> = keep(init_node(input_nodes() | distrib_stream()));
}

input_nodes() is the console that adds nodes and distrib_stream() the program; | puts them side by side. Each one waits for its own line and they do not disturb each other. Two terminals:

cargo run --offline --example stream -- --start localhost:8000
cargo run --offline --example stream -- --start localhost:8001 --add localhost:8000 n    # another node: type fire here

The nodes are added by hand: there is no discovery of nodes, and they connect directly by TCP (see the limits).

Restart-proof computations

What each local step returns is remembered on disk. If the process dies, a restarted one goes on from the last job() and does not execute the steps before it again (transient-core/examples/durable.rs):

pub fn order() -> Cloud<()> {
    cdo! {
        run_jobs();
        local(option("go", "place an order"));
        let charged = local_io(|| {
            println!("1. card charged");
            42i64
        });
        job();                                        // the checkpoint
        local_io(|| {
            println!("2. shipping (kill me now)");
            std::thread::sleep(Duration::from_secs(10));
            0i64
        });
        local_io(move || println!("3. done: {charged} charged exactly once"))
    }
}
cargo run --offline --example durable -- --start localhost:8000 --go          # prints 1 and 2: `kill -9` it now
cargo run --offline --example durable -- --start localhost:8000 --jobs exec   # prints 2 and 3: the card is not charged again

The same holds for computations that span several nodes: a node that is restarted goes on with what it was sending and opens its connections again, and the others wait for it. collectc(n, delta, action) gathers up to n answers, or those that arrive before delta, and keeps them across a restart. The files are in .tcachedata, in the current directory.

Web applications with minput

minput is a step that waits for a value that arrives by HTTP: an endpoint. A program that chains several minput is a web application, written as a sequence like any other (transient-core/examples/hello_web.rs):

pub fn app() -> Cloud<()> {
    cdo! {
        minput::<(), _>("start", "Welcome");                                   // the entry point
        let name = minput::<String, _>("name", "What is your name?");
        let surnames = minput::<String, _>("surnames", format!("Hello {name}, what are your surnames?"));
        local_io({
            let (name, surnames) = (name.clone(), surnames.clone());
            move || println!("{name} {surnames}")
        });
        moutput(&serde_json::json!({ "name": name, "surnames": surnames, "fullname": format!("{name} {surnames}") }))
    }
}

fn main() {
    let _: Result<(), String> = keep(init_node(app()));
}

Every response says what to call next, so a page, a script or curl just follows the links (the page of the example does not know the program):

/start/u                  ->  { "msg":"What is your name?", "req":{... "requrl":"http://localhost:8080/name/$string"} }
/name/Ana                 ->  { "msg":"Hello Ana, what are your surnames?", "req":{... ".../surnames/$stringx"} }
/surnames/Garcia%20Lopez  ->  { "fullname":"Ana Garcia Lopez", "name":"Ana", "surnames":"Garcia Lopez" }
  • Several users at once. The first response sets the cookie state, which is the session: each person goes through the program with their own values.
  • Composable. An application is a Cloud<()> like the others: app() | other_app() runs both in the same node, and the values of several minput can be waited for together, in any order, with clift2.
  • Restart-proof, with the same mechanism as the rest of the computations. The endpoints are stored like any other point of a computation: a node that is killed and started again serves the endpoint to the same session, to another one or to a request without a cookie, and goes on from there. collectc(n, delta, action) gathers the answers of several users (up to n, or those that arrive before delta) and keeps them across a restart, even a kill -9.
cd transient-core/examples/hello_web
cargo run --offline --example hello_web -- --start localhost:8080     # open http://localhost:8080/

A value cannot contain /. The node also serves the files of ./static (the page of the example is static/index.html).

The browser: one program for the server and the browser

axiom has the widgets that run in the browser (text boxes, buttons, links, selects, DOM builders), drawn by Rust compiled to wasm32-unknown-unknown. They compose with the same operators as the rest. A page that reads a name:

fn page() -> Trans<()> {
    tdo! {
        // a text box and a button: the button makes the box be read
        let name = render(input_string(Some("world")).within(div).at_end_again(input_submit("greet".to_string()).fire(BrowserEvent::OnClick)));
        render(raw_html(p(format!("hello {name}"))))
    }
}

#[wasm_bindgen(start)]
pub fn main() {
    run(page());
}

A page that uses the server. The program is one function, feature(): a link in the browser, and when it is clicked the server computes the Fibonacci numbers, one per second, prints each one and sends it to the page, which shows it (axiom/examples/features/fib.rs). on_browser says that the first part is the page's; at_remote goes to the server and comes back.

pub fn feature() -> Cloud<()> {
    on_browser(cdo! {
        local(render(wlink("go".to_string(), h1("hello fibonacci numbers"))));     // a widget: a link
        let r = at_remote(cdo! {                                                  // this runs in the server
            let r = local(threads(1, choose(fibs(10))));
            local_io(move || {
                println!("{r}");
                std::thread::sleep(Duration::from_secs(1));
            });
            cpure(r)
        });
        local(render(raw_html(h2(r))))                                            // a widget: the number, in the page
    })
}

There is a single program. The two targets (native for the server, wasm for the browser) each need a main, and each main is one line that runs that program (axiom/examples/webfib_server.rs and webfib_browser.rs):

// the server (native):   fib::feature() is the program, `init_node` starts the node
fn main() { let _: Result<(), String> = keep(init_node(fib::feature())); }

// the browser (wasm):    the same program
#[wasm_bindgen(start)]
pub fn main() { run(init_browser_app(fib::feature())); }

The core runs in the browser with a cooperative scheduler (sched.rs): there are no threads there, so a task is a callback of the event loop, and sleep and threads n work as they do with threads. The browser calls the server through a WebSocket: the server accepts it on the port where it serves the page.

rustup target add wasm32-unknown-unknown        # or the rust-std of that target
cargo install wasm-bindgen-cli --version 0.2.130
WASM_BINDGEN=wasm-bindgen axiom/browser/all.sh   # PASS/FAIL for each scenario, in Chromium (playwright)

Adding features: one line each

axiom/examples/master is a single page and a single server that run, together, the examples of this repository: a call to the server (hello), the forms and links of widgets, the chat, the server that measures a text (area), the Fibonacci numbers (fib), and in the console of the server the stream from every node (fire), the order of the restart-proof example and the questions of hello_web.

// axiom/examples/master/app.rs
pub fn master() -> Cloud<()> {
    on_server(input_nodes())
        | on_server(stream::distrib_stream())
        | on_server(purchase::order())
        | on_server(questions::app())
        | hello::feature()
        | widgets::feature()
        | chat::feature()
        | area::feature()
        | fib::feature()
}

Each feature is a function in a file of its own that returns a Cloud<()> and knows nothing about the others. To add one, write its function and add a line (| my_feature()): no other file is edited, and none of the others is disturbed. The same file is compiled to the server and to the browser; what is for only one of them is marked with on_server and on_browser.

axiom/browser/remote.sh master master      # builds both, serves the page, and a browser (Chromium) uses every feature in the same page

Build and test

Rust 1.85 or newer. No system libraries.

cargo build --examples     # the tests of several processes run the examples
cargo test --workspace     # a few minutes: some tests start, kill and restart nodes
cargo test --workspace --features tls   # and the secure communications (`tests/tls.rs`: needs the commands `openssl` and `curl`)

The tests that start processes use ports that the operating system gives. Do not kill cargo test in the middle (a timeout, for example): the nodes it started keep running.

The distributed tests are in transient-core/tests/distributed.rs and cleanup.rs, each one in four nodes of the same process. They check also that, when a computation ends, nothing hangs from the thread where the calls started, and that a collect that has enough results stops the node that was producing them, also through a chain of calls.

Secure communications (TLS)

transient-core has the feature tls (off by default; it brings rustls with ring):

init_tls("cert.pem", "key.pem")      // the certificate and the key of this node

From then on every connection to another node is encrypted, and the node also accepts https and wss from the browsers: the first byte of a connection (0x16, the start of a TLS handshake) tells it from a plain one, and the same port serves both. init_tls_default() takes cert.pem and key.pem of the current directory. A certificate for testing:

openssl req -x509 -newkey rsa:2048 -nodes -keyout key.pem -out cert.pem -days 365 -subj "/CN=localhost" \
        -addext "subjectAltName=DNS:localhost,IP:127.0.0.1" -addext "basicConstraints=critical,CA:FALSE"

init_tls encrypts and does not verify who is at the other end: it stops whoever listens to the network, not whoever impersonates a node. init_tls_verified(cert, key, trusted) also checks that the certificate of the node that is called is signed by one of those of the PEM file trusted (a self-signed certificate is its own authority, if it is not marked as a certificate authority) and is valid for the host that is called. Only TLS 1.3 and 1.2 are accepted, and with TLS on a node that speaks without encryption is refused. The code is in stream.rs (a Stream is a TCP socket or a TLS one) and tls.rs.

Examples

Each one is in transient-core/examples.

parallel_terms The operators over computations in parallel: +, |, lift2.
stream A stream from every node of the cluster; the console adds nodes with input_nodes().
durable A computation that survives kill -9.
hello_web Two chained minput (name and surnames) and a page that follows the responses.
web_demo Several minput programs: sessions, an applicative of inputs, a POST body, collectc.
node_demo Programs of several nodes: calls, jobs, endpoints, ping.
bench, console Small measurements and the console.
axiom/examples/widgets A person, radio buttons, check boxes, a select and a link, drawn by Rust compiled to wasm.

The page of an example is ./static/index.html; the examples with a page use the one of their own directory if the current one has none. The command line: --start localhost:8000 (or --start localhost/8000, or -p start/localhost/8000) starts a node; each option looks for its own --name in the command line when it is executed, so the options can be in any order (see the documentation of console.rs).

Status and limits

A young project: it has the tests of this repository (265, some with processes that are killed and restarted) and no experience of deployment. Before betting a project on it, try it with your own case. What to know:

Trust. What travels between nodes is not code: the program is in every node, and a message only says "go on at this point with these values". Even so, a node that can send messages can make another one run its own program with values of its choice, so the nodes of a cluster must trust each other:

  • Connections are accepted with a shared secret, the cookie of the cluster (--cookie; the default, cookie1, is public: change it).
  • With init_tls the traffic is encrypted; with init_tls_verified the caller also checks the certificate of the node that it calls. The called node does not ask for a certificate of the caller (there are no client certificates).
  • The points where a node continues have no permissions: whoever holds the cookie can address any of them. It is made for a cluster of your own or a permissioned one, not for an open network.

Delivery. There is no promise of exactly once. A job_task that was interrupted is executed again from its start (at least once), so what it does must tolerate it. In general, make idempotent the effects that must not be repeated (a payment).

Changing the program. A point where a node continues is named after its position in the program. If the program changes while there are computations in flight, their points may not match the new names, and a message for a point that does not exist is not delivered (the node reports it as an error). There is no versioning: let the computations in flight end before updating, or keep the old program running until they end.

Threads and blocking. A branch is a task of a Tokio pool (the feature tokio-sched, by default) or a thread of the system (without it), and the steps are plain functions, not async. The delay of sleep does not hold a thread; a step that blocks (a thread::sleep, a synchronous driver, a block_on) holds the thread of the system that runs it. With a few hundred branches that block at the same time it is not a problem; with hundreds of thousands it is, and an async program serves them better.

Futures of other crates. There is no primitive that awaits a Future from a step. The way is async_(|| runtime.block_on(f)), which holds a thread while it waits. Libraries with a synchronous interface (ureq, rusqlite) fit better than reqwest or sqlx.

Streams. A step that produces one result or many is the same Trans<A>: collect(n, t), await_(t) and the operators work the same way on both. collect stops at n results and cancels the branches that are left; collectc adds a time limit and keeps what it has gathered across a restart.

Notation. tdo! and cdo! are sugar over bind and cbind (they add no meaning: they can be written by hand), and they need the list of the variables that they capture, [x, y], because the steps are closures that can be run again after a restart. Rust does not allow new operators, nor overloading &&, || or the comparisons for these types: | is the alternative, and the operator over two terms is lift2 or clift2.

Not provided. Discovery and membership of nodes (they are added by hand, with the console command add or add_nodes), reaching nodes behind NAT, and any agreement between nodes (consensus): a protocol of that kind is written on top. The cells with formulas of axiom (they need the server to keep the state of the cells of all the nodes) and the editor of the page are not available yet.

Crates

Crate
transient-loggable The text form of the values that are stored and sent (Loggable).
axiom The widgets that run in the browser, the cells and the builder of DOM: they are drawn by Rust compiled to wasm and compose with the same operators.
transient-core Threads and continuations, state, backtracking, indeterminism, the operators over computations, the distributed layer (run_at, clustered, jobs, collectc, nodes over TCP, optionally under TLS), HTTP/REST with minput, the console and the stored state of the computations.

License

MIT.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages