Phoenix https://janezurevc.name/ en Real-time auto save with Phoenix LiveView https://janezurevc.name/real-time-auto-save-phoenix-liveview <span>Real-time auto save with Phoenix LiveView</span> <span><span lang="" about="https://janezurevc.name/users/slashrsm" typeof="schema:Person" property="schema:name" datatype="" xml:lang="">slashrsm</span></span> <span>Mon, 16.03.2020 - 21:18</span> <div class="field field--name-body field--type-text-with-summary field--label-hidden field--item"><h2>Background</h2> <p>In the past weeks I spent quite some time working on <a href="https://bitqa.app">BitQ&A</a>; my side project that explores possibilities that digital currencies offer. BitQ&A is a Phoenix application that I initially created for the <a href="https://hackathon.bitcoinassociation.net/">2nd Bitcoin SV virtual hackathon</a>. It was also the first project where I had an opportunity to try <a href="https://github.com/phoenixframework/phoenix_live_view">LiveView</a> (brilliant tool that brings rich real-time UX to Phoenix).</p> <p>I already used LiveView for numerous parts of the site (such as real-time Markdown previews), when a feature request for real-time auto save came in. Knowing how complicated this would be to achieve in tools that I used in the past, I decided to bite into this one. The more I thought about the problem the more I was convinced that LiveView is the way to go due to its speed and efficiency. I was aware that I will need to make sure that the constant inflow of changes won't kill my backend or the database, but I was curious if I can make it work.</p> <h2>The devil is in the details....</h2> <p>This article will describe a simplified version of the solution. In order to keep things simple we will save changes into the original schema. This comes with some drawbacks; changes will be immediately seen to everyone and we will run into issues in case of failed validations. The real life solution would require a bit smarter solution; possibly a separate draft schema (the approach used on BitQ&A), "forward" revisions or something similar. However, I do think this part is not essential to explain the approach that I took. Keep it simple, stupid! Right? Right!</p> <p>I also created a <a href="https://github.com/slashrsm/phoenix_auto_save/">GitHub repo</a> where you can see the working code, run it and play with it.</p> <p>If you already know how LiveView works feel free to skip to the <a href="#interesting">interesting part</a>.</p> <h2>More or less boring steps (<a href="https://github.com/slashrsm/phoenix_auto_save/tree/ec10a35b40d78dc8b32722441470681ddf6d95f4">ec10a3</a>)</h2> <p>We need a new Phoenix project with a schema that we'll work with. I decided to go with a Post with title and body (but we could use any number or type of fields):</p> <pre><code class="elixir"> # ... schema "posts" do field :body, :string field :title, :string timestamps() end # ... </code></pre> <p>If you are not sure how to get this far check <a href="https://hexdocs.pm/phoenix/overview.html">Phoenix documentation</a>. It is great. Really... you should read it.</p> <h2>We want LiveView! (<a href="https://github.com/slashrsm/phoenix_auto_save/commit/50709fd95237680092195083198f5e604471e223">50709f</a>)</h2> <p>There will be no juice without the LiveView, so let's bring it in by adding it to <code>mix.exs</code>:</p> <pre><code class="elixir"> # ... defp deps do [ # More dependencies ... {:phoenix_live_view, "~> 0.9.0"} ] end # ... </code></pre> <p>This was the most recent version at the time of writing. Check <a href="https://hex.pm/packages/phoenix_live_view">LiveView's page on hex.pm</a> for up to date information.</p> <p>We will also need to update a few things in our project to be able to use it. Things like importing its JavaScript part, enabling the endpoint that will be used to establish the socket connection, bring in helpers, ... LiveView has <a href="https://hexdocs.pm/phoenix_live_view/installation.html">great documentation that describes these steps in detail</a>.</p> <p>Good!</p> <h2>Let the real fun begin! (<a href="https://github.com/slashrsm/phoenix_auto_save/commit/dde99250770de65ffed0e896020c86ead8774ca1">dde992</a>)</h2> <p>The idea is to let LiveView take control of the edit form for our post schema and let it react on any change to the form. This will result in changes being sent to the server where we will be able to save them. This will be very fast and efficient since LiveView uses web sockets to communicate and tries to be smart about the data that is being sent over the wire. Also, by LiveView taking over the entire form we make it very easy to add more fields - we should only make sure that they appear on the form. And that's it... Easy peasy!</p> <p>We will need to change the extension of the template in question (<code>form.html.eex</code> to <code>form.html.leex</code>) and make LiveView trigger an event on every change to the form (<code>phx_change: :change</code> part):</p> <pre><code class="elixir"><%= f = form_for @changeset, @action, phx_change: :change %> </code></pre> <p>LiveView also has some strict requirements about the structure of the form in templates. <a href="https://hexdocs.pm/phoenix_live_view/Phoenix.LiveView.html#module-form-events">You can learn more about that in the documentation</a>.</p> <p>We also need to change how the form is rendered in its parent (<code>edit.html.eex</code> in our case):</p> <pre><code class="elixir"># ... <%= live_render( @conn, PhoenixAutoSaveWeb.PostFormLive, session: %{ "changeset" => @changeset, "action" => Routes.post_path(@conn, :update, @post), "post" => @post } ) %> # ... </code></pre> <div id="interesting"></div> <p>Now we need a module that will implement the server-side logic. It will generally have a function that is called when the LiveView establishes the connection and one or multiple functions that handle the events. The most interesting part in our case is the callback that reacts on changes in the form:</p> <pre><code class="elixir"># ... def handle_event("change", %{"post" => post_params}, socket) do {:ok, post} = Posts.update_post(socket.assigns.post, post_params) { :noreply, socket |> assign(:changeset, Posts.change_post(post)) |> assign(:post, post) } end # ... </code></pre> <p>Let me explain this in a bit more detail:</p> <ul><li>First argument is the event name. This comes from the <code>phx_change: :change</code> thing that we added to the form template. <code>:change</code> basically becomes <code>"change"</code>. It is the name of the event.</li> <li>Second argument are the current values in the form. We are only interested in the post part so we pattern match it.</li> <li>Last argument is the socket object where the current state of the LiveView is stored.</li> <li>In the first line of the body we take the current post and update it with the values from the form. <code>Posts.update_post/2</code> will also save the updated post into the database, essentially making the change persistent.</li> <li>At the end we update the socket with the new version of the post and our job is finished.</li> </ul><p>Now every time a change happens on the form it gets sent over and is saved. Amazing! (not so much... as you will see soon)</p> <p><a href="https://github.com/slashrsm/phoenix_auto_save/commit/dde99250770de65ffed0e896020c86ead8774ca1#diff-5676f873552d62aad96c2e01688de90dR1">Full code of the LiveView</a>.</p> <h2>Database gods will send me to hell unless.... (<a href="https://github.com/slashrsm/phoenix_auto_save/commit/f23ec8b0db4d66578015f154b5d451c8491a65e9">f23ec8</a>)</h2> <p>You probably already saw the nasty part... The approach above will result in a database <code>UPDATE</code> query literary for every letter while you are typing your fancy new blog post. Believe me, Postgres will hate you for that! And we wouldn't want that, would we? Imagine having hundreds of users writing their posts at the same time. Things would go very bad pretty soon....</p> <p>So how do we solve that? Well.... we can decide that auto save won't work and go on with our lives. Not so fast!</p> <p>What if we would keep the changes in the memory for a while and only save to the database periodically. Let's try:</p> <pre><code class="elixir"># ... defp schedule_save() do Process.send_after(self(), :store, 10 * 1_000) end def handle_event("change", %{"post" => post_params}, socket) do { :noreply, socket |> assign(:changeset, Posts.change_post(socket.assigns.post, post_params)) } end def handle_info(:store, socket) do {:ok, post} = Posts.update_post(socket.assigns.changeset) schedule_save() { :noreply, socket |> assign(:changeset, Posts.change_post(post)) |> assign(:post, post) } end # ... </code></pre> <p>Quite a lot going on here. Let's go step by step:</p> <ul><li><code>schedule_save/0</code> will schedule a save operation 10 seconds (arbitrary, could be anything) after being called. We initially do that when the LiveView connection is established.</li> <li><code>:change</code> event no longer triggers fully-fledged save operation. It rather only stores the changes into the changeset that is part of the socket object. This is a fast in-memory operation.</li> <li>periodic <code>:store</code> message will be processed by <code>handle_info/2</code>. It will essentially do what the <code>:change</code> handler was doing before. It updates the post, saves it into the database and updates the socket object.</li> <li>we schedule next save operation by calling <code>schedule_save()</code></li> </ul><p>Changes are now tracked in real-time and persisted periodically. Great user experience and Postgres will still be our friend. Much better!</p> <h2>But what if....</h2> <p>Current approach will work fine but can lead to loss of data in some cases. Let's imagine this case:</p> <ul><li>Author opens the form and starts writing the post. Changes are persisted periodically and life is good.</li> <li>At some point database update happens.</li> <li>Immediately after that our author gets a moment of supernatural inspiration and writes a huge amount out text in a single second.</li> <li>Supernatural powers apparently have side effects and our author closes the browser window before LiveView manages to save the most recent changes.</li> </ul><p><strong>Result:</strong> all changes since the last save - supernatural-powers driven moment of productivity - are lost. Not good!</p> <p>How can we solve this? We should try to detect the window close event and do one final save when that happens. Let's give it a try:</p> <pre><code class="elixir"># ... def terminate(_reason, socket) do {:ok, %Post{}} = Posts.update_post(socket.assigns.changeset) :ok end # ... </code></pre> <ul><li><code>terminate/2</code> callback will be called when the LiveView connection is terminated. This can happen for many reasons: timeout, the user navigates to another page, browser window is closed, ...</li> <li>In our case we are not interested in the termination reason (first argument). Whenever something went wrong we want to save the data.</li> <li>Post is saved using <code>Posts.update_post/1</code> - exactly the same as we do in <code>handle_event/3</code></li> </ul><h2>New posts? (<a href="https://github.com/slashrsm/phoenix_auto_save/commit/f12a7670480bb28bd6e13882ec88dedd0e2bbd6c">f12a76</a>)</h2> <p>What about new posts? Our approach assumes that the post already exists in the database and this is not the case on the create form. One way to solve this would be to save an empty post before loading the form, which is obviously not ideal.</p> <p>Proper solution would be to use one of the approaches that I already mentioned at the beginning - drafts, "forward" revisions, ...</p> <p>I hope that you will find this writing useful and maybe use auto save for one of your projects. Do you have any comments, ideas or maybe noticed something that could have been done better. Do not hesitate to comment below!</p> <p><em>Until next time!</em></p> </div> Mon, 16 Mar 2020 20:18:29 +0000 slashrsm 124 at https://janezurevc.name