r/Clojure • • Sep 23 '21

Reactive Clojure: You don't need a web framework, you need a web language

https://hyperfiddle.notion.site/hyperfiddle/Reactive-Clojure-You-don-t-need-a-web-framework-you-need-a-web-language-44b5bfa526be4af282863f34fa1cfffc
89 Upvotes

38 comments sorted by

8

u/mobiledevguy5554 Sep 23 '21

Would this work with Postgres or is it tied to Datomic?

12

u/dustingetz Sep 23 '21 edited Oct 11 '21

The language half of the stack does not use EAVT information model:

  • leonoel/missionary – functional effect and streaming system for Clojure/Script.

  • hyperfiddle/photon – "Reactive Clojure/Script" implemented as a macro, with network distribution.

  • hyperfiddle/photon-dom – fine-grained dom effects, server-streamed. No React.js dep

Above this point, no EAVT stuff.

  • hyperfiddle/zero – server-streamed web forms, database-connective and integrated with the EAVT entity graph information model. Zero boilerplate

  • hyperfiddle/hfql – server-streamed graph pull-query evaluator that composes with dom

  • hyperfiddle/hyperfiddle – server-streamed hypermedia UI DSL

This half needs EAVT (specifically the "entity" API and speculative transactions d/with). Datascript is fine, or can write an adapter to GraphQL. As for Datomic Cloud, Cognitect will need to give us entity API in Ions. Presumably Photon & Hyperfiddle will soon be compelling enough that they'll consider that. However my reddit comments about Postgres in ~2017-18 were wrong as proven by Hasura. We could maybe get Postgres to work.

3

u/mobiledevguy5554 Sep 24 '21

Thanks for the thorough explanation.

6

u/clickrush Sep 23 '21

So this is "streaming" HTML reactively based on both server/database and UI event updates?

The biggest risk/question for me would be this: what if I wanted to put something in the middle? Say a cache for reads that are not expected to update frequently?

11

u/dustingetz Sep 23 '21

Very close – Not streaming HTML, it's streaming lexical scope at the programming language layer (photon). The lexical scope itself is reactive. If a point in the lexical scope doesn't update, then there will be no network traffic so it's not clear that there is anything to optimize. But anyway yes if you wanted to, you can escape into "monad stuff" layer with a "reactive-quote" operator at which point all the async signal/stream types are at hand for you to transduce at the signal/stream level (filter, debounce, cache etc).

5

u/_pka Sep 24 '21

Very interesting project!

I've tried implementing an incremental DOM system in Haskell, and the biggest roadblock I hit was properly incrementalising all of the list primitives. Essentially, what you want is turning something like "sort a list" into "sort changes to a list, like insert, delete, update".

Some operations like map are trivial to incrementalise, but things like filter, sort, take are more difficult (for example, sort and filter require state; also, you'd like to turn a stable sort into a stable incremental sort). concatMap (which is mapcat in Clojure if I'm not mistaken) is also quite hairy to implement.

For example, let's say you want to filter all authorised users, sort them by their last names, take the first 100, and then take the 5 most recent comments of each of the resulting users and display that in a table - that's a composition of filter, sort, take, mapcat right there. So, if a user adds a comment, we'd like to insert it at the appropriate position in the table. Equally, if a user gets deleted we'd like to remove all of their comments and at the same time insert the comments of the 101st user at the end of the table. And so on.

This is not impossible to implement, and iirc Jane Street have done so in their Incremental library written in OCaml, but it's quite a lot of very hairy work.

Would you mind expanding a bit on how you managed to do that, if indeed you have?

3

u/dustingetz Sep 24 '21 edited Sep 24 '21

Deleted my answer because I answered too quickly. We have map and flatmap, so we have mapcat. We take the stance that Top-k queries should be done in a database, e.g. Materialized. This is okay since Photon is currently specialized for UI. We do not substitute all of clojure core with incremental data structures and incremental std lib, which is what you're asking. If we did that, then for example it might be possible to take a naive recursive fibonacci and incrementally maintain it such that it has iterative runtime performance. We don't have that. We don't think UIs need that. Hyperfiddle doesn't seem to need that. There is plenty of room for us to be wrong and end up needing that.

3

u/_pka Sep 25 '21

Just as a side note, I wasn’t expecting that you can incrementalise arbitrary functions (e.g. fibonacci) - afaik that’s an open research problem and it’s only possible if the language is restricted in certain ways.

If I understand correctly, you’ve got incremental map and flatMap, but no sort, filter, take, etc. Now imagine I want to show a sorted table with thousands of records, sorted on the frontend. Then, a record is inserted on the backend, the incremental change is propagated to the frontend, but since we have a non-incremental client-side sort, we can’t know at which position to insert the new record. Do we then just recompute the sorted list and replace the whole table, with all of its thousands of records?

3

u/dustingetz Sep 25 '21 edited Sep 25 '21
  • Photon flows are Missionary flows

  • Missionary has transduce over flow missionary.core/eduction which gives us reduce, filter, take, mapcat on flows

  • Photon has a special form "reactive-quote" which lets you escape to the missionary layer, and a special form for join (monad). Join works on photon flows too since photon compiles to missionary.

  • Photon has differential-for, which iirc is jane street's incremental map, see this REPL trace demonstrating stable insert/remove/update/reorder

The only missing piece is incremental sort. You want to sort as close to the "database" as possible. If your "queries" are a reduce over the event log, you want the sort to be done in that layer (on big database compute nodes), not the web client with resource constraints.

This comment uses words like "sorted on the frontend" – "frontend" is arbitrary! The app is an expression. It doesn't matter which node in the distributed system is doing the sorting. The optimal topology for a traditional database/UI is the one where sorting happens before the network transfer. The transfer will likely be in a differential-for and therefore you get ordinal diffs on the wire after the sorting is done.

query -> sort -> diff -> group-by -> map -> gather -> patch

2

u/_pka Sep 26 '21

Thanks for the explanation, I’ll have a deeper look. One more question: Missionary flows seem to be unidirectional, and one thing that gave me a lot of grief when I was toying with my implementation was take. Imagine you have an incremental list being replicated across nodes (let’s throw away the back/frontend distinction, although I think it is important, even if only because of performance considerations), and then you take the first 10 elements. Now a change comes in “delete the third element”, so far so good, but now we only have 9 elements downstream. This means that take has to initiate a query to get the previously 11th element from upstream so that it can add the missing element to downstream. This makes everything much more complicated, because flows/streams are not unidirectional anymore and have to be able to initiate queries to upstream and serve queries to downstream. How did you solve this?

As to sort, sometimes you want to sort things locally, without issuing a new query to the database, but I agree, this is not a deal breaker.

1

u/dustingetz Sep 26 '21

To be clear we are calling clojure.core/take's transducer arity in a missionary eduction over flows.

Photon is continuous time, it is not differential except for in one place, photon/for which is a special form for differential collection maintenance. photon/for takes a collection and returns a collection, managing application of the user-supplied expression in a stable way.

It sounds like you have a discrete-time language which is fully differential end-to-end.

However, even in the discrete time case I think this can be done with unidirectional data flow. The "delete 3rd element" diff originated from which input effect? A database transaction upstream in the DAG? A user interaction downstream in the dag that needs to loop through the dag from the beginning a-la React.js "Flux" pattern?

2

u/dustingetz Sep 24 '21 edited Sep 25 '21

An insight is that traditional web UIs are best modeled as continuous time signals, not discrete event streams. diff is fundamentally a discrete event stream primitive. I.e. you can reduce a stream of events to "integrate" them à la event sourcing. Event = diff.

Event streams = eager, can drive side effects. An example discrete effect workflow is: Click event -> websocket message -> query db -> send email -> transact. No events can be dropped! Diffs too can't be skipped.

Continuous signals = lazy. Nothing is computed until asked for. CT signals offer maximum work-skipping. UI rendering is lazy. If you miss a frame, you can skip it as the user just wants latest.

Diffs are history sensitive – to reconstruct the final state you must replay the entire log. To deploy a code change, the computation must "boot" by replaying the whole log and it takes unbounded time to boot. Off-screen nodes need to be kept alive lest they miss an event. Any dynamic switches in the DAG potentially require the whole log to be replayed. Including every database transaction.

This unbounded memory and boot time explains why 2010-era FRP failed in UI. Any Rx lib hello world is about flatMap on click events https://rxjs.dev/guide/overview . Event streams are a bad fit for dynamic UI rendering!

9

u/Liistrad Sep 23 '21

Very interesting and ambitious!

A couple of questions that come to mind:

  • does no-react means all UI elements are done from scratch? that sounds hard to adopt

  • is there an offline model?

7

u/guywithknife Sep 23 '21

does no-react means all UI elements are done from scratch? that sounds hard to adopt

One of the main reasons I choose react nowadays is the availability of component libraries. With shadow-cljs it’s trivial to use a javascript react library too. I like the idea behind this project, but this is a big reason why it’s unlikely I’d ever try it out myself. There’s simply no way I can recreate the third party react stuff I use.

18

u/dustingetz Sep 23 '21 edited Sep 23 '21

There’s simply no way I can recreate the third party react stuff I use.

With React, a spreadsheet-like infinite scroll component backed by a database is thousands of imperative LOC to coordinate the client/server datasync manually. They take years to mature and have hundreds of configuration options because they don't compose.

A reactive, server-streamed grid in photon looks something like this really quick sketch that I coded in 3 mins:

(def page-size 100)

(p/defn infinite-table [records-fn]
  (client
    (let [offset (dom/input)]
      (p/for [e (records-fn offset)]
        (let [{:keys [person/name
                      person/email]} (datomic.api/entity *db* e)]
          (dom/tr (dom/td name) (dom/td email)))))))

(client
  (binding [dom/parent (js/document.getElementById "root")]
    (infinite-table (p/fn [offset]
                      (server
                        (->>
                          (d/q '[:find [?e ...] :in $ :where [?e :person/name]] db)
                          (drop (* page-size offset))
                          (take page-size)))))))

And you'd test it at the REPL because it's an expression. The streaming, backpressured IO is reflected.

2

u/guywithknife Sep 24 '21

My point is that there are already many libraries out there. With styling, input events and so on. For example, I use Blueprintjs in many current projects, which provides a large set of widgets/components. One of these is a spreadsheet-like table component with sorting, editing, reordering and more. I also use react-grid-layout for card widgets that you can drag and resize and react-flip-toolkit for animation, among other things. There is a huge React ecosystem out there and duplicating all of that would take far, far too long.

Sure, your example is cool, but what about styling or user input, or any number of other features. If it suits your needs or lets you do something that doesn't have existing libraries, great, more power to you, but for most common use cases there are already React libraries and I don't have the time and resources to reimplement them when I can just use React.

I don't mean to diminish your work, its cool, I like it. But realistically, the React ecosystem has far too much traction, both in the clojurescript world (with reagent and re-frame based tools and libraries) and the javascript word (which I can trivially make use of using shadow-cljs). For these reasons, I don't see any realistic way I could use this in anything other than fun personal projects.

6

u/dustingetz Sep 24 '21

It should be straightforward to get React interop, a simple hook will probably work to bridge them. I hear you, the ecosystem compatibility is really important.

2

u/guywithknife Sep 24 '21

It should be straightforward to get React interop

That's good to hear. If you ever look into it, be sure to let us know, that would be incredibly useful! Although, I understand if its not a priority.

5

u/mobiledevguy5554 Sep 23 '21

I wish my CEO could write Clojure

1

u/robopiglet Mar 30 '22

That is pretty awesome. I'm not clear on how the UI is generated by that... can you clarify?

1

u/dustingetz Mar 30 '22

(dom/tr) produces fine-grained point writes to the dom. The reactive abstraction will incrementally maintain the Clojure expression, so the point writes will be correctly maintained and eventually cleaned up (the heavy reactive work is done by https://github.com/leonoel/missionary)

1

u/robopiglet Apr 01 '22

Thank you... I'll take a look at missionary. :-)

2

u/lgstein Sep 23 '21

How and what do you diff?

3

u/dustingetz Sep 23 '21

for loops are differential and take a react key. This gives you concurrent/stable insert/update/remove (it turns out the async REPL screenshot in the blog post uses differential-for as an example). If you choose the EAV entity information model, react-key is identity and can be omitted.

That's it, there is no virtual dom.

It is straightforward to make all of Photon differential a-la differential dataflow and we considered it, but we found it not a great fit for UI. To explain that is probably a whole blog post though.

2

u/TheLastSock Sep 25 '21

So, ever computer (browser & server) has a copy of the all the logic and you pass the context between them as needed along with any other produced state. Is that close?

1

u/dustingetz Sep 25 '21

One peer is in charge and bootstraps the other(s) over the wire. The subordinate peers whitelist/export a set of stream functions ("routes"), this gives you about the same data security as a REST API.

1

u/TheLastSock Sep 25 '21

Thanks, why is photon/for needed? I would think the photon/defn would return a stream fn which at runtime would execute a request whose response would be the payload and the client could pick it up there.

When do you think I can start fiddling with all this? ;)

2

u/dustingetz Sep 25 '21

photon/for is concurrent and differential, clojure.core/for will run sequentially (you are allowed to call clojure.core/for and reasonably any clojure.core fn or macro from photon and it will work within reason. For example ->> works in Photon)

We chose not to shadow/substitute clojure.core because we want as much valid Clojure code to seamlessly lift into Photon without changing the meaning, including macros (within reason – a core macro manipulating java thread bindings is not something we care about).

26

u/pxpxy Sep 23 '21

That’s a lot to take in. You sound very excited about it, which is great, but for the purpose of making it easier to understand you might want to separate the parts, the theoretical underpinnings, the actual projects and code, and what it means for hyper fiddle a bit more from each other. I’d also love some diagrams for an overview of what happens at what time, that would be easier to parse than the text.

8

u/SimonGray Sep 23 '21 edited Sep 23 '21

This is really blowing up on HN, Dustin!

4

u/agumonkey Sep 23 '21

funny I was just thinking about how we need a language level solution.. oh how I wish I met you when you started that project :)

kudos

1

u/TheLastSock Sep 25 '21

Left wing question, what is the Grammer of the url this system would use? E.g do you use the traditional path params and key value query params or does this do something novel? I have played with the idea of just using datalog.

Sorry, I feel I could ask questions all day long :).

1

u/dustingetz Sep 25 '21

s-expressions. routes are exported photon functions. clojure specs define a form that prompt for route parameters where needed. this is at hyperfiddle layer, not photon

3

u/joinr Sep 23 '21

Very cool Dustin. Reminds me (a little) of some work that the Haskell Haste folks were doing to blur the front/backend via the compiler. Interested to see what you learn along the way refactoring hyperfiddle.

2

u/cbleslie Sep 28 '21 edited Sep 12 '25

public spectacular person cause amusing physical snails narrow correct telephone

This post was mass deleted and anonymized with Redact

1

u/npafitis Sep 23 '21

Is there a real world example for this?

1

u/slifin Oct 20 '21

Just wanted to say thank you for hyperfiddle/rcf, only using it for synchronous example based tdd and it's such a sweet blend of repl and tdd there

It makes Uncle Bob's tdd vs repl conversation seem silly in retrospect

I'd love to know how other people are using wildcard/unification features in their real tests?

0

u/[deleted] Sep 23 '21

[deleted]

6

u/dustingetz Sep 24 '21 edited Sep 24 '21

LiveView it appears to be an imperative Rails-like machine that doesn't compose. Photon is damn close to referentially transparent.

From a DM: "We tried out LiveView on a few projects, and personally I found the experience underwhelming. The biggest problem is that you still have a "split brain" situation where part of your state is in DOM and another in JS code. Photon interests me as I can see opportunity to avoid the "split brain" problem"

The thesis of Hyperfiddle is that functional programming makes possible "low-code" higher abstractions that were not possible before, ushering in a new generation/era of end user programmers. And Clojure makes the right tradeoffs needed to layer this on top of how things already work today.